code
stringlengths 2
1.05M
|
---|
/**
*
* app.js
*
* This is the entry file for the application, mostly just setup and boilerplate
* code
*
*/
// Load the ServiceWorker, the Cache polyfill, the manifest.json file and the .htaccess file
import 'file?name=[name].[ext]!../serviceworker.js';
import 'file?name=[name].[ext]!../serviceworker-cache-polyfill.js';
import 'file?name=[name].[ext]!../manifest.json';
import 'file?name=[name].[ext]!../.htaccess';
import 'file?name=[name].[ext]!../favicon.ico';
import 'file?name=[name].[ext]!../favicon.png';
//Check for ServiceWorker support before trying to install it
if ('serviceWorker' in navigator) {
// Install ServiceWorker
navigator.serviceWorker.register('/serviceworker.js').then(() => {
}).catch((err) => {
// Installation failed
console.log('ServiceWorker registration failed, error:', err);
});
} else {
// No ServiceWorker Support
console.log('ServiceWorker is not supported in this browser');
}
// Import all the third party stuff
import React from 'react';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { homeReducer } from './reducers/reducers';
import FontFaceObserver from 'fontfaceobserver';
// When Open Sans is loaded, add the js-open-sans-loaded class to the body
// which swaps out the fonts
const openSansObserver = new FontFaceObserver('Open Sans');
openSansObserver.check().then(() => {
document.body.classList.add('js-open-sans-loaded');
}, (err) => {
document.body.classList.remove('js-open-sans-loaded');
});
// Import the components used as pages
import HomePage from './components/pages/HomePage.react';
import LoginPage from './components/pages/LoginPage.react';
import RegisterPage from './components/pages/RegisterPage.react';
import Dashboard from './components/pages/Dashboard.react';
import NotFound from './components/pages/NotFound.react';
import App from './components/App.react';
// Import the CSS file, which webpack transfers to the build folder
import '../css/main.css';
// Creates the Redux reducer with the redux-thunk middleware, which allows us
// to do asynchronous things in the actions
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const store = createStoreWithMiddleware(homeReducer);
function checkAuth(nextState, replaceState) {
let { loggedIn } = store.getState();
// check if the path isn't dashboard
// that way we can apply specific logic
// to display/render the path we want to
if (nextState.location.pathname !== '/dashboard') {
if (loggedIn) {
if (nextState.location.state && nextState.location.pathname) {
replaceState(null, nextState.location.pathname);
} else {
replaceState(null, '/');
}
}
} else {
// If the user is already logged in, forward them to the homepage
if (!loggedIn) {
if (nextState.location.state && nextState.location.pathname) {
replaceState(null, nextState.location.pathname);
} else {
replaceState(null, '/');
}
}
}
}
// Mostly boilerplate, except for the Routes. These are the pages you can go to,
// which are all wrapped in the App component, which contains the navigation etc
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route component={App}>
<Route path="/" component={HomePage} />
<Route onEnter={checkAuth}>
<Route path="/login" component={LoginPage} />
<Route path="/register" component={RegisterPage} />
<Route path="/dashboard" component={Dashboard} />
</Route>
<Route path="*" component={NotFound} />
</Route>
</Router>
</Provider>,
document.getElementById('app')
);
|
var express = require('express');
var router = express.Router();
var util = require('util');
var utils = require('../util/utils')
var getHttpScenarioName = function(scenario, method, code) {
var lookup = {
'Success': {
'200' : {
'head': 'HttpSuccess200Head',
'get': 'HttpSuccess200Get',
'options': 'HttpSuccess200Options',
'put': 'HttpSuccess200Put',
'post': 'HttpSuccess200Post',
'patch': 'HttpSuccess200Patch',
'delete': 'HttpSuccess200Delete'
},
'201' : {
'put': 'HttpSuccess201Put',
'post': 'HttpSuccess201Post'
},
'202' : {
'put': 'HttpSuccess202Put',
'post': 'HttpSuccess202Post',
'patch': 'HttpSuccess202Patch',
'delete': 'HttpSuccess202Delete'
},
'204' : {
'head': 'HttpSuccess204Head',
'put': 'HttpSuccess204Put',
'post': 'HttpSuccess204Post',
'patch': 'HttpSuccess204Patch',
'delete': 'HttpSuccess204Delete'
},
'404' : {
'head': 'HttpSuccess404Head'
}
},
'Redirect': {
'300' : {
'head': 'HttpRedirect300Head',
'get': 'HttpRedirect300Get'
},
'301' : {
'head': 'HttpRedirect300Head',
'put': 'HttpRedirect301Put',
'get': 'HttpRedirect301Get'
},
'302' : {
'head': 'HttpRedirect302Head',
'get': 'HttpRedirect302Get',
'patch': 'HttpRedirect302Patch'
},
'303' : {
'post': 'HttpRedirect303Post'
},
'307' : {
'head': 'HttpRedirect307Head',
'get': 'HttpRedirect307Get',
'options': 'HttpRedirect307Options',
'put': 'HttpRedirect307Put',
'post': 'HttpRedirect307Post',
'patch': 'HttpRedirect307Patch',
'delete': 'HttpRedirect307Delete'
}
},
'Retry': {
'408' : {
'head': 'HttpRetry408Head'
},
'502' : {
'options': 'HttpRetry502Options',
'get': 'HttpRetry502Get'
},
'500' : {
'put': 'HttpRetry500Put',
'patch': 'HttpRetry500Patch'
},
'503' : {
'post': 'HttpRetry503Post',
'delete': 'HttpRetry503Delete'
},
'504' : {
'put': 'HttpRetry504Put',
'patch': 'HttpRetry504Patch'
}
},
'Failure': {
'400' : {
'head': 'HttpClientFailure400Head',
'get': 'HttpClientFailure400Get',
'options': 'HttpClientFailure400Options',
'put': 'HttpClientFailure400Put',
'post': 'HttpClientFailure400Post',
'patch': 'HttpClientFailure400Patch',
'delete': 'HttpClientFailure400Delete'
},
'401' : {
'head': 'HttpClientFailure401Head'
},
'402' : {
'get': 'HttpClientFailure402Get'
},
'403' : {
'get': 'HttpClientFailure403Get',
'options': 'HttpClientFailure403Options'
},
'404' : {
'put': 'HttpClientFailure404Put'
},
'405' : {
'patch': 'HttpClientFailure405Patch'
},
'406' : {
'post': 'HttpClientFailure406Post'
},
'407' : {
'delete': 'HttpClientFailure407Delete'
},
'409' : {
'put': 'HttpClientFailure409Put'
},
'410' : {
'head': 'HttpClientFailure410Head'
},
'411' : {
'get': 'HttpClientFailure411Get'
},
'412' : {
'get': 'HttpClientFailure412Get',
'options': 'HttpClientFailure412Options'
},
'413' : {
'put': 'HttpClientFailure413Put'
},
'414' : {
'patch': 'HttpClientFailure414Patch'
},
'415' : {
'post': 'HttpClientFailure415Post'
},
'416' : {
'get': 'HttpClientFailure416Get'
},
'417' : {
'delete': 'HttpClientFailure417Delete'
},
'429' : {
'head': 'HttpClientFailure429Head'
},
'501' : {
'head': 'HttpServerFailure501Head',
'get': 'HttpServerFailure501Get'
},
'502' : {
'options': 'HttpServerFailure502Options',
'put': 'HttpServerFailure502Put'
},
'504' : {
'patch': 'HttpServerFailure504Patch'
},
'505' : {
'post': 'HttpServerFailure505Post',
'delete': 'HttpServerFailure505Delete'
}
}
};
var method = method.toLowerCase();
console.log('looking up http scenario ( ' + scenario + ', ' + code + ', ' + method + ')\n');
if (lookup[scenario] && lookup[scenario][code] && lookup[scenario][code][method]) {
return lookup[scenario][code][method];
} else {
return null;
}
};
var isRetryRequest = function(req, code, method) {
var cookies = req.headers['cookie'];
var cookieMatch;
if (cookies) {
cookieMatch = /tries=(\w+)/.exec(cookies);
if (cookieMatch && cookieMatch[1] && cookieMatch[1] === code + '_' + method) {
return true;
}
}
return false;
};
var addRetryTracker = function(res, code, method) {
res.cookie('tries', code + '_' + method, {'maxAge': 900000});
return res;
};
var removeRetryTracker = function(res) {
res.clearCookie('tries');
return res;
}
var getMultipleResponseScenarioName = function( scenario, code, type) {
if (scenario === 'A') {
if (code === '200' && type === 'valid') {
return "ResponsesScenarioA200MatchingModel";
} else if (code === '204' && type === 'none') {
return "ResponsesScenarioA204MatchingNoModel";
} else if (code === '201' && type === 'valid') {
return "ResponsesScenarioA201DefaultNoModel";
} else if (code === '202' && type === 'none') {
return "ResponsesScenarioA202DefaultNoModel";
} else if (code === '400' && type === 'valid') {
return "ResponsesScenarioA400DefaultModel";
} else {
return null;
}
} else if (scenario ==='B') {
if (code === '200' && type === 'valid') {
return "ResponsesScenarioB200MatchingModel";
} else if (code === '201' && type === 'valid') {
return "ResponsesScenarioB201MatchingModel";
} else if (code === '400' && type === 'valid') {
return "ResponsesScenarioB400DefaultModel";
} else {
return null;
}
} else if (scenario ==='C') {
if (code === '200' && type === 'valid') {
return "ResponsesScenarioC200MatchingModel";
} else if (code === '201' && type === 'valid') {
return "ResponsesScenarioC201MatchingModel";
} else if (code === '404' && type === 'valid') {
return "ResponsesScenarioC404MatchingModel";
} else if (code === '400' && type === 'valid') {
return "ResponsesScenarioC400DefaultModel";
} else {
return null;
}
} else if (scenario ==='D') {
if (code === '202' && type === 'none') {
return "ResponsesScenarioD202MatchingNoModel";
} else if (code === '204' && type === 'none') {
return "ResponsesScenarioD204MatchingNoModel";
} else if (code === '400' && type === 'valid') {
return "ResponsesScenarioD400DefaultModel";
} else {
return null;
}
} else if (scenario ==='E') {
if (code === '202' && type === 'invalid') {
return "ResponsesScenarioE202MatchingInvalid";
} else if (code === '204' && type === 'none') {
return "ResponsesScenarioE204MatchingNoModel";
} else if (code === '400' && type === 'none') {
return "ResponsesScenarioE400DefaultNoModel";
} else if (code === '400' && type === 'invalid') {
return "ResponsesScenarioE400DefaultInvalid";
} else {
return null;
}
} else if (scenario ==='F') {
if (code === '200' && type === 'valid') {
return "ResponsesScenarioF200DefaultModel";
} else if (code === '200' && type === 'none') {
return "ResponsesScenarioF200DefaultNone";
} else if (code === '400' && type === 'valid') {
return "ResponsesScenarioF400DefaultModel";
} else if (code === '400' && type === 'none') {
return "ResponsesScenarioF400DefaultNone";
} else {
return null;
}
} else if (scenario ==='G') {
if (code === '200' && type === 'invalid') {
return "ResponsesScenarioG200DefaultInvalid";
} else if (code === '200' && type === 'none') {
return "ResponsesScenarioG200DefaultNoModel";
} else if (code === '400' && type === 'invalid') {
return "ResponsesScenarioG400DefaultInvalid";
} else if (code === '400' && type === 'none') {
return "ResponsesScenarioG400DefaultNoModel";
} else {
return null;
}
} else if (scenario ==='H') {
if (code === '200' && type === 'none') {
return "ResponsesScenarioH200MatchingNone";
} else if (code === '200' && type === 'valid') {
return "ResponsesScenarioH200MatchingModel";
} if (code === '200' && type === 'invalid') {
return "ResponsesScenarioH200MatchingInvalid";
} else if (code === '400' && type === 'none') {
return "ResponsesScenarioH400NonMatchingNone";
} else if (code === '400' && type === 'valid') {
return "ResponsesScenarioH400NonMatchingModel";
} else if (code === '400' && type === 'invalid') {
return "ResponsesScenarioH400NonMatchingInvalid";
} else if (code === '202' && type === 'valid') {
return "ResponsesScenarioH202NonMatchingModel";
} else {
return null;
}
} else {
return null;
}
};
var httpResponses = function(coverage, optionalCoverage) {
coverage['HttpSuccess200Head'] = 0;
coverage['HttpSuccess200Get'] = 0;
optionalCoverage['HttpSuccess200Options'] = 0;
coverage['HttpSuccess200Put'] = 0;
coverage['HttpSuccess200Post'] = 0;
coverage['HttpSuccess200Patch'] = 0;
coverage['HttpSuccess200Delete'] = 0;
coverage['HttpSuccess201Put'] = 0;
coverage['HttpSuccess201Post'] = 0;
coverage['HttpSuccess202Put'] = 0;
coverage['HttpSuccess202Post'] = 0;
coverage['HttpSuccess202Patch'] = 0;
coverage['HttpSuccess202Delete'] = 0;
coverage['HttpSuccess204Head'] = 0;
coverage['HttpSuccess404Head'] = 0;
coverage['HttpSuccess204Put'] = 0;
coverage['HttpSuccess204Post'] = 0;
coverage['HttpSuccess204Patch'] = 0;
coverage['HttpSuccess204Delete'] = 0;
coverage['HttpRedirect300Head'] = 0;
coverage['HttpRedirect300Get'] = 0;
coverage['HttpRedirect300Head'] = 0;
coverage['HttpRedirect301Put'] = 0;
coverage['HttpRedirect301Get'] = 0;
coverage['HttpRedirect302Head'] = 0;
coverage['HttpRedirect302Get'] = 0;
coverage['HttpRedirect302Patch'] = 0;
coverage['HttpRedirect303Post'] = 0;
coverage['HttpRedirect307Head'] = 0;
coverage['HttpRedirect307Get'] = 0;
optionalCoverage['HttpRedirect307Options'] = 0;
coverage['HttpRedirect307Put'] = 0;
coverage['HttpRedirect307Post'] = 0;
coverage['HttpRedirect307Patch'] = 0;
coverage['HttpRedirect307Delete'] = 0;
coverage['HttpRetry408Head'] = 0;
coverage['HttpRetry500Put'] = 0;
coverage['HttpRetry500Patch'] = 0;
optionalCoverage['HttpRetry502Options'] = 0;
coverage['HttpRetry502Get'] = 0;
coverage['HttpRetry503Post'] = 0;
coverage['HttpRetry503Delete'] = 0;
coverage['HttpRetry504Put'] = 0;
coverage['HttpRetry504Patch'] = 0;
coverage['HttpClientFailure400Head'] = 0;
coverage['HttpClientFailure400Get'] = 0;
optionalCoverage['HttpClientFailure400Options'] = 0;
coverage['HttpClientFailure400Put'] = 0;
coverage['HttpClientFailure400Post'] = 0;
coverage['HttpClientFailure400Patch'] = 0;
coverage['HttpClientFailure400Delete'] = 0;
coverage['HttpClientFailure401Head'] = 0;
coverage['HttpClientFailure402Get'] = 0;
coverage['HttpClientFailure403Get'] = 0;
optionalCoverage['HttpClientFailure403Options'] = 0;
coverage['HttpClientFailure404Put'] = 0;
coverage['HttpClientFailure405Patch'] = 0;
coverage['HttpClientFailure406Post'] = 0;
coverage['HttpClientFailure407Delete'] = 0;
coverage['HttpClientFailure409Put'] = 0;
coverage['HttpClientFailure410Head'] = 0;
coverage['HttpClientFailure411Get'] = 0;
coverage['HttpClientFailure412Get'] = 0;
optionalCoverage['HttpClientFailure412Options'] = 0;
coverage['HttpClientFailure413Put'] = 0;
coverage['HttpClientFailure414Patch'] = 0;
coverage['HttpClientFailure415Post'] = 0;
coverage['HttpClientFailure416Get'] = 0;
coverage['HttpClientFailure417Delete'] = 0;
coverage['HttpClientFailure429Head'] = 0;
coverage['HttpServerFailure501Head'] = 0;
coverage['HttpServerFailure501Get'] = 0;
coverage['HttpServerFailure505Post'] = 0;
coverage['HttpServerFailure505Delete'] = 0;
coverage['ResponsesScenarioA200MatchingModel'] = 0;
coverage['ResponsesScenarioA204MatchingNoModel'] = 0;
coverage['ResponsesScenarioA201DefaultNoModel'] = 0;
coverage['ResponsesScenarioA202DefaultNoModel'] = 0;
coverage['ResponsesScenarioA400DefaultModel'] = 0;
coverage['ResponsesScenarioB200MatchingModel'] = 0;
coverage['ResponsesScenarioB201MatchingModel'] = 0;
coverage['ResponsesScenarioB400DefaultModel'] = 0;
coverage['ResponsesScenarioC200MatchingModel'] = 0;
coverage['ResponsesScenarioC201MatchingModel'] = 0;
coverage['ResponsesScenarioC404MatchingModel'] = 0;
coverage['ResponsesScenarioC400DefaultModel'] = 0;
coverage['ResponsesScenarioD202MatchingNoModel'] = 0;
coverage['ResponsesScenarioD204MatchingNoModel'] = 0;
coverage['ResponsesScenarioD400DefaultModel'] = 0;
coverage['ResponsesScenarioE202MatchingInvalid'] = 0;
coverage['ResponsesScenarioE204MatchingNoModel'] = 0;
coverage['ResponsesScenarioE400DefaultNoModel'] = 0;
coverage['ResponsesScenarioE400DefaultInvalid'] = 0;
coverage['ResponsesScenarioF200DefaultModel'] = 0;
coverage['ResponsesScenarioF200DefaultNone'] = 0;
coverage['ResponsesScenarioF400DefaultModel'] = 0;
coverage['ResponsesScenarioF400DefaultNone'] = 0;
coverage['ResponsesScenarioG200DefaultInvalid'] = 0;
coverage['ResponsesScenarioG200DefaultNoModel'] = 0;
coverage['ResponsesScenarioG400DefaultInvalid'] = 0;
coverage['ResponsesScenarioG400DefaultNoModel'] = 0;
coverage['ResponsesScenarioH200MatchingNone'] = 0;
coverage['ResponsesScenarioH200MatchingModel'] = 0;
coverage['ResponsesScenarioH200MatchingInvalid'] = 0;
coverage['ResponsesScenarioH400NonMatchingNone'] = 0;
coverage['ResponsesScenarioH400NonMatchingModel'] = 0;
coverage['ResponsesScenarioH400NonMatchingInvalid'] = 0;
coverage['ResponsesScenarioH202NonMatchingModel'] = 0;
coverage['ResponsesScenarioEmptyErrorBody'] = 0;
var updateScenarioCoverage = function(scenario, method) {
if (method.toLowerCase() === 'options') {
optionalCoverage[scenario]++
} else {
coverage[scenario]++;
}
};
router.all('/success/:code', function(req, res, next) {
var scenario = getHttpScenarioName("Success", req.method, req.params.code);
var code = JSON.parse(req.params.code);
if (scenario !== null) {
updateScenarioCoverage(scenario, req.method);
if (req.method === 'GET' || req.method === 'OPTIONS') {
res.status(code).end('true');
} else {
res.status(code).end();
}
}
else {
utils.send400(res, next, 'Unable to parse success scenario with return code "' + req.params.code + '"');
}
});
router.all('/success/:method/:code', function(req, res, next) {
res = removeRetryTracker(res);
if (req.method.toLowerCase() === req.params.method) {
res.status(JSON.parse(req.params.code)).end();
} else {
utils.send400(res, next, 'Unable to parse redirection, expected method "' + req.params.method + '" did not match actual method "' + req.method.toLowerCase() + '"');
}
});
router.all('/failure/:code', function(req, res, next) {
utils.send400(res, next, 'Client incorrectly redirected a request');
});
router.all('/failure/emptybody/error', function(req, res, next) {
coverage['ResponsesScenarioEmptyErrorBody']++;
utils.send400(res, next, '');
});
router.all('/redirect/:code', function(req, res, next) {
var scenario = getHttpScenarioName("Redirect", req.method, req.params.code);
if (scenario !== null) {
updateScenarioCoverage(scenario, req.method);
status = (JSON.parse(req.params.code));
if ((req.params.code === '301' || req.params.code === '302') && req.method !== 'HEAD' && req.method !== 'GET') {
res.append('Location', '/http/failure/500');
} else if (req.params.code === '303') {
res.append('Location', '/http/success/get/200');
} else {
res.append('Location', '/http/success/' + req.method.toLowerCase() + '/200');
}
if (req.method === 'GET' && req.params.code === '300') {
res.status(status).end('["/http/success/get/200"]');
} else {
res.status(status).end();
}
}
else {
utils.send400(res, next, 'Unable to parse redirection scenario with return code "' + req.params.code + '"');
}
});
router.all('/failure/:type/:code', function(req, res, next) {
var scenario = getHttpScenarioName("Failure", req.method, req.params.code);
if (scenario !== null) {
updateScenarioCoverage(scenario, req.method);
res.status(JSON.parse(req.params.code)).end();
}
else {
utils.send400(res, next, 'Unable to parse failure scenario with return code "' + req.params.code + '"');
}
});
router.all('/retry/:code', function( req, res, next) {
var scenario = getHttpScenarioName("Retry", req.method, req.params.code);
var code = JSON.parse(req.params.code);
if (scenario !== null) {
if (isRetryRequest(req, code, req.method.toLowerCase())) {
updateScenarioCoverage(scenario, req.method);
removeRetryTracker(res).status(200).end();
} else {
utils.sendError(code, addRetryTracker(res, code, req.method.toLowerCase()), next, "Retry scenario initial request");
}
}
else {
utils.send400(res, next, 'Unable to parse retry scenario with return code "' + req.params.code + '"');
}
});
router.get('/payloads/200/A/204/none/default/Error/response/:code/:type', function( req, res, next) {
var code = JSON.parse(req.params.code);
var scenario = getMultipleResponseScenarioName("A", req.params.code, req.params.type);
if (scenario !== null) {
coverage[scenario]++;
if (req.params.type === 'valid') {
if (code === 200 || code === 201) {
res.status(code).end('{ "statusCode": "' + code + '" }');
} else {
utils.sendError(400, res, next, 'client error');
}
} else if (req.params.type === 'none') {
res.status(code).end();
} else if (req.params.type === 'invalid') {
res.status(code).end();
} else {
utils.send400(res, next, 'Unable to parse multiple response scenario with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
}
else {
utils.send400(res, next, 'Unable to parse multiple response scenario A (One success response with model, one success response with no model, default error model) with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
});
router.get('/payloads/200/A/201/B/default/Error/response/:code/:type', function( req, res, next) {
var code = JSON.parse(req.params.code);
var scenario = getMultipleResponseScenarioName("B", req.params.code, req.params.type);
if (scenario !== null) {
coverage[scenario]++;
if (req.params.type === 'valid') {
if (code === 200 ) {
res.status(200).end('{ "statusCode": "200" }');
} else if (code === 201) {
res.status(201).end('{ "statusCode": "201" , "textStatusCode": "Created" }');
} else {
utils.send400(res, next, 'client error');
}
} else {
utils.send400(res, next, 'Unable to parse multiple response scenario B with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
}
else {
utils.send400(res, next, 'Unable to parse multiple response scenario B (Two success responses with common base model, default error response with model) with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
});
router.get('/payloads/200/A/201/C/404/D/default/Error/response/:code/:type', function( req, res, next) {
var code = JSON.parse(req.params.code);
var scenario = getMultipleResponseScenarioName("C", req.params.code, req.params.type);
if (scenario !== null) {
coverage[scenario]++;
if (req.params.type === 'valid') {
if (code === 200 ) {
res.status(200).end('{ "statusCode": "200" }');
} else if (code === 201) {
res.status(201).end('{ "httpCode": "201" }');
} else if (code === 404) {
res.status(404).end('{ "httpStatusCode": "404" }');
} else {
utils.send400(res, next, 'client error');
}
} else {
utils.send400(res, next, 'Unable to parse type "' + req.params.type + '" in response scenario C');
}
}
else {
utils.send400(res, next, 'Unable to parse multiple response scenario C (Three success responses with models with no common base type, default error response with model) with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
});
router.get('/payloads/202/none/204/none/default/Error/response/:code/:type', function( req, res, next) {
var code = JSON.parse(req.params.code);
var scenario = getMultipleResponseScenarioName("D", req.params.code, req.params.type);
if (scenario !== null) {
coverage[scenario]++;
if (req.params.type === 'none') {
res.status(code).end();
} else {
utils.send400(res, next, 'client error');
}
}
else {
utils.send400(res, next, 'Unable to parse multiple response scenario D (Two success responses with no model and one default response with no model) with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
});
router.get('/payloads/202/none/204/none/default/none/response/:code/:type', function( req, res, next) {
var code = JSON.parse(req.params.code);
var scenario = getMultipleResponseScenarioName("E", req.params.code, req.params.type);
if (scenario !== null) {
coverage[scenario]++;
if (req.params.type === 'none') {
res.status(code).end();
} else if (req.params.type === 'invalid') {
res.status(code).end('{ "property": "value" }');
} else {
utils.send400(res, next, 'Unable to parse type "' + req.params.type + '" in response scenario E');
}
}
else {
utils.send400(res, next, 'Unable to parse multiple response scenario E (Two success responses with no model and one default response with no model) with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
});
router.get('/payloads/default/A/response/:code/:type', function( req, res, next) {
var code = JSON.parse(req.params.code);
var scenario = getMultipleResponseScenarioName("F", req.params.code, req.params.type);
if (scenario !== null) {
coverage[scenario]++;
if (req.params.type === 'none') {
res.status(code).end();
} else if (req.params.type === 'valid') {
res.status(code).end('{ "statusCode": "' + code + '" }');
} else {
utils.send400(res, next, 'Unable to parse type "' + req.params.type + '" in response scenario F');
}
}
else {
utils.send400(res, next, 'Unable to parse multiple response scenario F (One default response with model) with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
});
router.get('/payloads/default/none/response/:code/:type', function( req, res, next) {
var code = JSON.parse(req.params.code);
var scenario = getMultipleResponseScenarioName("G", req.params.code, req.params.type);
if (scenario !== null) {
coverage[scenario]++;
if (req.params.type === 'none') {
res.status(code).end();
} else if (req.params.type === 'invalid') {
res.status(code).end('{ "statusCode": "' + code + '" }');
} else {
utils.send400(res, next, 'Unable to parse type "' + req.params.type + '" in response scenario F');
}
}
else {
utils.send400(res, next, 'Unable to parse multiple response scenario G (One default response with no model) with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
});
router.get('/payloads/200/A/response/:code/:type', function( req, res, next) {
var code = JSON.parse(req.params.code);
var scenario = getMultipleResponseScenarioName("H", req.params.code, req.params.type);
if (scenario !== null) {
coverage[scenario]++;
if (req.params.type === 'none') {
res.status(code).end();
} else if (req.params.type === 'valid') {
res.status(code).end('{ "statusCode": "' + code + '" }');
} else if (req.params.type === 'invalid') {
res.status(code).end('{ "statusCodeInvalid": "' + code + '" }');
} else {
utils.send400(res, next, 'Unable to parse type "' + req.params.type + '" in response scenario F');
}
}
else {
utils.send400(res, next, 'Unable to parse multiple response scenario H (One success response with model) with return code "' + req.params.code +
'" and type "' + req.params.type + '"');
}
});}
httpResponses.prototype.router = router;
module.exports = httpResponses;
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var he = require('he');
/* */
/**
* Convert a value to a string that is actually rendered.
*/
function _toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val, 10);
return (n || n === 0) ? n : val
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Remove an item from an array
*/
function remove (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
}
}
/**
* Camelize a hyphen-delmited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /([^-])([A-Z])/g;
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
});
/**
* Simple bind, faster than native
*/
function bind (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length;
return boundFn
}
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
var toString = Object.prototype.toString;
var OBJECT_STRING = '[object Object]';
function isPlainObject (obj) {
return toString.call(obj) === OBJECT_STRING
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; };
/**
* Generate a static keys string from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
/* eslint-disable eqeqeq */
return a == b || (
isObject(a) && isObject(b)
? JSON.stringify(a) === JSON.stringify(b)
: false
)
/* eslint-enable eqeqeq */
}
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/* */
var config = {
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: null,
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* List of asset types that a component can own.
*/
_assetTypes: [
'component',
'directive',
'filter'
],
/**
* List of lifecycle hooks.
*/
_lifecycleHooks: [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
],
/**
* Max circular updates allowed in a scheduler flush cycle.
*/
_maxUpdateCount: 100
};
var warn = noop;
var formatComponentName;
if (process.env.NODE_ENV !== 'production') {
var hasConsole = typeof console !== 'undefined';
warn = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + " " + (
vm ? formatLocation(formatComponentName(vm)) : ''
));
}
};
formatComponentName = function (vm) {
if (vm.$root === vm) {
return 'root instance'
}
var name = vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
return (
(name ? ("component <" + name + ">") : "anonymous component") +
(vm._isVue && vm.$options.__file ? (" at " + (vm.$options.__file)) : '')
)
};
var formatLocation = function (str) {
if (str === 'anonymous component') {
str += " - use the \"name\" option for better debugging messages.";
}
return ("\n(found in " + str + ")")
};
}
/* */
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
var bailRE = /[^\w.$]/;
function parsePath (path) {
if (bailRE.test(path)) {
return
} else {
var segments = path.split('.');
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = UA && UA.indexOf('android') > 0;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
var _isServer;
var isServerRendering = function () {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return /native code/.test(Ctor.toString())
}
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// the nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop); }
};
} else if (typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (cb, ctx) {
var _resolve;
callbacks.push(function () {
if (cb) { cb.call(ctx); }
if (_resolve) { _resolve(ctx); }
});
if (!pending) {
pending = true;
timerFunc();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = (function () {
function Set () {
this.set = Object.create(null);
}
Set.prototype.has = function has (key) {
return this.set[key] !== undefined
};
Set.prototype.add = function add (key) {
this.set[key] = 1;
};
Set.prototype.clear = function clear () {
this.set = Object.create(null);
};
return Set;
}());
}
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
if (process.env.NODE_ENV !== 'production') {
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
var warnNonPresent = function (target, key) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
"referenced during render. Make sure to declare reactive data " +
"properties in the data option.",
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
var hasHandler = {
has: function has (target, key) {
var has = key in target;
var isAllowed = allowedGlobals(key) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warnNonPresent(target, key);
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key);
}
return target[key]
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
var handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
var uid$2 = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid$2++;
this.subs = [];
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
};
Dep.prototype.removeSub = function removeSub (sub) {
remove(this.subs, sub);
};
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this);
}
};
Dep.prototype.notify = function notify () {
// stablize the subscriber list first
var subs = this.subs.slice();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
var targetStack = [];
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target); }
Dep.target = _target;
}
function popTarget () {
Dep.target = targetStack.pop();
}
/* */
var queue = [];
var has$1 = {};
var circular = {};
var waiting = false;
var flushing = false;
var index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
queue.length = 0;
has$1 = {};
if (process.env.NODE_ENV !== 'production') {
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; });
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
var watcher = queue[index];
var id = watcher.id;
has$1[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has$1[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > config._maxUpdateCount) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
);
break
}
}
}
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
resetSchedulerState();
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id;
if (has$1[id] == null) {
has$1[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i >= 0 && queue[i].id > watcher.id) {
i--;
}
queue.splice(Math.max(i, index) + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
nextTick(flushSchedulerQueue);
}
}
}
/* */
var uid$1 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options
) {
if ( options === void 0 ) options = {};
this.vm = vm;
vm._watchers.push(this);
// options
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
this.expression = expOrFn.toString();
this.cb = cb;
this.id = ++uid$1; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = function () {};
process.env.NODE_ENV !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this);
var value = this.getter.call(this.vm, this.vm);
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
var tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, this.vm);
} else {
process.env.NODE_ENV !== 'production' && warn(
("Error in watcher \"" + (this.expression) + "\""),
this.vm
);
throw e
}
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get();
this.dirty = false;
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed or is performing a v-for
// re-render (the watcher list is then filtered by v-for).
if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) {
remove(this.vm._watchers, this);
}
var i = this.deps.length;
while (i--) {
this$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
return
}
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) { _traverse(val[i], seen); }
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) { _traverse(val[keys[i]], seen); }
}
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
var i = arguments.length;
var args = new Array(i);
while (i--) {
args[i] = arguments$1[i];
}
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
inserted = args;
break
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) { ob.observeArray(inserted); }
// notify change
ob.dep.notify();
return result
});
});
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i], obj[keys[i]]);
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
};
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*
* istanbul ignore next
*/
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value) {
if (!isObject(value)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value);
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
var childOb = observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
}
if (Array.isArray(value)) {
dependArray(value);
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter();
}
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (obj, key, val) {
if (Array.isArray(obj)) {
obj.length = Math.max(obj.length, key);
obj.splice(key, 1, val);
return val
}
if (hasOwn(obj, key)) {
obj[key] = val;
return
}
var ob = obj.__ob__;
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return
}
if (!ob) {
obj[key] = val;
return
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (obj, key) {
var ob = obj.__ob__;
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(obj, key)) {
return
}
delete obj[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (var e = (void 0), i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
function initState (vm) {
vm._watchers = [];
initProps(vm);
initMethods(vm);
initData(vm);
initComputed(vm);
initWatch(vm);
}
var isReservedProp = makeMap('key,ref,slot');
function initProps (vm) {
var props = vm.$options.props;
if (props) {
var propsData = vm.$options.propsData || {};
var keys = vm.$options._propKeys = Object.keys(props);
var isRoot = !vm.$parent;
// root instance props should be converted
observerState.shouldConvert = isRoot;
var loop = function ( i ) {
var key = keys[i];
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
if (isReservedProp(key)) {
warn(
("\"" + key + "\" is a reserved attribute and cannot be used as component prop."),
vm
);
}
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm), function () {
if (vm.$parent && !observerState.isSettingProps) {
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
);
}
});
} else {
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm));
}
};
for (var i = 0; i < keys.length; i++) loop( i );
observerState.shouldConvert = true;
}
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? data.call(vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object.',
vm
);
}
// proxy data on instance
var keys = Object.keys(data);
var props = vm.$options.props;
var i = keys.length;
while (i--) {
if (props && hasOwn(props, keys[i])) {
process.env.NODE_ENV !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else {
proxy(vm, keys[i]);
}
}
// observe data
observe(data);
data.__ob__ && data.__ob__.vmCount++;
}
var computedSharedDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function initComputed (vm) {
var computed = vm.$options.computed;
if (computed) {
for (var key in computed) {
var userDef = computed[key];
if (typeof userDef === 'function') {
computedSharedDefinition.get = makeComputedGetter(userDef, vm);
computedSharedDefinition.set = noop;
} else {
computedSharedDefinition.get = userDef.get
? userDef.cache !== false
? makeComputedGetter(userDef.get, vm)
: bind(userDef.get, vm)
: noop;
computedSharedDefinition.set = userDef.set
? bind(userDef.set, vm)
: noop;
}
Object.defineProperty(vm, key, computedSharedDefinition);
}
}
}
function makeComputedGetter (getter, owner) {
var watcher = new Watcher(owner, getter, noop, {
lazy: true
});
return function computedGetter () {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.target) {
watcher.depend();
}
return watcher.value
}
}
function initMethods (vm) {
var methods = vm.$options.methods;
if (methods) {
for (var key in methods) {
vm[key] = methods[key] == null ? noop : bind(methods[key], vm);
if (process.env.NODE_ENV !== 'production' && methods[key] == null) {
warn(
"method \"" + key + "\" has an undefined value in the component definition. " +
"Did you reference the function correctly?",
vm
);
}
}
}
}
function initWatch (vm) {
var watch = vm.$options.watch;
if (watch) {
for (var key in watch) {
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
}
function createWatcher (vm, key, handler) {
var options;
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
vm.$watch(key, handler, options);
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {};
dataDef.get = function () {
return this._data
};
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Vue.prototype.$set = set;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this;
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
cb.call(vm, watcher.value);
}
return function unwatchFn () {
watcher.teardown();
}
};
}
function proxy (vm, key) {
if (!isReserved(key)) {
Object.defineProperty(vm, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return vm._data[key]
},
set: function proxySetter (val) {
vm._data[key] = val;
}
});
}
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
ns,
context,
componentOptions
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = ns;
this.context = context;
this.functionalContext = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.child = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
};
var emptyVNode = function () {
var node = new VNode();
node.text = '';
node.isComment = true;
return node
};
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.ns,
vnode.context,
vnode.componentOptions
);
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isCloned = true;
return cloned
}
function cloneVNodes (vnodes) {
var res = new Array(vnodes.length);
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneVNode(vnodes[i]);
}
return res
}
/* */
/* */
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, fn, event, capture;
for (name in on) {
cur = on[name];
old = oldOn[name];
if (!cur) {
process.env.NODE_ENV !== 'production' && warn(
"Invalid handler for event \"" + name + "\": got " + String(cur),
vm
);
} else if (!old) {
capture = name.charAt(0) === '!';
event = capture ? name.slice(1) : name;
if (Array.isArray(cur)) {
add(event, (cur.invoker = arrInvoker(cur)), capture);
} else {
if (!cur.invoker) {
fn = cur;
cur = on[name] = {};
cur.fn = fn;
cur.invoker = fnInvoker(cur);
}
add(event, cur.invoker, capture);
}
} else if (cur !== old) {
if (Array.isArray(old)) {
old.length = cur.length;
for (var i = 0; i < old.length; i++) { old[i] = cur[i]; }
on[name] = old;
} else {
old.fn = cur;
on[name] = old;
}
}
}
for (name in oldOn) {
if (!on[name]) {
event = name.charAt(0) === '!' ? name.slice(1) : name;
remove$$1(event, oldOn[name].invoker);
}
}
}
function arrInvoker (arr) {
return function (ev) {
var arguments$1 = arguments;
var single = arguments.length === 1;
for (var i = 0; i < arr.length; i++) {
single ? arr[i](ev) : arr[i].apply(null, arguments$1);
}
}
}
function fnInvoker (o) {
return function (ev) {
var single = arguments.length === 1;
single ? o.fn(ev) : o.fn.apply(null, arguments);
}
}
/* */
function normalizeChildren (
children,
ns,
nestedIndex
) {
if (isPrimitive(children)) {
return [createTextVNode(children)]
}
if (Array.isArray(children)) {
var res = [];
for (var i = 0, l = children.length; i < l; i++) {
var c = children[i];
var last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeChildren(c, ns, ((nestedIndex || '') + "_" + i)));
} else if (isPrimitive(c)) {
if (last && last.text) {
last.text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else if (c instanceof VNode) {
if (c.text && last && last.text) {
if (!last.isCloned) {
last.text += c.text;
}
} else {
// inherit parent namespace
if (ns) {
applyNS(c, ns);
}
// default key for nested array children (likely generated by v-for)
if (c.tag && c.key == null && nestedIndex != null) {
c.key = "__vlist" + nestedIndex + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
}
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
function applyNS (vnode, ns) {
if (vnode.tag && !vnode.ns) {
vnode.ns = ns;
if (vnode.children) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
applyNS(vnode.children[i], ns);
}
}
}
}
/* */
/* */
var activeInstance = null;
function initLifecycle (vm) {
var options = vm.$options;
// locate first non-abstract parent
var parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._mount = function (
el,
hydrating
) {
var vm = this;
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = emptyVNode;
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if (vm.$options.template && vm.$options.template.charAt(0) !== '#') {
warn(
'You are using the runtime-only build of Vue where the template ' +
'option is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
callHook(vm, 'beforeMount');
vm._watcher = new Watcher(vm, function () {
vm._update(vm._render(), hydrating);
}, noop);
hydrating = false;
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true;
callHook(vm, 'mounted');
}
return vm
};
Vue.prototype._update = function (vnode, hydrating) {
var vm = this;
if (vm._isMounted) {
callHook(vm, 'beforeUpdate');
}
var prevEl = vm.$el;
var prevVnode = vm._vnode;
var prevActiveInstance = activeInstance;
activeInstance = vm;
vm._vnode = vnode;
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(
vm.$el, vnode, hydrating, false /* removeOnly */,
vm.$options._parentElm,
vm.$options._refElm
);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
activeInstance = prevActiveInstance;
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
if (vm._isMounted) {
callHook(vm, 'updated');
}
};
Vue.prototype._updateFromParent = function (
propsData,
listeners,
parentVnode,
renderChildren
) {
var vm = this;
var hasChildren = !!(vm.$options._renderChildren || renderChildren);
vm.$options._parentVnode = parentVnode;
vm.$vnode = parentVnode; // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode;
}
vm.$options._renderChildren = renderChildren;
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = true;
}
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
vm[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = false;
}
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
vm._updateListeners(listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
};
Vue.prototype.$forceUpdate = function () {
var vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
var vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
var parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
var i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
};
}
function callHook (vm, hook) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
handlers[i].call(vm);
}
}
vm.$emit('hook:' + hook);
}
/* */
var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy };
var hooksToMerge = Object.keys(hooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (!Ctor) {
return
}
var baseCtor = context.$options._base;
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
if (typeof Ctor !== 'function') {
if (process.env.NODE_ENV !== 'production') {
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
if (!Ctor.cid) {
if (Ctor.resolved) {
Ctor = Ctor.resolved;
} else {
Ctor = resolveAsyncComponent(Ctor, baseCtor, function () {
// it's ok to queue this on every render because
// $forceUpdate is buffered by the scheduler.
context.$forceUpdate();
});
if (!Ctor) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
return
}
}
}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
data = data || {};
// extract props
var propsData = extractProps(data, Ctor);
// functional component
if (Ctor.options.functional) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
// replace with listeners with .native modifier
data.on = data.nativeOn;
if (Ctor.options.abstract) {
// abstract components do not keep anything
// other than props & listeners
data = {};
}
// merge component management hooks onto the placeholder node
mergeHooks(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
);
return vnode
}
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (propOptions) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData);
}
}
var vnode = Ctor.options.render.call(
null,
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
bind(createElement, { _self: Object.create(context) }),
{
props: props,
data: data,
parent: context,
children: normalizeChildren(children),
slots: function () { return resolveSlots(children, context); }
}
);
if (vnode instanceof VNode) {
vnode.functionalContext = context;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent, // activeInstance in lifecycle state
parentElm,
refElm
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children,
_parentElm: parentElm || null,
_refElm: refElm || null
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (inlineTemplate) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function init (
vnode,
hydrating,
parentElm,
refElm
) {
if (!vnode.child || vnode.child._isDestroyed) {
var child = vnode.child = createComponentInstanceForVnode(
vnode,
activeInstance,
parentElm,
refElm
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
} else if (vnode.data.keepAlive) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
prepatch(mountedNode, mountedNode);
return true // let the patcher know this is a reactivated component
}
}
function prepatch (
oldVnode,
vnode
) {
var options = vnode.componentOptions;
var child = vnode.child = oldVnode.child;
child._updateFromParent(
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
}
function insert (vnode) {
if (!vnode.child._isMounted) {
vnode.child._isMounted = true;
callHook(vnode.child, 'mounted');
}
if (vnode.data.keepAlive) {
vnode.child._inactive = false;
callHook(vnode.child, 'activated');
}
}
function destroy (vnode) {
if (!vnode.child._isDestroyed) {
if (!vnode.data.keepAlive) {
vnode.child.$destroy();
} else {
vnode.child._inactive = true;
callHook(vnode.child, 'deactivated');
}
}
}
function resolveAsyncComponent (
factory,
baseCtor,
cb
) {
if (factory.requested) {
// pool callbacks
factory.pendingCallbacks.push(cb);
} else {
factory.requested = true;
var cbs = factory.pendingCallbacks = [cb];
var sync = true;
var resolve = function (res) {
if (isObject(res)) {
res = baseCtor.extend(res);
}
// cache resolved
factory.resolved = res;
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i](res);
}
}
};
var reject = function (reason) {
process.env.NODE_ENV !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
};
var res = factory(resolve, reject);
// handle promise
if (res && typeof res.then === 'function' && !factory.resolved) {
res.then(resolve, reject);
}
sync = false;
// return in case resolved synchronously
return factory.resolved
}
}
function extractProps (data, Ctor) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (!propOptions) {
return
}
var res = {};
var attrs = data.attrs;
var props = data.props;
var domProps = data.domProps;
if (attrs || props || domProps) {
for (var key in propOptions) {
var altKey = hyphenate(key);
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey) ||
checkProp(res, domProps, key, altKey);
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (hash) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = hooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (a, b) {
// since all hooks have at most two args, use fixed args
// to avoid having to use fn.apply().
return function (_, __) {
a(_, __);
b(_, __);
}
}
/* */
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
tag,
data,
children
) {
if (data && (Array.isArray(data) || typeof data !== 'object')) {
children = data;
data = undefined;
}
// make sure to use real instance instead of proxy as context
return _createElement(this._self, tag, data, children)
}
function _createElement (
context,
tag,
data,
children
) {
if (data && data.__ob__) {
process.env.NODE_ENV !== 'production' && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return
}
if (!tag) {
// in case of component :is set to falsy value
return emptyVNode()
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function') {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
if (typeof tag === 'string') {
var Ctor;
var ns = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
return new VNode(
tag, data, normalizeChildren(children, ns),
undefined, undefined, ns, context
)
} else if ((Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
return createComponent(Ctor, data, context, children, tag)
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
var childNs = tag === 'foreignObject' ? 'xhtml' : ns;
return new VNode(
tag, data, normalizeChildren(children, childNs),
undefined, undefined, ns, context
)
}
} else {
// direct component options / constructor
return createComponent(tag, data, context, children)
}
}
/* */
function initRender (vm) {
vm.$vnode = null; // the placeholder node in parent tree
vm._vnode = null; // the root of the child tree
vm._staticTrees = null;
var parentVnode = vm.$options._parentVnode;
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext);
vm.$scopedSlots = {};
// bind the public createElement fn to this instance
// so that we get proper render context inside it.
vm.$createElement = bind(createElement, vm);
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
}
function renderMixin (Vue) {
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (vm._isMounted) {
// clone slot nodes on re-renders
for (var key in vm.$slots) {
vm.$slots[key] = cloneVNodes(vm.$slots[key]);
}
}
if (_parentVnode && _parentVnode.data.scopedSlots) {
vm.$scopedSlots = _parentVnode.data.scopedSlots;
}
if (staticRenderFns && !vm._staticTrees) {
vm._staticTrees = [];
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, vm);
} else {
if (process.env.NODE_ENV !== 'production') {
warn(("Error when rendering " + (formatComponentName(vm)) + ":"));
}
throw e
}
// return previous vnode to prevent render error causing blank component
vnode = vm._vnode;
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = emptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
// shorthands used in render functions
Vue.prototype._h = createElement;
// toString for mustaches
Vue.prototype._s = _toString;
// number conversion
Vue.prototype._n = toNumber;
// empty vnode
Vue.prototype._e = emptyVNode;
// loose equal
Vue.prototype._q = looseEqual;
// loose indexOf
Vue.prototype._i = looseIndexOf;
// render static tree by index
Vue.prototype._m = function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree by doing a shallow clone.
if (tree && !isInFor) {
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
}
// otherwise, render a fresh tree.
tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy);
markStatic(tree, ("__static__" + index), false);
return tree
};
// mark node as static (v-once)
Vue.prototype._o = function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
};
function markStatic (tree, key, isOnce) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
// filter resolution helper
var identity = function (_) { return _; };
Vue.prototype._f = function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
};
// render v-for
Vue.prototype._l = function renderList (
val,
render
) {
var ret, i, l, keys, key;
if (Array.isArray(val)) {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
return ret
};
// renderSlot
Vue.prototype._t = function (
name,
fallback,
props
) {
var scopedSlotFn = this.$scopedSlots[name];
if (scopedSlotFn) { // scoped slot
return scopedSlotFn(props || {}) || fallback
} else {
var slotNodes = this.$slots[name];
// warn duplicate slot usage
if (slotNodes && process.env.NODE_ENV !== 'production') {
slotNodes._rendered && warn(
"Duplicate presence of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
);
slotNodes._rendered = true;
}
return slotNodes || fallback
}
};
// apply v-bind object
Vue.prototype._b = function bindProps (
data,
tag,
value,
asProp
) {
if (value) {
if (!isObject(value)) {
process.env.NODE_ENV !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
for (var key in value) {
if (key === 'class' || key === 'style') {
data[key] = value[key];
} else {
var hash = asProp || config.mustUseProp(tag, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
hash[key] = value[key];
}
}
}
}
return data
};
// expose v-on keyCodes
Vue.prototype._k = function getKeyCodes (key) {
return config.keyCodes[key]
};
}
function resolveSlots (
renderChildren,
context
) {
var slots = {};
if (!renderChildren) {
return slots
}
var children = normalizeChildren(renderChildren) || [];
var defaultSlot = [];
var name, child;
for (var i = 0, l = children.length; i < l; i++) {
child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && (name = child.data.slot)) {
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore single whitespace
if (defaultSlot.length && !(
defaultSlot.length === 1 &&
(defaultSlot[0].text === ' ' || defaultSlot[0].isComment)
)) {
slots.default = defaultSlot;
}
return slots
}
/* */
function initEvents (vm) {
vm._events = Object.create(null);
// init parent attached events
var listeners = vm.$options._parentListeners;
var on = bind(vm.$on, vm);
var off = bind(vm.$off, vm);
vm._updateListeners = function (listeners, oldListeners) {
updateListeners(listeners, oldListeners || {}, on, off, vm);
};
if (listeners) {
vm._updateListeners(listeners);
}
}
function eventsMixin (Vue) {
Vue.prototype.$on = function (event, fn) {
var vm = this;(vm._events[event] || (vm._events[event] = [])).push(fn);
return vm
};
Vue.prototype.$once = function (event, fn) {
var vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
var vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (arguments.length === 1) {
vm._events[event] = null;
return vm
}
// specific handler
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
var vm = this;
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
var args = toArray(arguments, 1);
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args);
}
}
return vm
};
}
/* */
var uid = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid++;
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm);
} else {
vm._renderProxy = vm;
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
callHook(vm, 'beforeCreate');
initState(vm);
callHook(vm, 'created');
initRender(vm);
};
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
opts.parent = options.parent;
opts.propsData = options.propsData;
opts._parentVnode = options._parentVnode;
opts._parentListeners = options._parentListeners;
opts._renderChildren = options._renderChildren;
opts._componentTag = options._componentTag;
opts._parentElm = options._parentElm;
opts._refElm = options._refElm;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = Ctor.super.options;
var cachedSuperOptions = Ctor.superOptions;
var extendOptions = Ctor.extendOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed
Ctor.superOptions = superOptions;
extendOptions.render = options.render;
extendOptions.staticRenderFns = options.staticRenderFns;
extendOptions._scopeId = options._scopeId;
options = Ctor.options = mergeOptions(superOptions, extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue);
stateMixin(Vue);
eventsMixin(Vue);
lifecycleMixin(Vue);
renderMixin(Vue);
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
if (process.env.NODE_ENV !== 'production') {
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
if (!from) { return to }
var key, toVal, fromVal;
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (isPlainObject(toVal) && isPlainObject(fromVal)) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
};
/**
* Hooks and param attributes are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
config._lifecycleHooks.forEach(function (hook) {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (parentVal, childVal) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: res
}
config._assetTypes.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (parentVal, childVal) {
/* istanbul ignore if */
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = parent
? parent.concat(child)
: [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
extend(ret, childVal);
return ret
};
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else if (process.env.NODE_ENV !== 'production') {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
}
options.props = res;
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def };
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
if (process.env.NODE_ENV !== 'production') {
checkComponents(child);
}
normalizeProps(child);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
parent = typeof extendsFrom === 'function'
? mergeOptions(parent, extendsFrom.options, vm)
: mergeOptions(parent, extendsFrom, vm);
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
var mixin = child.mixins[i];
if (mixin.prototype instanceof Vue) {
mixin = mixin.options;
}
parent = mergeOptions(parent, mixin, vm);
}
}
var options = {};
var key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type];
var res = assets[id] ||
// camelCase ID
assets[camelize(id)] ||
// Pascal Case ID
assets[capitalize(camelize(id))];
if (process.env.NODE_ENV !== 'production' && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key];
var absent = !hasOwn(propsData, key);
var value = propsData[key];
// handle boolean props
if (isBooleanType(prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (value === '' || value === hyphenate(key)) {
value = true;
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldConvert = observerState.shouldConvert;
observerState.shouldConvert = true;
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
if (process.env.NODE_ENV !== 'production') {
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default;
// warn against non-factory defaults for Object & Array
if (isObject(def)) {
process.env.NODE_ENV !== 'production' && warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm[key] !== undefined) {
return vm[key]
}
// call factory function for non-Function types
return typeof def === 'function' && prop.type !== Function
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type;
var valid = !type || type === true;
var expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType);
valid = assertedType.valid;
}
}
if (!valid) {
warn(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
vm
);
return
}
var validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
/**
* Assert the type of a value
*/
function assertType (value, type) {
var valid;
var expectedType = getType(type);
if (expectedType === 'String') {
valid = typeof value === (expectedType = 'string');
} else if (expectedType === 'Number') {
valid = typeof value === (expectedType = 'number');
} else if (expectedType === 'Boolean') {
valid = typeof value === (expectedType = 'boolean');
} else if (expectedType === 'Function') {
valid = typeof value === (expectedType = 'function');
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid: valid,
expectedType: expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/);
return match && match[1]
}
function isBooleanType (fn) {
if (!Array.isArray(fn)) {
return getType(fn) === 'Boolean'
}
for (var i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === 'Boolean') {
return true
}
}
/* istanbul ignore next */
return false
}
/* */
// attributes that should be using props for binding
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
);
var isAttr = makeMap(
'accept,accept-charset,accesskey,action,align,alt,async,autocomplete,' +
'autofocus,autoplay,autosave,bgcolor,border,buffered,challenge,charset,' +
'checked,cite,class,code,codebase,color,cols,colspan,content,http-equiv,' +
'name,contenteditable,contextmenu,controls,coords,data,datetime,default,' +
'defer,dir,dirname,disabled,download,draggable,dropzone,enctype,method,for,' +
'form,formaction,headers,<th>,height,hidden,high,href,hreflang,http-equiv,' +
'icon,id,ismap,itemprop,keytype,kind,label,lang,language,list,loop,low,' +
'manifest,max,maxlength,media,method,GET,POST,min,multiple,email,file,' +
'muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,' +
'preload,radiogroup,readonly,rel,required,reversed,rows,rowspan,sandbox,' +
'scope,scoped,seamless,selected,shape,size,type,text,password,sizes,span,' +
'spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,' +
'target,title,type,usemap,value,width,wrap'
);
/* */
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: child.class
? [child.class, parent.class]
: parent.class
}
}
function genClassFromData (data) {
var dynamicClass = data.class;
var staticClass = data.staticClass;
if (staticClass || dynamicClass) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
var res = '';
if (!value) {
return res
}
if (typeof value === 'string') {
return value
}
if (Array.isArray(value)) {
var stringified;
for (var i = 0, l = value.length; i < l; i++) {
if (value[i]) {
if ((stringified = stringifyClass(value[i]))) {
res += stringified + ' ';
}
}
}
return res.slice(0, -1)
}
if (isObject(value)) {
for (var key in value) {
if (value[key]) { res += key + ' '; }
}
return res.slice(0, -1)
}
/* istanbul ignore next */
return res
}
/* */
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template'
);
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr',
true
);
// Elements that you can, intentionally, leave open
// (and which close themselves)
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source',
true
);
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track',
true
);
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font,' +
'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
);
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
};
var unknownElementCache = Object.create(null);
/* */
/**
* Query an element selector if it's not an element already.
*/
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^<!DOCTYPE [^>]+>/i;
var comment = /^<!--/;
var conditionalComment = /^<!\[/;
var IS_REGEX_CAPTURING_BROKEN = false;
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === '';
});
// Special Elements (can contain anything)
var isScriptOrStyle = makeMap('script,style', true);
var hasLang = function (attr) { return attr.name === 'lang' && attr.value !== 'html'; };
var isSpecialTag = function (tag, isSFC, stack) {
if (isScriptOrStyle(tag)) {
return true
}
if (isSFC && stack.length === 1) {
// top-level template that has no pre-processor
if (tag === 'template' && !stack[0].attrs.some(hasLang)) {
return false
} else {
return true
}
}
return false
};
var reCache = {};
var ltRE = /</g;
var gtRE = />/g;
var nlRE = / /g;
var ampRE = /&/g;
var quoteRE = /"/g;
function decodeAttr (value, shouldDecodeNewlines) {
if (shouldDecodeNewlines) {
value = value.replace(nlRE, '\n');
}
return value
.replace(ltRE, '<')
.replace(gtRE, '>')
.replace(ampRE, '&')
.replace(quoteRE, '"')
}
function parseHTML (html, options) {
var stack = [];
var expectHTML = options.expectHTML;
var isUnaryTag$$1 = options.isUnaryTag || no;
var index = 0;
var last, lastTag;
while (html) {
last = html;
// Make sure we're not in a script or style element
if (!lastTag || !isSpecialTag(lastTag, options.sfc, stack)) {
var textEnd = html.indexOf('<');
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
var commentEnd = html.indexOf('-->');
if (commentEnd >= 0) {
advance(commentEnd + 3);
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
var conditionalEnd = html.indexOf(']>');
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2);
continue
}
}
// Doctype:
var doctypeMatch = html.match(doctype);
if (doctypeMatch) {
advance(doctypeMatch[0].length);
continue
}
// End tag:
var endTagMatch = html.match(endTag);
if (endTagMatch) {
var curIndex = index;
advance(endTagMatch[0].length);
parseEndTag(endTagMatch[0], endTagMatch[1], curIndex, index);
continue
}
// Start tag:
var startTagMatch = parseStartTag();
if (startTagMatch) {
handleStartTag(startTagMatch);
continue
}
}
var text = (void 0), rest$1 = (void 0), next = (void 0);
if (textEnd > 0) {
rest$1 = html.slice(textEnd);
while (
!endTag.test(rest$1) &&
!startTagOpen.test(rest$1) &&
!comment.test(rest$1) &&
!conditionalComment.test(rest$1)
) {
// < in plain text, be forgiving and treat it as text
next = rest$1.indexOf('<', 1);
if (next < 0) { break }
textEnd += next;
rest$1 = html.slice(textEnd);
}
text = html.substring(0, textEnd);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));
var endTagLength = 0;
var rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
}
if (options.chars) {
options.chars(text);
}
return ''
});
index += html.length - rest.length;
html = rest;
parseEndTag('</' + stackedTag + '>', stackedTag, index - endTagLength, index);
}
if (html === last && options.chars) {
options.chars(html);
break
}
}
// Clean up any remaining tags
parseEndTag();
function advance (n) {
index += n;
html = html.substring(n);
}
function parseStartTag () {
var start = html.match(startTagOpen);
if (start) {
var match = {
tagName: start[1],
attrs: [],
start: index
};
advance(start[0].length);
var end, attr;
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length);
match.attrs.push(attr);
}
if (end) {
match.unarySlash = end[1];
advance(end[0].length);
match.end = index;
return match
}
}
}
function handleStartTag (match) {
var tagName = match.tagName;
var unarySlash = match.unarySlash;
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag('', lastTag);
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag('', tagName);
}
}
var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash;
var l = match.attrs.length;
var attrs = new Array(l);
for (var i = 0; i < l; i++) {
var args = match.attrs[i];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, attrs: attrs });
lastTag = tagName;
unarySlash = '';
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end);
}
}
function parseEndTag (tag, tagName, start, end) {
var pos;
if (start == null) { start = index; }
if (end == null) { end = index; }
// Find the closest opened tag of the same type
if (tagName) {
var needle = tagName.toLowerCase();
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].tag.toLowerCase() === needle) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0;
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (options.end) {
options.end(stack[i].tag, start, end);
}
}
// Remove the open elements from the stack
stack.length = pos;
lastTag = pos && stack[pos - 1].tag;
} else if (tagName.toLowerCase() === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end);
}
} else if (tagName.toLowerCase() === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end);
}
if (options.end) {
options.end(tagName, start, end);
}
}
}
}
/* */
function parseFilters (exp) {
var inSingle = false;
var inDouble = false;
var inTemplateString = false;
var inRegex = false;
var curly = 0;
var square = 0;
var paren = 0;
var lastFilterIndex = 0;
var c, prev, i, expression, filters;
for (i = 0; i < exp.length; i++) {
prev = c;
c = exp.charCodeAt(i);
if (inSingle) {
if (c === 0x27 && prev !== 0x5C) { inSingle = false; }
} else if (inDouble) {
if (c === 0x22 && prev !== 0x5C) { inDouble = false; }
} else if (inTemplateString) {
if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; }
} else if (inRegex) {
if (c === 0x2f && prev !== 0x5C) { inRegex = false; }
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1;
expression = exp.slice(0, i).trim();
} else {
pushFilter();
}
} else {
switch (c) {
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x60: inTemplateString = true; break // `
case 0x2f: inRegex = true; break // /
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim();
} else if (lastFilterIndex !== 0) {
pushFilter();
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());
lastFilterIndex = i + 1;
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i]);
}
}
return expression
}
function wrapFilter (exp, filter) {
var i = filter.indexOf('(');
if (i < 0) {
// _f: resolveFilter
return ("_f(\"" + filter + "\")(" + exp + ")")
} else {
var name = filter.slice(0, i);
var args = filter.slice(i + 1);
return ("_f(\"" + name + "\")(" + exp + "," + args)
}
}
/* */
var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g;
var regexEscapeRE = /[-.*+?^${}()|[\]/\\]/g;
var buildRegex = cached(function (delimiters) {
var open = delimiters[0].replace(regexEscapeRE, '\\$&');
var close = delimiters[1].replace(regexEscapeRE, '\\$&');
return new RegExp(open + '((?:.|\\n)+?)' + close, 'g')
});
function parseText (
text,
delimiters
) {
var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;
if (!tagRE.test(text)) {
return
}
var tokens = [];
var lastIndex = tagRE.lastIndex = 0;
var match, index;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+')
}
/* */
function baseWarn (msg) {
console.error(("[Vue parser]: " + msg));
}
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value });
}
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value });
}
function addDirective (
el,
name,
rawName,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });
}
function addHandler (
el,
name,
value,
modifiers,
important
) {
// check capture modifier
if (modifiers && modifiers.capture) {
delete modifiers.capture;
name = '!' + name; // mark the event as captured
}
var events;
if (modifiers && modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = { value: value, modifiers: modifiers };
var handlers = events[name];
/* istanbul ignore if */
if (Array.isArray(handlers)) {
important ? handlers.unshift(newHandler) : handlers.push(newHandler);
} else if (handlers) {
events[name] = important ? [newHandler, handlers] : [handlers, newHandler];
} else {
events[name] = newHandler;
}
}
function getBindingAttr (
el,
name,
getStatic
) {
var dynamicValue =
getAndRemoveAttr(el, ':' + name) ||
getAndRemoveAttr(el, 'v-bind:' + name);
if (dynamicValue != null) {
return parseFilters(dynamicValue)
} else if (getStatic !== false) {
var staticValue = getAndRemoveAttr(el, name);
if (staticValue != null) {
return JSON.stringify(staticValue)
}
}
}
function getAndRemoveAttr (el, name) {
var val;
if ((val = el.attrsMap[name]) != null) {
var list = el.attrsList;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i].name === name) {
list.splice(i, 1);
break
}
}
}
return val
}
var len;
var str;
var chr;
var index$1;
var expressionPos;
var expressionEndPos;
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
function parseModel (val) {
str = val;
len = str.length;
index$1 = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index$1)
}
function eof () {
return index$1 >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index$1;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index$1;
break
}
}
}
function parseString (chr) {
var stringQuote = chr;
while (!eof()) {
chr = next();
if (chr === stringQuote) {
break
}
}
}
/* */
var dirRE = /^v-|^@|^:/;
var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var bindRE = /^:|^v-bind:/;
var onRE = /^@|^v-on:/;
var argRE = /:(.*)$/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(he.decode);
// configurable state
var warn$1;
var platformGetTagNamespace;
var platformMustUseProp;
var platformIsPreTag;
var preTransforms;
var transforms;
var postTransforms;
var delimiters;
/**
* Convert HTML string to AST.
*/
function parse (
template,
options
) {
warn$1 = options.warn || baseWarn;
platformGetTagNamespace = options.getTagNamespace || no;
platformMustUseProp = options.mustUseProp || no;
platformIsPreTag = options.isPreTag || no;
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');
transforms = pluckModuleFunction(options.modules, 'transformNode');
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');
delimiters = options.delimiters;
var stack = [];
var preserveWhitespace = options.preserveWhitespace !== false;
var root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
parseHTML(template, {
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start: function start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs);
}
var element = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
};
if (ns) {
element.ns = ns;
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
process.env.NODE_ENV !== 'production' && warn$1(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
"<" + tag + ">."
);
}
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options);
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else {
processFor(element);
processIf(element);
processOnce(element);
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length;
processRef(element);
processSlot(element);
processComponent(element);
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production' && !warned) {
if (el.tag === 'slot' || el.tag === 'template') {
warned = true;
warn$1(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes:\n' + template
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warned = true;
warn$1(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements:\n' + template
);
}
}
}
// tree management
if (!root) {
root = element;
checkRootConstraints(root);
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element);
addIfCondition(root, {
exp: element.elseif,
block: element
});
} else if (process.env.NODE_ENV !== 'production' && !warned) {
warned = true;
warn$1(
"Component template should contain exactly one root element:" +
"\n\n" + template + "\n\n" +
"If you are using v-if on multiple elements, " +
"use v-else-if to chain them instead."
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else if (element.slotScope) { // scoped slot
currentParent.plain = false;
var name = element.slotTarget || 'default';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
} else {
currentParent.children.push(element);
element.parent = currentParent;
}
}
if (!unary) {
currentParent = element;
stack.push(element);
}
// apply post-transforms
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var lastNode = element.children[element.children.length - 1];
if (lastNode && lastNode.type === 3 && lastNode.text === ' ') {
element.children.pop();
}
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
},
chars: function chars (text) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production' && !warned && text === template) {
warned = true;
warn$1(
'Component template requires a root element, rather than just text:\n\n' + template
);
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text) {
return
}
text = inPre || text.trim()
? decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && currentParent.children.length ? ' ' : '';
if (text) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
currentParent.children.push({
type: 2,
expression: expression,
text: text
});
} else {
currentParent.children.push({
type: 3,
text: text
});
}
}
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
};
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processKey (el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn$1("<template> cannot be keyed. Place the key on real elements instead.");
}
el.key = exp;
}
}
function processRef (el) {
var ref = getBindingAttr(el, 'ref');
if (ref) {
el.ref = ref;
el.refInFor = checkInFor(el);
}
}
function processFor (el) {
var exp;
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
var inMatch = exp.match(forAliasRE);
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn$1(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim();
el.iterator1 = iteratorMatch[2].trim();
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim();
}
} else {
el.alias = alias;
}
}
}
function processIf (el) {
var exp = getAndRemoveAttr(el, 'v-if');
if (exp) {
el.if = exp;
addIfCondition(el, {
exp: exp,
block: el
});
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true;
}
var elseif = getAndRemoveAttr(el, 'v-else-if');
if (elseif) {
el.elseif = elseif;
}
}
}
function processIfConditions (el, parent) {
var prev = findPrevElement(parent.children);
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
});
} else if (process.env.NODE_ENV !== 'production') {
warn$1(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if."
);
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = [];
}
el.ifConditions.push(condition);
}
function processOnce (el) {
var once = getAndRemoveAttr(el, 'v-once');
if (once != null) {
el.once = true;
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if (process.env.NODE_ENV !== 'production' && el.key) {
warn$1(
"`key` does not work on <slot> because slots are abstract outlets " +
"and can possibly expand into multiple elements. " +
"Use the key on a wrapping element instead."
);
}
} else {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
function processComponent (el) {
var binding;
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding;
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true;
}
}
function processAttrs (el) {
var list = el.attrsList;
var i, l, name, rawName, value, arg, modifiers, isProp;
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name;
value = list[i].value;
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true;
// modifiers
modifiers = parseModifiers(name);
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
if (modifiers) {
if (modifiers.prop) {
isProp = true;
name = camelize(name);
if (name === 'innerHtml') { name = 'innerHTML'; }
}
if (modifiers.camel) {
name = camelize(name);
}
}
if (isProp || platformMustUseProp(el.tag, name)) {
addProp(el, name, value);
} else {
addAttr(el, name, value);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
addHandler(el, name, value, modifiers);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
var argMatch = name.match(argRE);
if (argMatch && (arg = argMatch[1])) {
name = name.slice(0, -(arg.length + 1));
}
addDirective(el, name, rawName, value, arg, modifiers);
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(value, delimiters);
if (expression) {
warn$1(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
);
}
}
addAttr(el, name, JSON.stringify(value));
}
}
}
function checkInFor (el) {
var parent = el;
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent;
}
return false
}
function parseModifiers (name) {
var match = name.match(modifierRE);
if (match) {
var ret = {};
match.forEach(function (m) { ret[m.slice(1)] = true; });
return ret
}
}
function makeAttrsMap (attrs) {
var map = {};
for (var i = 0, l = attrs.length; i < l; i++) {
if (process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE) {
warn$1('duplicate attribute: ' + attrs[i].name);
}
map[attrs[i].name] = attrs[i].value;
}
return map
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].tag) { return children[i] }
}
}
function isForbiddenTag (el) {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
var ieNSBug = /^xmlns:NS\d+/;
var ieNSPrefix = /^NS\d+:/;
/* istanbul ignore next */
function guardIESVGBug (attrs) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '');
res.push(attr);
}
}
return res
}
function checkForAliasModel (el, value) {
var _el = el;
while (_el) {
if (_el.for && _el.alias === value) {
warn$1(
"<" + (el.tag) + " v-model=\"" + value + "\">: " +
"You are binding v-model directly to a v-for iteration alias. " +
"This will not be able to modify the v-for source array because " +
"writing to the alias is like modifying a function local variable. " +
"Consider using an array of objects and use v-model on an object property instead."
);
}
_el = _el.parent;
}
}
/* */
var isStaticKey;
var isPlatformReservedTag;
var genStaticKeysCached = cached(genStaticKeys$1);
/**
* Goal of the optimizer: walk the generated template AST tree
* and detect sub-trees that are purely static, i.e. parts of
* the DOM that never needs to change.
*
* Once we detect these sub-trees, we can:
*
* 1. Hoist them into constants, so that we no longer need to
* create fresh nodes for them on each re-render;
* 2. Completely skip them in the patching process.
*/
function optimize (root, options) {
if (!root) { return }
isStaticKey = genStaticKeysCached(options.staticKeys || '');
isPlatformReservedTag = options.isReservedTag || no;
// first pass: mark all non-static nodes.
markStatic(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : '')
)
}
function markStatic (node) {
node.static = isStatic(node);
if (node.type === 1) {
// do not make component slot content static. this avoids
// 1. components not able to mutate slot nodes
// 2. static slot content fails for hot-reloading
if (
!isPlatformReservedTag(node.tag) &&
node.tag !== 'slot' &&
node.attrsMap['inline-template'] == null
) {
return
}
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
markStatic(child);
if (!child.static) {
node.static = false;
}
}
}
}
function markStaticRoots (node, isInFor) {
if (node.type === 1) {
if (node.static || node.once) {
node.staticInFor = isInFor;
}
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if (node.static && node.children.length && !(
node.children.length === 1 &&
node.children[0].type === 3
)) {
node.staticRoot = true;
return
} else {
node.staticRoot = false;
}
if (node.children) {
for (var i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for);
}
}
if (node.ifConditions) {
walkThroughConditionsBlocks(node.ifConditions, isInFor);
}
}
}
function walkThroughConditionsBlocks (conditionBlocks, isInFor) {
for (var i = 1, len = conditionBlocks.length; i < len; i++) {
markStaticRoots(conditionBlocks[i].block, isInFor);
}
}
function isStatic (node) {
if (node.type === 2) { // expression
return false
}
if (node.type === 3) { // text
return true
}
return !!(node.pre || (
!node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!isDirectChildOfTemplateFor(node) &&
Object.keys(node).every(isStaticKey)
))
}
function isDirectChildOfTemplateFor (node) {
while (node.parent) {
node = node.parent;
if (node.tag !== 'template') {
return false
}
if (node.for) {
return true
}
}
return false
}
/* */
var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
var modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: 'if($event.target !== $event.currentTarget)return;'
};
var isMouseEventRE = /^mouse|^pointer|^(click|dblclick|contextmenu|wheel)$/;
var mouseEventModifierCode = {
ctrl: 'if(!$event.ctrlKey)return;',
shift: 'if(!$event.shiftKey)return;',
alt: 'if(!$event.altKey)return;',
meta: 'if(!$event.metaKey)return;'
};
function genHandlers (events, native) {
var res = native ? 'nativeOn:{' : 'on:{';
for (var name in events) {
res += "\"" + name + "\":" + (genHandler(name, events[name])) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
} else if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
} else if (!handler.modifiers) {
return fnExpRE.test(handler.value) || simplePathRE.test(handler.value)
? handler.value
: ("function($event){" + (handler.value) + "}")
} else {
var code = '';
var keys = [];
var isMouseEvnet = isMouseEventRE.test(name);
for (var key in handler.modifiers) {
if (modifierCode[key]) {
code += modifierCode[key];
} else if (isMouseEvnet && mouseEventModifierCode[key]) {
code += mouseEventModifierCode[key];
} else {
keys.push(key);
}
}
if (keys.length) {
code = genKeyFilter(keys) + code;
}
var handlerCode = simplePathRE.test(handler.value)
? handler.value + '($event)'
: handler.value;
return 'function($event){' + code + handlerCode + '}'
}
}
function genKeyFilter (keys) {
var code = keys.length === 1
? normalizeKeyCode(keys[0])
: Array.prototype.concat.apply([], keys.map(normalizeKeyCode));
if (Array.isArray(code)) {
return ("if(" + (code.map(function (c) { return ("$event.keyCode!==" + c); }).join('&&')) + ")return;")
} else {
return ("if($event.keyCode!==" + code + ")return;")
}
}
function normalizeKeyCode (key) {
return (
parseInt(key, 10) || // number keyCode
keyCodes[key] || // built-in alias
("_k(" + (JSON.stringify(key)) + ")") // custom alias
)
}
/* */
function bind$1 (el, dir) {
el.wrapData = function (code) {
return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")")
};
}
var baseDirectives = {
bind: bind$1,
cloak: noop
};
/* */
// configurable state
var warn$2;
var transforms$1;
var dataGenFns;
var platformDirectives;
var staticRenderFns;
var onceCount;
var currentOptions;
function generate (
ast,
options
) {
// save previous staticRenderFns so generate calls can be nested
var prevStaticRenderFns = staticRenderFns;
var currentStaticRenderFns = staticRenderFns = [];
var prevOnceCount = onceCount;
onceCount = 0;
currentOptions = options;
warn$2 = options.warn || baseWarn;
transforms$1 = pluckModuleFunction(options.modules, 'transformCode');
dataGenFns = pluckModuleFunction(options.modules, 'genData');
platformDirectives = options.directives || {};
var code = ast ? genElement(ast) : '_h("div")';
staticRenderFns = prevStaticRenderFns;
onceCount = prevOnceCount;
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: currentStaticRenderFns
}
}
function genElement (el) {
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el)
} else if (el.once && !el.onceProcessed) {
return genOnce(el)
} else if (el.for && !el.forProcessed) {
return genFor(el)
} else if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.tag === 'template' && !el.slotTarget) {
return genChildren(el) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el)
} else {
// component or element
var code;
if (el.component) {
code = genComponent(el.component, el);
} else {
var data = el.plain ? undefined : genData(el);
var children = el.inlineTemplate ? null : genChildren(el);
code = "_h('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")";
}
// module transforms
for (var i = 0; i < transforms$1.length; i++) {
code = transforms$1[i](el, code);
}
return code
}
}
// hoist static sub-trees out
function genStatic (el) {
el.staticProcessed = true;
staticRenderFns.push(("with(this){return " + (genElement(el)) + "}"));
return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
}
// v-once
function genOnce (el) {
el.onceProcessed = true;
if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.staticInFor) {
var key = '';
var parent = el.parent;
while (parent) {
if (parent.for) {
key = parent.key;
break
}
parent = parent.parent;
}
if (!key) {
process.env.NODE_ENV !== 'production' && warn$2(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el)
}
return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")")
} else {
return genStatic(el)
}
}
function genIf (el) {
el.ifProcessed = true; // avoid recursion
return genIfConditions(el.ifConditions.slice())
}
function genIfConditions (conditions) {
if (!conditions.length) {
return '_e()'
}
var condition = conditions.shift();
if (condition.exp) {
return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions)))
} else {
return ("" + (genTernaryExp(condition.block)))
}
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return el.once ? genOnce(el) : genElement(el)
}
}
function genFor (el) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genElement(el)) +
'})'
}
function genData (el) {
var data = '{';
// directives first.
// directives may mutate the el's other properties before they are generated.
var dirs = genDirectives(el);
if (dirs) { data += dirs + ','; }
// key
if (el.key) {
data += "key:" + (el.key) + ",";
}
// ref
if (el.ref) {
data += "ref:" + (el.ref) + ",";
}
if (el.refInFor) {
data += "refInFor:true,";
}
// pre
if (el.pre) {
data += "pre:true,";
}
// record original tag name for components using "is" attribute
if (el.component) {
data += "tag:\"" + (el.tag) + "\",";
}
// module data generation functions
for (var i = 0; i < dataGenFns.length; i++) {
data += dataGenFns[i](el);
}
// attributes
if (el.attrs) {
data += "attrs:{" + (genProps(el.attrs)) + "},";
}
// DOM props
if (el.props) {
data += "domProps:{" + (genProps(el.props)) + "},";
}
// event handlers
if (el.events) {
data += (genHandlers(el.events)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(el.scopedSlots)) + ",";
}
// inline-template
if (el.inlineTemplate) {
var inlineTemplate = genInlineTemplate(el);
if (inlineTemplate) {
data += inlineTemplate + ",";
}
}
data = data.replace(/,$/, '') + '}';
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data);
}
return data
}
function genDirectives (el) {
var dirs = el.directives;
if (!dirs) { return }
var res = 'directives:[';
var hasRuntime = false;
var i, l, dir, needRuntime;
for (i = 0, l = dirs.length; i < l; i++) {
dir = dirs[i];
needRuntime = true;
var gen = platformDirectives[dir.name] || baseDirectives[dir.name];
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, warn$2);
}
if (needRuntime) {
hasRuntime = true;
res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},";
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
}
function genInlineTemplate (el) {
var ast = el.children[0];
if (process.env.NODE_ENV !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
warn$2('Inline-template components must have exactly one child element.');
}
if (ast.type === 1) {
var inlineRenderFns = generate(ast, currentOptions);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (slots) {
return ("scopedSlots:{" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "}")
}
function genScopedSlot (key, el) {
return key + ":function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el) || 'void 0'
: genElement(el)) + "}"
}
function genChildren (el) {
if (el.children.length) {
return '[' + el.children.map(genNode).join(',') + ']'
}
}
function genNode (node) {
if (node.type === 1) {
return genElement(node)
} else {
return genText(node)
}
}
function genText (text) {
return text.type === 2
? text.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(text.text))
}
function genSlot (el) {
var slotName = el.slotName || '"default"';
var children = genChildren(el);
return ("_t(" + slotName + (children ? ("," + children) : '') + (el.attrs ? ((children ? '' : ',null') + ",{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}") : '') + ")")
}
// componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (componentName, el) {
var children = el.inlineTemplate ? null : genChildren(el);
return ("_h(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")")
}
function genProps (props) {
var res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
/**
* Compile a template.
*/
function compile$2 (
template,
options
) {
var ast = parse(template.trim(), options);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
}
/* */
// operators like typeof, instanceof and in are allowed
var prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("- invalid " + type + " \"" + ident + "\" in expression: " + text));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"- avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + text
);
} else {
errors.push(("- invalid expression: " + text));
}
}
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
var ref = parseStaticClass(staticClass, options);
var dynamic = ref.dynamic;
var classResult = ref.classResult;
if (process.env.NODE_ENV !== 'production' && dynamic && staticClass) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been deprecated. ' +
'Use v-bind or the colon shorthand instead.'
);
}
if (!dynamic && classResult) {
el.staticClass = classResult;
}
var classBinding = getBindingAttr(el, 'class', false /* getStatic */);
if (classBinding) {
el.classBinding = classBinding;
} else if (dynamic) {
el.classBinding = classResult;
}
}
function genData$1 (el) {
var data = '';
if (el.staticClass) {
data += "staticClass:" + (el.staticClass) + ",";
}
if (el.classBinding) {
data += "class:" + (el.classBinding) + ",";
}
return data
}
function parseStaticClass (staticClass, options) {
// "a b c" -> ["a", "b", "c"] => staticClass: ["a", "b", "c"]
// "a {{x}} c" -> ["a", x, "c"] => classBinding: '["a", x, "c"]'
var dynamic = false;
var classResult = '';
if (staticClass) {
var classList = staticClass.trim().split(' ').map(function (name) {
var result = parseText(name, options.delimiters);
if (result) {
dynamic = true;
return result
}
return JSON.stringify(name)
});
if (classList.length) {
classResult = '[' + classList.join(',') + ']';
}
}
return { dynamic: dynamic, classResult: classResult }
}
var klass = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData$1
};
/* */
var normalize = cached(camelize);
function transformNode$1 (el, options) {
var warn = options.warn || baseWarn;
var staticStyle = getAndRemoveAttr(el, 'style');
var ref = parseStaticStyle(staticStyle, options);
var dynamic = ref.dynamic;
var styleResult = ref.styleResult;
if (process.env.NODE_ENV !== 'production' && dynamic) {
warn(
"style=\"" + (String(staticStyle)) + "\": " +
'Interpolation inside attributes has been deprecated. ' +
'Use v-bind or the colon shorthand instead.'
);
}
if (!dynamic && styleResult) {
el.staticStyle = styleResult;
}
var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
if (styleBinding) {
el.styleBinding = styleBinding;
} else if (dynamic) {
el.styleBinding = styleResult;
}
}
function genData$2 (el) {
var data = '';
if (el.staticStyle) {
data += "staticStyle:" + (el.staticStyle) + ",";
}
if (el.styleBinding) {
data += "style:" + (el.styleBinding) + ",";
}
return data
}
function parseStaticStyle (staticStyle, options) {
// "width: 200px; height: 200px;" -> {width: 200, height: 200}
// "width: 200px; height: {{y}}" -> {width: 200, height: y}
var dynamic = false;
var styleResult = '';
if (staticStyle) {
var styleList = staticStyle.trim().split(';').map(function (style) {
var result = style.trim().split(':');
if (result.length !== 2) {
return
}
var key = normalize(result[0].trim());
var value = result[1].trim();
var dynamicValue = parseText(value, options.delimiters);
if (dynamicValue) {
dynamic = true;
return key + ':' + dynamicValue
}
return key + ':' + JSON.stringify(value)
}).filter(function (result) { return result; });
if (styleList.length) {
styleResult = '{' + styleList.join(',') + '}';
}
}
return { dynamic: dynamic, styleResult: styleResult }
}
var style = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$2
};
/* */
function transformNode$2 (el, options) {
if (el.attrsMap.append === 'tree') {
el.appendAsTree = true;
}
}
function genData$3 (el) {
return el.appendAsTree ? "appendAsTree:true," : ''
}
var append = {
staticKeys: ['appendAsTree'],
transformNode: transformNode$2,
genData: genData$3
};
var modules = [
klass,
style,
append
];
/* */
function model (
el,
dir,
_warn
) {
genDefaultModel(el, dir.value, dir.modifiers);
}
function genDefaultModel (
el,
value,
modifiers
) {
var ref = modifiers || {};
var lazy = ref.lazy;
var trim = ref.trim;
var event = lazy ? 'change' : 'input';
var isNative = el.tag === 'input' || el.tag === 'textarea';
var valueExpression = isNative
? ("$event.target.attr.value" + (trim ? '.trim()' : ''))
: "$event";
var code = genAssignmentCode(value, valueExpression);
addAttr(el, 'value', ("(" + value + ")"));
addHandler(el, event, code, null, true);
}
function genAssignmentCode (value, assignment) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" +
"if (!Array.isArray($$exp)){" +
value + "=" + assignment + "}" +
"else{$$exp.splice($$idx, 1, " + assignment + ")}"
}
}
var directives = {
model: model
};
var latestNodeId = 1;
function TextNode (text) {
this.instanceId = '';
this.nodeId = latestNodeId++;
this.parentNode = null;
this.nodeType = 3;
this.text = text;
}
var renderer = {
TextNode: TextNode,
instances: {},
modules: {},
components: {}
};
var isReservedTag$1 = makeMap(
'div,img,image,input,switch,indicator,list,scroller,cell,template,text,slider,image'
);
function isUnaryTag$1 () { /* console.log('isUnaryTag') */ }
function mustUseProp$1 () { /* console.log('mustUseProp') */ }
function getTagNamespace$1 () { /* console.log('getTagNamespace') */ }
/* */
var cache = Object.create(null);
var baseOptions = {
preserveWhitespace: false,
modules: modules,
staticKeys: genStaticKeys(modules),
directives: directives,
isReservedTag: isReservedTag$1,
isUnaryTag: isUnaryTag$1,
mustUseProp: mustUseProp$1,
getTagNamespace: getTagNamespace$1
};
function compile$1 (
template,
options
) {
options = options
? extend(extend({}, baseOptions), options)
: baseOptions;
return compile$2(template, options)
}
function makeFunction (code) {
try {
return new Function(code)
} catch (e) {
return noop
}
}
/* */
function compile$$1 (
template,
options
) {
options = options || {};
var errors = [];
// allow injecting modules/directives
var baseModules = baseOptions.modules || [];
var modules = options.modules
? baseModules.concat(options.modules)
: baseModules;
var directives = options.directives
? extend(extend({}, baseOptions.directives), options.directives)
: baseOptions.directives;
var compiled = compile$1(template, {
modules: modules,
directives: directives,
warn: function (msg) {
errors.push(msg);
}
});
compiled.errors = errors.concat(detectErrors(compiled.ast));
return compiled
}
exports.compile = compile$$1;
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'format', 'sr', {
label: 'Формат',
panelTitle: 'Формат',
tag_address: 'Adresa',
tag_div: 'Нормално (DIV)',
tag_h1: 'Heading 1',
tag_h2: 'Heading 2',
tag_h3: 'Heading 3',
tag_h4: 'Heading 4',
tag_h5: 'Heading 5',
tag_h6: 'Heading 6',
tag_p: 'Normal',
tag_pre: 'Formatirano'
});
|
import UiModules from 'ui/modules';
import { words, camelCase, kebabCase } from 'lodash';
export function kbnUrlDirective(name) {
const srcAttr = kebabCase(name);
const attr = kebabCase(words(name).slice(1));
UiModules
.get('kibana')
.directive(name, function (Private, chrome) {
return {
restrict: 'A',
link: function ($scope, $el, $attr) {
$attr.$observe(name, function (val) {
$attr.$set(attr, chrome.addBasePath(val));
});
}
};
});
}
kbnUrlDirective('kbnHref');
|
'use strict';
describe('utils', function () {
var expect = require('chai').expect;
var utils = require('../src/utils');
var dropElement = utils.dropElement;
it('can drop first element of array', function () {
expect(dropElement([0, 1, 2], 0)).to.eql([1, 2]);
});
it('can drop middle element of array', function () {
expect(dropElement([0, 1, 2], 1)).to.eql([0, 2]);
});
it('can drop last element of array', function () {
expect(dropElement([0, 1, 2], 2)).to.eql([0, 1]);
});
it('can handle empty array', function () {
expect(dropElement([], 0)).to.eql([]);
});
it('can handle dropping out of range index', function () {
expect(dropElement([0, 1, 2], 5)).to.eql([0, 1, 2]);
});
it('can handle dropping negative index', function () {
expect(dropElement([0, 1, 2], -5)).to.eql([0, 1, 2]);
});
});
|
/**
@module ember
@submodule ember-application
*/
import { dictionary } from 'ember-utils';
import { ENV, environment } from 'ember-environment';
import {
assert,
debug,
libraries,
isTesting,
get,
run,
runInDebug
} from 'ember-metal';
import {
Namespace,
setNamespaceSearchDisabled,
runLoadHooks,
_loaded,
buildFakeRegistryWithDeprecations,
RSVP
} from 'ember-runtime';
import { EventDispatcher, jQuery } from 'ember-views';
import {
Route,
Router,
HashLocation,
HistoryLocation,
AutoLocation,
NoneLocation,
BucketCache
} from 'ember-routing';
import ApplicationInstance from './application-instance';
import { privatize as P } from 'container';
import Engine from './engine';
import { setupApplicationRegistry } from 'ember-glimmer';
import { RouterService } from 'ember-routing';
import { isFeatureEnabled } from 'ember-metal';
let librariesRegistered = false;
/**
An instance of `Ember.Application` is the starting point for every Ember
application. It helps to instantiate, initialize and coordinate the many
objects that make up your app.
Each Ember app has one and only one `Ember.Application` object. In fact, the
very first thing you should do in your application is create the instance:
```javascript
window.App = Ember.Application.create();
```
Typically, the application object is the only global variable. All other
classes in your app should be properties on the `Ember.Application` instance,
which highlights its first role: a global namespace.
For example, if you define a view class, it might look like this:
```javascript
App.MyView = Ember.View.extend();
```
By default, calling `Ember.Application.create()` will automatically initialize
your application by calling the `Ember.Application.initialize()` method. If
you need to delay initialization, you can call your app's `deferReadiness()`
method. When you are ready for your app to be initialized, call its
`advanceReadiness()` method.
You can define a `ready` method on the `Ember.Application` instance, which
will be run by Ember when the application is initialized.
Because `Ember.Application` inherits from `Ember.Namespace`, any classes
you create will have useful string representations when calling `toString()`.
See the `Ember.Namespace` documentation for more information.
While you can think of your `Ember.Application` as a container that holds the
other classes in your application, there are several other responsibilities
going on under-the-hood that you may want to understand.
### Event Delegation
Ember uses a technique called _event delegation_. This allows the framework
to set up a global, shared event listener instead of requiring each view to
do it manually. For example, instead of each view registering its own
`mousedown` listener on its associated element, Ember sets up a `mousedown`
listener on the `body`.
If a `mousedown` event occurs, Ember will look at the target of the event and
start walking up the DOM node tree, finding corresponding views and invoking
their `mouseDown` method as it goes.
`Ember.Application` has a number of default events that it listens for, as
well as a mapping from lowercase events to camel-cased view method names. For
example, the `keypress` event causes the `keyPress` method on the view to be
called, the `dblclick` event causes `doubleClick` to be called, and so on.
If there is a bubbling browser event that Ember does not listen for by
default, you can specify custom events and their corresponding view method
names by setting the application's `customEvents` property:
```javascript
let App = Ember.Application.create({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
```
To prevent Ember from setting up a listener for a default event,
specify the event name with a `null` value in the `customEvents`
property:
```javascript
let App = Ember.Application.create({
customEvents: {
// prevent listeners for mouseenter/mouseleave events
mouseenter: null,
mouseleave: null
}
});
```
By default, the application sets up these event listeners on the document
body. However, in cases where you are embedding an Ember application inside
an existing page, you may want it to set up the listeners on an element
inside the body.
For example, if only events inside a DOM element with the ID of `ember-app`
should be delegated, set your application's `rootElement` property:
```javascript
let App = Ember.Application.create({
rootElement: '#ember-app'
});
```
The `rootElement` can be either a DOM element or a jQuery-compatible selector
string. Note that *views appended to the DOM outside the root element will
not receive events.* If you specify a custom root element, make sure you only
append views inside it!
To learn more about the events Ember components use, see
[components/handling-events](https://guides.emberjs.com/v2.6.0/components/handling-events/#toc_event-names).
### Initializers
Libraries on top of Ember can add initializers, like so:
```javascript
Ember.Application.initializer({
name: 'api-adapter',
initialize: function(application) {
application.register('api-adapter:main', ApiAdapter);
}
});
```
Initializers provide an opportunity to access the internal registry, which
organizes the different components of an Ember application. Additionally
they provide a chance to access the instantiated application. Beyond
being used for libraries, initializers are also a great way to organize
dependency injection or setup in your own application.
### Routing
In addition to creating your application's router, `Ember.Application` is
also responsible for telling the router when to start routing. Transitions
between routes can be logged with the `LOG_TRANSITIONS` flag, and more
detailed intra-transition logging can be logged with
the `LOG_TRANSITIONS_INTERNAL` flag:
```javascript
let App = Ember.Application.create({
LOG_TRANSITIONS: true, // basic logging of successful transitions
LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps
});
```
By default, the router will begin trying to translate the current URL into
application state once the browser emits the `DOMContentReady` event. If you
need to defer routing, you can call the application's `deferReadiness()`
method. Once routing can begin, call the `advanceReadiness()` method.
If there is any setup required before routing begins, you can implement a
`ready()` method on your app that will be invoked immediately before routing
begins.
@class Application
@namespace Ember
@extends Ember.Engine
@uses RegistryProxyMixin
@public
*/
const Application = Engine.extend({
/**
The root DOM element of the Application. This can be specified as an
element or a
[jQuery-compatible selector string](http://api.jquery.com/category/selectors/).
This is the element that will be passed to the Application's,
`eventDispatcher`, which sets up the listeners for event delegation. Every
view in your application should be a child of the element you specify here.
@property rootElement
@type DOMElement
@default 'body'
@public
*/
rootElement: 'body',
/**
The `Ember.EventDispatcher` responsible for delegating events to this
application's views.
The event dispatcher is created by the application at initialization time
and sets up event listeners on the DOM element described by the
application's `rootElement` property.
See the documentation for `Ember.EventDispatcher` for more information.
@property eventDispatcher
@type Ember.EventDispatcher
@default null
@public
*/
eventDispatcher: null,
/**
The DOM events for which the event dispatcher should listen.
By default, the application's `Ember.EventDispatcher` listens
for a set of standard DOM events, such as `mousedown` and
`keyup`, and delegates them to your application's `Ember.View`
instances.
If you would like additional bubbling events to be delegated to your
views, set your `Ember.Application`'s `customEvents` property
to a hash containing the DOM event name as the key and the
corresponding view method name as the value. Setting an event to
a value of `null` will prevent a default event listener from being
added for that event.
To add new events to be listened to:
```javascript
let App = Ember.Application.create({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
```
To prevent default events from being listened to:
```javascript
let App = Ember.Application.create({
customEvents: {
// remove support for mouseenter / mouseleave events
mouseenter: null,
mouseleave: null
}
});
```
@property customEvents
@type Object
@default null
@public
*/
customEvents: null,
/**
Whether the application should automatically start routing and render
templates to the `rootElement` on DOM ready. While default by true,
other environments such as FastBoot or a testing harness can set this
property to `false` and control the precise timing and behavior of the boot
process.
@property autoboot
@type Boolean
@default true
@private
*/
autoboot: true,
/**
Whether the application should be configured for the legacy "globals mode".
Under this mode, the Application object serves as a global namespace for all
classes.
```javascript
let App = Ember.Application.create({
...
});
App.Router.reopen({
location: 'none'
});
App.Router.map({
...
});
App.MyComponent = Ember.Component.extend({
...
});
```
This flag also exposes other internal APIs that assumes the existence of
a special "default instance", like `App.__container__.lookup(...)`.
This option is currently not configurable, its value is derived from
the `autoboot` flag – disabling `autoboot` also implies opting-out of
globals mode support, although they are ultimately orthogonal concerns.
Some of the global modes features are already deprecated in 1.x. The
existence of this flag is to untangle the globals mode code paths from
the autoboot code paths, so that these legacy features can be reviewed
for deprecation/removal separately.
Forcing the (autoboot=true, _globalsMode=false) here and running the tests
would reveal all the places where we are still relying on these legacy
behavior internally (mostly just tests).
@property _globalsMode
@type Boolean
@default true
@private
*/
_globalsMode: true,
init(options) {
this._super(...arguments);
if (!this.$) {
this.$ = jQuery;
}
registerLibraries();
runInDebug(() => logLibraryVersions());
// Start off the number of deferrals at 1. This will be decremented by
// the Application's own `boot` method.
this._readinessDeferrals = 1;
this._booted = false;
this.autoboot = this._globalsMode = !!this.autoboot;
if (this._globalsMode) {
this._prepareForGlobalsMode();
}
if (this.autoboot) {
this.waitForDOMReady();
}
},
/**
Create an ApplicationInstance for this application.
@private
@method buildInstance
@return {Ember.ApplicationInstance} the application instance
*/
buildInstance(options = {}) {
options.base = this;
options.application = this;
return ApplicationInstance.create(options);
},
/**
Enable the legacy globals mode by allowing this application to act
as a global namespace. See the docs on the `_globalsMode` property
for details.
Most of these features are already deprecated in 1.x, so we can
stop using them internally and try to remove them.
@private
@method _prepareForGlobalsMode
*/
_prepareForGlobalsMode() {
// Create subclass of Ember.Router for this Application instance.
// This is to ensure that someone reopening `App.Router` does not
// tamper with the default `Ember.Router`.
this.Router = (this.Router || Router).extend();
this._buildDeprecatedInstance();
},
/*
Build the deprecated instance for legacy globals mode support.
Called when creating and resetting the application.
This is orthogonal to autoboot: the deprecated instance needs to
be created at Application construction (not boot) time to expose
App.__container__. If autoboot sees that this instance exists,
it will continue booting it to avoid doing unncessary work (as
opposed to building a new instance at boot time), but they are
otherwise unrelated.
@private
@method _buildDeprecatedInstance
*/
_buildDeprecatedInstance() {
// Build a default instance
let instance = this.buildInstance();
// Legacy support for App.__container__ and other global methods
// on App that rely on a single, default instance.
this.__deprecatedInstance__ = instance;
this.__container__ = instance.__container__;
},
/**
Automatically kick-off the boot process for the application once the
DOM has become ready.
The initialization itself is scheduled on the actions queue which
ensures that code-loading finishes before booting.
If you are asynchronously loading code, you should call `deferReadiness()`
to defer booting, and then call `advanceReadiness()` once all of your code
has finished loading.
@private
@method waitForDOMReady
*/
waitForDOMReady() {
if (!this.$ || this.$.isReady) {
run.schedule('actions', this, 'domReady');
} else {
this.$().ready(run.bind(this, 'domReady'));
}
},
/**
This is the autoboot flow:
1. Boot the app by calling `this.boot()`
2. Create an instance (or use the `__deprecatedInstance__` in globals mode)
3. Boot the instance by calling `instance.boot()`
4. Invoke the `App.ready()` callback
5. Kick-off routing on the instance
Ideally, this is all we would need to do:
```javascript
_autoBoot() {
this.boot().then(() => {
let instance = (this._globalsMode) ? this.__deprecatedInstance__ : this.buildInstance();
return instance.boot();
}).then((instance) => {
App.ready();
instance.startRouting();
});
}
```
Unfortunately, we cannot actually write this because we need to participate
in the "synchronous" boot process. While the code above would work fine on
the initial boot (i.e. DOM ready), when `App.reset()` is called, we need to
boot a new instance synchronously (see the documentation on `_bootSync()`
for details).
Because of this restriction, the actual logic of this method is located
inside `didBecomeReady()`.
@private
@method domReady
*/
domReady() {
if (this.isDestroyed) {
return;
}
this._bootSync();
// Continues to `didBecomeReady`
},
/**
Use this to defer readiness until some condition is true.
Example:
```javascript
let App = Ember.Application.create();
App.deferReadiness();
// Ember.$ is a reference to the jQuery object/function
Ember.$.getJSON('/auth-token', function(token) {
App.token = token;
App.advanceReadiness();
});
```
This allows you to perform asynchronous setup logic and defer
booting your application until the setup has finished.
However, if the setup requires a loading UI, it might be better
to use the router for this purpose.
@method deferReadiness
@public
*/
deferReadiness() {
assert('You must call deferReadiness on an instance of Ember.Application', this instanceof Application);
assert('You cannot defer readiness since the `ready()` hook has already been called.', this._readinessDeferrals > 0);
this._readinessDeferrals++;
},
/**
Call `advanceReadiness` after any asynchronous setup logic has completed.
Each call to `deferReadiness` must be matched by a call to `advanceReadiness`
or the application will never become ready and routing will not begin.
@method advanceReadiness
@see {Ember.Application#deferReadiness}
@public
*/
advanceReadiness() {
assert('You must call advanceReadiness on an instance of Ember.Application', this instanceof Application);
this._readinessDeferrals--;
if (this._readinessDeferrals === 0) {
run.once(this, this.didBecomeReady);
}
},
/**
Initialize the application and return a promise that resolves with the `Ember.Application`
object when the boot process is complete.
Run any application initializers and run the application load hook. These hooks may
choose to defer readiness. For example, an authentication hook might want to defer
readiness until the auth token has been retrieved.
By default, this method is called automatically on "DOM ready"; however, if autoboot
is disabled, this is automatically called when the first application instance is
created via `visit`.
@private
@method boot
@return {Promise<Ember.Application,Error>}
*/
boot() {
if (this._bootPromise) { return this._bootPromise; }
try {
this._bootSync();
} catch (_) {
// Ignore th error: in the asynchronous boot path, the error is already reflected
// in the promise rejection
}
return this._bootPromise;
},
/**
Unfortunately, a lot of existing code assumes the booting process is
"synchronous". Specifically, a lot of tests assumes the last call to
`app.advanceReadiness()` or `app.reset()` will result in the app being
fully-booted when the current runloop completes.
We would like new code (like the `visit` API) to stop making this assumption,
so we created the asynchronous version above that returns a promise. But until
we have migrated all the code, we would have to expose this method for use
*internally* in places where we need to boot an app "synchronously".
@private
*/
_bootSync() {
if (this._booted) { return; }
// Even though this returns synchronously, we still need to make sure the
// boot promise exists for book-keeping purposes: if anything went wrong in
// the boot process, we need to store the error as a rejection on the boot
// promise so that a future caller of `boot()` can tell what failed.
let defer = this._bootResolver = new RSVP.defer();
this._bootPromise = defer.promise;
try {
this.runInitializers();
runLoadHooks('application', this);
this.advanceReadiness();
// Continues to `didBecomeReady`
} catch (error) {
// For the asynchronous boot path
defer.reject(error);
// For the synchronous boot path
throw error;
}
},
/**
Reset the application. This is typically used only in tests. It cleans up
the application in the following order:
1. Deactivate existing routes
2. Destroy all objects in the container
3. Create a new application container
4. Re-route to the existing url
Typical Example:
```javascript
let App;
run(function() {
App = Ember.Application.create();
});
module('acceptance test', {
setup: function() {
App.reset();
}
});
test('first test', function() {
// App is freshly reset
});
test('second test', function() {
// App is again freshly reset
});
```
Advanced Example:
Occasionally you may want to prevent the app from initializing during
setup. This could enable extra configuration, or enable asserting prior
to the app becoming ready.
```javascript
let App;
run(function() {
App = Ember.Application.create();
});
module('acceptance test', {
setup: function() {
run(function() {
App.reset();
App.deferReadiness();
});
}
});
test('first test', function() {
ok(true, 'something before app is initialized');
run(function() {
App.advanceReadiness();
});
ok(true, 'something after app is initialized');
});
```
@method reset
@public
*/
reset() {
assert(`Calling reset() on instances of \`Ember.Application\` is not
supported when globals mode is disabled; call \`visit()\` to
create new \`Ember.ApplicationInstance\`s and dispose them
via their \`destroy()\` method instead.`, this._globalsMode && this.autoboot);
let instance = this.__deprecatedInstance__;
this._readinessDeferrals = 1;
this._bootPromise = null;
this._bootResolver = null;
this._booted = false;
function handleReset() {
run(instance, 'destroy');
this._buildDeprecatedInstance();
run.schedule('actions', this, '_bootSync');
}
run.join(this, handleReset);
},
/**
@private
@method didBecomeReady
*/
didBecomeReady() {
try {
// TODO: Is this still needed for _globalsMode = false?
if (!isTesting()) {
// Eagerly name all classes that are already loaded
Namespace.processAll();
setNamespaceSearchDisabled(true);
}
// See documentation on `_autoboot()` for details
if (this.autoboot) {
let instance;
if (this._globalsMode) {
// If we already have the __deprecatedInstance__ lying around, boot it to
// avoid unnecessary work
instance = this.__deprecatedInstance__;
} else {
// Otherwise, build an instance and boot it. This is currently unreachable,
// because we forced _globalsMode to === autoboot; but having this branch
// allows us to locally toggle that flag for weeding out legacy globals mode
// dependencies independently
instance = this.buildInstance();
}
instance._bootSync();
// TODO: App.ready() is not called when autoboot is disabled, is this correct?
this.ready();
instance.startRouting();
}
// For the asynchronous boot path
this._bootResolver.resolve(this);
// For the synchronous boot path
this._booted = true;
} catch (error) {
// For the asynchronous boot path
this._bootResolver.reject(error);
// For the synchronous boot path
throw error;
}
},
/**
Called when the Application has become ready, immediately before routing
begins. The call will be delayed until the DOM has become ready.
@event ready
@public
*/
ready() { return this; },
// This method must be moved to the application instance object
willDestroy() {
this._super(...arguments);
setNamespaceSearchDisabled(false);
this._booted = false;
this._bootPromise = null;
this._bootResolver = null;
if (_loaded.application === this) {
_loaded.application = undefined;
}
if (this._globalsMode && this.__deprecatedInstance__) {
this.__deprecatedInstance__.destroy();
}
},
/**
Boot a new instance of `Ember.ApplicationInstance` for the current
application and navigate it to the given `url`. Returns a `Promise` that
resolves with the instance when the initial routing and rendering is
complete, or rejects with any error that occured during the boot process.
When `autoboot` is disabled, calling `visit` would first cause the
application to boot, which runs the application initializers.
This method also takes a hash of boot-time configuration options for
customizing the instance's behavior. See the documentation on
`Ember.ApplicationInstance.BootOptions` for details.
`Ember.ApplicationInstance.BootOptions` is an interface class that exists
purely to document the available options; you do not need to construct it
manually. Simply pass a regular JavaScript object containing of the
desired options:
```javascript
MyApp.visit("/", { location: "none", rootElement: "#container" });
```
### Supported Scenarios
While the `BootOptions` class exposes a large number of knobs, not all
combinations of them are valid; certain incompatible combinations might
result in unexpected behavior.
For example, booting the instance in the full browser environment
while specifying a foriegn `document` object (e.g. `{ isBrowser: true,
document: iframe.contentDocument }`) does not work correctly today,
largely due to Ember's jQuery dependency.
Currently, there are three officially supported scenarios/configurations.
Usages outside of these scenarios are not guaranteed to work, but please
feel free to file bug reports documenting your experience and any issues
you encountered to help expand support.
#### Browser Applications (Manual Boot)
The setup is largely similar to how Ember works out-of-the-box. Normally,
Ember will boot a default instance for your Application on "DOM ready".
However, you can customize this behavior by disabling `autoboot`.
For example, this allows you to render a miniture demo of your application
into a specific area on your marketing website:
```javascript
import MyApp from 'my-app';
$(function() {
let App = MyApp.create({ autoboot: false });
let options = {
// Override the router's location adapter to prevent it from updating
// the URL in the address bar
location: 'none',
// Override the default `rootElement` on the app to render into a
// specific `div` on the page
rootElement: '#demo'
};
// Start the app at the special demo URL
App.visit('/demo', options);
});
````
Or perhaps you might want to boot two instances of your app on the same
page for a split-screen multiplayer experience:
```javascript
import MyApp from 'my-app';
$(function() {
let App = MyApp.create({ autoboot: false });
let sessionId = MyApp.generateSessionID();
let player1 = App.visit(`/matches/join?name=Player+1&session=${sessionId}`, { rootElement: '#left', location: 'none' });
let player2 = App.visit(`/matches/join?name=Player+2&session=${sessionId}`, { rootElement: '#right', location: 'none' });
Promise.all([player1, player2]).then(() => {
// Both apps have completed the initial render
$('#loading').fadeOut();
});
});
```
Do note that each app instance maintains their own registry/container, so
they will run in complete isolation by default.
#### Server-Side Rendering (also known as FastBoot)
This setup allows you to run your Ember app in a server environment using
Node.js and render its content into static HTML for SEO purposes.
```javascript
const HTMLSerializer = new SimpleDOM.HTMLSerializer(SimpleDOM.voidMap);
function renderURL(url) {
let dom = new SimpleDOM.Document();
let rootElement = dom.body;
let options = { isBrowser: false, document: dom, rootElement: rootElement };
return MyApp.visit(options).then(instance => {
try {
return HTMLSerializer.serialize(rootElement.firstChild);
} finally {
instance.destroy();
}
});
}
```
In this scenario, because Ember does not have access to a global `document`
object in the Node.js environment, you must provide one explicitly. In practice,
in the non-browser environment, the stand-in `document` object only need to
implement a limited subset of the full DOM API. The `SimpleDOM` library is known
to work.
Since there is no access to jQuery in the non-browser environment, you must also
specify a DOM `Element` object in the same `document` for the `rootElement` option
(as opposed to a selector string like `"body"`).
See the documentation on the `isBrowser`, `document` and `rootElement` properties
on `Ember.ApplicationInstance.BootOptions` for details.
#### Server-Side Resource Discovery
This setup allows you to run the routing layer of your Ember app in a server
environment using Node.js and completely disable rendering. This allows you
to simulate and discover the resources (i.e. AJAX requests) needed to fufill
a given request and eagerly "push" these resources to the client.
```app/initializers/network-service.js
import BrowserNetworkService from 'app/services/network/browser';
import NodeNetworkService from 'app/services/network/node';
// Inject a (hypothetical) service for abstracting all AJAX calls and use
// the appropiate implementaion on the client/server. This also allows the
// server to log all the AJAX calls made during a particular request and use
// that for resource-discovery purpose.
export function initialize(application) {
if (window) { // browser
application.register('service:network', BrowserNetworkService);
} else { // node
application.register('service:network', NodeNetworkService);
}
application.inject('route', 'network', 'service:network');
};
export default {
name: 'network-service',
initialize: initialize
};
```
```app/routes/post.js
import Ember from 'ember';
// An example of how the (hypothetical) service is used in routes.
export default Ember.Route.extend({
model(params) {
return this.network.fetch(`/api/posts/${params.post_id}.json`);
},
afterModel(post) {
if (post.isExternalContent) {
return this.network.fetch(`/api/external/?url=${post.externalURL}`);
} else {
return post;
}
}
});
```
```javascript
// Finally, put all the pieces together
function discoverResourcesFor(url) {
return MyApp.visit(url, { isBrowser: false, shouldRender: false }).then(instance => {
let networkService = instance.lookup('service:network');
return networkService.requests; // => { "/api/posts/123.json": "..." }
});
}
```
@public
@method visit
@param url {String} The initial URL to navigate to
@param options {Ember.ApplicationInstance.BootOptions}
@return {Promise<Ember.ApplicationInstance, Error>}
*/
visit(url, options) {
return this.boot().then(() => {
let instance = this.buildInstance();
return instance.boot(options)
.then(() => instance.visit(url))
.catch(error => {
run(instance, 'destroy');
throw error;
});
});
}
});
Object.defineProperty(Application.prototype, 'registry', {
configurable: true,
enumerable: false,
get() {
return buildFakeRegistryWithDeprecations(this, 'Application');
}
});
Application.reopenClass({
/**
This creates a registry with the default Ember naming conventions.
It also configures the registry:
* registered views are created every time they are looked up (they are
not singletons)
* registered templates are not factories; the registered value is
returned directly.
* the router receives the application as its `namespace` property
* all controllers receive the router as their `target` and `controllers`
properties
* all controllers receive the application as their `namespace` property
* the application view receives the application controller as its
`controller` property
* the application view receives the application template as its
`defaultTemplate` property
@method buildRegistry
@static
@param {Ember.Application} namespace the application for which to
build the registry
@return {Ember.Registry} the built registry
@private
*/
buildRegistry(application, options = {}) {
let registry = this._super(...arguments);
commonSetupRegistry(registry);
setupApplicationRegistry(registry);
return registry;
}
});
function commonSetupRegistry(registry) {
registry.register('-view-registry:main', { create() { return dictionary(null); } });
registry.register('route:basic', Route);
registry.register('event_dispatcher:main', EventDispatcher);
registry.injection('router:main', 'namespace', 'application:main');
registry.register('location:auto', AutoLocation);
registry.register('location:hash', HashLocation);
registry.register('location:history', HistoryLocation);
registry.register('location:none', NoneLocation);
registry.register(P`-bucket-cache:main`, BucketCache);
if (isFeatureEnabled('ember-routing-router-service')) {
registry.register('service:router', RouterService);
registry.injection('service:router', 'router', 'router:main');
}
}
function registerLibraries() {
if (!librariesRegistered) {
librariesRegistered = true;
if (environment.hasDOM && typeof jQuery === 'function') {
libraries.registerCoreLibrary('jQuery', jQuery().jquery);
}
}
}
function logLibraryVersions() {
runInDebug(() => {
if (ENV.LOG_VERSION) {
// we only need to see this once per Application#init
ENV.LOG_VERSION = false;
let libs = libraries._registry;
let nameLengths = libs.map(item => get(item, 'name.length'));
let maxNameLength = Math.max.apply(this, nameLengths);
debug('-------------------------------');
for (let i = 0; i < libs.length; i++) {
let lib = libs[i];
let spaces = new Array(maxNameLength - lib.name.length + 1).join(' ');
debug([lib.name, spaces, ' : ', lib.version].join(''));
}
debug('-------------------------------');
}
});
}
export default Application;
|
/*!
* Add to Homescreen v2.0.8 ~ Copyright (c) 2013 Matteo Spinelli, http://cubiq.org
* Released under MIT license, http://cubiq.org/license
*/
var addToHome = (function (w) {
var nav = w.navigator,
isIDevice = 'platform' in nav && (/iphone|ipod|ipad/gi).test(nav.platform),
isIPad,
isRetina,
isSafari,
isStandalone,
OSVersion,
startX = 0,
startY = 0,
lastVisit = 0,
isExpired,
isSessionActive,
isReturningVisitor,
balloon,
overrideChecks,
positionInterval,
closeTimeout,
options = {
autostart: true, // Automatically open the balloon
returningVisitor: false, // Show the balloon to returning visitors only (setting this to true is highly recommended)
animationIn: 'drop', // drop || bubble || fade
animationOut: 'fade', // drop || bubble || fade
startDelay: 1000, // 2 seconds from page load before the balloon appears
lifespan: 3000, // 15 seconds before it is automatically destroyed
bottomOffset: 14, // Distance of the balloon from bottom
expire: 10, // Minutes to wait before showing the popup again (0 = always displayed)
message: '', // Customize your message or force a language ('' = automatic)
touchIcon: false, // Display the touch icon
arrow: true, // Display the balloon arrow
hookOnLoad: true, // Should we hook to onload event? (really advanced usage)
closeButton: false, // Let the user close the balloon
iterations: 100 // Internal/debug use
},
intl = {
ar: '<span dir="rtl">قم بتثبيت هذا التطبيق على <span dir="ltr">%device:</span>انقر<span dir="ltr">%icon</span> ،<strong>ثم اضفه الى الشاشة الرئيسية.</strong></span>',
ca_es: 'Per instal·lar aquesta aplicació al vostre %device premeu %icon i llavors <strong>Afegir a pantalla d\'inici</strong>.',
cs_cz: 'Pro instalaci aplikace na Váš %device, stiskněte %icon a v nabídce <strong>Přidat na plochu</strong>.',
da_dk: 'Tilføj denne side til din %device: tryk på %icon og derefter <strong>Føj til hjemmeskærm</strong>.',
de_de: 'Installieren Sie diese App auf Ihrem %device: %icon antippen und dann <strong>Zum Home-Bildschirm</strong>.',
el_gr: 'Εγκαταστήσετε αυτήν την Εφαρμογή στήν συσκευή σας %device: %icon μετά πατάτε <strong>Προσθήκη σε Αφετηρία</strong>.',
en_us: 'Install this web app on your %device: tap %icon and then <strong>Add to Home Screen</strong>.',
es_es: 'Para instalar esta app en su %device, pulse %icon y seleccione <strong>Añadir a pantalla de inicio</strong>.',
fi_fi: 'Asenna tämä web-sovellus laitteeseesi %device: paina %icon ja sen jälkeen valitse <strong>Lisää Koti-valikkoon</strong>.',
fr_fr: 'Ajoutez cette application sur votre %device en cliquant sur %icon, puis <strong>Ajouter à l\'écran d\'accueil</strong>.',
he_il: '<span dir="rtl">התקן אפליקציה זו על ה-%device שלך: הקש %icon ואז <strong>הוסף למסך הבית</strong>.</span>',
hr_hr: 'Instaliraj ovu aplikaciju na svoj %device: klikni na %icon i odaberi <strong>Dodaj u početni zaslon</strong>.',
hu_hu: 'Telepítse ezt a web-alkalmazást az Ön %device-jára: nyomjon a %icon-ra majd a <strong>Főképernyőhöz adás</strong> gombra.',
it_it: 'Installa questa applicazione sul tuo %device: premi su %icon e poi <strong>Aggiungi a Home</strong>.',
ja_jp: 'このウェブアプリをあなたの%deviceにインストールするには%iconをタップして<strong>ホーム画面に追加</strong>を選んでください。',
ko_kr: '%device에 웹앱을 설치하려면 %icon을 터치 후 "홈화면에 추가"를 선택하세요',
nb_no: 'Installer denne appen på din %device: trykk på %icon og deretter <strong>Legg til på Hjem-skjerm</strong>',
nl_nl: 'Installeer deze webapp op uw %device: tik %icon en dan <strong>Voeg toe aan beginscherm</strong>.',
pl_pl: 'Aby zainstalować tę aplikacje na %device: naciśnij %icon a następnie <strong>Dodaj jako ikonę</strong>.',
pt_br: 'Instale este aplicativo em seu %device: aperte %icon e selecione <strong>Adicionar à Tela Inicio</strong>.',
pt_pt: 'Para instalar esta aplicação no seu %device, prima o %icon e depois em <strong>Adicionar ao ecrã principal</strong>.',
ru_ru: 'Установите это веб-приложение на ваш %device: нажмите %icon, затем <strong>Добавить в «Домой»</strong>.',
sv_se: 'Lägg till denna webbapplikation på din %device: tryck på %icon och därefter <strong>Lägg till på hemskärmen</strong>.',
th_th: 'ติดตั้งเว็บแอพฯ นี้บน %device ของคุณ: แตะ %icon และ <strong>เพิ่มที่หน้าจอโฮม</strong>',
tr_tr: 'Bu uygulamayı %device\'a eklemek için %icon simgesine sonrasında <strong>Ana Ekrana Ekle</strong> düğmesine basın.',
uk_ua: 'Встановіть цей веб сайт на Ваш %device: натисніть %icon, а потім <strong>На початковий екран</strong>.',
zh_cn: '您可以将此应用程式安装到您的 %device 上。请按 %icon 然后点选<strong>添加至主屏幕</strong>。',
zh_tw: '您可以將此應用程式安裝到您的 %device 上。請按 %icon 然後點選<strong>加入主畫面螢幕</strong>。'
};
function init () {
// Preliminary check, all further checks are performed on iDevices only
if ( !isIDevice ) return;
var now = Date.now(),
i;
// Merge local with global options
if ( w.addToHomeConfig ) {
for ( i in w.addToHomeConfig ) {
options[i] = w.addToHomeConfig[i];
}
}
if ( !options.autostart ) options.hookOnLoad = false;
isIPad = (/ipad/gi).test(nav.platform);
isRetina = w.devicePixelRatio && w.devicePixelRatio > 1;
isSafari = (/Safari/i).test(nav.appVersion) && !(/CriOS/i).test(nav.appVersion);
isStandalone = nav.standalone;
OSVersion = nav.appVersion.match(/OS (\d+_\d+)/i);
OSVersion = OSVersion && OSVersion[1] ? +OSVersion[1].replace('_', '.') : 0;
lastVisit = +w.localStorage.getItem('addToHome');
isSessionActive = w.sessionStorage.getItem('addToHomeSession');
isReturningVisitor = options.returningVisitor ? lastVisit && lastVisit + 28*24*60*60*1000 > now : true;
if ( !lastVisit ) lastVisit = now;
// If it is expired we need to reissue a new balloon
isExpired = isReturningVisitor && lastVisit <= now;
if ( options.hookOnLoad ) w.addEventListener('load', loaded, false);
else if ( !options.hookOnLoad && options.autostart ) loaded();
}
function loaded () {
w.removeEventListener('load', loaded, false);
if ( !isReturningVisitor ) w.localStorage.setItem('addToHome', Date.now());
else if ( options.expire && isExpired ) w.localStorage.setItem('addToHome', Date.now() + options.expire * 60000);
if ( !overrideChecks && ( !isSafari || !isExpired || isSessionActive || isStandalone || !isReturningVisitor ) ) return;
var touchIcon = '',
platform = nav.platform.split(' ')[0],
language = nav.language.replace('-', '_');
balloon = document.createElement('div');
balloon.id = 'addToHomeScreen';
balloon.style.cssText += 'left:-9999px;-webkit-transition-property:-webkit-transform,opacity;-webkit-transition-duration:0;-webkit-transform:translate3d(0,0,0);position:' + (OSVersion < 5 ? 'absolute' : 'fixed');
// Localize message
if ( options.message in intl ) { // You may force a language despite the user's locale
language = options.message;
options.message = '';
}
if ( options.message === '' ) { // We look for a suitable language (defaulted to en_us)
options.message = language in intl ? intl[language] : intl['en_us'];
}
if ( options.touchIcon ) {
touchIcon = isRetina ?
document.querySelector('head link[rel^=apple-touch-icon][sizes="114x114"],head link[rel^=apple-touch-icon][sizes="144x144"],head link[rel^=apple-touch-icon]') :
document.querySelector('head link[rel^=apple-touch-icon][sizes="57x57"],head link[rel^=apple-touch-icon]');
if ( touchIcon ) {
touchIcon = '<span style="background-image:url(' + touchIcon.href + ')" class="addToHomeTouchIcon"></span>';
}
}
balloon.className = (isIPad ? 'addToHomeIpad' : 'addToHomeIphone') + (touchIcon ? ' addToHomeWide' : '');
balloon.innerHTML = touchIcon +
options.message.replace('%device', platform).replace('%icon', OSVersion >= 4.2 ? '<span class="addToHomeShare' + (OSVersion >= 7 ? ' addToHomeShareOS7' : '') + '"></span>' : '<span class="addToHomePlus">+</span>') +
(options.arrow ? '<span class="addToHomeArrow"></span>' : '') +
(options.closeButton ? '<span class="addToHomeClose">\u00D7</span>' : '');
document.body.appendChild(balloon);
// Add the close action
if ( options.closeButton ) balloon.addEventListener('click', clicked, false);
if ( !isIPad && OSVersion >= 6 ) window.addEventListener('orientationchange', orientationCheck, false);
setTimeout(show, options.startDelay);
}
function show () {
var duration,
iPadXShift = 208;
// Set the initial position
if ( isIPad ) {
if ( OSVersion < 5 ) {
startY = w.scrollY;
startX = w.scrollX;
} else if ( OSVersion < 6 ) {
iPadXShift = 160;
}
balloon.style.top = startY + options.bottomOffset + 'px';
balloon.style.left = startX + iPadXShift - Math.round(balloon.offsetWidth / 2) + 'px';
switch ( options.animationIn ) {
case 'drop':
duration = '0.6s';
balloon.style.webkitTransform = 'translate3d(0,' + -(w.scrollY + options.bottomOffset + balloon.offsetHeight) + 'px,0)';
break;
case 'bubble':
duration = '0.6s';
balloon.style.opacity = '0';
balloon.style.webkitTransform = 'translate3d(0,' + (startY + 50) + 'px,0)';
break;
default:
duration = '1s';
balloon.style.opacity = '0';
}
} else {
startY = w.innerHeight + w.scrollY;
if ( OSVersion < 5 ) {
startX = Math.round((w.innerWidth - balloon.offsetWidth) / 2) + w.scrollX;
balloon.style.left = startX + 'px';
balloon.style.top = startY - balloon.offsetHeight - options.bottomOffset + 'px';
} else {
balloon.style.left = '50%';
balloon.style.marginLeft = -Math.round(balloon.offsetWidth / 2) - ( w.orientation%180 && OSVersion >= 6 ? 40 : 0 ) + 'px';
balloon.style.bottom = options.bottomOffset + 'px';
}
switch (options.animationIn) {
case 'drop':
duration = '1s';
balloon.style.webkitTransform = 'translate3d(0,' + -(startY + options.bottomOffset) + 'px,0)';
break;
case 'bubble':
duration = '0.6s';
balloon.style.webkitTransform = 'translate3d(0,' + (balloon.offsetHeight + options.bottomOffset + 50) + 'px,0)';
break;
default:
duration = '1s';
balloon.style.opacity = '0';
}
}
balloon.offsetHeight; // repaint trick
balloon.style.webkitTransitionDuration = duration;
balloon.style.opacity = '1';
balloon.style.webkitTransform = 'translate3d(0,0,0)';
balloon.addEventListener('webkitTransitionEnd', transitionEnd, false);
closeTimeout = setTimeout(close, options.lifespan);
}
function manualShow (override) {
if ( !isIDevice || balloon ) return;
overrideChecks = override;
loaded();
}
function close () {
clearInterval( positionInterval );
clearTimeout( closeTimeout );
closeTimeout = null;
// check if the popup is displayed and prevent errors
if ( !balloon ) return;
var posY = 0,
posX = 0,
opacity = '1',
duration = '0';
if ( options.closeButton ) balloon.removeEventListener('click', clicked, false);
if ( !isIPad && OSVersion >= 6 ) window.removeEventListener('orientationchange', orientationCheck, false);
if ( OSVersion < 5 ) {
posY = isIPad ? w.scrollY - startY : w.scrollY + w.innerHeight - startY;
posX = isIPad ? w.scrollX - startX : w.scrollX + Math.round((w.innerWidth - balloon.offsetWidth)/2) - startX;
}
balloon.style.webkitTransitionProperty = '-webkit-transform,opacity';
switch ( options.animationOut ) {
case 'drop':
if ( isIPad ) {
duration = '0.4s';
opacity = '0';
posY += 50;
} else {
duration = '0.6s';
posY += balloon.offsetHeight + options.bottomOffset + 50;
}
break;
case 'bubble':
if ( isIPad ) {
duration = '0.8s';
posY -= balloon.offsetHeight + options.bottomOffset + 50;
} else {
duration = '0.4s';
opacity = '0';
posY -= 50;
}
break;
default:
duration = '0.8s';
opacity = '0';
}
balloon.addEventListener('webkitTransitionEnd', transitionEnd, false);
balloon.style.opacity = opacity;
balloon.style.webkitTransitionDuration = duration;
balloon.style.webkitTransform = 'translate3d(' + posX + 'px,' + posY + 'px,0)';
}
function clicked () {
w.sessionStorage.setItem('addToHomeSession', '1');
isSessionActive = true;
close();
}
function transitionEnd () {
balloon.removeEventListener('webkitTransitionEnd', transitionEnd, false);
balloon.style.webkitTransitionProperty = '-webkit-transform';
balloon.style.webkitTransitionDuration = '0.2s';
// We reached the end!
if ( !closeTimeout ) {
balloon.parentNode.removeChild(balloon);
balloon = null;
return;
}
// On iOS 4 we start checking the element position
if ( OSVersion < 5 && closeTimeout ) positionInterval = setInterval(setPosition, options.iterations);
}
function setPosition () {
var matrix = new WebKitCSSMatrix(w.getComputedStyle(balloon, null).webkitTransform),
posY = isIPad ? w.scrollY - startY : w.scrollY + w.innerHeight - startY,
posX = isIPad ? w.scrollX - startX : w.scrollX + Math.round((w.innerWidth - balloon.offsetWidth) / 2) - startX;
// Screen didn't move
if ( posY == matrix.m42 && posX == matrix.m41 ) return;
balloon.style.webkitTransform = 'translate3d(' + posX + 'px,' + posY + 'px,0)';
}
// Clear local and session storages (this is useful primarily in development)
function reset () {
w.localStorage.removeItem('addToHome');
w.sessionStorage.removeItem('addToHomeSession');
}
function orientationCheck () {
balloon.style.marginLeft = -Math.round(balloon.offsetWidth / 2) - ( w.orientation%180 && OSVersion >= 6 ? 40 : 0 ) + 'px';
}
// Bootstrap!
init();
return {
show: manualShow,
close: close,
reset: reset
};
})(window);
|
var HandlebarsLayouts = require('handlebars-layouts');
var moment = require('moment');
module.exports = function(Handlebars) {
Handlebars.registerHelper(HandlebarsLayouts(Handlebars));
Handlebars.registerHelper('json', function(obj) {
return JSON.stringify(obj);
});
Handlebars.registerHelper('removeIndex', function(url) {
return url.replace('index.html', '');
});
Handlebars.registerHelper('formatDate', function(context, options) {
var format = options.hash.format || "YYYY-MM-DD";
if (context === "now") {
context = new Date();
}
return moment(context).format(format);
});
};
|
/*!
* jQuery JavaScript Library v1.10.0 -wrap,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-offset
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-26T21:58Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.0 -wrap,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-offset",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.9.4-pre
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-15
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function() { return 0; },
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied if the test fails
* @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler
*/
function addHandle( attrs, handler, test ) {
attrs = attrs.split("|");
var current,
i = attrs.length,
setHandle = test ? null : handler;
while ( i-- ) {
// Don't override a user's handler
if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) {
Expr.attrHandle[ attrs[i] ] = setHandle;
}
}
}
/**
* Fetches boolean attributes by node
* @param {Element} elem
* @param {String} name
*/
function boolHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
var val = elem.getAttributeNode( name );
return val && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
/**
* Fetches attributes without interpolation
* http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
* @param {Element} elem
* @param {String} name
*/
function interpolationHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
/**
* Uses defaultValue to retrieve value in IE6/7
* @param {Element} elem
* @param {String} name
*/
function valueHandler( elem ) {
// Ignore the value *property* on inputs by using defaultValue
// Fallback to Sizzle.attr by returning undefined where appropriate
// XML does not need to be checked as this will not be assigned for XML documents
if ( elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns Returns -1 if a precedes b, 1 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
// Support: IE<8
// Prevent attribute/property "interpolation"
div.innerHTML = "<a href='#'></a>";
addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" );
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
addHandle( booleans, boolHandler, div.getAttribute("disabled") == null );
div.className = "i";
return !div.getAttribute("className");
});
// Support: IE<9
// Retrieving value should defer to defaultValue
support.input = assert(function( div ) {
div.innerHTML = "<input>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
});
// IE6/7 still return empty string for value,
// but are actually retrieving the property
addHandle( "value", valueHandler, support.attributes && support.input );
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( doc.createElement("div") ) & 1;
});
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined );
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Initialize against the default document
setDocument();
// Support: Chrome<<14
// Always assume duplicates if they aren't passed to the comparison function
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Finish early in limited (non-browser) environments
all = div.getElementsByTagName("*") || [];
a = div.getElementsByTagName("a")[ 0 ];
if ( !a || !a.style || !all.length ) {
return support;
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName("tbody").length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName("link").length;
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Will be defined later
support.inlineBlockNeedsLayout = false;
support.shrinkWrapBlocks = false;
support.pixelPosition = false;
support.deleteExpando = true;
support.noCloneEvent = true;
support.reliableMarginRight = true;
support.boxSizingReliable = true;
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: IE<9
// Iteration over object's inherited properties before its own.
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior.
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})({});
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"applet": true,
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
data = null,
i = 0,
elem = this[0];
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = ret.push( cur );
break;
}
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
tween.unit = unit;
tween.start = +start || +target || 0;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
doAnimation.finish = function() {
anim.stop( true );
};
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.cur && hooks.cur.finish ) {
hooks.cur.finish.call( this );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
})( window );
|
var app = angular.module('perf', ['ngBench'])
.directive('noopDir', function() {
return {
compile: function($element, $attrs) {
return function($scope, $element) {
return 1;
}
}
};
})
app.directive('nativeClick', ['$parse', function($parse) {
return {
compile: function($element, $attrs) {
var expr = $parse($attrs.tstEvent);
return function($scope, $element) {
$element[0].addEventListener('click', function() {
console.log('clicked');
}, false);
}
}
};
}])
.directive('dlgtClick', function() {
return {
compile: function($element, $attrs) {
var evt = $attrs.dlgtClick;
// We don't setup the global event listeners as the costs are small and one time only...
}
};
})
.controller('MainCtrl', ['$compile', '$rootScope', '$templateCache',
function($compile, $rootScope, $templateCache) {
// TODO: Make ngRepeatCount configurable via the UI!
var self = this;
this.ngRepeatCount = 20;
this.manualRepeatCount = 5;
this.benchmarks = [{
title: 'ng-click',
factory: function() {
return createBenchmark({
directive: 'ng-click="a()"'
});
},
active: true
},{
title: 'ng-click without jqLite',
factory: function() {
return createBenchmark({
directive: 'native-click="a()"'
});
},
active: true
},{
title: 'baseline: ng-show',
factory: function() {
return createBenchmark({
directive: 'ng-show="true"'
});
},
active: true
},{
title: 'baseline: text interpolation',
factory: function() {
return createBenchmark({
text: '{{row}}'
});
},
active: true
},{
title: 'delegate event directive (only compile)',
factory: function() {
return createBenchmark({
directive: 'dlgt-click="a()"'
});
},
active: true
},{
title: 'baseline: noop directive (compile and link)',
factory: function() {
return createBenchmark({
directive: 'noop-dir'
});
},
active: true
},{
title: 'baseline: no directive',
factory: function() {
return createBenchmark({});
},
active: true
}];
function createBenchmark(options) {
options.directive = options.directive || '';
options.text = options.text || '';
var templateHtml = '<div><span ng-repeat="row in rows">';
for (var i=0; i<self.manualRepeatCount; i++) {
templateHtml += '<span '+options.directive+'>'+options.text+'</span>';
}
templateHtml += '</span></div>';
var compiledTemplate = $compile(templateHtml);
var rows = [];
for (var i=0; i<self.ngRepeatCount; i++) {
rows.push('row'+i);
}
return function(container) {
var scope = $rootScope.$new();
try {
scope.rows = rows;
compiledTemplate(scope, function(clone) {
container.appendChild(clone[0]);
});
scope.$digest();
} finally {
scope.$destroy();
}
}
}
}])
|
#pragma strict
var key : String;
var input : InputItem;
function UpdateInput () {
//Just get the axis value from Unity's input
input.axis = Input.GetAxisRaw(key);
}
|
define([
'bluebird',
'common/runtime',
'kb_common/html',
'common/format'
], function (
Promise,
Runtime,
html,
format
) {
var t = html.tag,
span = t('span');
function factory(config) {
var config = config || {},
container,
runtime = Runtime.make(),
busConnection = runtime.bus().connect(),
channel = busConnection.channel('default'),
clockId = html.genId(),
startTime;
function buildLayout() {
return span({
id: clockId,
style: {}
});
}
function renderClock() {
if (!startTime) {
return;
}
var now = new Date(),
elapsed = now.getTime() - startTime;
var clockNode = document.getElementById(clockId);
if (config.on && config.on.tick) {
try {
var result = config.on.tick(elapsed);
clockNode.innerHTML = result.content;
if (result.stop) {
busConnection.stop();
}
} catch (err) {
console.error('Error handling clock tick, closing clock', err);
stop();
}
} else {
if (!clockNode) {
console.warn('Could not find clock node at' + clockId, 'Stopping the clock');
stop();
return;
}
clockNode.innerHTML = [config.prefix || '', format.niceDuration(elapsed), config.suffix || ''].join('');
}
}
function start(arg) {
return Promise.try(function () {
container = arg.node;
var layout = buildLayout();
container.innerHTML = layout;
startTime = arg.startTime;
channel.on('clock-tick', function () {
renderClock();
});
});
}
function stop() {
return Promise.try(function () {
busConnection.stop();
});
}
return {
start: start,
stop: stop
};
}
return {
make: function (config) {
return factory(config);
}
};
});
|
'use strict';
var XOAuth2 = require('../../../../lib/authentication/xoauth2')
var mech = new XOAuth2()
require('should')
/* jshint -W030 */
/* jshint -W106 */
describe('XOAuth2 authentication', function() {
describe('Detect SASL mechanisms', function() {
it('Should return false if \'oauth2_auth\' property doesn\'t exist', function() {
var options = {}
mech.match(options).should.equal(false)
})
it('Should return false if \'oauth2_auth\' does not have correct value', function() {
var options = { oauth2_auth: 'oauth2_auth' }
mech.match(options).should.equal(false)
})
it('Should return true if \'oauth2_auth\' has correct value', function() {
var options = { oauth2_auth: mech.NS_GOOGLE_AUTH }
mech.match(options).should.equal(true)
})
})
})
|
/**
* Copyright (c) 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.
*
* @providesModule UserAgent_DEPRECATED
*/
/**
* Provides entirely client-side User Agent and OS detection. You should prefer
* the non-deprecated UserAgent module when possible, which exposes our
* authoritative server-side PHP-based detection to the client.
*
* Usage is straightforward:
*
* if (UserAgent_DEPRECATED.ie()) {
* // IE
* }
*
* You can also do version checks:
*
* if (UserAgent_DEPRECATED.ie() >= 7) {
* // IE7 or better
* }
*
* The browser functions will return NaN if the browser does not match, so
* you can also do version compares the other way:
*
* if (UserAgent_DEPRECATED.ie() < 7) {
* // IE6 or worse
* }
*
* Note that the version is a float and may include a minor version number,
* so you should always use range operators to perform comparisons, not
* strict equality.
*
* **Note:** You should **strongly** prefer capability detection to browser
* version detection where it's reasonable:
*
* http://www.quirksmode.org/js/support.html
*
* Further, we have a large number of mature wrapper functions and classes
* which abstract away many browser irregularities. Check the documentation,
* grep for things, or ask on javascript@lists.facebook.com before writing yet
* another copy of "event || window.event".
*
*/
var _populated = false;
// Browsers
var _ie, _firefox, _opera, _webkit, _chrome;
// Actual IE browser for compatibility mode
var _ie_real_version;
// Platforms
var _osx, _windows, _linux, _android;
// Architectures
var _win64;
// Devices
var _iphone, _ipad, _native;
var _mobile;
function _populate() {
if (_populated) {
return;
}
_populated = true;
// To work around buggy JS libraries that can't handle multi-digit
// version numbers, Opera 10's user agent string claims it's Opera
// 9, then later includes a Version/X.Y field:
//
// Opera/9.80 (foo) Presto/2.2.15 Version/10.10
var uas = navigator.userAgent;
var agent = /(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(uas);
var os = /(Mac OS X)|(Windows)|(Linux)/.exec(uas);
_iphone = /\b(iPhone|iP[ao]d)/.exec(uas);
_ipad = /\b(iP[ao]d)/.exec(uas);
_android = /Android/i.exec(uas);
_native = /FBAN\/\w+;/i.exec(uas);
_mobile = /Mobile/i.exec(uas);
// Note that the IE team blog would have you believe you should be checking
// for 'Win64; x64'. But MSDN then reveals that you can actually be coming
// from either x64 or ia64; so ultimately, you should just check for Win64
// as in indicator of whether you're in 64-bit IE. 32-bit IE on 64-bit
// Windows will send 'WOW64' instead.
_win64 = !!(/Win64/.exec(uas));
if (agent) {
_ie = agent[1] ? parseFloat(agent[1]) : (
agent[5] ? parseFloat(agent[5]) : NaN);
// IE compatibility mode
if (_ie && document && document.documentMode) {
_ie = document.documentMode;
}
// grab the "true" ie version from the trident token if available
var trident = /(?:Trident\/(\d+.\d+))/.exec(uas);
_ie_real_version = trident ? parseFloat(trident[1]) + 4 : _ie;
_firefox = agent[2] ? parseFloat(agent[2]) : NaN;
_opera = agent[3] ? parseFloat(agent[3]) : NaN;
_webkit = agent[4] ? parseFloat(agent[4]) : NaN;
if (_webkit) {
// We do not add the regexp to the above test, because it will always
// match 'safari' only since 'AppleWebKit' appears before 'Chrome' in
// the userAgent string.
agent = /(?:Chrome\/(\d+\.\d+))/.exec(uas);
_chrome = agent && agent[1] ? parseFloat(agent[1]) : NaN;
} else {
_chrome = NaN;
}
} else {
_ie = _firefox = _opera = _chrome = _webkit = NaN;
}
if (os) {
if (os[1]) {
// Detect OS X version. If no version number matches, set _osx to true.
// Version examples: 10, 10_6_1, 10.7
// Parses version number as a float, taking only first two sets of
// digits. If only one set of digits is found, returns just the major
// version number.
var ver = /(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(uas);
_osx = ver ? parseFloat(ver[1].replace('_', '.')) : true;
} else {
_osx = false;
}
_windows = !!os[2];
_linux = !!os[3];
} else {
_osx = _windows = _linux = false;
}
}
var UserAgent_DEPRECATED = {
/**
* Check if the UA is Internet Explorer.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
ie: function() {
return _populate() || _ie;
},
/**
* Check if we're in Internet Explorer compatibility mode.
*
* @return bool true if in compatibility mode, false if
* not compatibility mode or not ie
*/
ieCompatibilityMode: function() {
return _populate() || (_ie_real_version > _ie);
},
/**
* Whether the browser is 64-bit IE. Really, this is kind of weak sauce; we
* only need this because Skype can't handle 64-bit IE yet. We need to remove
* this when we don't need it -- tracked by #601957.
*/
ie64: function() {
return UserAgent_DEPRECATED.ie() && _win64;
},
/**
* Check if the UA is Firefox.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
firefox: function() {
return _populate() || _firefox;
},
/**
* Check if the UA is Opera.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
opera: function() {
return _populate() || _opera;
},
/**
* Check if the UA is WebKit.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
webkit: function() {
return _populate() || _webkit;
},
/**
* For Push
* WILL BE REMOVED VERY SOON. Use UserAgent_DEPRECATED.webkit
*/
safari: function() {
return UserAgent_DEPRECATED.webkit();
},
/**
* Check if the UA is a Chrome browser.
*
*
* @return float|NaN Version number (if match) or NaN.
*/
chrome : function() {
return _populate() || _chrome;
},
/**
* Check if the user is running Windows.
*
* @return bool `true' if the user's OS is Windows.
*/
windows: function() {
return _populate() || _windows;
},
/**
* Check if the user is running Mac OS X.
*
* @return float|bool Returns a float if a version number is detected,
* otherwise true/false.
*/
osx: function() {
return _populate() || _osx;
},
/**
* Check if the user is running Linux.
*
* @return bool `true' if the user's OS is some flavor of Linux.
*/
linux: function() {
return _populate() || _linux;
},
/**
* Check if the user is running on an iPhone or iPod platform.
*
* @return bool `true' if the user is running some flavor of the
* iPhone OS.
*/
iphone: function() {
return _populate() || _iphone;
},
mobile: function() {
return _populate() || (_iphone || _ipad || _android || _mobile);
},
nativeApp: function() {
// webviews inside of the native apps
return _populate() || _native;
},
android: function() {
return _populate() || _android;
},
ipad: function() {
return _populate() || _ipad;
}
};
module.exports = UserAgent_DEPRECATED;
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _gracefulFs;
function _load_gracefulFs() {
return (_gracefulFs = _interopRequireDefault(require('graceful-fs')));
}
var _callsites;
function _load_callsites() {
return (_callsites = _interopRequireDefault(require('callsites')));
}
var _sourceMap;
function _load_sourceMap() {
return (_sourceMap = require('source-map'));
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
// Copied from https://github.com/rexxars/sourcemap-decorate-callsites/blob/5b9735a156964973a75dc62fd2c7f0c1975458e8/lib/index.js#L113-L158
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
const addSourceMapConsumer = (callsite, consumer) => {
const getLineNumber = callsite.getLineNumber;
const getColumnNumber = callsite.getColumnNumber;
let position = null;
function getPosition() {
if (!position) {
position = consumer.originalPositionFor({
column: getColumnNumber.call(callsite),
line: getLineNumber.call(callsite)
});
}
return position;
}
Object.defineProperties(callsite, {
getColumnNumber: {
value: function() {
return getPosition().column || getColumnNumber.call(callsite);
},
writable: false
},
getLineNumber: {
value: function() {
return getPosition().line || getLineNumber.call(callsite);
},
writable: false
}
});
};
exports.default = (level, sourceMaps) => {
const levelAfterThisCall = level + 1;
const stack = (0, (_callsites || _load_callsites()).default)()[
levelAfterThisCall
];
const sourceMapFileName = sourceMaps && sourceMaps[stack.getFileName()];
if (sourceMapFileName) {
try {
const sourceMap = (
_gracefulFs || _load_gracefulFs()
).default.readFileSync(sourceMapFileName, 'utf8');
addSourceMapConsumer(
stack,
new (_sourceMap || _load_sourceMap()).SourceMapConsumer(sourceMap)
);
} catch (e) {
// ignore
}
}
return stack;
};
|
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<828a9eaf11630242cd7ab3fe95dfdb7a>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable */
'use strict';
/*::
import type { ConcreteRequest, Query } from 'relay-runtime';
type RelayMockPayloadGeneratorTest20Fragment$fragmentType = any;
export type RelayMockPayloadGeneratorTest17Query$variables = {||};
export type RelayMockPayloadGeneratorTest17Query$data = {|
+node: ?{|
+$fragmentSpreads: RelayMockPayloadGeneratorTest20Fragment$fragmentType,
|},
|};
export type RelayMockPayloadGeneratorTest17Query = {|
variables: RelayMockPayloadGeneratorTest17Query$variables,
response: RelayMockPayloadGeneratorTest17Query$data,
|};
*/
var node/*: ConcreteRequest*/ = (function(){
var v0 = [
{
"kind": "Literal",
"name": "id",
"value": "my-id"
}
],
v1 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "RelayMockPayloadGeneratorTest17Query",
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "RelayMockPayloadGeneratorTest20Fragment"
}
],
"storageKey": "node(id:\"my-id\")"
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "RelayMockPayloadGeneratorTest17Query",
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v1/*: any*/),
(v2/*: any*/),
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Text",
"kind": "LinkedField",
"name": "body",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "text",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "actor",
"plural": false,
"selections": [
(v1/*: any*/),
(v3/*: any*/),
(v2/*: any*/)
],
"storageKey": null
},
{
"alias": "myActor",
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "actor",
"plural": false,
"selections": [
(v1/*: any*/),
(v2/*: any*/),
{
"kind": "InlineFragment",
"selections": [
{
"alias": "pageName",
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
}
],
"type": "Page",
"abstractKey": null
}
],
"storageKey": null
},
(v3/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "username",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "profile_picture",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "uri",
"storageKey": null
}
],
"storageKey": null
}
],
"type": "User",
"abstractKey": null
}
],
"storageKey": "node(id:\"my-id\")"
}
]
},
"params": {
"cacheID": "f650620f2370783134ce97a6e17e3790",
"id": null,
"metadata": {},
"name": "RelayMockPayloadGeneratorTest17Query",
"operationKind": "query",
"text": "query RelayMockPayloadGeneratorTest17Query {\n node(id: \"my-id\") {\n __typename\n ...RelayMockPayloadGeneratorTest20Fragment\n id\n }\n}\n\nfragment RelayMockPayloadGeneratorTest17Fragment on Page {\n id\n pageName: name\n}\n\nfragment RelayMockPayloadGeneratorTest18Fragment on User {\n id\n name\n username\n}\n\nfragment RelayMockPayloadGeneratorTest19Fragment on User {\n ...RelayMockPayloadGeneratorTest18Fragment\n profile_picture {\n uri\n }\n}\n\nfragment RelayMockPayloadGeneratorTest20Fragment on User {\n body {\n text\n }\n actor {\n __typename\n name\n id\n }\n myActor: actor {\n __typename\n ...RelayMockPayloadGeneratorTest17Fragment\n id\n }\n ...RelayMockPayloadGeneratorTest18Fragment\n ...RelayMockPayloadGeneratorTest19Fragment\n}\n"
}
};
})();
if (__DEV__) {
(node/*: any*/).hash = "0b3d641ae5319ba8c18ea9bdc28f596a";
}
module.exports = ((node/*: any*/)/*: Query<
RelayMockPayloadGeneratorTest17Query$variables,
RelayMockPayloadGeneratorTest17Query$data,
>*/);
|
/**
* Copyright (c) 2008-2011 The Open Planning Project
*
* Published under the BSD license.
* See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
* of the license.
*/
/**
* @requires plugins/Tool.js
* @requires widgets/WMSStylesDialog.js
*/
/** api: (define)
* module = gxp.plugins
* class = Styler
*/
/** api: (extends)
* plugins/Tool.js
*/
Ext.namespace("gxp.plugins");
/** api: constructor
* .. class:: Styler(config)
*
* Plugin providing a styles editing dialog for geoserver layers.
*/
gxp.plugins.Styler = Ext.extend(gxp.plugins.Tool, {
/** api: ptype = gxp_styler */
ptype: "gxp_styler",
/** api: config[menuText]
* ``String``
* Text for layer properties menu item (i18n).
*/
menuText: "Edit Styles",
/** api: config[tooltip]
* ``String``
* Text for layer properties action tooltip (i18n).
*/
tooltip: "Manage layer styles",
/** api: config[sameOriginStyling]
* ``Boolean``
* Only allow editing of styles for layers whose sources have a URL that
* matches the origin of this applicaiton. It is strongly discouraged to
* do styling through commonly used proxies as all authorization headers
* and cookies are shared with all remote sources. Default is ``true``.
*/
sameOriginStyling: true,
/** api: config[rasterStyling]
* ``Boolean`` If set to true, single-band raster styling will be
* supported. Default is ``false``.
*/
rasterStyling: false,
constructor: function(config) {
gxp.plugins.Styler.superclass.constructor.apply(this, arguments);
if (!this.outputConfig) {
this.outputConfig = {
autoHeight: true,
width: 265
};
}
Ext.applyIf(this.outputConfig, {
closeAction: "close"
});
},
/** api: method[addActions]
*/
addActions: function() {
var layerProperties;
var actions = gxp.plugins.Styler.superclass.addActions.apply(this, [{
menuText: this.menuText,
iconCls: "gxp-icon-palette",
disabled: true,
tooltip: this.tooltip,
handler: function() {
this.addOutput();
},
scope: this
}]);
this.launchAction = actions[0];
this.target.on({
layerselectionchange: this.handleLayerChange,
scope: this
});
return actions;
},
/** private: method[handleLayerChange]
* :arg record: ``GeoExt.data.LayerRecord``
*
* Handle changes to the target viewer's selected layer.
*/
handleLayerChange: function(record) {
this.launchAction.disable();
if (record && record.get("styles")) {
var source = this.target.getSource(record);
if (source instanceof gxp.plugins.WMSSource) {
source.describeLayer(record, function(describeRec) {
this.checkIfStyleable(record, describeRec);
}, this);
}
}
},
/** private: method[checkIfStyleable]
* :arg layerRec: ``GeoExt.data.LayerRecord``
* :arg describeRec: ``Ext.data.Record`` Record from a
* `GeoExt.data.DescribeLayerStore``.
*
* Given a layer record and the corresponding describe layer record,
* determine if the target layer can be styled. If so, enable the launch
* action.
*/
checkIfStyleable: function(layerRec, describeRec) {
var owsTypes = ["WFS"];
if (this.rasterStyling === true) {
owsTypes.push("WCS");
}
if (describeRec && owsTypes.indexOf(describeRec.get("owsType")) !== -1) {
var editableStyles = false;
var source = this.target.layerSources[layerRec.get("source")];
var url = source.url.split("?")
.shift().replace(/\/(wms|ows)\/?$/, "/rest/styles");
if (this.sameOriginStyling) {
// this could be made more robust
// for now, only style for sources with relative url
editableStyles = url.charAt(0) === "/";
} else {
editableStyles = true;
}
if (editableStyles) {
if (this.target.isAuthorized()) {
// check if service is available
this.enableActionIfAvailable(url);
}
}
}
},
/** private: method[enableActionIfAvailable]
* :arg url: ``String`` URL of style service
*
* Enable the launch action if the service is available.
*/
enableActionIfAvailable: function(url) {
Ext.Ajax.request({
method: "PUT",
url: url,
callback: function(options, success, response) {
// we expect a 405 error code here if we are dealing
// with GeoServer and have write access.
this.launchAction.setDisabled(response.status !== 405);
},
scope: this
});
},
addOutput: function(config) {
config = config || {};
var record = this.target.selectedLayer;
var origCfg = this.initialConfig.outputConfig || {};
this.outputConfig.title = origCfg.title ||
this.menuText + ": " + record.get("title");
Ext.apply(config, gxp.WMSStylesDialog.createGeoServerStylerConfig(record));
if (this.rasterStyling === true) {
config.plugins.push({
ptype: "gxp_wmsrasterstylesdialog"
});
}
Ext.applyIf(config, {style: "padding: 10px"});
var output = gxp.plugins.Styler.superclass.addOutput.call(this, config);
output.stylesStore.on("load", function() {
this.outputTarget || output.ownerCt.ownerCt.center();
});
}
});
Ext.preg(gxp.plugins.Styler.prototype.ptype, gxp.plugins.Styler);
|
// eslint-disable-next-line import/prefer-default-export
export { default as InjectionZone } from './InjectionZone';
|
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v19.1.4
* @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 gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var expressionService_1 = require("../valueService/expressionService");
var ValueFormatterService = /** @class */ (function () {
function ValueFormatterService() {
}
ValueFormatterService.prototype.formatValue = function (column, rowNode, $scope, value) {
var formatter;
var colDef = column.getColDef();
// if floating, give preference to the floating formatter
if (rowNode && rowNode.rowPinned) {
formatter = colDef.pinnedRowValueFormatter ? colDef.pinnedRowValueFormatter : colDef.valueFormatter;
}
else {
formatter = colDef.valueFormatter;
}
var result = null;
if (formatter) {
var params = {
value: value,
node: rowNode,
data: rowNode ? rowNode.data : null,
colDef: column.getColDef(),
column: column,
api: this.gridOptionsWrapper.getApi(),
columnApi: this.gridOptionsWrapper.getColumnApi(),
context: this.gridOptionsWrapper.getContext()
};
// originally we put the angular 1 scope here, but we don't want the scope
// in the params interface, as other frameworks will see the interface, and
// angular 1 is not cool any more. so we hack the scope in here (we cannot
// include it above, as it's not in the interface, so would cause a compile error).
// in the future, when we stop supporting angular 1, we can take this out.
params.$scope = $scope;
result = this.expressionService.evaluate(formatter, params);
}
else if (colDef.refData) {
return colDef.refData[value];
}
// if we don't do this, then arrays get displayed as 1,2,3, but we want 1, 2, 3 (ie with spaces)
if ((result === null || result === undefined) && Array.isArray(value)) {
result = value.join(', ');
}
return result;
};
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], ValueFormatterService.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('expressionService'),
__metadata("design:type", expressionService_1.ExpressionService)
], ValueFormatterService.prototype, "expressionService", void 0);
ValueFormatterService = __decorate([
context_1.Bean('valueFormatterService')
], ValueFormatterService);
return ValueFormatterService;
}());
exports.ValueFormatterService = ValueFormatterService;
|
/*!
* Vue.js v2.6.1
* (c) 2014-2019 Evan You
* Released under the MIT License.
*/
/* */
const emptyObject = Object.freeze({});
// These helpers produce better VM code in JS engines due to their
// explicitness and function inlining.
function isUndef (v) {
return v === undefined || v === null
}
function isDef (v) {
return v !== undefined && v !== null
}
function isTrue (v) {
return v === true
}
function isFalse (v) {
return v === false
}
/**
* Check if value is primitive.
*/
function isPrimitive (value) {
return (
typeof value === 'string' ||
typeof value === 'number' ||
// $flow-disable-line
typeof value === 'symbol' ||
typeof value === 'boolean'
)
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Get the raw type string of a value, e.g., [object Object].
*/
const _toString = Object.prototype.toString;
function toRawType (value) {
return _toString.call(value).slice(8, -1)
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
function isPlainObject (obj) {
return _toString.call(obj) === '[object Object]'
}
function isRegExp (v) {
return _toString.call(v) === '[object RegExp]'
}
/**
* Check if val is a valid array index.
*/
function isValidArrayIndex (val) {
const n = parseFloat(String(val));
return n >= 0 && Math.floor(n) === n && isFinite(val)
}
function isPromise (val) {
return (
isDef(val) &&
typeof val.then === 'function' &&
typeof val.catch === 'function'
)
}
/**
* Convert a value to a string that is actually rendered.
*/
function toString (val) {
return val == null
? ''
: Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert an input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
const n = parseFloat(val);
return isNaN(n) ? val : n
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
const map = Object.create(null);
const list = str.split(',');
for (let i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? val => map[val.toLowerCase()]
: val => map[val]
}
/**
* Check if a tag is a built-in tag.
*/
const isBuiltInTag = makeMap('slot,component', true);
/**
* Check if an attribute is a reserved attribute.
*/
const isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
/**
* Remove an item from an array.
*/
function remove (arr, item) {
if (arr.length) {
const index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether an object has the property.
*/
const hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
const cache = Object.create(null);
return (function cachedFn (str) {
const hit = cache[str];
return hit || (cache[str] = fn(str))
})
}
/**
* Camelize a hyphen-delimited string.
*/
const camelizeRE = /-(\w)/g;
const camelize = cached((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
});
/**
* Capitalize a string.
*/
const capitalize = cached((str) => {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
const hyphenateRE = /\B([A-Z])/g;
const hyphenate = cached((str) => {
return str.replace(hyphenateRE, '-$1').toLowerCase()
});
/**
* Simple bind polyfill for environments that do not support it,
* e.g., PhantomJS 1.x. Technically, we don't need this anymore
* since native bind is now performant enough in most browsers.
* But removing it would mean breaking code that was able to run in
* PhantomJS 1.x, so this must be kept for backward compatibility.
*/
/* istanbul ignore next */
function polyfillBind (fn, ctx) {
function boundFn (a) {
const l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
boundFn._length = fn.length;
return boundFn
}
function nativeBind (fn, ctx) {
return fn.bind(ctx)
}
const bind = Function.prototype.bind
? nativeBind
: polyfillBind;
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
let i = list.length - start;
const ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (const key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
const res = {};
for (let i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/* eslint-disable no-unused-vars */
/**
* Perform no operation.
* Stubbing args to make Flow happy without leaving useless transpiled code
* with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).
*/
function noop (a, b, c) {}
/**
* Always return false.
*/
const no = (a, b, c) => false;
/* eslint-enable no-unused-vars */
/**
* Return the same value.
*/
const identity = (_) => _;
/**
* Generate a string containing static keys from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce((keys, m) => {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
if (a === b) return true
const isObjectA = isObject(a);
const isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
const isArrayA = Array.isArray(a);
const isArrayB = Array.isArray(b);
if (isArrayA && isArrayB) {
return a.length === b.length && a.every((e, i) => {
return looseEqual(e, b[i])
})
} else if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime()
} else if (!isArrayA && !isArrayB) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(key => {
return looseEqual(a[key], b[key])
})
} else {
/* istanbul ignore next */
return false
}
} catch (e) {
/* istanbul ignore next */
return false
}
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
/**
* Return the first index at which a loosely equal value can be
* found in the array (if value is a plain object, the array must
* contain an object of the same shape), or -1 if it is not present.
*/
function looseIndexOf (arr, val) {
for (let i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) return i
}
return -1
}
/**
* Ensure a function is called only once.
*/
function once (fn) {
let called = false;
return function () {
if (!called) {
called = true;
fn.apply(this, arguments);
}
}
}
const SSR_ATTR = 'data-server-rendered';
const ASSET_TYPES = [
'component',
'directive',
'filter'
];
const LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated',
'errorCaptured',
'serverPrefetch'
];
/* */
var config = ({
/**
* Option merge strategies (used in core/util/options)
*/
// $flow-disable-line
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Show production mode tip message on boot?
*/
productionTip: "development" !== 'production',
/**
* Whether to enable devtools
*/
devtools: "development" !== 'production',
/**
* Whether to record perf
*/
performance: false,
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Warn handler for watcher warns
*/
warnHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
// $flow-disable-line
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if an attribute is reserved so that it cannot be used as a component
* prop. This is platform-dependent and may be overwritten.
*/
isReservedAttr: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* Perform updates asynchronously. Intended to be used by Vue Test Utils
* This will significantly reduce performance if set to false.
*/
async: true,
/**
* Exposed for legacy reasons
*/
_lifecycleHooks: LIFECYCLE_HOOKS
});
/* */
/**
* unicode letters used for parsing html tags, component names and property paths.
* using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname
* skipping \u10000-\uEFFFF due to it freezing up PhantomJS
*/
const unicodeLetters = 'a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD';
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
const c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
const bailRE = new RegExp(`[^${unicodeLetters}.$_\\d]`);
function parsePath (path) {
if (bailRE.test(path)) {
return
}
const segments = path.split('.');
return function (obj) {
for (let i = 0; i < segments.length; i++) {
if (!obj) return
obj = obj[segments[i]];
}
return obj
}
}
/* */
// can we use __proto__?
const hasProto = '__proto__' in {};
// Browser environment sniffing
const inBrowser = typeof window !== 'undefined';
const inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
const weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
const UA = inBrowser && window.navigator.userAgent.toLowerCase();
const isIE = UA && /msie|trident/.test(UA);
const isIE9 = UA && UA.indexOf('msie 9.0') > 0;
const isEdge = UA && UA.indexOf('edge/') > 0;
const isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');
const isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');
const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
const isPhantomJS = UA && /phantomjs/.test(UA);
// Firefox has a "watch" function on Object.prototype...
const nativeWatch = ({}).watch;
let supportsPassive = false;
if (inBrowser) {
try {
const opts = {};
Object.defineProperty(opts, 'passive', ({
get () {
/* istanbul ignore next */
supportsPassive = true;
}
})); // https://github.com/facebook/flow/issues/285
window.addEventListener('test-passive', null, opts);
} catch (e) {}
}
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
let _isServer;
const isServerRendering = () => {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && !inWeex && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'] && global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
const devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}
const hasSymbol =
typeof Symbol !== 'undefined' && isNative(Symbol) &&
typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys);
let _Set;
/* istanbul ignore if */ // $flow-disable-line
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = class Set {
constructor () {
this.set = Object.create(null);
}
has (key) {
return this.set[key] === true
}
add (key) {
this.set[key] = true;
}
clear () {
this.set = Object.create(null);
}
};
}
/* */
let warn = noop;
let tip = noop;
let generateComponentTrace = (noop); // work around flow check
let formatComponentName = (noop);
{
const hasConsole = typeof console !== 'undefined';
const classifyRE = /(?:^|[-_])(\w)/g;
const classify = str => str
.replace(classifyRE, c => c.toUpperCase())
.replace(/[-_]/g, '');
warn = (msg, vm) => {
const trace = vm ? generateComponentTrace(vm) : '';
if (config.warnHandler) {
config.warnHandler.call(null, msg, vm, trace);
} else if (hasConsole && (!config.silent)) {
console.error(`[Vue warn]: ${msg}${trace}`);
}
};
tip = (msg, vm) => {
if (hasConsole && (!config.silent)) {
console.warn(`[Vue tip]: ${msg}` + (
vm ? generateComponentTrace(vm) : ''
));
}
};
formatComponentName = (vm, includeFile) => {
if (vm.$root === vm) {
return '<Root>'
}
const options = typeof vm === 'function' && vm.cid != null
? vm.options
: vm._isVue
? vm.$options || vm.constructor.options
: vm;
let name = options.name || options._componentTag;
const file = options.__file;
if (!name && file) {
const match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (
(name ? `<${classify(name)}>` : `<Anonymous>`) +
(file && includeFile !== false ? ` at ${file}` : '')
)
};
const repeat = (str, n) => {
let res = '';
while (n) {
if (n % 2 === 1) res += str;
if (n > 1) str += str;
n >>= 1;
}
return res
};
generateComponentTrace = vm => {
if (vm._isVue && vm.$parent) {
const tree = [];
let currentRecursiveSequence = 0;
while (vm) {
if (tree.length > 0) {
const last = tree[tree.length - 1];
if (last.constructor === vm.constructor) {
currentRecursiveSequence++;
vm = vm.$parent;
continue
} else if (currentRecursiveSequence > 0) {
tree[tree.length - 1] = [last, currentRecursiveSequence];
currentRecursiveSequence = 0;
}
}
tree.push(vm);
vm = vm.$parent;
}
return '\n\nfound in\n\n' + tree
.map((vm, i) => `${
i === 0 ? '---> ' : repeat(' ', 5 + i * 2)
}${
Array.isArray(vm)
? `${formatComponentName(vm[0])}... (${vm[1]} recursive calls)`
: formatComponentName(vm)
}`)
.join('\n')
} else {
return `\n\n(found in ${formatComponentName(vm)})`
}
};
}
/* */
let uid = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
class Dep {
constructor () {
this.id = uid++;
this.subs = [];
}
addSub (sub) {
this.subs.push(sub);
}
removeSub (sub) {
remove(this.subs, sub);
}
depend () {
if (Dep.target) {
Dep.target.addDep(this);
}
}
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice();
if (!config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort((a, b) => a.id - b.id);
}
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
}
}
// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
Dep.target = null;
const targetStack = [];
function pushTarget (target) {
targetStack.push(target);
Dep.target = target;
}
function popTarget () {
targetStack.pop();
Dep.target = targetStack[targetStack.length - 1];
}
/* */
class VNode {
// rendered in this component's scope
// component instance
// component placeholder node
// strictly internal
// contains raw HTML? (server only)
// hoisted static node
// necessary for enter transition check
// empty comment placeholder?
// is a cloned node?
// is a v-once node?
// async component factory function
// real context vm for functional nodes
// for SSR caching
// used to store functional render context for devtools
// functional scope id support
constructor (
tag,
data,
children,
text,
elm,
context,
componentOptions,
asyncFactory
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = undefined;
this.context = context;
this.fnContext = undefined;
this.fnOptions = undefined;
this.fnScopeId = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.componentInstance = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
this.asyncFactory = asyncFactory;
this.asyncMeta = undefined;
this.isAsyncPlaceholder = false;
}
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
get child () {
return this.componentInstance
}
}
const createEmptyVNode = (text = '') => {
const node = new VNode();
node.text = text;
node.isComment = true;
return node
};
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
const cloned = new VNode(
vnode.tag,
vnode.data,
// #7975
// clone children array to avoid mutating original in case of cloning
// a child.
vnode.children && vnode.children.slice(),
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions,
vnode.asyncFactory
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isComment = vnode.isComment;
cloned.fnContext = vnode.fnContext;
cloned.fnOptions = vnode.fnOptions;
cloned.fnScopeId = vnode.fnScopeId;
cloned.asyncMeta = vnode.asyncMeta;
cloned.isCloned = true;
return cloned
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
];
/**
* Intercept mutating methods and emit events
*/
methodsToPatch.forEach(function (method) {
// cache original method
const original = arrayProto[method];
def(arrayMethods, method, function mutator (...args) {
const result = original.apply(this, args);
const ob = this.__ob__;
let inserted;
switch (method) {
case 'push':
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) ob.observeArray(inserted);
// notify change
ob.dep.notify();
return result
});
});
/* */
const arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* In some cases we may want to disable observation inside a component's
* update computation.
*/
let shouldObserve = true;
function toggleObserving (value) {
shouldObserve = value;
}
/**
* Observer class that is attached to each observed
* object. Once attached, the observer converts the target
* object's property keys into getter/setters that
* collect dependencies and dispatch updates.
*/
class Observer {
// number of vms that have this object as root $data
constructor (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
if (hasProto) {
protoAugment(value, arrayMethods);
} else {
copyAugment(value, arrayMethods, arrayKeys);
}
this.observeArray(value);
} else {
this.walk(value);
}
}
/**
* Walk through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj) {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i]);
}
}
/**
* Observe a list of Array items.
*/
observeArray (items) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
}
}
// helpers
/**
* Augment a target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment a target Object or Array by defining
* hidden properties.
*/
/* istanbul ignore next */
function copyAugment (target, src, keys) {
for (let i = 0, l = keys.length; i < l; i++) {
const key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value, asRootData) {
if (!isObject(value) || value instanceof VNode) {
return
}
let ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value);
}
if (asRootData && ob) {
ob.vmCount++;
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter,
shallow
) {
const dep = new Dep();
const property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
const getter = property && property.get;
const setter = property && property.set;
if ((!getter || setter) && arguments.length === 2) {
val = obj[key];
}
let childOb = !shallow && observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
if (Array.isArray(value)) {
dependArray(value);
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (customSetter) {
customSetter();
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = !shallow && observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set (target, key, val) {
if (isUndef(target) || isPrimitive(target)
) {
warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target)}`);
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val
}
if (key in target && !(key in Object.prototype)) {
target[key] = val;
return val
}
const ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return val
}
if (!ob) {
target[key] = val;
return val
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (target, key) {
if (isUndef(target) || isPrimitive(target)
) {
warn(`Cannot delete reactive property on undefined, null, or primitive value: ${(target)}`);
}
if (Array.isArray(target) && isValidArrayIndex(key)) {
target.splice(key, 1);
return
}
const ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(target, key)) {
return
}
delete target[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (let e, i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
const strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
{
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
`option "${key}" can only be used during instance ` +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
if (!from) return to
let key, toVal, fromVal;
const keys = hasSymbol
? Reflect.ownKeys(from)
: Object.keys(from);
for (let i = 0; i < keys.length; i++) {
key = keys[i];
// in case the object is already observed...
if (key === '__ob__') continue
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set(to, key, fromVal);
} else if (
toVal !== fromVal &&
isPlainObject(toVal) &&
isPlainObject(fromVal)
) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
function mergeDataOrFn (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
typeof childVal === 'function' ? childVal.call(this, this) : childVal,
typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal
)
}
} else {
return function mergedInstanceDataFn () {
// instance merge
const instanceData = typeof childVal === 'function'
? childVal.call(vm, vm)
: childVal;
const defaultData = typeof parentVal === 'function'
? parentVal.call(vm, vm)
: parentVal;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
}
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
if (childVal && typeof childVal !== 'function') {
warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
return mergeDataOrFn(parentVal, childVal)
}
return mergeDataOrFn(parentVal, childVal, vm)
};
/**
* Hooks and props are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
const res = childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal;
return res
? dedupeHooks(res)
: res
}
function dedupeHooks (hooks) {
const res = [];
for (let i = 0; i < hooks.length; i++) {
if (res.indexOf(hooks[i]) === -1) {
res.push(hooks[i]);
}
}
return res
}
LIFECYCLE_HOOKS.forEach(hook => {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (
parentVal,
childVal,
vm,
key
) {
const res = Object.create(parentVal || null);
if (childVal) {
assertObjectType(key, childVal, vm);
return extend(res, childVal)
} else {
return res
}
}
ASSET_TYPES.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (
parentVal,
childVal,
vm,
key
) {
// work around Firefox's Object.prototype.watch...
if (parentVal === nativeWatch) parentVal = undefined;
if (childVal === nativeWatch) childVal = undefined;
/* istanbul ignore if */
if (!childVal) return Object.create(parentVal || null)
{
assertObjectType(key, childVal, vm);
}
if (!parentVal) return childVal
const ret = {};
extend(ret, parentVal);
for (const key in childVal) {
let parent = ret[key];
const child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = parent
? parent.concat(child)
: Array.isArray(child) ? child : [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.inject =
strats.computed = function (
parentVal,
childVal,
vm,
key
) {
if (childVal && "development" !== 'production') {
assertObjectType(key, childVal, vm);
}
if (!parentVal) return childVal
const ret = Object.create(null);
extend(ret, parentVal);
if (childVal) extend(ret, childVal);
return ret
};
strats.provide = mergeDataOrFn;
/**
* Default strategy.
*/
const defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (const key in options.components) {
validateComponentName(key);
}
}
function validateComponentName (name) {
if (!new RegExp(`^[a-zA-Z][\\-\\.0-9_${unicodeLetters}]*$`).test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'should conform to valid custom element name in html5 specification.'
);
}
if (isBuiltInTag(name) || config.isReservedTag(name)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + name
);
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options, vm) {
const props = options.props;
if (!props) return
const res = {};
let i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (const key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
} else {
warn(
`Invalid value for option "props": expected an Array or an Object, ` +
`but got ${toRawType(props)}.`,
vm
);
}
options.props = res;
}
/**
* Normalize all injections into Object-based format
*/
function normalizeInject (options, vm) {
const inject = options.inject;
if (!inject) return
const normalized = options.inject = {};
if (Array.isArray(inject)) {
for (let i = 0; i < inject.length; i++) {
normalized[inject[i]] = { from: inject[i] };
}
} else if (isPlainObject(inject)) {
for (const key in inject) {
const val = inject[key];
normalized[key] = isPlainObject(val)
? extend({ from: key }, val)
: { from: val };
}
} else {
warn(
`Invalid value for option "inject": expected an Array or an Object, ` +
`but got ${toRawType(inject)}.`,
vm
);
}
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
const dirs = options.directives;
if (dirs) {
for (const key in dirs) {
const def$$1 = dirs[key];
if (typeof def$$1 === 'function') {
dirs[key] = { bind: def$$1, update: def$$1 };
}
}
}
}
function assertObjectType (name, value, vm) {
if (!isPlainObject(value)) {
warn(
`Invalid value for option "${name}": expected an Object, ` +
`but got ${toRawType(value)}.`,
vm
);
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
{
checkComponents(child);
}
if (typeof child === 'function') {
child = child.options;
}
normalizeProps(child, vm);
normalizeInject(child, vm);
normalizeDirectives(child);
// Apply extends and mixins on the child options,
// but only if it is a raw options object that isn't
// the result of another mergeOptions call.
// Only merged options has the _base property.
if (!child._base) {
if (child.extends) {
parent = mergeOptions(parent, child.extends, vm);
}
if (child.mixins) {
for (let i = 0, l = child.mixins.length; i < l; i++) {
parent = mergeOptions(parent, child.mixins[i], vm);
}
}
}
const options = {};
let key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
const strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
const assets = options[type];
// check local registration variations first
if (hasOwn(assets, id)) return assets[id]
const camelizedId = camelize(id);
if (hasOwn(assets, camelizedId)) return assets[camelizedId]
const PascalCaseId = capitalize(camelizedId);
if (hasOwn(assets, PascalCaseId)) return assets[PascalCaseId]
// fallback to prototype chain
const res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
if (warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
const prop = propOptions[key];
const absent = !hasOwn(propsData, key);
let value = propsData[key];
// boolean casting
const booleanIndex = getTypeIndex(Boolean, prop.type);
if (booleanIndex > -1) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (value === '' || value === hyphenate(key)) {
// only cast empty string / same name to boolean if
// boolean has higher priority
const stringIndex = getTypeIndex(String, prop.type);
if (stringIndex < 0 || booleanIndex < stringIndex) {
value = true;
}
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
const prevShouldObserve = shouldObserve;
toggleObserving(true);
observe(value);
toggleObserving(prevShouldObserve);
}
{
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
const def = prop.default;
// warn against non-factory defaults for Object & Array
if (isObject(def)) {
warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm._props[key] !== undefined
) {
return vm._props[key]
}
// call factory function for non-Function types
// a value is Function if its prototype is function even across different execution context
return typeof def === 'function' && getType(prop.type) !== 'Function'
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
let type = prop.type;
let valid = !type || type === true;
const expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (let i = 0; i < type.length && !valid; i++) {
const assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
if (!valid) {
warn(
getInvalidTypeMessage(name, value, expectedTypes),
vm
);
return
}
const validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
function assertType (value, type) {
let valid;
const expectedType = getType(type);
if (simpleCheckRE.test(expectedType)) {
const t = typeof value;
valid = t === expectedType.toLowerCase();
// for primitive wrapper objects
if (!valid && t === 'object') {
valid = value instanceof type;
}
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid,
expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
const match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : ''
}
function isSameType (a, b) {
return getType(a) === getType(b)
}
function getTypeIndex (type, expectedTypes) {
if (!Array.isArray(expectedTypes)) {
return isSameType(expectedTypes, type) ? 0 : -1
}
for (let i = 0, len = expectedTypes.length; i < len; i++) {
if (isSameType(expectedTypes[i], type)) {
return i
}
}
return -1
}
function getInvalidTypeMessage (name, value, expectedTypes) {
let message = `Invalid prop: type check failed for prop "${name}".` +
` Expected ${expectedTypes.map(capitalize).join(', ')}`;
const expectedType = expectedTypes[0];
const receivedType = toRawType(value);
const expectedValue = styleValue(value, expectedType);
const receivedValue = styleValue(value, receivedType);
// check if we need to specify expected value
if (expectedTypes.length === 1 &&
isExplicable(expectedType) &&
!isBoolean(expectedType, receivedType)) {
message += ` with value ${expectedValue}`;
}
message += `, got ${receivedType} `;
// check if we need to specify received value
if (isExplicable(receivedType)) {
message += `with value ${receivedValue}.`;
}
return message
}
function styleValue (value, type) {
if (type === 'String') {
return `"${value}"`
} else if (type === 'Number') {
return `${Number(value)}`
} else {
return `${value}`
}
}
function isExplicable (value) {
const explicitTypes = ['string', 'number', 'boolean'];
return explicitTypes.some(elem => value.toLowerCase() === elem)
}
function isBoolean (...args) {
return args.some(elem => elem.toLowerCase() === 'boolean')
}
/* */
function handleError (err, vm, info) {
if (vm) {
let cur = vm;
while ((cur = cur.$parent)) {
const hooks = cur.$options.errorCaptured;
if (hooks) {
for (let i = 0; i < hooks.length; i++) {
try {
const capture = hooks[i].call(cur, err, vm, info) === false;
if (capture) return
} catch (e) {
globalHandleError(e, cur, 'errorCaptured hook');
}
}
}
}
}
globalHandleError(err, vm, info);
}
function invokeWithErrorHandling (
handler,
context,
args,
vm,
info
) {
let res;
try {
res = args ? handler.apply(context, args) : handler.call(context);
if (res && !res._isVue && isPromise(res)) {
res.catch(e => handleError(e, vm, info + ` (Promise/async)`));
}
} catch (e) {
handleError(e, vm, info);
}
return res
}
function globalHandleError (err, vm, info) {
if (config.errorHandler) {
try {
return config.errorHandler.call(null, err, vm, info)
} catch (e) {
logError(e, null, 'config.errorHandler');
}
}
logError(err, vm, info);
}
function logError (err, vm, info) {
{
warn(`Error in ${info}: "${err.toString()}"`, vm);
}
/* istanbul ignore else */
if ((inBrowser || inWeex) && typeof console !== 'undefined') {
console.error(err);
} else {
throw err
}
}
/* */
let isUsingMicroTask = false;
const callbacks = [];
let pending = false;
function flushCallbacks () {
pending = false;
const copies = callbacks.slice(0);
callbacks.length = 0;
for (let i = 0; i < copies.length; i++) {
copies[i]();
}
}
// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc;
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve();
timerFunc = () => {
p.then(flushCallbacks);
// In problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) setTimeout(noop);
};
isUsingMicroTask = true;
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
let counter = 1;
const observer = new MutationObserver(flushCallbacks);
const textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = () => {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
isUsingMicroTask = true;
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// Fallback to setImmediate.
// Techinically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = () => {
setImmediate(flushCallbacks);
};
} else {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0);
};
}
function nextTick (cb, ctx) {
let _resolve;
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx);
} catch (e) {
handleError(e, ctx, 'nextTick');
}
} else if (_resolve) {
_resolve(ctx);
}
});
if (!pending) {
pending = true;
timerFunc();
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve;
})
}
}
/* */
let mark;
let measure;
{
const perf = inBrowser && window.performance;
/* istanbul ignore if */
if (
perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures
) {
mark = tag => perf.mark(tag);
measure = (name, startTag, endTag) => {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
// perf.clearMeasures(name)
};
}
}
/* not type checking this file because flow doesn't play well with Proxy */
let initProxy;
{
const allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
const warnNonPresent = (target, key) => {
warn(
`Property or method "${key}" is not defined on the instance but ` +
'referenced during render. Make sure that this property is reactive, ' +
'either in the data option, or for class-based components, by ' +
'initializing the property. ' +
'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.',
target
);
};
const warnReservedPrefix = (target, key) => {
warn(
`Property "${key}" must be accessed with "$data.${key}" because ` +
'properties starting with "$" or "_" are not proxied in the Vue instance to ' +
'prevent conflicts with Vue internals' +
'See: https://vuejs.org/v2/api/#data',
target
);
};
const hasProxy =
typeof Proxy !== 'undefined' && isNative(Proxy);
if (hasProxy) {
const isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact');
config.keyCodes = new Proxy(config.keyCodes, {
set (target, key, value) {
if (isBuiltInModifier(key)) {
warn(`Avoid overwriting built-in modifier in config.keyCodes: .${key}`);
return false
} else {
target[key] = value;
return true
}
}
});
}
const hasHandler = {
has (target, key) {
const has = key in target;
const isAllowed = allowedGlobals(key) ||
(typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data));
if (!has && !isAllowed) {
if (key in target.$data) warnReservedPrefix(target, key);
else warnNonPresent(target, key);
}
return has || !isAllowed
}
};
const getHandler = {
get (target, key) {
if (typeof key === 'string' && !(key in target)) {
if (key in target.$data) warnReservedPrefix(target, key);
else warnNonPresent(target, key);
}
return target[key]
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
const options = vm.$options;
const handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
const seenObjects = new _Set();
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
function traverse (val) {
_traverse(val, seenObjects);
seenObjects.clear();
}
function _traverse (val, seen) {
let i, keys;
const isA = Array.isArray(val);
if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) {
return
}
if (val.__ob__) {
const depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) _traverse(val[i], seen);
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) _traverse(val[keys[i]], seen);
}
}
/* */
const normalizeEvent = cached((name) => {
const passive = name.charAt(0) === '&';
name = passive ? name.slice(1) : name;
const once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first
name = once$$1 ? name.slice(1) : name;
const capture = name.charAt(0) === '!';
name = capture ? name.slice(1) : name;
return {
name,
once: once$$1,
capture,
passive
}
});
function createFnInvoker (fns, vm) {
function invoker () {
const fns = invoker.fns;
if (Array.isArray(fns)) {
const cloned = fns.slice();
for (let i = 0; i < cloned.length; i++) {
invokeWithErrorHandling(cloned[i], null, arguments, vm, `v-on handler`);
}
} else {
// return handler return value for single handlers
return invokeWithErrorHandling(fns, null, arguments, vm, `v-on handler`)
}
}
invoker.fns = fns;
return invoker
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
createOnceHandler,
vm
) {
let name, def$$1, cur, old, event;
for (name in on) {
def$$1 = cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (isUndef(cur)) {
warn(
`Invalid handler for event "${event.name}": got ` + String(cur),
vm
);
} else if (isUndef(old)) {
if (isUndef(cur.fns)) {
cur = on[name] = createFnInvoker(cur, vm);
}
if (isTrue(event.once)) {
cur = on[name] = createOnceHandler(event.name, cur, event.capture);
}
add(event.name, cur, event.capture, event.passive, event.params);
} else if (cur !== old) {
old.fns = cur;
on[name] = old;
}
}
for (name in oldOn) {
if (isUndef(on[name])) {
event = normalizeEvent(name);
remove$$1(event.name, oldOn[name], event.capture);
}
}
}
/* */
function mergeVNodeHook (def, hookKey, hook) {
if (def instanceof VNode) {
def = def.data.hook || (def.data.hook = {});
}
let invoker;
const oldHook = def[hookKey];
function wrappedHook () {
hook.apply(this, arguments);
// important: remove merged hook to ensure it's called only once
// and prevent memory leak
remove(invoker.fns, wrappedHook);
}
if (isUndef(oldHook)) {
// no existing hook
invoker = createFnInvoker([wrappedHook]);
} else {
/* istanbul ignore if */
if (isDef(oldHook.fns) && isTrue(oldHook.merged)) {
// already a merged invoker
invoker = oldHook;
invoker.fns.push(wrappedHook);
} else {
// existing plain hook
invoker = createFnInvoker([oldHook, wrappedHook]);
}
}
invoker.merged = true;
def[hookKey] = invoker;
}
/* */
function extractPropsFromVNodeData (
data,
Ctor,
tag
) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
const propOptions = Ctor.options.props;
if (isUndef(propOptions)) {
return
}
const res = {};
const { attrs, props } = data;
if (isDef(attrs) || isDef(props)) {
for (const key in propOptions) {
const altKey = hyphenate(key);
{
const keyInLowerCase = key.toLowerCase();
if (
key !== keyInLowerCase &&
attrs && hasOwn(attrs, keyInLowerCase)
) {
tip(
`Prop "${keyInLowerCase}" is passed to component ` +
`${formatComponentName(tag || Ctor)}, but the declared prop name is` +
` "${key}". ` +
`Note that HTML attributes are case-insensitive and camelCased ` +
`props need to use their kebab-case equivalents when using in-DOM ` +
`templates. You should probably use "${altKey}" instead of "${key}".`
);
}
}
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey, false);
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (isDef(hash)) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
/* */
// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
function simpleNormalizeChildren (children) {
for (let i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
function normalizeChildren (children) {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
function isTextNode (node) {
return isDef(node) && isDef(node.text) && isFalse(node.isComment)
}
function normalizeArrayChildren (children, nestedIndex) {
const res = [];
let i, c, lastIndex, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (isUndef(c) || typeof c === 'boolean') continue
lastIndex = res.length - 1;
last = res[lastIndex];
// nested
if (Array.isArray(c)) {
if (c.length > 0) {
c = normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`);
// merge adjacent text nodes
if (isTextNode(c[0]) && isTextNode(last)) {
res[lastIndex] = createTextVNode(last.text + (c[0]).text);
c.shift();
}
res.push.apply(res, c);
}
} else if (isPrimitive(c)) {
if (isTextNode(last)) {
// merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
res[lastIndex] = createTextVNode(last.text + c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (isTextNode(c) && isTextNode(last)) {
// merge adjacent text nodes
res[lastIndex] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (isTrue(children._isVList) &&
isDef(c.tag) &&
isUndef(c.key) &&
isDef(nestedIndex)) {
c.key = `__vlist${nestedIndex}_${i}__`;
}
res.push(c);
}
}
}
return res
}
/* */
function ensureCtor (comp, base) {
if (
comp.__esModule ||
(hasSymbol && comp[Symbol.toStringTag] === 'Module')
) {
comp = comp.default;
}
return isObject(comp)
? base.extend(comp)
: comp
}
function createAsyncPlaceholder (
factory,
data,
context,
children,
tag
) {
const node = createEmptyVNode();
node.asyncFactory = factory;
node.asyncMeta = { data, context, children, tag };
return node
}
function resolveAsyncComponent (
factory,
baseCtor,
context
) {
if (isTrue(factory.error) && isDef(factory.errorComp)) {
return factory.errorComp
}
if (isDef(factory.resolved)) {
return factory.resolved
}
if (isTrue(factory.loading) && isDef(factory.loadingComp)) {
return factory.loadingComp
}
if (isDef(factory.contexts)) {
// already pending
factory.contexts.push(context);
} else {
const contexts = factory.contexts = [context];
let sync = true;
const forceRender = (renderCompleted) => {
for (let i = 0, l = contexts.length; i < l; i++) {
contexts[i].$forceUpdate();
}
if (renderCompleted) {
contexts.length = 0;
}
};
const resolve = once((res) => {
// cache resolved
factory.resolved = ensureCtor(res, baseCtor);
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
forceRender(true);
} else {
contexts.length = 0;
}
});
const reject = once(reason => {
warn(
`Failed to resolve async component: ${String(factory)}` +
(reason ? `\nReason: ${reason}` : '')
);
if (isDef(factory.errorComp)) {
factory.error = true;
forceRender(true);
}
});
const res = factory(resolve, reject);
if (isObject(res)) {
if (isPromise(res)) {
// () => Promise
if (isUndef(factory.resolved)) {
res.then(resolve, reject);
}
} else if (isPromise(res.component)) {
res.component.then(resolve, reject);
if (isDef(res.error)) {
factory.errorComp = ensureCtor(res.error, baseCtor);
}
if (isDef(res.loading)) {
factory.loadingComp = ensureCtor(res.loading, baseCtor);
if (res.delay === 0) {
factory.loading = true;
} else {
setTimeout(() => {
if (isUndef(factory.resolved) && isUndef(factory.error)) {
factory.loading = true;
forceRender(false);
}
}, res.delay || 200);
}
}
if (isDef(res.timeout)) {
setTimeout(() => {
if (isUndef(factory.resolved)) {
reject(
`timeout (${res.timeout}ms)`
);
}
}, res.timeout);
}
}
}
sync = false;
// return in case resolved synchronously
return factory.loading
? factory.loadingComp
: factory.resolved
}
}
/* */
function isAsyncPlaceholder (node) {
return node.isComment && node.asyncFactory
}
/* */
function getFirstComponentChild (children) {
if (Array.isArray(children)) {
for (let i = 0; i < children.length; i++) {
const c = children[i];
if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) {
return c
}
}
}
}
/* */
/* */
function initEvents (vm) {
vm._events = Object.create(null);
vm._hasHookEvent = false;
// init parent attached events
const listeners = vm.$options._parentListeners;
if (listeners) {
updateComponentListeners(vm, listeners);
}
}
let target;
function add (event, fn) {
target.$on(event, fn);
}
function remove$1 (event, fn) {
target.$off(event, fn);
}
function createOnceHandler (event, fn) {
const _target = target;
return function onceHandler () {
const res = fn.apply(null, arguments);
if (res !== null) {
_target.$off(event, onceHandler);
}
}
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm);
target = undefined;
}
function eventsMixin (Vue) {
const hookRE = /^hook:/;
Vue.prototype.$on = function (event, fn) {
const vm = this;
if (Array.isArray(event)) {
for (let i = 0, l = event.length; i < l; i++) {
vm.$on(event[i], fn);
}
} else {
(vm._events[event] || (vm._events[event] = [])).push(fn);
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true;
}
}
return vm
};
Vue.prototype.$once = function (event, fn) {
const vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
const vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// array of events
if (Array.isArray(event)) {
for (let i = 0, l = event.length; i < l; i++) {
vm.$off(event[i], fn);
}
return vm
}
// specific event
const cbs = vm._events[event];
if (!cbs) {
return vm
}
if (!fn) {
vm._events[event] = null;
return vm
}
// specific handler
let cb;
let i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
const vm = this;
{
const lowerCaseEvent = event.toLowerCase();
if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
tip(
`Event "${lowerCaseEvent}" is emitted in component ` +
`${formatComponentName(vm)} but the handler is registered for "${event}". ` +
`Note that HTML attributes are case-insensitive and you cannot use ` +
`v-on to listen to camelCase events when using in-DOM templates. ` +
`You should probably use "${hyphenate(event)}" instead of "${event}".`
);
}
}
let cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
const args = toArray(arguments, 1);
const info = `event handler for "${event}"`;
for (let i = 0, l = cbs.length; i < l; i++) {
invokeWithErrorHandling(cbs[i], vm, args, vm, info);
}
}
return vm
};
}
/* */
/**
* Runtime helper for resolving raw children VNodes into a slot object.
*/
function resolveSlots (
children,
context
) {
if (!children || !children.length) {
return {}
}
const slots = {};
for (let i = 0, l = children.length; i < l; i++) {
const child = children[i];
const data = child.data;
// remove slot attribute if the node is resolved as a Vue slot node
if (data && data.attrs && data.attrs.slot) {
delete data.attrs.slot;
}
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.fnContext === context) &&
data && data.slot != null
) {
const name = data.slot;
const slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children || []);
} else {
slot.push(child);
}
} else {
(slots.default || (slots.default = [])).push(child);
}
}
// ignore slots that contains only whitespace
for (const name in slots) {
if (slots[name].every(isWhitespace)) {
delete slots[name];
}
}
return slots
}
function isWhitespace (node) {
return (node.isComment && !node.asyncFactory) || node.text === ' '
}
function resolveScopedSlots (
fns, // see flow/vnode
hasDynamicKeys,
res
) {
res = res || { $stable: !hasDynamicKeys };
for (let i = 0; i < fns.length; i++) {
const slot = fns[i];
if (Array.isArray(slot)) {
resolveScopedSlots(slot, hasDynamicKeys, res);
} else if (slot) {
res[slot.key] = slot.fn;
}
}
return res
}
/* */
let activeInstance = null;
let isUpdatingChildComponent = false;
function setActiveInstance(vm) {
const prevActiveInstance = activeInstance;
activeInstance = vm;
return () => {
activeInstance = prevActiveInstance;
}
}
function initLifecycle (vm) {
const options = vm.$options;
// locate first non-abstract parent
let parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = null;
vm._directInactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._update = function (vnode, hydrating) {
const vm = this;
const prevEl = vm.$el;
const prevVnode = vm._vnode;
const restoreActiveInstance = setActiveInstance(vm);
vm._vnode = vnode;
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
restoreActiveInstance();
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
};
Vue.prototype.$forceUpdate = function () {
const vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
const vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
const parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
let i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
// fire destroyed hook
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// release circular reference (#6759)
if (vm.$vnode) {
vm.$vnode.parent = null;
}
};
}
function mountComponent (
vm,
el,
hydrating
) {
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode;
{
/* istanbul ignore if */
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
callHook(vm, 'beforeMount');
let updateComponent;
/* istanbul ignore if */
if (config.performance && mark) {
updateComponent = () => {
const name = vm._name;
const id = vm._uid;
const startTag = `vue-perf-start:${id}`;
const endTag = `vue-perf-end:${id}`;
mark(startTag);
const vnode = vm._render();
mark(endTag);
measure(`vue ${name} render`, startTag, endTag);
mark(startTag);
vm._update(vnode, hydrating);
mark(endTag);
measure(`vue ${name} patch`, startTag, endTag);
};
} else {
updateComponent = () => {
vm._update(vm._render(), hydrating);
};
}
// we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate');
}
}
}, true /* isRenderWatcher */);
hydrating = false;
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true;
callHook(vm, 'mounted');
}
return vm
}
function updateChildComponent (
vm,
propsData,
listeners,
parentVnode,
renderChildren
) {
{
isUpdatingChildComponent = true;
}
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren.
// check if there are dynamic scopedSlots (hand-written or compiled but with
// dynamic slot names). Static scoped slots compiled from template has the
// "$stable" marker.
const hasDynamicScopedSlot = !!(
(parentVnode.data.scopedSlots && !parentVnode.data.scopedSlots.$stable) ||
(vm.$scopedSlots !== emptyObject && !vm.$scopedSlots.$stable)
);
// Any static slot children from the parent may have changed during parent's
// update. Dynamic scoped slots may also have changed. In such cases, a forced
// update is necessary to ensure correctness.
const needsForceUpdate = !!(
renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
hasDynamicScopedSlot
);
vm.$options._parentVnode = parentVnode;
vm.$vnode = parentVnode; // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode;
}
vm.$options._renderChildren = renderChildren;
// update $attrs and $listeners hash
// these are also reactive so they may trigger child update if the child
// used them during render
vm.$attrs = parentVnode.data.attrs || emptyObject;
vm.$listeners = listeners || emptyObject;
// update props
if (propsData && vm.$options.props) {
toggleObserving(false);
const props = vm._props;
const propKeys = vm.$options._propKeys || [];
for (let i = 0; i < propKeys.length; i++) {
const key = propKeys[i];
const propOptions = vm.$options.props; // wtf flow?
props[key] = validateProp(key, propOptions, propsData, vm);
}
toggleObserving(true);
// keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// update listeners
listeners = listeners || emptyObject;
const oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
// resolve slots + force update if has children
if (needsForceUpdate) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
{
isUpdatingChildComponent = false;
}
}
function isInInactiveTree (vm) {
while (vm && (vm = vm.$parent)) {
if (vm._inactive) return true
}
return false
}
function activateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = false;
if (isInInactiveTree(vm)) {
return
}
} else if (vm._directInactive) {
return
}
if (vm._inactive || vm._inactive === null) {
vm._inactive = false;
for (let i = 0; i < vm.$children.length; i++) {
activateChildComponent(vm.$children[i]);
}
callHook(vm, 'activated');
}
}
function deactivateChildComponent (vm, direct) {
if (direct) {
vm._directInactive = true;
if (isInInactiveTree(vm)) {
return
}
}
if (!vm._inactive) {
vm._inactive = true;
for (let i = 0; i < vm.$children.length; i++) {
deactivateChildComponent(vm.$children[i]);
}
callHook(vm, 'deactivated');
}
}
function callHook (vm, hook) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget();
const handlers = vm.$options[hook];
const info = `${hook} hook`;
if (handlers) {
for (let i = 0, j = handlers.length; i < j; i++) {
invokeWithErrorHandling(handlers[i], vm, null, vm, info);
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
popTarget();
}
/* */
const MAX_UPDATE_COUNT = 100;
const queue = [];
const activatedChildren = [];
let has = {};
let circular = {};
let waiting = false;
let flushing = false;
let index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
index = queue.length = activatedChildren.length = 0;
has = {};
{
circular = {};
}
waiting = flushing = false;
}
// Async edge case #6566 requires saving the timestamp when event listeners are
// attached. However, calling performance.now() has a perf overhead especially
// if the page has thousands of event listeners. Instead, we take a timestamp
// every time the scheduler flushes and use that for all event listeners
// attached during that flush.
let currentFlushTimestamp = 0;
// Async edge case fix requires storing an event listener's attach timestamp.
let getNow = Date.now;
// Determine what event timestamp the browser is using. Annoyingly, the
// timestamp can either be hi-res ( relative to poge load) or low-res
// (relative to UNIX epoch), so in order to compare time we have to use the
// same timestamp type when saving the flush timestamp.
if (inBrowser && getNow() > document.createEvent('Event').timeStamp) {
// if the low-res timestamp which is bigger than the event timestamp
// (which is evaluated AFTER) it means the event is using a hi-res timestamp,
// and we need to use the hi-res version for event listeners as well.
getNow = () => performance.now();
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
currentFlushTimestamp = getNow();
flushing = true;
let watcher, id;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort((a, b) => a.id - b.id);
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index];
if (watcher.before) {
watcher.before();
}
id = watcher.id;
has[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if (has[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? `in watcher with expression "${watcher.expression}"`
: `in a component render function.`
),
watcher.vm
);
break
}
}
}
// keep copies of post queues before resetting state
const activatedQueue = activatedChildren.slice();
const updatedQueue = queue.slice();
resetSchedulerState();
// call component updated and activated hooks
callActivatedHooks(activatedQueue);
callUpdatedHooks(updatedQueue);
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
}
function callUpdatedHooks (queue) {
let i = queue.length;
while (i--) {
const watcher = queue[i];
const vm = watcher.vm;
if (vm._watcher === watcher && vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'updated');
}
}
}
/**
* Queue a kept-alive component that was activated during patch.
* The queue will be processed after the entire tree has been patched.
*/
function queueActivatedComponent (vm) {
// setting _inactive to false here so that a render function can
// rely on checking whether it's in an inactive tree (e.g. router-view)
vm._inactive = false;
activatedChildren.push(vm);
}
function callActivatedHooks (queue) {
for (let i = 0; i < queue.length; i++) {
queue[i]._inactive = true;
activateChildComponent(queue[i], true /* true */);
}
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
const id = watcher.id;
if (has[id] == null) {
has[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1;
while (i > index && queue[i].id > watcher.id) {
i--;
}
queue.splice(i + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
if (!config.async) {
flushSchedulerQueue();
return
}
nextTick(flushSchedulerQueue);
}
}
}
/* */
let uid$1 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
class Watcher {
constructor (
vm,
expOrFn,
cb,
options,
isRenderWatcher
) {
this.vm = vm;
if (isRenderWatcher) {
vm._watcher = this;
}
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
this.before = options.before;
} else {
this.deep = this.user = this.lazy = this.sync = false;
}
this.cb = cb;
this.id = ++uid$1; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
this.expression = expOrFn.toString();
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = noop;
warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
pushTarget(this);
let value;
const vm = this.vm;
try {
value = this.getter.call(vm, vm);
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`);
} else {
throw e
}
} finally {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
}
return value
}
/**
* Add a dependency to this directive.
*/
addDep (dep) {
const id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
}
/**
* Clean up for dependency collection.
*/
cleanupDeps () {
let i = this.deps.length;
while (i--) {
const dep = this.deps[i];
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this);
}
}
let tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
}
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
}
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
run () {
if (this.active) {
const value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
const oldValue = this.value;
this.value = value;
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
handleError(e, this.vm, `callback for watcher "${this.expression}"`);
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
}
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
evaluate () {
this.value = this.get();
this.dirty = false;
}
/**
* Depend on all deps collected by this watcher.
*/
depend () {
let i = this.deps.length;
while (i--) {
this.deps[i].depend();
}
}
/**
* Remove self from all dependencies' subscriber list.
*/
teardown () {
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this);
}
let i = this.deps.length;
while (i--) {
this.deps[i].removeSub(this);
}
this.active = false;
}
}
}
/* */
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function proxy (target, sourceKey, key) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
};
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val;
};
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function initState (vm) {
vm._watchers = [];
const opts = vm.$options;
if (opts.props) initProps(vm, opts.props);
if (opts.methods) initMethods(vm, opts.methods);
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) initComputed(vm, opts.computed);
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch);
}
}
function initProps (vm, propsOptions) {
const propsData = vm.$options.propsData || {};
const props = vm._props = {};
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
const keys = vm.$options._propKeys = [];
const isRoot = !vm.$parent;
// root instance props should be converted
if (!isRoot) {
toggleObserving(false);
}
for (const key in propsOptions) {
keys.push(key);
const value = validateProp(key, propsOptions, propsData, vm);
/* istanbul ignore else */
{
const hyphenatedKey = hyphenate(key);
if (isReservedAttribute(hyphenatedKey) ||
config.isReservedAttr(hyphenatedKey)) {
warn(
`"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
vm
);
}
defineReactive$$1(props, key, value, () => {
if (!isRoot && !isUpdatingChildComponent) {
warn(
`Avoid mutating a prop directly since the value will be ` +
`overwritten whenever the parent component re-renders. ` +
`Instead, use a data or computed property based on the prop's ` +
`value. Prop being mutated: "${key}"`,
vm
);
}
});
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, `_props`, key);
}
}
toggleObserving(true);
}
function initData (vm) {
let data = vm.$options.data;
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
);
}
// proxy data on instance
const keys = Object.keys(data);
const props = vm.$options.props;
const methods = vm.$options.methods;
let i = keys.length;
while (i--) {
const key = keys[i];
{
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
);
}
}
if (props && hasOwn(props, key)) {
warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
);
} else if (!isReserved(key)) {
proxy(vm, `_data`, key);
}
}
// observe data
observe(data, true /* asRootData */);
}
function getData (data, vm) {
// #7573 disable dep collection when invoking data getters
pushTarget();
try {
return data.call(vm, vm)
} catch (e) {
handleError(e, vm, `data()`);
return {}
} finally {
popTarget();
}
}
const computedWatcherOptions = { lazy: true };
function initComputed (vm, computed) {
// $flow-disable-line
const watchers = vm._computedWatchers = Object.create(null);
// computed properties are just getters during SSR
const isSSR = isServerRendering();
for (const key in computed) {
const userDef = computed[key];
const getter = typeof userDef === 'function' ? userDef : userDef.get;
if (getter == null) {
warn(
`Getter is missing for computed property "${key}".`,
vm
);
}
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
);
}
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef);
} else {
if (key in vm.$data) {
warn(`The computed property "${key}" is already defined in data.`, vm);
} else if (vm.$options.props && key in vm.$options.props) {
warn(`The computed property "${key}" is already defined as a prop.`, vm);
}
}
}
}
function defineComputed (
target,
key,
userDef
) {
const shouldCache = !isServerRendering();
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: createGetterInvoker(userDef);
sharedPropertyDefinition.set = noop;
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: createGetterInvoker(userDef.get)
: noop;
sharedPropertyDefinition.set = userDef.set || noop;
}
if (sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
`Computed property "${key}" was assigned to but it has no setter.`,
this
);
};
}
Object.defineProperty(target, key, sharedPropertyDefinition);
}
function createComputedGetter (key) {
return function computedGetter () {
const watcher = this._computedWatchers && this._computedWatchers[key];
if (watcher) {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.target) {
watcher.depend();
}
return watcher.value
}
}
}
function createGetterInvoker(fn) {
return function computedGetter () {
return fn.call(this, this)
}
}
function initMethods (vm, methods) {
const props = vm.$options.props;
for (const key in methods) {
{
if (typeof methods[key] !== 'function') {
warn(
`Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +
`Did you reference the function correctly?`,
vm
);
}
if (props && hasOwn(props, key)) {
warn(
`Method "${key}" has already been defined as a prop.`,
vm
);
}
if ((key in vm) && isReserved(key)) {
warn(
`Method "${key}" conflicts with an existing Vue instance method. ` +
`Avoid defining component methods that start with _ or $.`
);
}
}
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm);
}
}
function initWatch (vm, watch) {
for (const key in watch) {
const handler = watch[key];
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
function createWatcher (
vm,
expOrFn,
handler,
options
) {
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
return vm.$watch(expOrFn, handler, options)
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
const dataDef = {};
dataDef.get = function () { return this._data };
const propsDef = {};
propsDef.get = function () { return this._props };
{
dataDef.set = function () {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
propsDef.set = function () {
warn(`$props is readonly.`, this);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Object.defineProperty(Vue.prototype, '$props', propsDef);
Vue.prototype.$set = set;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
const vm = this;
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {};
options.user = true;
const watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
try {
cb.call(vm, watcher.value);
} catch (error) {
handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`);
}
}
return function unwatchFn () {
watcher.teardown();
}
};
}
/* */
function initProvide (vm) {
const provide = vm.$options.provide;
if (provide) {
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide;
}
}
function initInjections (vm) {
const result = resolveInject(vm.$options.inject, vm);
if (result) {
toggleObserving(false);
Object.keys(result).forEach(key => {
/* istanbul ignore else */
{
defineReactive$$1(vm, key, result[key], () => {
warn(
`Avoid mutating an injected value directly since the changes will be ` +
`overwritten whenever the provided component re-renders. ` +
`injection being mutated: "${key}"`,
vm
);
});
}
});
toggleObserving(true);
}
}
function resolveInject (inject, vm) {
if (inject) {
// inject is :any because flow is not smart enough to figure out cached
const result = Object.create(null);
const keys = hasSymbol
? Reflect.ownKeys(inject)
: Object.keys(inject);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
// #6574 in case the inject object is observed...
if (key === '__ob__') continue
const provideKey = inject[key].from;
let source = vm;
while (source) {
if (source._provided && hasOwn(source._provided, provideKey)) {
result[key] = source._provided[provideKey];
break
}
source = source.$parent;
}
if (!source) {
if ('default' in inject[key]) {
const provideDefault = inject[key].default;
result[key] = typeof provideDefault === 'function'
? provideDefault.call(vm)
: provideDefault;
} else {
warn(`Injection "${key}" not found`, vm);
}
}
}
return result
}
}
/* */
function normalizeScopedSlots (
slots,
normalSlots
) {
let res;
if (!slots) {
res = {};
} else if (slots._normalized) {
return slots
} else {
res = {};
for (const key in slots) {
if (slots[key] && key[0] !== '$') {
res[key] = normalizeScopedSlot(slots[key]);
}
}
}
// expose normal slots on scopedSlots
for (const key in normalSlots) {
if (!(key in res)) {
res[key] = proxyNormalSlot(normalSlots, key);
}
}
res._normalized = true;
res.$stable = slots ? slots.$stable : true;
return res
}
function normalizeScopedSlot(fn) {
return scope => {
const res = fn(scope);
return res && typeof res === 'object' && !Array.isArray(res)
? [res] // single vnode
: normalizeChildren(res)
}
}
function proxyNormalSlot(slots, key) {
return () => slots[key]
}
/* */
/**
* Runtime helper for rendering v-for lists.
*/
function renderList (
val,
render
) {
let ret, i, l, keys, key;
if (Array.isArray(val) || typeof val === 'string') {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
if (hasSymbol && val[Symbol.iterator]) {
ret = [];
const iterator = val[Symbol.iterator]();
let result = iterator.next();
while (!result.done) {
ret.push(render(result.value, ret.length));
result = iterator.next();
}
} else {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
}
if (!isDef(ret)) {
ret = [];
}
(ret)._isVList = true;
return ret
}
/* */
/**
* Runtime helper for rendering <slot>
*/
function renderSlot (
name,
fallback,
props,
bindObject
) {
const scopedSlotFn = this.$scopedSlots[name];
let nodes;
if (scopedSlotFn) { // scoped slot
props = props || {};
if (bindObject) {
if (!isObject(bindObject)) {
warn(
'slot v-bind without argument expects an Object',
this
);
}
props = extend(extend({}, bindObject), props);
}
nodes = scopedSlotFn(props) || fallback;
} else {
nodes = this.$slots[name] || fallback;
}
const target = props && props.slot;
if (target) {
return this.$createElement('template', { slot: target }, nodes)
} else {
return nodes
}
}
/* */
/**
* Runtime helper for resolving filters
*/
function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
}
/* */
function isKeyNotMatch (expect, actual) {
if (Array.isArray(expect)) {
return expect.indexOf(actual) === -1
} else {
return expect !== actual
}
}
/**
* Runtime helper for checking keyCodes from config.
* exposed as Vue.prototype._k
* passing in eventKeyName as last argument separately for backwards compat
*/
function checkKeyCodes (
eventKeyCode,
key,
builtInKeyCode,
eventKeyName,
builtInKeyName
) {
const mappedKeyCode = config.keyCodes[key] || builtInKeyCode;
if (builtInKeyName && eventKeyName && !config.keyCodes[key]) {
return isKeyNotMatch(builtInKeyName, eventKeyName)
} else if (mappedKeyCode) {
return isKeyNotMatch(mappedKeyCode, eventKeyCode)
} else if (eventKeyName) {
return hyphenate(eventKeyName) !== key
}
}
/* */
/**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/
function bindObjectProps (
data,
tag,
value,
asProp,
isSync
) {
if (value) {
if (!isObject(value)) {
warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
let hash;
for (const key in value) {
if (
key === 'class' ||
key === 'style' ||
isReservedAttribute(key)
) {
hash = data;
} else {
const type = data.attrs && data.attrs.type;
hash = asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
}
const camelizedKey = camelize(key);
if (!(key in hash) && !(camelizedKey in hash)) {
hash[key] = value[key];
if (isSync) {
const on = data.on || (data.on = {});
on[`update:${camelizedKey}`] = function ($event) {
value[key] = $event;
};
}
}
}
}
}
return data
}
/* */
/**
* Runtime helper for rendering static trees.
*/
function renderStatic (
index,
isInFor
) {
const cached = this._staticTrees || (this._staticTrees = []);
let tree = cached[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree.
if (tree && !isInFor) {
return tree
}
// otherwise, render a fresh tree.
tree = cached[index] = this.$options.staticRenderFns[index].call(
this._renderProxy,
null,
this // for render fns generated for functional component templates
);
markStatic(tree, `__static__${index}`, false);
return tree
}
/**
* Runtime helper for v-once.
* Effectively it means marking the node as static with a unique key.
*/
function markOnce (
tree,
index,
key
) {
markStatic(tree, `__once__${index}${key ? `_${key}` : ``}`, true);
return tree
}
function markStatic (
tree,
key,
isOnce
) {
if (Array.isArray(tree)) {
for (let i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], `${key}_${i}`, isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
/* */
function bindObjectListeners (data, value) {
if (value) {
if (!isPlainObject(value)) {
warn(
'v-on without argument expects an Object value',
this
);
} else {
const on = data.on = data.on ? extend({}, data.on) : {};
for (const key in value) {
const existing = on[key];
const ours = value[key];
on[key] = existing ? [].concat(existing, ours) : ours;
}
}
}
return data
}
/* */
function bindDynamicKeys (baseObj, values) {
for (let i = 0; i < values.length; i += 2) {
const key = values[i];
if (typeof key === 'string' && key) {
baseObj[values[i]] = values[i + 1];
} else if (key !== '' && key !== null) {
// null is a speical value for explicitly removing a binding
warn(
`Invalid value for dynamic directive argument (expected string or null): ${key}`,
this
);
}
}
return baseObj
}
// helper to dynamically append modifier runtime markers to event names.
// ensure only append when value is already string, otherwise it will be cast
// to string and cause the type check to miss.
function prependModifier (value, symbol) {
return typeof value === 'string' ? symbol + value : value
}
/* */
function installRenderHelpers (target) {
target._o = markOnce;
target._n = toNumber;
target._s = toString;
target._l = renderList;
target._t = renderSlot;
target._q = looseEqual;
target._i = looseIndexOf;
target._m = renderStatic;
target._f = resolveFilter;
target._k = checkKeyCodes;
target._b = bindObjectProps;
target._v = createTextVNode;
target._e = createEmptyVNode;
target._u = resolveScopedSlots;
target._g = bindObjectListeners;
target._d = bindDynamicKeys;
target._p = prependModifier;
}
/* */
function FunctionalRenderContext (
data,
props,
children,
parent,
Ctor
) {
const options = Ctor.options;
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
let contextVm;
if (hasOwn(parent, '_uid')) {
contextVm = Object.create(parent);
// $flow-disable-line
contextVm._original = parent;
} else {
// the context vm passed in is a functional context as well.
// in this case we want to make sure we are able to get a hold to the
// real context instance.
contextVm = parent;
// $flow-disable-line
parent = parent._original;
}
const isCompiled = isTrue(options._compiled);
const needNormalization = !isCompiled;
this.data = data;
this.props = props;
this.children = children;
this.parent = parent;
this.listeners = data.on || emptyObject;
this.injections = resolveInject(options.inject, parent);
this.slots = () => resolveSlots(children, parent);
Object.defineProperty(this, 'scopedSlots', ({
enumerable: true,
get () {
return normalizeScopedSlots(data.scopedSlots, this.slots())
}
}));
// support for compiled functional template
if (isCompiled) {
// exposing $options for renderStatic()
this.$options = options;
// pre-resolve slots for renderSlot()
this.$slots = this.slots();
this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots);
}
if (options._scopeId) {
this._c = (a, b, c, d) => {
const vnode = createElement(contextVm, a, b, c, d, needNormalization);
if (vnode && !Array.isArray(vnode)) {
vnode.fnScopeId = options._scopeId;
vnode.fnContext = parent;
}
return vnode
};
} else {
this._c = (a, b, c, d) => createElement(contextVm, a, b, c, d, needNormalization);
}
}
installRenderHelpers(FunctionalRenderContext.prototype);
function createFunctionalComponent (
Ctor,
propsData,
data,
contextVm,
children
) {
const options = Ctor.options;
const props = {};
const propOptions = options.props;
if (isDef(propOptions)) {
for (const key in propOptions) {
props[key] = validateProp(key, propOptions, propsData || emptyObject);
}
} else {
if (isDef(data.attrs)) mergeProps(props, data.attrs);
if (isDef(data.props)) mergeProps(props, data.props);
}
const renderContext = new FunctionalRenderContext(
data,
props,
children,
contextVm,
Ctor
);
const vnode = options.render.call(null, renderContext._c, renderContext);
if (vnode instanceof VNode) {
return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext)
} else if (Array.isArray(vnode)) {
const vnodes = normalizeChildren(vnode) || [];
const res = new Array(vnodes.length);
for (let i = 0; i < vnodes.length; i++) {
res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext);
}
return res
}
}
function cloneAndMarkFunctionalResult (vnode, data, contextVm, options, renderContext) {
// #7817 clone node before setting fnContext, otherwise if the node is reused
// (e.g. it was from a cached normal slot) the fnContext causes named slots
// that should not be matched to match.
const clone = cloneVNode(vnode);
clone.fnContext = contextVm;
clone.fnOptions = options;
{
(clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext;
}
if (data.slot) {
(clone.data || (clone.data = {})).slot = data.slot;
}
return clone
}
function mergeProps (to, from) {
for (const key in from) {
to[camelize(key)] = from[key];
}
}
/* */
/* */
/* */
/* */
// inline hooks to be invoked on component VNodes during patch
const componentVNodeHooks = {
init (vnode, hydrating) {
if (
vnode.componentInstance &&
!vnode.componentInstance._isDestroyed &&
vnode.data.keepAlive
) {
// kept-alive components, treat as a patch
const mountedNode = vnode; // work around flow
componentVNodeHooks.prepatch(mountedNode, mountedNode);
} else {
const child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
}
},
prepatch (oldVnode, vnode) {
const options = vnode.componentOptions;
const child = vnode.componentInstance = oldVnode.componentInstance;
updateChildComponent(
child,
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
},
insert (vnode) {
const { context, componentInstance } = vnode;
if (!componentInstance._isMounted) {
componentInstance._isMounted = true;
callHook(componentInstance, 'mounted');
}
if (vnode.data.keepAlive) {
if (context._isMounted) {
// vue-router#1212
// During updates, a kept-alive component's child components may
// change, so directly walking the tree here may call activated hooks
// on incorrect children. Instead we push them into a queue which will
// be processed after the whole patch process ended.
queueActivatedComponent(componentInstance);
} else {
activateChildComponent(componentInstance, true /* direct */);
}
}
},
destroy (vnode) {
const { componentInstance } = vnode;
if (!componentInstance._isDestroyed) {
if (!vnode.data.keepAlive) {
componentInstance.$destroy();
} else {
deactivateChildComponent(componentInstance, true /* direct */);
}
}
}
};
const hooksToMerge = Object.keys(componentVNodeHooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (isUndef(Ctor)) {
return
}
const baseCtor = context.$options._base;
// plain options object: turn it into a constructor
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
// if at this stage it's not a constructor or an async component factory,
// reject.
if (typeof Ctor !== 'function') {
{
warn(`Invalid Component definition: ${String(Ctor)}`, context);
}
return
}
// async component
let asyncFactory;
if (isUndef(Ctor.cid)) {
asyncFactory = Ctor;
Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context);
if (Ctor === undefined) {
// return a placeholder node for async component, which is rendered
// as a comment node but preserves all the raw information for the node.
// the information will be used for async server-rendering and hydration.
return createAsyncPlaceholder(
asyncFactory,
data,
context,
children,
tag
)
}
}
data = data || {};
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
// transform component v-model data into props & events
if (isDef(data.model)) {
transformModel(Ctor.options, data);
}
// extract props
const propsData = extractPropsFromVNodeData(data, Ctor, tag);
// functional component
if (isTrue(Ctor.options.functional)) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
const listeners = data.on;
// replace with listeners with .native modifier
// so it gets processed during parent component patch.
data.on = data.nativeOn;
if (isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners & slot
// work around flow
const slot = data.slot;
data = {};
if (slot) {
data.slot = slot;
}
}
// install component management hooks onto the placeholder node
installComponentHooks(data);
// return a placeholder vnode
const name = Ctor.options.name || tag;
const vnode = new VNode(
`vue-component-${Ctor.cid}${name ? `-${name}` : ''}`,
data, undefined, undefined, undefined, context,
{ Ctor, propsData, listeners, tag, children },
asyncFactory
);
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent, // activeInstance in lifecycle state
) {
const options = {
_isComponent: true,
_parentVnode: vnode,
parent
};
// check inline-template render functions
const inlineTemplate = vnode.data.inlineTemplate;
if (isDef(inlineTemplate)) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnode.componentOptions.Ctor(options)
}
function installComponentHooks (data) {
const hooks = data.hook || (data.hook = {});
for (let i = 0; i < hooksToMerge.length; i++) {
const key = hooksToMerge[i];
const existing = hooks[key];
const toMerge = componentVNodeHooks[key];
if (existing !== toMerge && !(existing && existing._merged)) {
hooks[key] = existing ? mergeHook$1(toMerge, existing) : toMerge;
}
}
}
function mergeHook$1 (f1, f2) {
const merged = (a, b) => {
// flow complains about extra args which is why we use any
f1(a, b);
f2(a, b);
};
merged._merged = true;
return merged
}
// transform component v-model info (value and callback) into
// prop and event handler respectively.
function transformModel (options, data) {
const prop = (options.model && options.model.prop) || 'value';
const event = (options.model && options.model.event) || 'input';
const addTo = (options.props && prop in options.props) ? 'props' : 'attrs'
;(data[addTo] || (data[addTo] = {}))[prop] = data.model.value;
const on = data.on || (data.on = {});
const existing = on[event];
const callback = data.model.callback;
if (isDef(existing)) {
if (
Array.isArray(existing)
? existing.indexOf(callback) === -1
: existing !== callback
) {
on[event] = [callback].concat(existing);
}
} else {
on[event] = callback;
}
}
/* */
const SIMPLE_NORMALIZE = 1;
const ALWAYS_NORMALIZE = 2;
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
context,
tag,
data,
children,
normalizationType,
alwaysNormalize
) {
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children;
children = data;
data = undefined;
}
if (isTrue(alwaysNormalize)) {
normalizationType = ALWAYS_NORMALIZE;
}
return _createElement(context, tag, data, children, normalizationType)
}
function _createElement (
context,
tag,
data,
children,
normalizationType
) {
if (isDef(data) && isDef((data).__ob__)) {
warn(
`Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` +
'Always create fresh vnode data objects in each render!',
context
);
return createEmptyVNode()
}
// object syntax in v-bind
if (isDef(data) && isDef(data.is)) {
tag = data.is;
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// warn against non-primitive key
if (isDef(data) && isDef(data.key) && !isPrimitive(data.key)
) {
{
warn(
'Avoid using non-primitive value as key, ' +
'use string/number value instead.',
context
);
}
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function'
) {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children);
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children);
}
let vnode, ns;
if (typeof tag === 'string') {
let Ctor;
ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag);
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
);
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children);
}
if (Array.isArray(vnode)) {
return vnode
} else if (isDef(vnode)) {
if (isDef(ns)) applyNS(vnode, ns);
if (isDef(data)) registerDeepBindings(data);
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns, force) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
ns = undefined;
force = true;
}
if (isDef(vnode.children)) {
for (let i = 0, l = vnode.children.length; i < l; i++) {
const child = vnode.children[i];
if (isDef(child.tag) && (
isUndef(child.ns) || (isTrue(force) && child.tag !== 'svg'))) {
applyNS(child, ns, force);
}
}
}
}
// ref #5318
// necessary to ensure parent re-render when deep bindings like :style and
// :class are used on slot nodes
function registerDeepBindings (data) {
if (isObject(data.style)) {
traverse(data.style);
}
if (isObject(data.class)) {
traverse(data.class);
}
}
/* */
function initRender (vm) {
vm._vnode = null; // the root of the child tree
vm._staticTrees = null; // v-once cached trees
const options = vm.$options;
const parentVnode = vm.$vnode = options._parentVnode; // the placeholder node in parent tree
const renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(options._renderChildren, renderContext);
vm.$scopedSlots = emptyObject;
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false);
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true);
// $attrs & $listeners are exposed for easier HOC creation.
// they need to be reactive so that HOCs using them are always updated
const parentData = parentVnode && parentVnode.data;
/* istanbul ignore else */
{
defineReactive$$1(vm, '$attrs', parentData && parentData.attrs || emptyObject, () => {
!isUpdatingChildComponent && warn(`$attrs is readonly.`, vm);
}, true);
defineReactive$$1(vm, '$listeners', options._parentListeners || emptyObject, () => {
!isUpdatingChildComponent && warn(`$listeners is readonly.`, vm);
}, true);
}
}
function renderMixin (Vue) {
// install runtime convenience helpers
installRenderHelpers(Vue.prototype);
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
Vue.prototype._render = function () {
const vm = this;
const { render, _parentVnode } = vm.$options;
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots
);
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
let vnode;
try {
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
handleError(e, vm, `render`);
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (vm.$options.renderError) {
try {
vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e);
} catch (e) {
handleError(e, vm, `renderError`);
vnode = vm._vnode;
}
} else {
vnode = vm._vnode;
}
}
// if the returned array contains only a single node, allow it
if (Array.isArray(vnode) && vnode.length === 1) {
vnode = vnode[0];
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = createEmptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
}
/* */
let uid$3 = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
const vm = this;
// a uid
vm._uid = uid$3++;
let startTag, endTag;
/* istanbul ignore if */
if (config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`;
endTag = `vue-perf-end:${vm._uid}`;
mark(startTag);
}
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
{
initProxy(vm);
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, 'beforeCreate');
initInjections(vm); // resolve injections before data/props
initState(vm);
initProvide(vm); // resolve provide after data/props
callHook(vm, 'created');
/* istanbul ignore if */
if (config.performance && mark) {
vm._name = formatComponentName(vm, false);
mark(endTag);
measure(`vue ${vm._name} init`, startTag, endTag);
}
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
};
}
function initInternalComponent (vm, options) {
const opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
const parentVnode = options._parentVnode;
opts.parent = options.parent;
opts._parentVnode = parentVnode;
const vnodeComponentOptions = parentVnode.componentOptions;
opts.propsData = vnodeComponentOptions.propsData;
opts._parentListeners = vnodeComponentOptions.listeners;
opts._renderChildren = vnodeComponentOptions.children;
opts._componentTag = vnodeComponentOptions.tag;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
let options = Ctor.options;
if (Ctor.super) {
const superOptions = resolveConstructorOptions(Ctor.super);
const cachedSuperOptions = Ctor.superOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed,
// need to resolve new options.
Ctor.superOptions = superOptions;
// check if there are any late-modified/attached options (#4976)
const modifiedOptions = resolveModifiedOptions(Ctor);
// update base extend options
if (modifiedOptions) {
extend(Ctor.extendOptions, modifiedOptions);
}
options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function resolveModifiedOptions (Ctor) {
let modified;
const latest = Ctor.options;
const sealed = Ctor.sealedOptions;
for (const key in latest) {
if (latest[key] !== sealed[key]) {
if (!modified) modified = {};
modified[key] = latest[key];
}
}
return modified
}
function Vue (options) {
if (!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue);
stateMixin(Vue);
eventsMixin(Vue);
lifecycleMixin(Vue);
renderMixin(Vue);
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
const args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
installedPlugins.push(plugin);
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
return this
};
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
let cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
const Super = this;
const SuperId = Super.cid;
const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
const name = extendOptions.name || Super.options.name;
if (name) {
validateComponentName(name);
}
const Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
Sub['super'] = Super;
// For props and computed properties, we define the proxy getters on
// the Vue instances at extension time, on the extended prototype. This
// avoids Object.defineProperty calls for each instance created.
if (Sub.options.props) {
initProps$1(Sub);
}
if (Sub.options.computed) {
initComputed$1(Sub);
}
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend;
Sub.mixin = Super.mixin;
Sub.use = Super.use;
// create asset registers, so extended classes
// can have their private assets too.
ASSET_TYPES.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
Sub.sealedOptions = extend({}, Sub.options);
// cache constructor
cachedCtors[SuperId] = Sub;
return Sub
};
}
function initProps$1 (Comp) {
const props = Comp.options.props;
for (const key in props) {
proxy(Comp.prototype, `_props`, key);
}
}
function initComputed$1 (Comp) {
const computed = Comp.options.computed;
for (const key in computed) {
defineComputed(Comp.prototype, key, computed[key]);
}
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
ASSET_TYPES.forEach(type => {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if (type === 'component') {
validateComponentName(id);
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
/* */
function getComponentName (opts) {
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern, name) {
if (Array.isArray(pattern)) {
return pattern.indexOf(name) > -1
} else if (typeof pattern === 'string') {
return pattern.split(',').indexOf(name) > -1
} else if (isRegExp(pattern)) {
return pattern.test(name)
}
/* istanbul ignore next */
return false
}
function pruneCache (keepAliveInstance, filter) {
const { cache, keys, _vnode } = keepAliveInstance;
for (const key in cache) {
const cachedNode = cache[key];
if (cachedNode) {
const name = getComponentName(cachedNode.componentOptions);
if (name && !filter(name)) {
pruneCacheEntry(cache, key, keys, _vnode);
}
}
}
}
function pruneCacheEntry (
cache,
key,
keys,
current
) {
const cached$$1 = cache[key];
if (cached$$1 && (!current || cached$$1.tag !== current.tag)) {
cached$$1.componentInstance.$destroy();
}
cache[key] = null;
remove(keys, key);
}
const patternTypes = [String, RegExp, Array];
var KeepAlive = {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes,
max: [String, Number]
},
created () {
this.cache = Object.create(null);
this.keys = [];
},
destroyed () {
for (const key in this.cache) {
pruneCacheEntry(this.cache, key, this.keys);
}
},
mounted () {
this.$watch('include', val => {
pruneCache(this, name => matches(val, name));
});
this.$watch('exclude', val => {
pruneCache(this, name => !matches(val, name));
});
},
render () {
const slot = this.$slots.default;
const vnode = getFirstComponentChild(slot);
const componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
const name = getComponentName(componentOptions);
const { include, exclude } = this;
if (
// not included
(include && (!name || !matches(include, name))) ||
// excluded
(exclude && name && matches(exclude, name))
) {
return vnode
}
const { cache, keys } = this;
const key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
: vnode.key;
if (cache[key]) {
vnode.componentInstance = cache[key].componentInstance;
// make current key freshest
remove(keys, key);
keys.push(key);
} else {
cache[key] = vnode;
keys.push(key);
// prune oldest entry
if (this.max && keys.length > parseInt(this.max)) {
pruneCacheEntry(cache, keys[0], keys, this._vnode);
}
}
vnode.data.keepAlive = true;
}
return vnode || (slot && slot[0])
}
};
var builtInComponents = {
KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
const configDef = {};
configDef.get = () => config;
{
configDef.set = () => {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
);
};
}
Object.defineProperty(Vue, 'config', configDef);
// exposed util methods.
// NOTE: these are not considered part of the public API - avoid relying on
// them unless you are aware of the risk.
Vue.util = {
warn,
extend,
mergeOptions,
defineReactive: defineReactive$$1
};
Vue.set = set;
Vue.delete = del;
Vue.nextTick = nextTick;
// 2.6 explicit observable API
Vue.observable = (obj) => {
observe(obj);
return obj
};
Vue.options = Object.create(null);
ASSET_TYPES.forEach(type => {
Vue.options[type + 's'] = Object.create(null);
});
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue;
extend(Vue.options.components, builtInComponents);
initUse(Vue);
initMixin$1(Vue);
initExtend(Vue);
initAssetRegisters(Vue);
}
initGlobalAPI(Vue);
Object.defineProperty(Vue.prototype, '$isServer', {
get: isServerRendering
});
Object.defineProperty(Vue.prototype, '$ssrContext', {
get () {
/* istanbul ignore next */
return this.$vnode && this.$vnode.ssrContext
}
});
// expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue, 'FunctionalRenderContext', {
value: FunctionalRenderContext
});
Vue.version = '2.6.1';
/* */
// these are reserved for web because they are directly compiled away
// during template compilation
const isReservedAttr = makeMap('style,class');
// attributes that should be using props for binding
const acceptValue = makeMap('input,textarea,option,select,progress');
const mustUseProp = (tag, type, attr) => {
return (
(attr === 'value' && acceptValue(tag)) && type !== 'button' ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
)
};
const isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
const isValidContentEditableValue = makeMap('events,caret,typing,plaintext-only');
const convertEnumeratedValue = (key, value) => {
return isFalsyAttrValue(value) || value === 'false'
? 'false'
// allow arbitrary string value for contenteditable
: key === 'contenteditable' && isValidContentEditableValue(value)
? value
: 'true'
};
const isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
);
const xlinkNS = 'http://www.w3.org/1999/xlink';
const isXlink = (name) => {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
};
const getXlinkProp = (name) => {
return isXlink(name) ? name.slice(6, name.length) : ''
};
const isFalsyAttrValue = (val) => {
return val == null || val === false
};
/* */
function genClassForVnode (vnode) {
let data = vnode.data;
let parentNode = vnode;
let childNode = vnode;
while (isDef(childNode.componentInstance)) {
childNode = childNode.componentInstance._vnode;
if (childNode && childNode.data) {
data = mergeClassData(childNode.data, data);
}
}
while (isDef(parentNode = parentNode.parent)) {
if (parentNode && parentNode.data) {
data = mergeClassData(data, parentNode.data);
}
}
return renderClass(data.staticClass, data.class)
}
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: isDef(child.class)
? [child.class, parent.class]
: parent.class
}
}
function renderClass (
staticClass,
dynamicClass
) {
if (isDef(staticClass) || isDef(dynamicClass)) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
if (Array.isArray(value)) {
return stringifyArray(value)
}
if (isObject(value)) {
return stringifyObject(value)
}
if (typeof value === 'string') {
return value
}
/* istanbul ignore next */
return ''
}
function stringifyArray (value) {
let res = '';
let stringified;
for (let i = 0, l = value.length; i < l; i++) {
if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') {
if (res) res += ' ';
res += stringified;
}
}
return res
}
function stringifyObject (value) {
let res = '';
for (const key in value) {
if (value[key]) {
if (res) res += ' ';
res += key;
}
}
return res
}
/* */
const namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML'
};
const isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template,blockquote,iframe,tfoot'
);
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
const isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' +
'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
);
const isPreTag = (tag) => tag === 'pre';
const isReservedTag = (tag) => {
return isHTMLTag(tag) || isSVG(tag)
};
function getTagNamespace (tag) {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
const unknownElementCache = Object.create(null);
function isUnknownElement (tag) {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase();
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
const el = document.createElement(tag);
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
const isTextInputType = makeMap('text,number,password,search,email,tel,url');
/* */
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
const selected = document.querySelector(el);
if (!selected) {
warn(
'Cannot find element: ' + el
);
return document.createElement('div')
}
return selected
} else {
return el
}
}
/* */
function createElement$1 (tagName, vnode) {
const elm = document.createElement(tagName);
if (tagName !== 'select') {
return elm
}
// false or null will remove the attribute but undefined will not
if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) {
elm.setAttribute('multiple', 'multiple');
}
return elm
}
function createElementNS (namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName)
}
function createTextNode (text) {
return document.createTextNode(text)
}
function createComment (text) {
return document.createComment(text)
}
function insertBefore (parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode);
}
function removeChild (node, child) {
node.removeChild(child);
}
function appendChild (node, child) {
node.appendChild(child);
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.tagName
}
function setTextContent (node, text) {
node.textContent = text;
}
function setStyleScope (node, scopeId) {
node.setAttribute(scopeId, '');
}
var nodeOps = /*#__PURE__*/Object.freeze({
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
setStyleScope: setStyleScope
});
/* */
var ref = {
create (_, vnode) {
registerRef(vnode);
},
update (oldVnode, vnode) {
if (oldVnode.data.ref !== vnode.data.ref) {
registerRef(oldVnode, true);
registerRef(vnode);
}
},
destroy (vnode) {
registerRef(vnode, true);
}
};
function registerRef (vnode, isRemoval) {
const key = vnode.data.ref;
if (!isDef(key)) return
const vm = vnode.context;
const ref = vnode.componentInstance || vnode.elm;
const refs = vm.$refs;
if (isRemoval) {
if (Array.isArray(refs[key])) {
remove(refs[key], ref);
} else if (refs[key] === ref) {
refs[key] = undefined;
}
} else {
if (vnode.data.refInFor) {
if (!Array.isArray(refs[key])) {
refs[key] = [ref];
} else if (refs[key].indexOf(ref) < 0) {
// $flow-disable-line
refs[key].push(ref);
}
} else {
refs[key] = ref;
}
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
const emptyNode = new VNode('', {}, []);
const hooks = ['create', 'activate', 'update', 'remove', 'destroy'];
function sameVnode (a, b) {
return (
a.key === b.key && (
(
a.tag === b.tag &&
a.isComment === b.isComment &&
isDef(a.data) === isDef(b.data) &&
sameInputType(a, b)
) || (
isTrue(a.isAsyncPlaceholder) &&
a.asyncFactory === b.asyncFactory &&
isUndef(b.asyncFactory.error)
)
)
)
}
function sameInputType (a, b) {
if (a.tag !== 'input') return true
let i;
const typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type;
const typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type;
return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
let i, key;
const map = {};
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) map[key] = i;
}
return map
}
function createPatchFunction (backend) {
let i, j;
const cbs = {};
const { modules, nodeOps } = backend;
for (i = 0; i < hooks.length; ++i) {
cbs[hooks[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (isDef(modules[j][hooks[i]])) {
cbs[hooks[i]].push(modules[j][hooks[i]]);
}
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove$$1 () {
if (--remove$$1.listeners === 0) {
removeNode(childElm);
}
}
remove$$1.listeners = listeners;
return remove$$1
}
function removeNode (el) {
const parent = nodeOps.parentNode(el);
// element may have already been removed due to v-html / v-text
if (isDef(parent)) {
nodeOps.removeChild(parent, el);
}
}
function isUnknownElement$$1 (vnode, inVPre) {
return (
!inVPre &&
!vnode.ns &&
!(
config.ignoredElements.length &&
config.ignoredElements.some(ignore => {
return isRegExp(ignore)
? ignore.test(vnode.tag)
: ignore === vnode.tag
})
) &&
config.isUnknownElement(vnode.tag)
)
}
let creatingElmInVPre = 0;
function createElm (
vnode,
insertedVnodeQueue,
parentElm,
refElm,
nested,
ownerArray,
index
) {
if (isDef(vnode.elm) && isDef(ownerArray)) {
// This vnode was used in a previous render!
// now it's used as a new node, overwriting its elm would cause
// potential patch errors down the road when it's used as an insertion
// reference node. Instead, we clone the node on-demand before creating
// associated DOM element for it.
vnode = ownerArray[index] = cloneVNode(vnode);
}
vnode.isRootInsert = !nested; // for transition enter check
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
const data = vnode.data;
const children = vnode.children;
const tag = vnode.tag;
if (isDef(tag)) {
{
if (data && data.pre) {
creatingElmInVPre++;
}
if (isUnknownElement$$1(vnode, creatingElmInVPre)) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
);
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode);
setScope(vnode);
/* istanbul ignore if */
{
createChildren(vnode, children, insertedVnodeQueue);
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
insert(parentElm, vnode.elm, refElm);
}
if (data && data.pre) {
creatingElmInVPre--;
}
} else if (isTrue(vnode.isComment)) {
vnode.elm = nodeOps.createComment(vnode.text);
insert(parentElm, vnode.elm, refElm);
} else {
vnode.elm = nodeOps.createTextNode(vnode.text);
insert(parentElm, vnode.elm, refElm);
}
}
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
let i = vnode.data;
if (isDef(i)) {
const isReactivated = isDef(vnode.componentInstance) && i.keepAlive;
if (isDef(i = i.hook) && isDef(i = i.init)) {
i(vnode, false /* hydrating */);
}
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(vnode.componentInstance)) {
initComponent(vnode, insertedVnodeQueue);
insert(parentElm, vnode.elm, refElm);
if (isTrue(isReactivated)) {
reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);
}
return true
}
}
}
function initComponent (vnode, insertedVnodeQueue) {
if (isDef(vnode.data.pendingInsert)) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
vnode.data.pendingInsert = null;
}
vnode.elm = vnode.componentInstance.$el;
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
setScope(vnode);
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode);
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode);
}
}
function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
let i;
// hack for #4339: a reactivated component with inner transition
// does not trigger because the inner node's created hooks are not called
// again. It's not ideal to involve module-specific logic in here but
// there doesn't seem to be a better way to do it.
let innerNode = vnode;
while (innerNode.componentInstance) {
innerNode = innerNode.componentInstance._vnode;
if (isDef(i = innerNode.data) && isDef(i = i.transition)) {
for (i = 0; i < cbs.activate.length; ++i) {
cbs.activate[i](emptyNode, innerNode);
}
insertedVnodeQueue.push(innerNode);
break
}
}
// unlike a newly created component,
// a reactivated keep-alive component doesn't insert itself
insert(parentElm, vnode.elm, refElm);
}
function insert (parent, elm, ref$$1) {
if (isDef(parent)) {
if (isDef(ref$$1)) {
if (nodeOps.parentNode(ref$$1) === parent) {
nodeOps.insertBefore(parent, elm, ref$$1);
}
} else {
nodeOps.appendChild(parent, elm);
}
}
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
{
checkDuplicateKeys(children);
}
for (let i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true, children, i);
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)));
}
}
function isPatchable (vnode) {
while (vnode.componentInstance) {
vnode = vnode.componentInstance._vnode;
}
return isDef(vnode.tag)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode);
}
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (isDef(i.create)) i.create(emptyNode, vnode);
if (isDef(i.insert)) insertedVnodeQueue.push(vnode);
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
let i;
if (isDef(i = vnode.fnScopeId)) {
nodeOps.setStyleScope(vnode.elm, i);
} else {
let ancestor = vnode;
while (ancestor) {
if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setStyleScope(vnode.elm, i);
}
ancestor = ancestor.parent;
}
}
// for slot content they should also get the scopeId from the host instance.
if (isDef(i = activeInstance) &&
i !== vnode.context &&
i !== vnode.fnContext &&
isDef(i = i.$options._scopeId)
) {
nodeOps.setStyleScope(vnode.elm, i);
}
}
function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, false, vnodes, startIdx);
}
}
function invokeDestroyHook (vnode) {
let i, j;
const data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) i(vnode);
for (i = 0; i < cbs.destroy.length; ++i) cbs.destroy[i](vnode);
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
const ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch);
invokeDestroyHook(ch);
} else { // Text node
removeNode(ch.elm);
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (isDef(rm) || isDef(vnode.data)) {
let i;
const listeners = cbs.remove.length + 1;
if (isDef(rm)) {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners;
} else {
// directly removing
rm = createRmCb(vnode.elm, listeners);
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm);
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm);
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm);
} else {
rm();
}
} else {
removeNode(vnode.elm);
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
let oldStartIdx = 0;
let newStartIdx = 0;
let oldEndIdx = oldCh.length - 1;
let oldStartVnode = oldCh[0];
let oldEndVnode = oldCh[oldEndIdx];
let newEndIdx = newCh.length - 1;
let newStartVnode = newCh[0];
let newEndVnode = newCh[newEndIdx];
let oldKeyToIdx, idxInOld, vnodeToMove, refElm;
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
const canMove = !removeOnly;
{
checkDuplicateKeys(newCh);
}
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx);
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx);
idxInOld = isDef(newStartVnode.key)
? oldKeyToIdx[newStartVnode.key]
: findIdxInOld(newStartVnode, oldCh, oldStartIdx, oldEndIdx);
if (isUndef(idxInOld)) { // New element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx);
} else {
vnodeToMove = oldCh[idxInOld];
if (sameVnode(vnodeToMove, newStartVnode)) {
patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx);
oldCh[idxInOld] = undefined;
canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm);
} else {
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, false, newCh, newStartIdx);
}
}
newStartVnode = newCh[++newStartIdx];
}
}
if (oldStartIdx > oldEndIdx) {
refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function checkDuplicateKeys (children) {
const seenKeys = {};
for (let i = 0; i < children.length; i++) {
const vnode = children[i];
const key = vnode.key;
if (isDef(key)) {
if (seenKeys[key]) {
warn(
`Duplicate keys detected: '${key}'. This may cause an update error.`,
vnode.context
);
} else {
seenKeys[key] = true;
}
}
}
}
function findIdxInOld (node, oldCh, start, end) {
for (let i = start; i < end; i++) {
const c = oldCh[i];
if (isDef(c) && sameVnode(node, c)) return i
}
}
function patchVnode (
oldVnode,
vnode,
insertedVnodeQueue,
ownerArray,
index,
removeOnly
) {
if (oldVnode === vnode) {
return
}
if (isDef(vnode.elm) && isDef(ownerArray)) {
// clone reused vnode
vnode = ownerArray[index] = cloneVNode(vnode);
}
const elm = vnode.elm = oldVnode.elm;
if (isTrue(oldVnode.isAsyncPlaceholder)) {
if (isDef(vnode.asyncFactory.resolved)) {
hydrate(oldVnode.elm, vnode, insertedVnodeQueue);
} else {
vnode.isAsyncPlaceholder = true;
}
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (isTrue(vnode.isStatic) &&
isTrue(oldVnode.isStatic) &&
vnode.key === oldVnode.key &&
(isTrue(vnode.isCloned) || isTrue(vnode.isOnce))
) {
vnode.componentInstance = oldVnode.componentInstance;
return
}
let i;
const data = vnode.data;
if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode);
}
const oldCh = oldVnode.children;
const ch = vnode.children;
if (isDef(data) && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) cbs.update[i](oldVnode, vnode);
if (isDef(i = data.hook) && isDef(i = i.update)) i(oldVnode, vnode);
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly);
} else if (isDef(ch)) {
{
checkDuplicateKeys(ch);
}
if (isDef(oldVnode.text)) nodeOps.setTextContent(elm, '');
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '');
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text);
}
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) i(oldVnode, vnode);
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (isTrue(initial) && isDef(vnode.parent)) {
vnode.parent.data.pendingInsert = queue;
} else {
for (let i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i]);
}
}
}
let hydrationBailed = false;
// list of modules that can skip create hook during hydration because they
// are already rendered on the client or has no need for initialization
// Note: style is excluded because it relies on initial clone for future
// deep updates (#7063).
const isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key');
// Note: this is a browser-only function so we can assume elms are DOM nodes.
function hydrate (elm, vnode, insertedVnodeQueue, inVPre) {
let i;
const { tag, data, children } = vnode;
inVPre = inVPre || (data && data.pre);
vnode.elm = elm;
if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) {
vnode.isAsyncPlaceholder = true;
return true
}
// assert node match
{
if (!assertNodeMatch(elm, vnode, inVPre)) {
return false
}
}
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) i(vnode, true /* hydrating */);
if (isDef(i = vnode.componentInstance)) {
// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue);
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
// empty element, allow client to pick up and populate children
if (!elm.hasChildNodes()) {
createChildren(vnode, children, insertedVnodeQueue);
} else {
// v-html and domProps: innerHTML
if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) {
if (i !== elm.innerHTML) {
/* istanbul ignore if */
if (typeof console !== 'undefined' &&
!hydrationBailed
) {
hydrationBailed = true;
console.warn('Parent: ', elm);
console.warn('server innerHTML: ', i);
console.warn('client innerHTML: ', elm.innerHTML);
}
return false
}
} else {
// iterate and compare children lists
let childrenMatch = true;
let childNode = elm.firstChild;
for (let i = 0; i < children.length; i++) {
if (!childNode || !hydrate(childNode, children[i], insertedVnodeQueue, inVPre)) {
childrenMatch = false;
break
}
childNode = childNode.nextSibling;
}
// if childNode is not null, it means the actual childNodes list is
// longer than the virtual children list.
if (!childrenMatch || childNode) {
/* istanbul ignore if */
if (typeof console !== 'undefined' &&
!hydrationBailed
) {
hydrationBailed = true;
console.warn('Parent: ', elm);
console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
}
return false
}
}
}
}
if (isDef(data)) {
let fullInvoke = false;
for (const key in data) {
if (!isRenderedModule(key)) {
fullInvoke = true;
invokeCreateHooks(vnode, insertedVnodeQueue);
break
}
}
if (!fullInvoke && data['class']) {
// ensure collecting deps for deep class bindings for future updates
traverse(data['class']);
}
}
} else if (elm.data !== vnode.text) {
elm.data = vnode.text;
}
return true
}
function assertNodeMatch (node, vnode, inVPre) {
if (isDef(vnode.tag)) {
return vnode.tag.indexOf('vue-component') === 0 || (
!isUnknownElement$$1(vnode, inVPre) &&
vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
)
} else {
return node.nodeType === (vnode.isComment ? 8 : 3)
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly) {
if (isUndef(vnode)) {
if (isDef(oldVnode)) invokeDestroyHook(oldVnode);
return
}
let isInitialPatch = false;
const insertedVnodeQueue = [];
if (isUndef(oldVnode)) {
// empty mount (likely as component), create new root element
isInitialPatch = true;
createElm(vnode, insertedVnodeQueue);
} else {
const isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly);
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) {
oldVnode.removeAttribute(SSR_ATTR);
hydrating = true;
}
if (isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true);
return oldVnode
} else {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
);
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode);
}
// replacing existing element
const oldElm = oldVnode.elm;
const parentElm = nodeOps.parentNode(oldElm);
// create new node
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm,
nodeOps.nextSibling(oldElm)
);
// update parent placeholder node element, recursively
if (isDef(vnode.parent)) {
let ancestor = vnode.parent;
const patchable = isPatchable(vnode);
while (ancestor) {
for (let i = 0; i < cbs.destroy.length; ++i) {
cbs.destroy[i](ancestor);
}
ancestor.elm = vnode.elm;
if (patchable) {
for (let i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, ancestor);
}
// #6513
// invoke insert hooks that may have been merged by create hooks.
// e.g. for directives that uses the "inserted" hook.
const insert = ancestor.data.hook.insert;
if (insert.merged) {
// start at index 1 to avoid re-invoking component mounted hook
for (let i = 1; i < insert.fns.length; i++) {
insert.fns[i]();
}
}
} else {
registerRef(ancestor);
}
ancestor = ancestor.parent;
}
}
// destroy old node
if (isDef(parentElm)) {
removeVnodes(parentElm, [oldVnode], 0, 0);
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode);
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);
return vnode.elm
}
}
/* */
var directives = {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives (vnode) {
updateDirectives(vnode, emptyNode);
}
};
function updateDirectives (oldVnode, vnode) {
if (oldVnode.data.directives || vnode.data.directives) {
_update(oldVnode, vnode);
}
}
function _update (oldVnode, vnode) {
const isCreate = oldVnode === emptyNode;
const isDestroy = vnode === emptyNode;
const oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);
const newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);
const dirsWithInsert = [];
const dirsWithPostpatch = [];
let key, oldDir, dir;
for (key in newDirs) {
oldDir = oldDirs[key];
dir = newDirs[key];
if (!oldDir) {
// new directive, bind
callHook$1(dir, 'bind', vnode, oldVnode);
if (dir.def && dir.def.inserted) {
dirsWithInsert.push(dir);
}
} else {
// existing directive, update
dir.oldValue = oldDir.value;
dir.oldArg = oldDir.arg;
callHook$1(dir, 'update', vnode, oldVnode);
if (dir.def && dir.def.componentUpdated) {
dirsWithPostpatch.push(dir);
}
}
}
if (dirsWithInsert.length) {
const callInsert = () => {
for (let i = 0; i < dirsWithInsert.length; i++) {
callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);
}
};
if (isCreate) {
mergeVNodeHook(vnode, 'insert', callInsert);
} else {
callInsert();
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode, 'postpatch', () => {
for (let i = 0; i < dirsWithPostpatch.length; i++) {
callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);
}
});
}
if (!isCreate) {
for (key in oldDirs) {
if (!newDirs[key]) {
// no longer present, unbind
callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);
}
}
}
}
const emptyModifiers = Object.create(null);
function normalizeDirectives$1 (
dirs,
vm
) {
const res = Object.create(null);
if (!dirs) {
// $flow-disable-line
return res
}
let i, dir;
for (i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!dir.modifiers) {
// $flow-disable-line
dir.modifiers = emptyModifiers;
}
res[getRawDirName(dir)] = dir;
dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
}
// $flow-disable-line
return res
}
function getRawDirName (dir) {
return dir.rawName || `${dir.name}.${Object.keys(dir.modifiers || {}).join('.')}`
}
function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) {
const fn = dir.def && dir.def[hook];
if (fn) {
try {
fn(vnode.elm, dir, vnode, oldVnode, isDestroy);
} catch (e) {
handleError(e, vnode.context, `directive ${dir.name} ${hook} hook`);
}
}
}
var baseModules = [
ref,
directives
];
/* */
function updateAttrs (oldVnode, vnode) {
const opts = vnode.componentOptions;
if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) {
return
}
if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) {
return
}
let key, cur, old;
const elm = vnode.elm;
const oldAttrs = oldVnode.data.attrs || {};
let attrs = vnode.data.attrs || {};
// clone observed objects, as the user probably wants to mutate it
if (isDef(attrs.__ob__)) {
attrs = vnode.data.attrs = extend({}, attrs);
}
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
setAttr(elm, key, cur);
}
}
// #4391: in IE9, setting type can reset value for input[type=radio]
// #6666: IE/Edge forces progress value down to 1 before setting a max
/* istanbul ignore if */
if ((isIE || isEdge) && attrs.value !== oldAttrs.value) {
setAttr(elm, 'value', attrs.value);
}
for (key in oldAttrs) {
if (isUndef(attrs[key])) {
if (isXlink(key)) {
elm.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else if (!isEnumeratedAttr(key)) {
elm.removeAttribute(key);
}
}
}
}
function setAttr (el, key, value) {
if (el.tagName.indexOf('-') > -1) {
baseSetAttr(el, key, value);
} else if (isBooleanAttr(key)) {
// set attribute for blank value
// e.g. <option disabled>Select one</option>
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
// technically allowfullscreen is a boolean attribute for <iframe>,
// but Flash expects a value of "true" when used on <embed> tag
value = key === 'allowfullscreen' && el.tagName === 'EMBED'
? 'true'
: key;
el.setAttribute(key, value);
}
} else if (isEnumeratedAttr(key)) {
el.setAttribute(key, convertEnumeratedValue(key, value));
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
el.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else {
el.setAttributeNS(xlinkNS, key, value);
}
} else {
baseSetAttr(el, key, value);
}
}
function baseSetAttr (el, key, value) {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
// #7138: IE10 & 11 fires input event when setting placeholder on
// <textarea>... block the first input event and remove the blocker
// immediately.
/* istanbul ignore if */
if (
isIE && !isIE9 &&
el.tagName === 'TEXTAREA' &&
key === 'placeholder' && value !== '' && !el.__ieph
) {
const blocker = e => {
e.stopImmediatePropagation();
el.removeEventListener('input', blocker);
};
el.addEventListener('input', blocker);
// $flow-disable-line
el.__ieph = true; /* IE placeholder patched */
}
el.setAttribute(key, value);
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
};
/* */
function updateClass (oldVnode, vnode) {
const el = vnode.elm;
const data = vnode.data;
const oldData = oldVnode.data;
if (
isUndef(data.staticClass) &&
isUndef(data.class) && (
isUndef(oldData) || (
isUndef(oldData.staticClass) &&
isUndef(oldData.class)
)
)
) {
return
}
let cls = genClassForVnode(vnode);
// handle transition classes
const transitionClass = el._transitionClasses;
if (isDef(transitionClass)) {
cls = concat(cls, stringifyClass(transitionClass));
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls);
el._prevClass = cls;
}
}
var klass = {
create: updateClass,
update: updateClass
};
/* */
const validDivisionCharRE = /[\w).+\-_$\]]/;
function parseFilters (exp) {
let inSingle = false;
let inDouble = false;
let inTemplateString = false;
let inRegex = false;
let curly = 0;
let square = 0;
let paren = 0;
let lastFilterIndex = 0;
let c, prev, i, expression, filters;
for (i = 0; i < exp.length; i++) {
prev = c;
c = exp.charCodeAt(i);
if (inSingle) {
if (c === 0x27 && prev !== 0x5C) inSingle = false;
} else if (inDouble) {
if (c === 0x22 && prev !== 0x5C) inDouble = false;
} else if (inTemplateString) {
if (c === 0x60 && prev !== 0x5C) inTemplateString = false;
} else if (inRegex) {
if (c === 0x2f && prev !== 0x5C) inRegex = false;
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1;
expression = exp.slice(0, i).trim();
} else {
pushFilter();
}
} else {
switch (c) {
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x60: inTemplateString = true; break // `
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
if (c === 0x2f) { // /
let j = i - 1;
let p;
// find first non-whitespace prev char
for (; j >= 0; j--) {
p = exp.charAt(j);
if (p !== ' ') break
}
if (!p || !validDivisionCharRE.test(p)) {
inRegex = true;
}
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim();
} else if (lastFilterIndex !== 0) {
pushFilter();
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());
lastFilterIndex = i + 1;
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i]);
}
}
return expression
}
function wrapFilter (exp, filter) {
const i = filter.indexOf('(');
if (i < 0) {
// _f: resolveFilter
return `_f("${filter}")(${exp})`
} else {
const name = filter.slice(0, i);
const args = filter.slice(i + 1);
return `_f("${name}")(${exp}${args !== ')' ? ',' + args : args}`
}
}
/* */
/* eslint-disable no-unused-vars */
function baseWarn (msg, range) {
console.error(`[Vue compiler]: ${msg}`);
}
/* eslint-enable no-unused-vars */
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(m => m[key]).filter(_ => _)
: []
}
function addProp (el, name, value, range, dynamic) {
(el.props || (el.props = [])).push(rangeSetItem({ name, value, dynamic }, range));
el.plain = false;
}
function addAttr (el, name, value, range, dynamic) {
const attrs = dynamic
? (el.dynamicAttrs || (el.dynamicAttrs = []))
: (el.attrs || (el.attrs = []));
attrs.push(rangeSetItem({ name, value, dynamic }, range));
el.plain = false;
}
// add a raw attr (use this in preTransforms)
function addRawAttr (el, name, value, range) {
el.attrsMap[name] = value;
el.attrsList.push(rangeSetItem({ name, value }, range));
}
function addDirective (
el,
name,
rawName,
value,
arg,
isDynamicArg,
modifiers,
range
) {
(el.directives || (el.directives = [])).push(rangeSetItem({
name,
rawName,
value,
arg,
isDynamicArg,
modifiers
}, range));
el.plain = false;
}
function prependModifierMarker (symbol, name, dynamic) {
return dynamic
? `_p(${name},"${symbol}")`
: symbol + name // mark the event as captured
}
function addHandler (
el,
name,
value,
modifiers,
important,
warn,
range,
dynamic
) {
modifiers = modifiers || emptyObject;
// warn prevent and passive modifier
/* istanbul ignore if */
if (
warn &&
modifiers.prevent && modifiers.passive
) {
warn(
'passive and prevent can\'t be used together. ' +
'Passive handler can\'t prevent default event.',
range
);
}
// normalize click.right and click.middle since they don't actually fire
// this is technically browser-specific, but at least for now browsers are
// the only target envs that have right/middle clicks.
if (modifiers.right) {
if (dynamic) {
name = `(${name})==='click'?'contextmenu':(${name})`;
} else if (name === 'click') {
name = 'contextmenu';
delete modifiers.right;
}
} else if (modifiers.middle) {
if (dynamic) {
name = `(${name})==='click'?'mouseup':(${name})`;
} else if (name === 'click') {
name = 'mouseup';
}
}
// check capture modifier
if (modifiers.capture) {
delete modifiers.capture;
name = prependModifierMarker('!', name, dynamic);
}
if (modifiers.once) {
delete modifiers.once;
name = prependModifierMarker('~', name, dynamic);
}
/* istanbul ignore if */
if (modifiers.passive) {
delete modifiers.passive;
name = prependModifierMarker('&', name, dynamic);
}
let events;
if (modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
const newHandler = rangeSetItem({ value: value.trim(), dynamic }, range);
if (modifiers !== emptyObject) {
newHandler.modifiers = modifiers;
}
const handlers = events[name];
/* istanbul ignore if */
if (Array.isArray(handlers)) {
important ? handlers.unshift(newHandler) : handlers.push(newHandler);
} else if (handlers) {
events[name] = important ? [newHandler, handlers] : [handlers, newHandler];
} else {
events[name] = newHandler;
}
el.plain = false;
}
function getRawBindingAttr (
el,
name
) {
return el.rawAttrsMap[':' + name] ||
el.rawAttrsMap['v-bind:' + name] ||
el.rawAttrsMap[name]
}
function getBindingAttr (
el,
name,
getStatic
) {
const dynamicValue =
getAndRemoveAttr(el, ':' + name) ||
getAndRemoveAttr(el, 'v-bind:' + name);
if (dynamicValue != null) {
return parseFilters(dynamicValue)
} else if (getStatic !== false) {
const staticValue = getAndRemoveAttr(el, name);
if (staticValue != null) {
return JSON.stringify(staticValue)
}
}
}
// note: this only removes the attr from the Array (attrsList) so that it
// doesn't get processed by processAttrs.
// By default it does NOT remove it from the map (attrsMap) because the map is
// needed during codegen.
function getAndRemoveAttr (
el,
name,
removeFromMap
) {
let val;
if ((val = el.attrsMap[name]) != null) {
const list = el.attrsList;
for (let i = 0, l = list.length; i < l; i++) {
if (list[i].name === name) {
list.splice(i, 1);
break
}
}
}
if (removeFromMap) {
delete el.attrsMap[name];
}
return val
}
function getAndRemoveAttrByRegex (
el,
name
) {
const list = el.attrsList;
for (let i = 0, l = list.length; i < l; i++) {
const attr = list[i];
if (name.test(attr.name)) {
list.splice(i, 1);
return attr
}
}
}
function rangeSetItem (
item,
range
) {
if (range) {
if (range.start != null) {
item.start = range.start;
}
if (range.end != null) {
item.end = range.end;
}
}
return item
}
/* */
/**
* Cross-platform code generation for component v-model
*/
function genComponentModel (
el,
value,
modifiers
) {
const { number, trim } = modifiers || {};
const baseValueExpression = '$$v';
let valueExpression = baseValueExpression;
if (trim) {
valueExpression =
`(typeof ${baseValueExpression} === 'string'` +
`? ${baseValueExpression}.trim()` +
`: ${baseValueExpression})`;
}
if (number) {
valueExpression = `_n(${valueExpression})`;
}
const assignment = genAssignmentCode(value, valueExpression);
el.model = {
value: `(${value})`,
expression: JSON.stringify(value),
callback: `function (${baseValueExpression}) {${assignment}}`
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/
function genAssignmentCode (
value,
assignment
) {
const res = parseModel(value);
if (res.key === null) {
return `${value}=${assignment}`
} else {
return `$set(${res.exp}, ${res.key}, ${assignment})`
}
}
/**
* Parse a v-model expression into a base path and a final key segment.
* Handles both dot-path and possible square brackets.
*
* Possible cases:
*
* - test
* - test[key]
* - test[test1[key]]
* - test["a"][key]
* - xxx.test[a[a].test1[key]]
* - test.xxx.a["asa"][test1[key]]
*
*/
let len, str, chr, index$1, expressionPos, expressionEndPos;
function parseModel (val) {
// Fix https://github.com/vuejs/vue/pull/7730
// allow v-model="obj.val " (trailing whitespace)
val = val.trim();
len = val.length;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
index$1 = val.lastIndexOf('.');
if (index$1 > -1) {
return {
exp: val.slice(0, index$1),
key: '"' + val.slice(index$1 + 1) + '"'
}
} else {
return {
exp: val,
key: null
}
}
}
str = val;
index$1 = expressionPos = expressionEndPos = 0;
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.slice(0, expressionPos),
key: val.slice(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index$1)
}
function eof () {
return index$1 >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
let inBracket = 1;
expressionPos = index$1;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) inBracket++;
if (chr === 0x5D) inBracket--;
if (inBracket === 0) {
expressionEndPos = index$1;
break
}
}
}
function parseString (chr) {
const stringQuote = chr;
while (!eof()) {
chr = next();
if (chr === stringQuote) {
break
}
}
}
/* */
let warn$1;
// in some cases, the event used has to be determined at runtime
// so we used some reserved tokens during compile.
const RANGE_TOKEN = '__r';
const CHECKBOX_RADIO_TOKEN = '__c';
function model (
el,
dir,
_warn
) {
warn$1 = _warn;
const value = dir.value;
const modifiers = dir.modifiers;
const tag = el.tag;
const type = el.attrsMap.type;
{
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (tag === 'input' && type === 'file') {
warn$1(
`<${el.tag} v-model="${value}" type="file">:\n` +
`File inputs are read only. Use a v-on:change listener instead.`,
el.rawAttrsMap['v-model']
);
}
}
if (el.component) {
genComponentModel(el, value, modifiers);
// component v-model doesn't need extra runtime
return false
} else if (tag === 'select') {
genSelect(el, value, modifiers);
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers);
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers);
} else if (tag === 'input' || tag === 'textarea') {
genDefaultModel(el, value, modifiers);
} else if (!config.isReservedTag(tag)) {
genComponentModel(el, value, modifiers);
// component v-model doesn't need extra runtime
return false
} else {
warn$1(
`<${el.tag} v-model="${value}">: ` +
`v-model is not supported on this element type. ` +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.',
el.rawAttrsMap['v-model']
);
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el,
value,
modifiers
) {
const number = modifiers && modifiers.number;
const valueBinding = getBindingAttr(el, 'value') || 'null';
const trueValueBinding = getBindingAttr(el, 'true-value') || 'true';
const falseValueBinding = getBindingAttr(el, 'false-value') || 'false';
addProp(el, 'checked',
`Array.isArray(${value})` +
`?_i(${value},${valueBinding})>-1` + (
trueValueBinding === 'true'
? `:(${value})`
: `:_q(${value},${trueValueBinding})`
)
);
addHandler(el, 'change',
`var $$a=${value},` +
'$$el=$event.target,' +
`$$c=$$el.checked?(${trueValueBinding}):(${falseValueBinding});` +
'if(Array.isArray($$a)){' +
`var $$v=${number ? '_n(' + valueBinding + ')' : valueBinding},` +
'$$i=_i($$a,$$v);' +
`if($$el.checked){$$i<0&&(${genAssignmentCode(value, '$$a.concat([$$v])')})}` +
`else{$$i>-1&&(${genAssignmentCode(value, '$$a.slice(0,$$i).concat($$a.slice($$i+1))')})}` +
`}else{${genAssignmentCode(value, '$$c')}}`,
null, true
);
}
function genRadioModel (
el,
value,
modifiers
) {
const number = modifiers && modifiers.number;
let valueBinding = getBindingAttr(el, 'value') || 'null';
valueBinding = number ? `_n(${valueBinding})` : valueBinding;
addProp(el, 'checked', `_q(${value},${valueBinding})`);
addHandler(el, 'change', genAssignmentCode(value, valueBinding), null, true);
}
function genSelect (
el,
value,
modifiers
) {
const number = modifiers && modifiers.number;
const selectedVal = `Array.prototype.filter` +
`.call($event.target.options,function(o){return o.selected})` +
`.map(function(o){var val = "_value" in o ? o._value : o.value;` +
`return ${number ? '_n(val)' : 'val'}})`;
const assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]';
let code = `var $$selectedVal = ${selectedVal};`;
code = `${code} ${genAssignmentCode(value, assignment)}`;
addHandler(el, 'change', code, null, true);
}
function genDefaultModel (
el,
value,
modifiers
) {
const type = el.attrsMap.type;
// warn if v-bind:value conflicts with v-model
// except for inputs with v-bind:type
{
const value = el.attrsMap['v-bind:value'] || el.attrsMap[':value'];
const typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (value && !typeBinding) {
const binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value';
warn$1(
`${binding}="${value}" conflicts with v-model on the same element ` +
'because the latter already expands to a value binding internally',
el.rawAttrsMap[binding]
);
}
}
const { lazy, number, trim } = modifiers || {};
const needCompositionGuard = !lazy && type !== 'range';
const event = lazy
? 'change'
: type === 'range'
? RANGE_TOKEN
: 'input';
let valueExpression = '$event.target.value';
if (trim) {
valueExpression = `$event.target.value.trim()`;
}
if (number) {
valueExpression = `_n(${valueExpression})`;
}
let code = genAssignmentCode(value, valueExpression);
if (needCompositionGuard) {
code = `if($event.target.composing)return;${code}`;
}
addProp(el, 'value', `(${value})`);
addHandler(el, event, code, null, true);
if (trim || number) {
addHandler(el, 'blur', '$forceUpdate()');
}
}
/* */
// normalize v-model event tokens that can only be determined at runtime.
// it's important to place the event as the first in the array because
// the whole point is ensuring the v-model callback gets called before
// user-attached handlers.
function normalizeEvents (on) {
/* istanbul ignore if */
if (isDef(on[RANGE_TOKEN])) {
// IE input[type=range] only supports `change` event
const event = isIE ? 'change' : 'input';
on[event] = [].concat(on[RANGE_TOKEN], on[event] || []);
delete on[RANGE_TOKEN];
}
// This was originally intended to fix #4521 but no longer necessary
// after 2.5. Keeping it for backwards compat with generated code from < 2.4
/* istanbul ignore if */
if (isDef(on[CHECKBOX_RADIO_TOKEN])) {
on.change = [].concat(on[CHECKBOX_RADIO_TOKEN], on.change || []);
delete on[CHECKBOX_RADIO_TOKEN];
}
}
let target$1;
function createOnceHandler$1 (event, handler, capture) {
const _target = target$1; // save current target element in closure
return function onceHandler () {
const res = handler.apply(null, arguments);
if (res !== null) {
remove$2(event, onceHandler, capture, _target);
}
}
}
function add$1 (
name,
handler,
capture,
passive
) {
// async edge case #6566: inner click event triggers patch, event handler
// attached to outer element during patch, and triggered again. This
// happens because browsers fire microtask ticks between event propagation.
// the solution is simple: we save the timestamp when a handler is attached,
// and the handler would only fire if the event passed to it was fired
// AFTER it was attached.
if (isUsingMicroTask) {
const attachedTimestamp = currentFlushTimestamp;
const original = handler;
handler = original._wrapper = function (e) {
if (e.timeStamp >= attachedTimestamp) {
return original.apply(this, arguments)
}
};
}
target$1.addEventListener(
name,
handler,
supportsPassive
? { capture, passive }
: capture
);
}
function remove$2 (
name,
handler,
capture,
_target
) {
(_target || target$1).removeEventListener(
name,
handler._wrapper || handler,
capture
);
}
function updateDOMListeners (oldVnode, vnode) {
if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) {
return
}
const on = vnode.data.on || {};
const oldOn = oldVnode.data.on || {};
target$1 = vnode.elm;
normalizeEvents(on);
updateListeners(on, oldOn, add$1, remove$2, createOnceHandler$1, vnode.context);
target$1 = undefined;
}
var events = {
create: updateDOMListeners,
update: updateDOMListeners
};
/* */
let svgContainer;
function updateDOMProps (oldVnode, vnode) {
if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) {
return
}
let key, cur;
const elm = vnode.elm;
const oldProps = oldVnode.data.domProps || {};
let props = vnode.data.domProps || {};
// clone observed objects, as the user probably wants to mutate it
if (isDef(props.__ob__)) {
props = vnode.data.domProps = extend({}, props);
}
for (key in oldProps) {
if (isUndef(props[key])) {
elm[key] = '';
}
}
for (key in props) {
cur = props[key];
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if (key === 'textContent' || key === 'innerHTML') {
if (vnode.children) vnode.children.length = 0;
if (cur === oldProps[key]) continue
// #6601 work around Chrome version <= 55 bug where single textNode
// replaced by innerHTML/textContent retains its parentNode property
if (elm.childNodes.length === 1) {
elm.removeChild(elm.childNodes[0]);
}
}
// skip the update if old and new VDOM state is the same.
// the only exception is `value` where the DOM value may be temporarily
// out of sync with VDOM state due to focus, composition and modifiers.
// This also covers #4521 by skipping the unnecesarry `checked` update.
if (key !== 'value' && cur === oldProps[key]) {
continue
}
if (key === 'value') {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur;
// avoid resetting cursor position when value is the same
const strCur = isUndef(cur) ? '' : String(cur);
if (shouldUpdateValue(elm, strCur)) {
elm.value = strCur;
}
} else if (key === 'innerHTML' && isSVG(elm.tagName) && isUndef(elm.innerHTML)) {
// IE doesn't support innerHTML for SVG elements
svgContainer = svgContainer || document.createElement('div');
svgContainer.innerHTML = `<svg>${cur}</svg>`;
const svg = svgContainer.firstChild;
while (elm.firstChild) {
elm.removeChild(elm.firstChild);
}
while (svg.firstChild) {
elm.appendChild(svg.firstChild);
}
} else {
elm[key] = cur;
}
}
}
// check platforms/web/util/attrs.js acceptValue
function shouldUpdateValue (elm, checkVal) {
return (!elm.composing && (
elm.tagName === 'OPTION' ||
isNotInFocusAndDirty(elm, checkVal) ||
isDirtyWithModifiers(elm, checkVal)
))
}
function isNotInFocusAndDirty (elm, checkVal) {
// return true when textbox (.number and .trim) loses focus and its value is
// not equal to the updated value
let notInFocus = true;
// #6157
// work around IE bug when accessing document.activeElement in an iframe
try { notInFocus = document.activeElement !== elm; } catch (e) {}
return notInFocus && elm.value !== checkVal
}
function isDirtyWithModifiers (elm, newVal) {
const value = elm.value;
const modifiers = elm._vModifiers; // injected by v-model runtime
if (isDef(modifiers)) {
if (modifiers.number) {
return toNumber(value) !== toNumber(newVal)
}
if (modifiers.trim) {
return value.trim() !== newVal.trim()
}
}
return value !== newVal
}
var domProps = {
create: updateDOMProps,
update: updateDOMProps
};
/* */
const parseStyleText = cached(function (cssText) {
const res = {};
const listDelimiter = /;(?![^(]*\))/g;
const propertyDelimiter = /:(.+)/;
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
const tmp = item.split(propertyDelimiter);
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());
}
});
return res
});
// merge static and dynamic style data on the same vnode
function normalizeStyleData (data) {
const style = normalizeStyleBinding(data.style);
// static style is pre-processed into an object during compilation
// and is always a fresh object, so it's safe to merge into it
return data.staticStyle
? extend(data.staticStyle, style)
: style
}
// normalize possible array / string values into Object
function normalizeStyleBinding (bindingStyle) {
if (Array.isArray(bindingStyle)) {
return toObject(bindingStyle)
}
if (typeof bindingStyle === 'string') {
return parseStyleText(bindingStyle)
}
return bindingStyle
}
/**
* parent component style should be after child's
* so that parent component's style could override it
*/
function getStyle (vnode, checkChild) {
const res = {};
let styleData;
if (checkChild) {
let childNode = vnode;
while (childNode.componentInstance) {
childNode = childNode.componentInstance._vnode;
if (
childNode && childNode.data &&
(styleData = normalizeStyleData(childNode.data))
) {
extend(res, styleData);
}
}
}
if ((styleData = normalizeStyleData(vnode.data))) {
extend(res, styleData);
}
let parentNode = vnode;
while ((parentNode = parentNode.parent)) {
if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
extend(res, styleData);
}
}
return res
}
/* */
const cssVarRE = /^--/;
const importantRE = /\s*!important$/;
const setProp = (el, name, val) => {
/* istanbul ignore if */
if (cssVarRE.test(name)) {
el.style.setProperty(name, val);
} else if (importantRE.test(val)) {
el.style.setProperty(hyphenate(name), val.replace(importantRE, ''), 'important');
} else {
const normalizedName = normalize(name);
if (Array.isArray(val)) {
// Support values array created by autoprefixer, e.g.
// {display: ["-webkit-box", "-ms-flexbox", "flex"]}
// Set them one by one, and the browser will only set those it can recognize
for (let i = 0, len = val.length; i < len; i++) {
el.style[normalizedName] = val[i];
}
} else {
el.style[normalizedName] = val;
}
}
};
const vendorNames = ['Webkit', 'Moz', 'ms'];
let emptyStyle;
const normalize = cached(function (prop) {
emptyStyle = emptyStyle || document.createElement('div').style;
prop = camelize(prop);
if (prop !== 'filter' && (prop in emptyStyle)) {
return prop
}
const capName = prop.charAt(0).toUpperCase() + prop.slice(1);
for (let i = 0; i < vendorNames.length; i++) {
const name = vendorNames[i] + capName;
if (name in emptyStyle) {
return name
}
}
});
function updateStyle (oldVnode, vnode) {
const data = vnode.data;
const oldData = oldVnode.data;
if (isUndef(data.staticStyle) && isUndef(data.style) &&
isUndef(oldData.staticStyle) && isUndef(oldData.style)
) {
return
}
let cur, name;
const el = vnode.elm;
const oldStaticStyle = oldData.staticStyle;
const oldStyleBinding = oldData.normalizedStyle || oldData.style || {};
// if static style exists, stylebinding already merged into it when doing normalizeStyleData
const oldStyle = oldStaticStyle || oldStyleBinding;
const style = normalizeStyleBinding(vnode.data.style) || {};
// store normalized style under a different key for next diff
// make sure to clone it if it's reactive, since the user likely wants
// to mutate it.
vnode.data.normalizedStyle = isDef(style.__ob__)
? extend({}, style)
: style;
const newStyle = getStyle(vnode, true);
for (name in oldStyle) {
if (isUndef(newStyle[name])) {
setProp(el, name, '');
}
}
for (name in newStyle) {
cur = newStyle[name];
if (cur !== oldStyle[name]) {
// ie9 setting to null has no effect, must use empty string
setProp(el, name, cur == null ? '' : cur);
}
}
}
var style = {
create: updateStyle,
update: updateStyle
};
/* */
const whitespaceRE = /\s+/;
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function addClass (el, cls) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(whitespaceRE).forEach(c => el.classList.add(c));
} else {
el.classList.add(cls);
}
} else {
const cur = ` ${el.getAttribute('class') || ''} `;
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim());
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function removeClass (el, cls) {
/* istanbul ignore if */
if (!cls || !(cls = cls.trim())) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(whitespaceRE).forEach(c => el.classList.remove(c));
} else {
el.classList.remove(cls);
}
if (!el.classList.length) {
el.removeAttribute('class');
}
} else {
let cur = ` ${el.getAttribute('class') || ''} `;
const tar = ' ' + cls + ' ';
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ');
}
cur = cur.trim();
if (cur) {
el.setAttribute('class', cur);
} else {
el.removeAttribute('class');
}
}
}
/* */
function resolveTransition (def$$1) {
if (!def$$1) {
return
}
/* istanbul ignore else */
if (typeof def$$1 === 'object') {
const res = {};
if (def$$1.css !== false) {
extend(res, autoCssTransition(def$$1.name || 'v'));
}
extend(res, def$$1);
return res
} else if (typeof def$$1 === 'string') {
return autoCssTransition(def$$1)
}
}
const autoCssTransition = cached(name => {
return {
enterClass: `${name}-enter`,
enterToClass: `${name}-enter-to`,
enterActiveClass: `${name}-enter-active`,
leaveClass: `${name}-leave`,
leaveToClass: `${name}-leave-to`,
leaveActiveClass: `${name}-leave-active`
}
});
const hasTransition = inBrowser && !isIE9;
const TRANSITION = 'transition';
const ANIMATION = 'animation';
// Transition property/event sniffing
let transitionProp = 'transition';
let transitionEndEvent = 'transitionend';
let animationProp = 'animation';
let animationEndEvent = 'animationend';
if (hasTransition) {
/* istanbul ignore if */
if (window.ontransitionend === undefined &&
window.onwebkittransitionend !== undefined
) {
transitionProp = 'WebkitTransition';
transitionEndEvent = 'webkitTransitionEnd';
}
if (window.onanimationend === undefined &&
window.onwebkitanimationend !== undefined
) {
animationProp = 'WebkitAnimation';
animationEndEvent = 'webkitAnimationEnd';
}
}
// binding to window is necessary to make hot reload work in IE in strict mode
const raf = inBrowser
? window.requestAnimationFrame
? window.requestAnimationFrame.bind(window)
: setTimeout
: /* istanbul ignore next */ fn => fn();
function nextFrame (fn) {
raf(() => {
raf(fn);
});
}
function addTransitionClass (el, cls) {
const transitionClasses = el._transitionClasses || (el._transitionClasses = []);
if (transitionClasses.indexOf(cls) < 0) {
transitionClasses.push(cls);
addClass(el, cls);
}
}
function removeTransitionClass (el, cls) {
if (el._transitionClasses) {
remove(el._transitionClasses, cls);
}
removeClass(el, cls);
}
function whenTransitionEnds (
el,
expectedType,
cb
) {
const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
if (!type) return cb()
const event = type === TRANSITION ? transitionEndEvent : animationEndEvent;
let ended = 0;
const end = () => {
el.removeEventListener(event, onEnd);
cb();
};
const onEnd = e => {
if (e.target === el) {
if (++ended >= propCount) {
end();
}
}
};
setTimeout(() => {
if (ended < propCount) {
end();
}
}, timeout + 1);
el.addEventListener(event, onEnd);
}
const transformRE = /\b(transform|all)(,|$)/;
function getTransitionInfo (el, expectedType) {
const styles = window.getComputedStyle(el);
// JSDOM may return undefined for transition properties
const transitionDelays = (styles[transitionProp + 'Delay'] || '').split(', ');
const transitionDurations = (styles[transitionProp + 'Duration'] || '').split(', ');
const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
const animationDelays = (styles[animationProp + 'Delay'] || '').split(', ');
const animationDurations = (styles[animationProp + 'Duration'] || '').split(', ');
const animationTimeout = getTimeout(animationDelays, animationDurations);
let type;
let timeout = 0;
let propCount = 0;
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION;
timeout = transitionTimeout;
propCount = transitionDurations.length;
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION;
timeout = animationTimeout;
propCount = animationDurations.length;
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout);
type = timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null;
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0;
}
const hasTransform =
type === TRANSITION &&
transformRE.test(styles[transitionProp + 'Property']);
return {
type,
timeout,
propCount,
hasTransform
}
}
function getTimeout (delays, durations) {
/* istanbul ignore next */
while (delays.length < durations.length) {
delays = delays.concat(delays);
}
return Math.max.apply(null, durations.map((d, i) => {
return toMs(d) + toMs(delays[i])
}))
}
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers
// in a locale-dependent way, using a comma instead of a dot.
// If comma is not replaced with a dot, the input will be rounded down (i.e. acting
// as a floor function) causing unexpected behaviors
function toMs (s) {
return Number(s.slice(0, -1).replace(',', '.')) * 1000
}
/* */
function enter (vnode, toggleDisplay) {
const el = vnode.elm;
// call leave callback now
if (isDef(el._leaveCb)) {
el._leaveCb.cancelled = true;
el._leaveCb();
}
const data = resolveTransition(vnode.data.transition);
if (isUndef(data)) {
return
}
/* istanbul ignore if */
if (isDef(el._enterCb) || el.nodeType !== 1) {
return
}
const {
css,
type,
enterClass,
enterToClass,
enterActiveClass,
appearClass,
appearToClass,
appearActiveClass,
beforeEnter,
enter,
afterEnter,
enterCancelled,
beforeAppear,
appear,
afterAppear,
appearCancelled,
duration
} = data;
// activeInstance will always be the <transition> component managing this
// transition. One edge case to check is when the <transition> is placed
// as the root node of a child component. In that case we need to check
// <transition>'s parent for appear check.
let context = activeInstance;
let transitionNode = activeInstance.$vnode;
while (transitionNode && transitionNode.parent) {
transitionNode = transitionNode.parent;
context = transitionNode.context;
}
const isAppear = !context._isMounted || !vnode.isRootInsert;
if (isAppear && !appear && appear !== '') {
return
}
const startClass = isAppear && appearClass
? appearClass
: enterClass;
const activeClass = isAppear && appearActiveClass
? appearActiveClass
: enterActiveClass;
const toClass = isAppear && appearToClass
? appearToClass
: enterToClass;
const beforeEnterHook = isAppear
? (beforeAppear || beforeEnter)
: beforeEnter;
const enterHook = isAppear
? (typeof appear === 'function' ? appear : enter)
: enter;
const afterEnterHook = isAppear
? (afterAppear || afterEnter)
: afterEnter;
const enterCancelledHook = isAppear
? (appearCancelled || enterCancelled)
: enterCancelled;
const explicitEnterDuration = toNumber(
isObject(duration)
? duration.enter
: duration
);
if (explicitEnterDuration != null) {
checkDuration(explicitEnterDuration, 'enter', vnode);
}
const expectsCSS = css !== false && !isIE9;
const userWantsControl = getHookArgumentsLength(enterHook);
const cb = el._enterCb = once(() => {
if (expectsCSS) {
removeTransitionClass(el, toClass);
removeTransitionClass(el, activeClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, startClass);
}
enterCancelledHook && enterCancelledHook(el);
} else {
afterEnterHook && afterEnterHook(el);
}
el._enterCb = null;
});
if (!vnode.data.show) {
// remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode, 'insert', () => {
const parent = el.parentNode;
const pendingNode = parent && parent._pending && parent._pending[vnode.key];
if (pendingNode &&
pendingNode.tag === vnode.tag &&
pendingNode.elm._leaveCb
) {
pendingNode.elm._leaveCb();
}
enterHook && enterHook(el, cb);
});
}
// start enter transition
beforeEnterHook && beforeEnterHook(el);
if (expectsCSS) {
addTransitionClass(el, startClass);
addTransitionClass(el, activeClass);
nextFrame(() => {
removeTransitionClass(el, startClass);
if (!cb.cancelled) {
addTransitionClass(el, toClass);
if (!userWantsControl) {
if (isValidDuration(explicitEnterDuration)) {
setTimeout(cb, explicitEnterDuration);
} else {
whenTransitionEnds(el, type, cb);
}
}
}
});
}
if (vnode.data.show) {
toggleDisplay && toggleDisplay();
enterHook && enterHook(el, cb);
}
if (!expectsCSS && !userWantsControl) {
cb();
}
}
function leave (vnode, rm) {
const el = vnode.elm;
// call enter callback now
if (isDef(el._enterCb)) {
el._enterCb.cancelled = true;
el._enterCb();
}
const data = resolveTransition(vnode.data.transition);
if (isUndef(data) || el.nodeType !== 1) {
return rm()
}
/* istanbul ignore if */
if (isDef(el._leaveCb)) {
return
}
const {
css,
type,
leaveClass,
leaveToClass,
leaveActiveClass,
beforeLeave,
leave,
afterLeave,
leaveCancelled,
delayLeave,
duration
} = data;
const expectsCSS = css !== false && !isIE9;
const userWantsControl = getHookArgumentsLength(leave);
const explicitLeaveDuration = toNumber(
isObject(duration)
? duration.leave
: duration
);
if (isDef(explicitLeaveDuration)) {
checkDuration(explicitLeaveDuration, 'leave', vnode);
}
const cb = el._leaveCb = once(() => {
if (el.parentNode && el.parentNode._pending) {
el.parentNode._pending[vnode.key] = null;
}
if (expectsCSS) {
removeTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveActiveClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, leaveClass);
}
leaveCancelled && leaveCancelled(el);
} else {
rm();
afterLeave && afterLeave(el);
}
el._leaveCb = null;
});
if (delayLeave) {
delayLeave(performLeave);
} else {
performLeave();
}
function performLeave () {
// the delayed leave may have already been cancelled
if (cb.cancelled) {
return
}
// record leaving element
if (!vnode.data.show && el.parentNode) {
(el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode;
}
beforeLeave && beforeLeave(el);
if (expectsCSS) {
addTransitionClass(el, leaveClass);
addTransitionClass(el, leaveActiveClass);
nextFrame(() => {
removeTransitionClass(el, leaveClass);
if (!cb.cancelled) {
addTransitionClass(el, leaveToClass);
if (!userWantsControl) {
if (isValidDuration(explicitLeaveDuration)) {
setTimeout(cb, explicitLeaveDuration);
} else {
whenTransitionEnds(el, type, cb);
}
}
}
});
}
leave && leave(el, cb);
if (!expectsCSS && !userWantsControl) {
cb();
}
}
}
// only used in dev mode
function checkDuration (val, name, vnode) {
if (typeof val !== 'number') {
warn(
`<transition> explicit ${name} duration is not a valid number - ` +
`got ${JSON.stringify(val)}.`,
vnode.context
);
} else if (isNaN(val)) {
warn(
`<transition> explicit ${name} duration is NaN - ` +
'the duration expression might be incorrect.',
vnode.context
);
}
}
function isValidDuration (val) {
return typeof val === 'number' && !isNaN(val)
}
/**
* Normalize a transition hook's argument length. The hook may be:
* - a merged hook (invoker) with the original in .fns
* - a wrapped component method (check ._length)
* - a plain function (.length)
*/
function getHookArgumentsLength (fn) {
if (isUndef(fn)) {
return false
}
const invokerFns = fn.fns;
if (isDef(invokerFns)) {
// invoker
return getHookArgumentsLength(
Array.isArray(invokerFns)
? invokerFns[0]
: invokerFns
)
} else {
return (fn._length || fn.length) > 1
}
}
function _enter (_, vnode) {
if (vnode.data.show !== true) {
enter(vnode);
}
}
var transition = inBrowser ? {
create: _enter,
activate: _enter,
remove (vnode, rm) {
/* istanbul ignore else */
if (vnode.data.show !== true) {
leave(vnode, rm);
} else {
rm();
}
}
} : {};
var platformModules = [
attrs,
klass,
events,
domProps,
style,
transition
];
/* */
// the directive module should be applied last, after all
// built-in modules have been applied.
const modules = platformModules.concat(baseModules);
const patch = createPatchFunction({ nodeOps, modules });
/**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', () => {
const el = document.activeElement;
if (el && el.vmodel) {
trigger(el, 'input');
}
});
}
const directive = {
inserted (el, binding, vnode, oldVnode) {
if (vnode.tag === 'select') {
// #6903
if (oldVnode.elm && !oldVnode.elm._vOptions) {
mergeVNodeHook(vnode, 'postpatch', () => {
directive.componentUpdated(el, binding, vnode);
});
} else {
setSelected(el, binding, vnode.context);
}
el._vOptions = [].map.call(el.options, getValue);
} else if (vnode.tag === 'textarea' || isTextInputType(el.type)) {
el._vModifiers = binding.modifiers;
if (!binding.modifiers.lazy) {
el.addEventListener('compositionstart', onCompositionStart);
el.addEventListener('compositionend', onCompositionEnd);
// Safari < 10.2 & UIWebView doesn't fire compositionend when
// switching focus before confirming composition choice
// this also fixes the issue where some browsers e.g. iOS Chrome
// fires "change" instead of "input" on autocomplete.
el.addEventListener('change', onCompositionEnd);
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true;
}
}
}
},
componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context);
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
const prevOptions = el._vOptions;
const curOptions = el._vOptions = [].map.call(el.options, getValue);
if (curOptions.some((o, i) => !looseEqual(o, prevOptions[i]))) {
// trigger change event if
// no matching option found for at least one value
const needReset = el.multiple
? binding.value.some(v => hasNoMatchingOption(v, curOptions))
: binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions);
if (needReset) {
trigger(el, 'change');
}
}
}
}
};
function setSelected (el, binding, vm) {
actuallySetSelected(el, binding, vm);
/* istanbul ignore if */
if (isIE || isEdge) {
setTimeout(() => {
actuallySetSelected(el, binding, vm);
}, 0);
}
}
function actuallySetSelected (el, binding, vm) {
const value = binding.value;
const isMultiple = el.multiple;
if (isMultiple && !Array.isArray(value)) {
warn(
`<select multiple v-model="${binding.expression}"> ` +
`expects an Array value for its binding, but got ${
Object.prototype.toString.call(value).slice(8, -1)
}`,
vm
);
return
}
let selected, option;
for (let i = 0, l = el.options.length; i < l; i++) {
option = el.options[i];
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1;
if (option.selected !== selected) {
option.selected = selected;
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i;
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1;
}
}
function hasNoMatchingOption (value, options) {
return options.every(o => !looseEqual(o, value))
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true;
}
function onCompositionEnd (e) {
// prevent triggering an input event for no reason
if (!e.target.composing) return
e.target.composing = false;
trigger(e.target, 'input');
}
function trigger (el, type) {
const e = document.createEvent('HTMLEvents');
e.initEvent(type, true, true);
el.dispatchEvent(e);
}
/* */
// recursively search for possible transition defined inside the component root
function locateNode (vnode) {
return vnode.componentInstance && (!vnode.data || !vnode.data.transition)
? locateNode(vnode.componentInstance._vnode)
: vnode
}
var show = {
bind (el, { value }, vnode) {
vnode = locateNode(vnode);
const transition$$1 = vnode.data && vnode.data.transition;
const originalDisplay = el.__vOriginalDisplay =
el.style.display === 'none' ? '' : el.style.display;
if (value && transition$$1) {
vnode.data.show = true;
enter(vnode, () => {
el.style.display = originalDisplay;
});
} else {
el.style.display = value ? originalDisplay : 'none';
}
},
update (el, { value, oldValue }, vnode) {
/* istanbul ignore if */
if (!value === !oldValue) return
vnode = locateNode(vnode);
const transition$$1 = vnode.data && vnode.data.transition;
if (transition$$1) {
vnode.data.show = true;
if (value) {
enter(vnode, () => {
el.style.display = el.__vOriginalDisplay;
});
} else {
leave(vnode, () => {
el.style.display = 'none';
});
}
} else {
el.style.display = value ? el.__vOriginalDisplay : 'none';
}
},
unbind (
el,
binding,
vnode,
oldVnode,
isDestroy
) {
if (!isDestroy) {
el.style.display = el.__vOriginalDisplay;
}
}
};
var platformDirectives = {
model: directive,
show
};
/* */
const transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterToClass: String,
leaveToClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String,
appearToClass: String,
duration: [Number, String, Object]
};
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recursively retrieve the real component to be rendered
function getRealChild (vnode) {
const compOptions = vnode && vnode.componentOptions;
if (compOptions && compOptions.Ctor.options.abstract) {
return getRealChild(getFirstComponentChild(compOptions.children))
} else {
return vnode
}
}
function extractTransitionData (comp) {
const data = {};
const options = comp.$options;
// props
for (const key in options.propsData) {
data[key] = comp[key];
}
// events.
// extract listeners and pass them directly to the transition methods
const listeners = options._parentListeners;
for (const key in listeners) {
data[camelize(key)] = listeners[key];
}
return data
}
function placeholder (h, rawChild) {
if (/\d-keep-alive$/.test(rawChild.tag)) {
return h('keep-alive', {
props: rawChild.componentOptions.propsData
})
}
}
function hasParentTransition (vnode) {
while ((vnode = vnode.parent)) {
if (vnode.data.transition) {
return true
}
}
}
function isSameChild (child, oldChild) {
return oldChild.key === child.key && oldChild.tag === child.tag
}
const isNotTextNode = (c) => c.tag || isAsyncPlaceholder(c);
const isVShowDirective = d => d.name === 'show';
var Transition = {
name: 'transition',
props: transitionProps,
abstract: true,
render (h) {
let children = this.$slots.default;
if (!children) {
return
}
// filter out text nodes (possible whitespaces)
children = children.filter(isNotTextNode);
/* istanbul ignore if */
if (!children.length) {
return
}
// warn multiple elements
if (children.length > 1) {
warn(
'<transition> can only be used on a single element. Use ' +
'<transition-group> for lists.',
this.$parent
);
}
const mode = this.mode;
// warn invalid mode
if (mode && mode !== 'in-out' && mode !== 'out-in'
) {
warn(
'invalid <transition> mode: ' + mode,
this.$parent
);
}
const rawChild = children[0];
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (hasParentTransition(this.$vnode)) {
return rawChild
}
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
const child = getRealChild(rawChild);
/* istanbul ignore if */
if (!child) {
return rawChild
}
if (this._leaving) {
return placeholder(h, rawChild)
}
// ensure a key that is unique to the vnode type and to this transition
// component instance. This key will be used to remove pending leaving nodes
// during entering.
const id = `__transition-${this._uid}-`;
child.key = child.key == null
? child.isComment
? id + 'comment'
: id + child.tag
: isPrimitive(child.key)
? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)
: child.key;
const data = (child.data || (child.data = {})).transition = extractTransitionData(this);
const oldRawChild = this._vnode;
const oldChild = getRealChild(oldRawChild);
// mark v-show
// so that the transition module can hand over the control to the directive
if (child.data.directives && child.data.directives.some(isVShowDirective)) {
child.data.show = true;
}
if (
oldChild &&
oldChild.data &&
!isSameChild(child, oldChild) &&
!isAsyncPlaceholder(oldChild) &&
// #6687 component root is a comment node
!(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment)
) {
// replace old child transition data with fresh one
// important for dynamic transitions!
const oldData = oldChild.data.transition = extend({}, data);
// handle transition mode
if (mode === 'out-in') {
// return placeholder node and queue update when leave finishes
this._leaving = true;
mergeVNodeHook(oldData, 'afterLeave', () => {
this._leaving = false;
this.$forceUpdate();
});
return placeholder(h, rawChild)
} else if (mode === 'in-out') {
if (isAsyncPlaceholder(child)) {
return oldRawChild
}
let delayedLeave;
const performLeave = () => { delayedLeave(); };
mergeVNodeHook(data, 'afterEnter', performLeave);
mergeVNodeHook(data, 'enterCancelled', performLeave);
mergeVNodeHook(oldData, 'delayLeave', leave => { delayedLeave = leave; });
}
}
return rawChild
}
};
/* */
const props = extend({
tag: String,
moveClass: String
}, transitionProps);
delete props.mode;
var TransitionGroup = {
props,
beforeMount () {
const update = this._update;
this._update = (vnode, hydrating) => {
const restoreActiveInstance = setActiveInstance(this);
// force removing pass
this.__patch__(
this._vnode,
this.kept,
false, // hydrating
true // removeOnly (!important, avoids unnecessary moves)
);
this._vnode = this.kept;
restoreActiveInstance();
update.call(this, vnode, hydrating);
};
},
render (h) {
const tag = this.tag || this.$vnode.data.tag || 'span';
const map = Object.create(null);
const prevChildren = this.prevChildren = this.children;
const rawChildren = this.$slots.default || [];
const children = this.children = [];
const transitionData = extractTransitionData(this);
for (let i = 0; i < rawChildren.length; i++) {
const c = rawChildren[i];
if (c.tag) {
if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {
children.push(c);
map[c.key] = c
;(c.data || (c.data = {})).transition = transitionData;
} else {
const opts = c.componentOptions;
const name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag;
warn(`<transition-group> children must be keyed: <${name}>`);
}
}
}
if (prevChildren) {
const kept = [];
const removed = [];
for (let i = 0; i < prevChildren.length; i++) {
const c = prevChildren[i];
c.data.transition = transitionData;
c.data.pos = c.elm.getBoundingClientRect();
if (map[c.key]) {
kept.push(c);
} else {
removed.push(c);
}
}
this.kept = h(tag, null, kept);
this.removed = removed;
}
return h(tag, null, children)
},
updated () {
const children = this.prevChildren;
const moveClass = this.moveClass || ((this.name || 'v') + '-move');
if (!children.length || !this.hasMove(children[0].elm, moveClass)) {
return
}
// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs);
children.forEach(recordPosition);
children.forEach(applyTranslation);
// force reflow to put everything in position
// assign to this to avoid being removed in tree-shaking
// $flow-disable-line
this._reflow = document.body.offsetHeight;
children.forEach((c) => {
if (c.data.moved) {
const el = c.elm;
const s = el.style;
addTransitionClass(el, moveClass);
s.transform = s.WebkitTransform = s.transitionDuration = '';
el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {
if (e && e.target !== el) {
return
}
if (!e || /transform$/.test(e.propertyName)) {
el.removeEventListener(transitionEndEvent, cb);
el._moveCb = null;
removeTransitionClass(el, moveClass);
}
});
}
});
},
methods: {
hasMove (el, moveClass) {
/* istanbul ignore if */
if (!hasTransition) {
return false
}
/* istanbul ignore if */
if (this._hasMove) {
return this._hasMove
}
// Detect whether an element with the move class applied has
// CSS transitions. Since the element may be inside an entering
// transition at this very moment, we make a clone of it and remove
// all other transition classes applied to ensure only the move class
// is applied.
const clone = el.cloneNode();
if (el._transitionClasses) {
el._transitionClasses.forEach((cls) => { removeClass(clone, cls); });
}
addClass(clone, moveClass);
clone.style.display = 'none';
this.$el.appendChild(clone);
const info = getTransitionInfo(clone);
this.$el.removeChild(clone);
return (this._hasMove = info.hasTransform)
}
}
};
function callPendingCbs (c) {
/* istanbul ignore if */
if (c.elm._moveCb) {
c.elm._moveCb();
}
/* istanbul ignore if */
if (c.elm._enterCb) {
c.elm._enterCb();
}
}
function recordPosition (c) {
c.data.newPos = c.elm.getBoundingClientRect();
}
function applyTranslation (c) {
const oldPos = c.data.pos;
const newPos = c.data.newPos;
const dx = oldPos.left - newPos.left;
const dy = oldPos.top - newPos.top;
if (dx || dy) {
c.data.moved = true;
const s = c.elm.style;
s.transform = s.WebkitTransform = `translate(${dx}px,${dy}px)`;
s.transitionDuration = '0s';
}
}
var platformComponents = {
Transition,
TransitionGroup
};
/* */
// install platform specific utils
Vue.config.mustUseProp = mustUseProp;
Vue.config.isReservedTag = isReservedTag;
Vue.config.isReservedAttr = isReservedAttr;
Vue.config.getTagNamespace = getTagNamespace;
Vue.config.isUnknownElement = isUnknownElement;
// install platform runtime directives & components
extend(Vue.options.directives, platformDirectives);
extend(Vue.options.components, platformComponents);
// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop;
// public mount method
Vue.prototype.$mount = function (
el,
hydrating
) {
el = el && inBrowser ? query(el) : undefined;
return mountComponent(this, el, hydrating)
};
// devtools global hook
/* istanbul ignore next */
if (inBrowser) {
setTimeout(() => {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue);
} else {
console[console.info ? 'info' : 'log'](
'Download the Vue Devtools extension for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
);
}
}
if (config.productionTip !== false &&
typeof console !== 'undefined'
) {
console[console.info ? 'info' : 'log'](
`You are running Vue in development mode.\n` +
`Make sure to turn on production mode when deploying for production.\n` +
`See more tips at https://vuejs.org/guide/deployment.html`
);
}
}, 0);
}
/* */
const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g;
const regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g;
const buildRegex = cached(delimiters => {
const open = delimiters[0].replace(regexEscapeRE, '\\$&');
const close = delimiters[1].replace(regexEscapeRE, '\\$&');
return new RegExp(open + '((?:.|\\n)+?)' + close, 'g')
});
function parseText (
text,
delimiters
) {
const tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;
if (!tagRE.test(text)) {
return
}
const tokens = [];
const rawTokens = [];
let lastIndex = tagRE.lastIndex = 0;
let match, index, tokenValue;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
rawTokens.push(tokenValue = text.slice(lastIndex, index));
tokens.push(JSON.stringify(tokenValue));
}
// tag token
const exp = parseFilters(match[1].trim());
tokens.push(`_s(${exp})`);
rawTokens.push({ '@binding': exp });
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
rawTokens.push(tokenValue = text.slice(lastIndex));
tokens.push(JSON.stringify(tokenValue));
}
return {
expression: tokens.join('+'),
tokens: rawTokens
}
}
/* */
function transformNode (el, options) {
const warn = options.warn || baseWarn;
const staticClass = getAndRemoveAttr(el, 'class');
if (staticClass) {
const res = parseText(staticClass, options.delimiters);
if (res) {
warn(
`class="${staticClass}": ` +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div class="{{ val }}">, use <div :class="val">.',
el.rawAttrsMap['class']
);
}
}
if (staticClass) {
el.staticClass = JSON.stringify(staticClass);
}
const classBinding = getBindingAttr(el, 'class', false /* getStatic */);
if (classBinding) {
el.classBinding = classBinding;
}
}
function genData (el) {
let data = '';
if (el.staticClass) {
data += `staticClass:${el.staticClass},`;
}
if (el.classBinding) {
data += `class:${el.classBinding},`;
}
return data
}
var klass$1 = {
staticKeys: ['staticClass'],
transformNode,
genData
};
/* */
function transformNode$1 (el, options) {
const warn = options.warn || baseWarn;
const staticStyle = getAndRemoveAttr(el, 'style');
if (staticStyle) {
/* istanbul ignore if */
{
const res = parseText(staticStyle, options.delimiters);
if (res) {
warn(
`style="${staticStyle}": ` +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div style="{{ val }}">, use <div :style="val">.',
el.rawAttrsMap['style']
);
}
}
el.staticStyle = JSON.stringify(parseStyleText(staticStyle));
}
const styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
if (styleBinding) {
el.styleBinding = styleBinding;
}
}
function genData$1 (el) {
let data = '';
if (el.staticStyle) {
data += `staticStyle:${el.staticStyle},`;
}
if (el.styleBinding) {
data += `style:(${el.styleBinding}),`;
}
return data
}
var style$1 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$1
};
/* */
let decoder;
var he = {
decode (html) {
decoder = decoder || document.createElement('div');
decoder.innerHTML = html;
return decoder.textContent
}
};
/* */
const isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr'
);
// Elements that you can, intentionally, leave open
// (and which close themselves)
const canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'
);
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
const isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track'
);
/**
* Not type-checking this file because it's mostly vendor code.
*/
// Regular Expressions for parsing tags and attributes
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/;
const dynamicArgAttribute = /^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/;
const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z${unicodeLetters}]*`;
const qnameCapture = `((?:${ncname}\\:)?${ncname})`;
const startTagOpen = new RegExp(`^<${qnameCapture}`);
const startTagClose = /^\s*(\/?)>/;
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`);
const doctype = /^<!DOCTYPE [^>]+>/i;
// #7298: escape - to avoid being pased as HTML comment when inlined in page
const comment = /^<!\--/;
const conditionalComment = /^<!\[/;
// Special Elements (can contain anything)
const isPlainTextElement = makeMap('script,style,textarea', true);
const reCache = {};
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n',
'	': '\t',
''': "'"
};
const encodedAttr = /&(?:lt|gt|quot|amp|#39);/g;
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g;
// #5992
const isIgnoreNewlineTag = makeMap('pre,textarea', true);
const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n';
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr;
return value.replace(re, match => decodingMap[match])
}
function parseHTML (html, options) {
const stack = [];
const expectHTML = options.expectHTML;
const isUnaryTag$$1 = options.isUnaryTag || no;
const canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no;
let index = 0;
let last, lastTag;
while (html) {
last = html;
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
let textEnd = html.indexOf('<');
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
const commentEnd = html.indexOf('-->');
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3);
}
advance(commentEnd + 3);
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>');
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2);
continue
}
}
// Doctype:
const doctypeMatch = html.match(doctype);
if (doctypeMatch) {
advance(doctypeMatch[0].length);
continue
}
// End tag:
const endTagMatch = html.match(endTag);
if (endTagMatch) {
const curIndex = index;
advance(endTagMatch[0].length);
parseEndTag(endTagMatch[1], curIndex, index);
continue
}
// Start tag:
const startTagMatch = parseStartTag();
if (startTagMatch) {
handleStartTag(startTagMatch);
if (shouldIgnoreFirstNewline(startTagMatch.tagName, html)) {
advance(1);
}
continue
}
}
let text, rest, next;
if (textEnd >= 0) {
rest = html.slice(textEnd);
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
next = rest.indexOf('<', 1);
if (next < 0) break
textEnd += next;
rest = html.slice(textEnd);
}
text = html.substring(0, textEnd);
}
if (textEnd < 0) {
text = html;
}
if (text) {
advance(text.length);
}
if (options.chars && text) {
options.chars(text, index - text.length, index);
}
} else {
let endTagLength = 0;
const stackedTag = lastTag.toLowerCase();
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1);
}
if (options.chars) {
options.chars(text);
}
return ''
});
index += html.length - rest.length;
html = rest;
parseEndTag(stackedTag, index - endTagLength, index);
}
if (html === last) {
options.chars && options.chars(html);
if (!stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`, { start: index + html.length });
}
break
}
}
// Clean up any remaining tags
parseEndTag();
function advance (n) {
index += n;
html = html.substring(n);
}
function parseStartTag () {
const start = html.match(startTagOpen);
if (start) {
const match = {
tagName: start[1],
attrs: [],
start: index
};
advance(start[0].length);
let end, attr;
while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) {
attr.start = index;
advance(attr[0].length);
attr.end = index;
match.attrs.push(attr);
}
if (end) {
match.unarySlash = end[1];
advance(end[0].length);
match.end = index;
return match
}
}
}
function handleStartTag (match) {
const tagName = match.tagName;
const unarySlash = match.unarySlash;
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag);
}
if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) {
parseEndTag(tagName);
}
}
const unary = isUnaryTag$$1(tagName) || !!unarySlash;
const l = match.attrs.length;
const attrs = new Array(l);
for (let i = 0; i < l; i++) {
const args = match.attrs[i];
const value = args[3] || args[4] || args[5] || '';
const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'
? options.shouldDecodeNewlinesForHref
: options.shouldDecodeNewlines;
attrs[i] = {
name: args[1],
value: decodeAttr(value, shouldDecodeNewlines)
};
if (options.outputSourceRange) {
attrs[i].start = args.start + args[0].match(/^\s*/).length;
attrs[i].end = args.end;
}
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end });
lastTag = tagName;
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end);
}
}
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName;
if (start == null) start = index;
if (end == null) end = index;
// Find the closest opened tag of the same type
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0;
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
if (i > pos || !tagName &&
options.warn
) {
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`,
{ start: stack[i].start }
);
}
if (options.end) {
options.end(stack[i].tag, start, end);
}
}
// Remove the open elements from the stack
stack.length = pos;
lastTag = pos && stack[pos - 1].tag;
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end);
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end);
}
if (options.end) {
options.end(tagName, start, end);
}
}
}
}
/* */
const onRE = /^@|^v-on:/;
const dirRE = /^v-|^@|^:/;
const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
const stripParensRE = /^\(|\)$/g;
const dynamicArgRE = /^\[.*\]$/;
const argRE = /:(.*)$/;
const bindRE = /^:|^\.|^v-bind:/;
const modifierRE = /\.[^.]+/g;
const slotRE = /^v-slot(:|$)|^#/;
const lineBreakRE = /[\r\n]/;
const whitespaceRE$1 = /\s+/g;
const invalidAttributeRE = /[\s"'<>\/=]/;
const decodeHTMLCached = cached(he.decode);
// configurable state
let warn$2;
let delimiters;
let transforms;
let preTransforms;
let postTransforms;
let platformIsPreTag;
let platformMustUseProp;
let platformGetTagNamespace;
let maybeComponent;
function createASTElement (
tag,
attrs,
parent
) {
return {
type: 1,
tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
rawAttrsMap: {},
parent,
children: []
}
}
/**
* Convert HTML string to AST.
*/
function parse (
template,
options
) {
warn$2 = options.warn || baseWarn;
platformIsPreTag = options.isPreTag || no;
platformMustUseProp = options.mustUseProp || no;
platformGetTagNamespace = options.getTagNamespace || no;
const isReservedTag = options.isReservedTag || no;
maybeComponent = (el) => !!el.component || !isReservedTag(el.tag);
transforms = pluckModuleFunction(options.modules, 'transformNode');
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode');
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode');
delimiters = options.delimiters;
const stack = [];
const preserveWhitespace = options.preserveWhitespace !== false;
const whitespaceOption = options.whitespace;
let root;
let currentParent;
let inVPre = false;
let inPre = false;
let warned = false;
function warnOnce (msg, range) {
if (!warned) {
warned = true;
warn$2(msg, range);
}
}
function closeElement (element) {
trimEndingWhitespace(element);
if (!inVPre && !element.processed) {
element = processElement(element, options);
}
// tree management
if (!stack.length && element !== root) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
{
checkRootConstraints(element);
}
addIfCondition(root, {
exp: element.elseif,
block: element
});
} else {
warnOnce(
`Component template should contain exactly one root element. ` +
`If you are using v-if on multiple elements, ` +
`use v-else-if to chain them instead.`,
{ start: element.start }
);
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent);
} else {
if (element.slotScope) {
// scoped slot
// keep it in the children list so that v-else(-if) conditions can
// find it as the prev node.
const name = element.slotTarget || '"default"'
;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
}
currentParent.children.push(element);
element.parent = currentParent;
}
}
// final children cleanup
// filter out scoped slots
element.children = element.children.filter(c => !(c).slotScope);
// remove trailing whitespace node again
trimEndingWhitespace(element);
// check pre state
if (element.pre) {
inVPre = false;
}
if (platformIsPreTag(element.tag)) {
inPre = false;
}
// apply post-transforms
for (let i = 0; i < postTransforms.length; i++) {
postTransforms[i](element, options);
}
}
function trimEndingWhitespace (el) {
// remove trailing whitespace node
if (!inPre) {
let lastNode;
while (
(lastNode = el.children[el.children.length - 1]) &&
lastNode.type === 3 &&
lastNode.text === ' '
) {
el.children.pop();
}
}
}
function checkRootConstraints (el) {
if (el.tag === 'slot' || el.tag === 'template') {
warnOnce(
`Cannot use <${el.tag}> as component root element because it may ` +
'contain multiple nodes.',
{ start: el.start }
);
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warnOnce(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements.',
el.rawAttrsMap['v-for']
);
}
}
parseHTML(template, {
warn: warn$2,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref,
shouldKeepComment: options.comments,
outputSourceRange: options.outputSourceRange,
start (tag, attrs, unary, start) {
// check namespace.
// inherit parent ns if there is one
const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs);
}
let element = createASTElement(tag, attrs, currentParent);
if (ns) {
element.ns = ns;
}
{
if (options.outputSourceRange) {
element.start = start;
element.rawAttrsMap = element.attrsList.reduce((cumulated, attr) => {
cumulated[attr.name] = attr;
return cumulated
}, {});
}
attrs.forEach(attr => {
if (invalidAttributeRE.test(attr.name)) {
warn$2(
`Invalid dynamic argument expression: attribute names cannot contain ` +
`spaces, quotes, <, >, / or =.`,
{
start: attr.start + attr.name.indexOf(`[`),
end: attr.start + attr.name.length
}
);
}
});
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true;
warn$2(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
`<${tag}>` + ', as they will not be parsed.',
{ start: element.start }
);
}
// apply pre-transforms
for (let i = 0; i < preTransforms.length; i++) {
element = preTransforms[i](element, options) || element;
}
if (!inVPre) {
processPre(element);
if (element.pre) {
inVPre = true;
}
}
if (platformIsPreTag(element.tag)) {
inPre = true;
}
if (inVPre) {
processRawAttrs(element);
} else if (!element.processed) {
// structural directives
processFor(element);
processIf(element);
processOnce(element);
}
if (!root) {
root = element;
{
checkRootConstraints(root);
}
}
if (!unary) {
currentParent = element;
stack.push(element);
} else {
closeElement(element);
}
},
end (tag, start, end) {
const element = stack[stack.length - 1];
// pop stack
stack.length -= 1;
currentParent = stack[stack.length - 1];
if (options.outputSourceRange) {
element.end = end;
}
closeElement(element);
},
chars (text, start, end) {
if (!currentParent) {
{
if (text === template) {
warnOnce(
'Component template requires a root element, rather than just text.',
{ start }
);
} else if ((text = text.trim())) {
warnOnce(
`text "${text}" outside root element will be ignored.`,
{ start }
);
}
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text
) {
return
}
const children = currentParent.children;
if (inPre || text.trim()) {
text = isTextTag(currentParent) ? text : decodeHTMLCached(text);
} else if (!children.length) {
// remove the whitespace-only node right after an opening tag
text = '';
} else if (whitespaceOption) {
if (whitespaceOption === 'condense') {
// in condense mode, remove the whitespace node if it contains
// line break, otherwise condense to a single space
text = lineBreakRE.test(text) ? '' : ' ';
} else {
text = ' ';
}
} else {
text = preserveWhitespace ? ' ' : '';
}
if (text) {
if (whitespaceOption === 'condense') {
// condense consecutive whitespaces into single space
text = text.replace(whitespaceRE$1, ' ');
}
let res;
let child;
if (!inVPre && text !== ' ' && (res = parseText(text, delimiters))) {
child = {
type: 2,
expression: res.expression,
tokens: res.tokens,
text
};
} else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') {
child = {
type: 3,
text
};
}
if (child) {
if (options.outputSourceRange) {
child.start = start;
child.end = end;
}
children.push(child);
}
}
},
comment (text, start, end) {
// adding anyting as a sibling to the root node is forbidden
// comments should still be allowed, but ignored
if (currentParent) {
const child = {
type: 3,
text,
isComment: true
};
if (options.outputSourceRange) {
child.start = start;
child.end = end;
}
currentParent.children.push(child);
}
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
const list = el.attrsList;
const len = list.length;
if (len) {
const attrs = el.attrs = new Array(len);
for (let i = 0; i < len; i++) {
attrs[i] = {
name: list[i].name,
value: JSON.stringify(list[i].value)
};
if (list[i].start != null) {
attrs[i].start = list[i].start;
attrs[i].end = list[i].end;
}
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true;
}
}
function processElement (
element,
options
) {
processKey(element);
// determine whether this is a plain element after
// removing structural attributes
element.plain = (
!element.key &&
!element.scopedSlots &&
!element.attrsList.length
);
processRef(element);
processSlotContent(element);
processSlotOutlet(element);
processComponent(element);
for (let i = 0; i < transforms.length; i++) {
element = transforms[i](element, options) || element;
}
processAttrs(element);
return element
}
function processKey (el) {
const exp = getBindingAttr(el, 'key');
if (exp) {
{
if (el.tag === 'template') {
warn$2(
`<template> cannot be keyed. Place the key on real elements instead.`,
getRawBindingAttr(el, 'key')
);
}
if (el.for) {
const iterator = el.iterator2 || el.iterator1;
const parent = el.parent;
if (iterator && iterator === exp && parent && parent.tag === 'transition-group') {
warn$2(
`Do not use v-for index as key on <transition-group> children, ` +
`this is the same as not using keys.`,
getRawBindingAttr(el, 'key'),
true /* tip */
);
}
}
}
el.key = exp;
}
}
function processRef (el) {
const ref = getBindingAttr(el, 'ref');
if (ref) {
el.ref = ref;
el.refInFor = checkInFor(el);
}
}
function processFor (el) {
let exp;
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
const res = parseFor(exp);
if (res) {
extend(el, res);
} else {
warn$2(
`Invalid v-for expression: ${exp}`,
el.rawAttrsMap['v-for']
);
}
}
}
function parseFor (exp) {
const inMatch = exp.match(forAliasRE);
if (!inMatch) return
const res = {};
res.for = inMatch[2].trim();
const alias = inMatch[1].trim().replace(stripParensRE, '');
const iteratorMatch = alias.match(forIteratorRE);
if (iteratorMatch) {
res.alias = alias.replace(forIteratorRE, '').trim();
res.iterator1 = iteratorMatch[1].trim();
if (iteratorMatch[2]) {
res.iterator2 = iteratorMatch[2].trim();
}
} else {
res.alias = alias;
}
return res
}
function processIf (el) {
const exp = getAndRemoveAttr(el, 'v-if');
if (exp) {
el.if = exp;
addIfCondition(el, {
exp: exp,
block: el
});
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true;
}
const elseif = getAndRemoveAttr(el, 'v-else-if');
if (elseif) {
el.elseif = elseif;
}
}
}
function processIfConditions (el, parent) {
const prev = findPrevElement(parent.children);
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
});
} else {
warn$2(
`v-${el.elseif ? ('else-if="' + el.elseif + '"') : 'else'} ` +
`used on element <${el.tag}> without corresponding v-if.`,
el.rawAttrsMap[el.elseif ? 'v-else-if' : 'v-else']
);
}
}
function findPrevElement (children) {
let i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (children[i].text !== ' ') {
warn$2(
`text "${children[i].text.trim()}" between v-if and v-else(-if) ` +
`will be ignored.`,
children[i]
);
}
children.pop();
}
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = [];
}
el.ifConditions.push(condition);
}
function processOnce (el) {
const once$$1 = getAndRemoveAttr(el, 'v-once');
if (once$$1 != null) {
el.once = true;
}
}
// handle content being passed to a component as slot,
// e.g. <template slot="xxx">, <div slot-scope="xxx">
function processSlotContent (el) {
let slotScope;
if (el.tag === 'template') {
slotScope = getAndRemoveAttr(el, 'scope');
/* istanbul ignore if */
if (slotScope) {
warn$2(
`the "scope" attribute for scoped slots have been deprecated and ` +
`replaced by "slot-scope" since 2.5. The new "slot-scope" attribute ` +
`can also be used on plain elements in addition to <template> to ` +
`denote scoped slots.`,
el.rawAttrsMap['scope'],
true
);
}
el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope');
} else if ((slotScope = getAndRemoveAttr(el, 'slot-scope'))) {
/* istanbul ignore if */
if (el.attrsMap['v-for']) {
warn$2(
`Ambiguous combined usage of slot-scope and v-for on <${el.tag}> ` +
`(v-for takes higher priority). Use a wrapper <template> for the ` +
`scoped slot to make it clearer.`,
el.rawAttrsMap['slot-scope'],
true
);
}
el.slotScope = slotScope;
}
// slot="xxx"
const slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
el.slotTargetDynamic = !!(el.attrsMap[':slot'] || el.attrsMap['v-bind:slot']);
// preserve slot as an attribute for native shadow DOM compat
// only for non-scoped slots.
if (el.tag !== 'template' && !el.slotScope) {
addAttr(el, 'slot', slotTarget, getRawBindingAttr(el, 'slot'));
}
}
// 2.6 v-slot syntax
{
if (el.tag === 'template') {
// v-slot on <template>
const slotBinding = getAndRemoveAttrByRegex(el, slotRE);
if (slotBinding) {
{
if (el.slotTarget || el.slotScope) {
warn$2(
`Unexpected mixed usage of different slot syntaxes.`,
el
);
}
if (el.parent && !maybeComponent(el.parent)) {
warn$2(
`<template v-slot> can only appear at the root level inside ` +
`the receiving the component`,
el
);
}
}
const { name, dynamic } = getSlotName(slotBinding);
el.slotTarget = name;
el.slotTargetDynamic = dynamic;
el.slotScope = slotBinding.value || `_`; // force it into a scoped slot for perf
}
} else {
// v-slot on component, denotes default slot
const slotBinding = getAndRemoveAttrByRegex(el, slotRE);
if (slotBinding) {
{
if (!maybeComponent(el)) {
warn$2(
`v-slot can only be used on components or <template>.`,
slotBinding
);
}
if (el.slotScope || el.slotTarget) {
warn$2(
`Unexpected mixed usage of different slot syntaxes.`,
el
);
}
if (el.scopedSlots) {
warn$2(
`To avoid scope ambiguity, the default slot should also use ` +
`<template> syntax when there are other named slots.`,
slotBinding
);
}
}
// add the component's children to its default slot
const slots = el.scopedSlots || (el.scopedSlots = {});
const { name, dynamic } = getSlotName(slotBinding);
const slotContainer = slots[name] = createASTElement('template', [], el);
slotContainer.slotTarget = name;
slotContainer.slotTargetDynamic = dynamic;
slotContainer.children = el.children.filter(c => !(c).slotScope);
slotContainer.slotScope = slotBinding.value || `_`;
// remove children as they are returned from scopedSlots now
el.children = [];
// mark el non-plain so data gets generated
el.plain = false;
}
}
}
}
function getSlotName (binding) {
let name = binding.name.replace(slotRE, '');
if (!name) {
if (binding.name[0] !== '#') {
name = 'default';
} else {
warn$2(
`v-slot shorthand syntax requires a slot name.`,
binding
);
}
}
return dynamicArgRE.test(name)
// dynamic [name]
? { name: name.slice(1, -1), dynamic: true }
// static name
: { name: `"${name}"`, dynamic: false }
}
// handle <slot/> outlets
function processSlotOutlet (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name');
if (el.key) {
warn$2(
`\`key\` does not work on <slot> because slots are abstract outlets ` +
`and can possibly expand into multiple elements. ` +
`Use the key on a wrapping element instead.`,
getRawBindingAttr(el, 'key')
);
}
}
}
function processComponent (el) {
let binding;
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding;
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true;
}
}
function processAttrs (el) {
const list = el.attrsList;
let i, l, name, rawName, value, modifiers, syncGen, isDynamic;
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name;
value = list[i].value;
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true;
// modifiers
modifiers = parseModifiers(name.replace(dirRE, ''));
// support .foo shorthand syntax for the .prop modifier
if (modifiers) {
name = name.replace(modifierRE, '');
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '');
value = parseFilters(value);
isDynamic = dynamicArgRE.test(name);
if (isDynamic) {
name = name.slice(1, -1);
}
if (
value.trim().length === 0
) {
warn$2(
`The value for a v-bind expression cannot be empty. Found in "v-bind:${name}"`
);
}
if (modifiers) {
if (modifiers.prop && !isDynamic) {
name = camelize(name);
if (name === 'innerHtml') name = 'innerHTML';
}
if (modifiers.camel && !isDynamic) {
name = camelize(name);
}
if (modifiers.sync) {
syncGen = genAssignmentCode(value, `$event`);
if (!isDynamic) {
addHandler(
el,
`update:${camelize(name)}`,
syncGen,
null,
false,
warn$2,
list[i]
);
if (hyphenate(name) !== camelize(name)) {
addHandler(
el,
`update:${hyphenate(name)}`,
syncGen,
null,
false,
warn$2,
list[i]
);
}
} else {
// handler w/ dynamic event name
addHandler(
el,
`"update:"+(${name})`,
syncGen,
null,
false,
warn$2,
list[i],
true // dynamic
);
}
}
}
if ((modifiers && modifiers.prop) || (
!el.component && platformMustUseProp(el.tag, el.attrsMap.type, name)
)) {
addProp(el, name, value, list[i], isDynamic);
} else {
addAttr(el, name, value, list[i], isDynamic);
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '');
isDynamic = dynamicArgRE.test(name);
if (isDynamic) {
name = name.slice(1, -1);
}
addHandler(el, name, value, modifiers, false, warn$2, list[i], isDynamic);
} else { // normal directives
name = name.replace(dirRE, '');
// parse arg
const argMatch = name.match(argRE);
let arg = argMatch && argMatch[1];
isDynamic = false;
if (arg) {
name = name.slice(0, -(arg.length + 1));
if (dynamicArgRE.test(arg)) {
arg = arg.slice(1, -1);
isDynamic = true;
}
}
addDirective(el, name, rawName, value, arg, isDynamic, modifiers, list[i]);
if (name === 'model') {
checkForAliasModel(el, value);
}
}
} else {
// literal attribute
{
const res = parseText(value, delimiters);
if (res) {
warn$2(
`${name}="${value}": ` +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.',
list[i]
);
}
}
addAttr(el, name, JSON.stringify(value), list[i]);
// #6887 firefox doesn't update muted state if set via attribute
// even immediately after element creation
if (!el.component &&
name === 'muted' &&
platformMustUseProp(el.tag, el.attrsMap.type, name)) {
addProp(el, name, 'true', list[i]);
}
}
}
}
function checkInFor (el) {
let parent = el;
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent;
}
return false
}
function parseModifiers (name) {
const match = name.match(modifierRE);
if (match) {
const ret = {};
match.forEach(m => { ret[m.slice(1)] = true; });
return ret
}
}
function makeAttrsMap (attrs) {
const map = {};
for (let i = 0, l = attrs.length; i < l; i++) {
if (
map[attrs[i].name] && !isIE && !isEdge
) {
warn$2('duplicate attribute: ' + attrs[i].name, attrs[i]);
}
map[attrs[i].name] = attrs[i].value;
}
return map
}
// for script (e.g. type="x/template") or style, do not decode content
function isTextTag (el) {
return el.tag === 'script' || el.tag === 'style'
}
function isForbiddenTag (el) {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
const ieNSBug = /^xmlns:NS\d+/;
const ieNSPrefix = /^NS\d+:/;
/* istanbul ignore next */
function guardIESVGBug (attrs) {
const res = [];
for (let i = 0; i < attrs.length; i++) {
const attr = attrs[i];
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '');
res.push(attr);
}
}
return res
}
function checkForAliasModel (el, value) {
let _el = el;
while (_el) {
if (_el.for && _el.alias === value) {
warn$2(
`<${el.tag} v-model="${value}">: ` +
`You are binding v-model directly to a v-for iteration alias. ` +
`This will not be able to modify the v-for source array because ` +
`writing to the alias is like modifying a function local variable. ` +
`Consider using an array of objects and use v-model on an object property instead.`,
el.rawAttrsMap['v-model']
);
}
_el = _el.parent;
}
}
/* */
function preTransformNode (el, options) {
if (el.tag === 'input') {
const map = el.attrsMap;
if (!map['v-model']) {
return
}
let typeBinding;
if (map[':type'] || map['v-bind:type']) {
typeBinding = getBindingAttr(el, 'type');
}
if (!map.type && !typeBinding && map['v-bind']) {
typeBinding = `(${map['v-bind']}).type`;
}
if (typeBinding) {
const ifCondition = getAndRemoveAttr(el, 'v-if', true);
const ifConditionExtra = ifCondition ? `&&(${ifCondition})` : ``;
const hasElse = getAndRemoveAttr(el, 'v-else', true) != null;
const elseIfCondition = getAndRemoveAttr(el, 'v-else-if', true);
// 1. checkbox
const branch0 = cloneASTElement(el);
// process for on the main node
processFor(branch0);
addRawAttr(branch0, 'type', 'checkbox');
processElement(branch0, options);
branch0.processed = true; // prevent it from double-processed
branch0.if = `(${typeBinding})==='checkbox'` + ifConditionExtra;
addIfCondition(branch0, {
exp: branch0.if,
block: branch0
});
// 2. add radio else-if condition
const branch1 = cloneASTElement(el);
getAndRemoveAttr(branch1, 'v-for', true);
addRawAttr(branch1, 'type', 'radio');
processElement(branch1, options);
addIfCondition(branch0, {
exp: `(${typeBinding})==='radio'` + ifConditionExtra,
block: branch1
});
// 3. other
const branch2 = cloneASTElement(el);
getAndRemoveAttr(branch2, 'v-for', true);
addRawAttr(branch2, ':type', typeBinding);
processElement(branch2, options);
addIfCondition(branch0, {
exp: ifCondition,
block: branch2
});
if (hasElse) {
branch0.else = true;
} else if (elseIfCondition) {
branch0.elseif = elseIfCondition;
}
return branch0
}
}
}
function cloneASTElement (el) {
return createASTElement(el.tag, el.attrsList.slice(), el.parent)
}
var model$1 = {
preTransformNode
};
var modules$1 = [
klass$1,
style$1,
model$1
];
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', `_s(${dir.value})`, dir);
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', `_s(${dir.value})`, dir);
}
}
var directives$1 = {
model,
text,
html
};
/* */
const baseOptions = {
expectHTML: true,
modules: modules$1,
directives: directives$1,
isPreTag,
isUnaryTag,
mustUseProp,
canBeLeftOpenTag,
isReservedTag,
getTagNamespace,
staticKeys: genStaticKeys(modules$1)
};
/* */
let isStaticKey;
let isPlatformReservedTag;
const genStaticKeysCached = cached(genStaticKeys$1);
/**
* Goal of the optimizer: walk the generated template AST tree
* and detect sub-trees that are purely static, i.e. parts of
* the DOM that never needs to change.
*
* Once we detect these sub-trees, we can:
*
* 1. Hoist them into constants, so that we no longer need to
* create fresh nodes for them on each re-render;
* 2. Completely skip them in the patching process.
*/
function optimize (root, options) {
if (!root) return
isStaticKey = genStaticKeysCached(options.staticKeys || '');
isPlatformReservedTag = options.isReservedTag || no;
// first pass: mark all non-static nodes.
markStatic$1(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap' +
(keys ? ',' + keys : '')
)
}
function markStatic$1 (node) {
node.static = isStatic(node);
if (node.type === 1) {
// do not make component slot content static. this avoids
// 1. components not able to mutate slot nodes
// 2. static slot content fails for hot-reloading
if (
!isPlatformReservedTag(node.tag) &&
node.tag !== 'slot' &&
node.attrsMap['inline-template'] == null
) {
return
}
for (let i = 0, l = node.children.length; i < l; i++) {
const child = node.children[i];
markStatic$1(child);
if (!child.static) {
node.static = false;
}
}
if (node.ifConditions) {
for (let i = 1, l = node.ifConditions.length; i < l; i++) {
const block = node.ifConditions[i].block;
markStatic$1(block);
if (!block.static) {
node.static = false;
}
}
}
}
}
function markStaticRoots (node, isInFor) {
if (node.type === 1) {
if (node.static || node.once) {
node.staticInFor = isInFor;
}
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if (node.static && node.children.length && !(
node.children.length === 1 &&
node.children[0].type === 3
)) {
node.staticRoot = true;
return
} else {
node.staticRoot = false;
}
if (node.children) {
for (let i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for);
}
}
if (node.ifConditions) {
for (let i = 1, l = node.ifConditions.length; i < l; i++) {
markStaticRoots(node.ifConditions[i].block, isInFor);
}
}
}
}
function isStatic (node) {
if (node.type === 2) { // expression
return false
}
if (node.type === 3) { // text
return true
}
return !!(node.pre || (
!node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!isDirectChildOfTemplateFor(node) &&
Object.keys(node).every(isStaticKey)
))
}
function isDirectChildOfTemplateFor (node) {
while (node.parent) {
node = node.parent;
if (node.tag !== 'template') {
return false
}
if (node.for) {
return true
}
}
return false
}
/* */
const fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
const fnInvokeRE = /\([^)]*?\);*$/;
const simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/;
// KeyboardEvent.keyCode aliases
const keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
// KeyboardEvent.key aliases
const keyNames = {
// #7880: IE11 and Edge use `Esc` for Escape key name.
esc: ['Esc', 'Escape'],
tab: 'Tab',
enter: 'Enter',
// #9112: IE11 uses `Spacebar` for Space key name.
space: [' ', 'Spacebar'],
// #7806: IE11 uses key names without `Arrow` prefix for arrow keys.
up: ['Up', 'ArrowUp'],
left: ['Left', 'ArrowLeft'],
right: ['Right', 'ArrowRight'],
down: ['Down', 'ArrowDown'],
// #9112: IE11 uses `Del` for Delete key name.
'delete': ['Backspace', 'Delete', 'Del']
};
// #4868: modifiers that prevent the execution of the listener
// need to explicitly return null so that we can determine whether to remove
// the listener for .once
const genGuard = condition => `if(${condition})return null;`;
const modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: genGuard(`$event.target !== $event.currentTarget`),
ctrl: genGuard(`!$event.ctrlKey`),
shift: genGuard(`!$event.shiftKey`),
alt: genGuard(`!$event.altKey`),
meta: genGuard(`!$event.metaKey`),
left: genGuard(`'button' in $event && $event.button !== 0`),
middle: genGuard(`'button' in $event && $event.button !== 1`),
right: genGuard(`'button' in $event && $event.button !== 2`)
};
function genHandlers (
events,
isNative
) {
const prefix = isNative ? 'nativeOn:' : 'on:';
let staticHandlers = ``;
let dynamicHandlers = ``;
for (const name in events) {
const handlerCode = genHandler(events[name]);
if (events[name] && events[name].dynamic) {
dynamicHandlers += `${name},${handlerCode},`;
} else {
staticHandlers += `"${name}":${handlerCode},`;
}
}
staticHandlers = `{${staticHandlers.slice(0, -1)}}`;
if (dynamicHandlers) {
return prefix + `_d(${staticHandlers},[${dynamicHandlers.slice(0, -1)}])`
} else {
return prefix + staticHandlers
}
}
function genHandler (handler) {
if (!handler) {
return 'function(){}'
}
if (Array.isArray(handler)) {
return `[${handler.map(handler => genHandler(handler)).join(',')}]`
}
const isMethodPath = simplePathRE.test(handler.value);
const isFunctionExpression = fnExpRE.test(handler.value);
const isFunctionInvocation = simplePathRE.test(handler.value.replace(fnInvokeRE, ''));
if (!handler.modifiers) {
if (isMethodPath || isFunctionExpression) {
return handler.value
}
return `function($event){${
isFunctionInvocation ? `return ${handler.value}` : handler.value
}}` // inline statement
} else {
let code = '';
let genModifierCode = '';
const keys = [];
for (const key in handler.modifiers) {
if (modifierCode[key]) {
genModifierCode += modifierCode[key];
// left/right
if (keyCodes[key]) {
keys.push(key);
}
} else if (key === 'exact') {
const modifiers = (handler.modifiers);
genModifierCode += genGuard(
['ctrl', 'shift', 'alt', 'meta']
.filter(keyModifier => !modifiers[keyModifier])
.map(keyModifier => `$event.${keyModifier}Key`)
.join('||')
);
} else {
keys.push(key);
}
}
if (keys.length) {
code += genKeyFilter(keys);
}
// Make sure modifiers like prevent and stop get executed after key filtering
if (genModifierCode) {
code += genModifierCode;
}
const handlerCode = isMethodPath
? `return ${handler.value}($event)`
: isFunctionExpression
? `return (${handler.value})($event)`
: isFunctionInvocation
? `return ${handler.value}`
: handler.value;
return `function($event){${code}${handlerCode}}`
}
}
function genKeyFilter (keys) {
return `if(('keyCode' in $event)&&${keys.map(genFilterCode).join('&&')})return null;`
}
function genFilterCode (key) {
const keyVal = parseInt(key, 10);
if (keyVal) {
return `$event.keyCode!==${keyVal}`
}
const keyCode = keyCodes[key];
const keyName = keyNames[key];
return (
`_k($event.keyCode,` +
`${JSON.stringify(key)},` +
`${JSON.stringify(keyCode)},` +
`$event.key,` +
`${JSON.stringify(keyName)}` +
`)`
)
}
/* */
function on (el, dir) {
if (dir.modifiers) {
warn(`v-on without argument does not support modifiers.`);
}
el.wrapListeners = (code) => `_g(${code},${dir.value})`;
}
/* */
function bind$1 (el, dir) {
el.wrapData = (code) => {
return `_b(${code},'${el.tag}',${dir.value},${
dir.modifiers && dir.modifiers.prop ? 'true' : 'false'
}${
dir.modifiers && dir.modifiers.sync ? ',true' : ''
})`
};
}
/* */
var baseDirectives = {
on,
bind: bind$1,
cloak: noop
};
/* */
class CodegenState {
constructor (options) {
this.options = options;
this.warn = options.warn || baseWarn;
this.transforms = pluckModuleFunction(options.modules, 'transformCode');
this.dataGenFns = pluckModuleFunction(options.modules, 'genData');
this.directives = extend(extend({}, baseDirectives), options.directives);
const isReservedTag = options.isReservedTag || no;
this.maybeComponent = (el) => !!el.component || !isReservedTag(el.tag);
this.onceId = 0;
this.staticRenderFns = [];
this.pre = false;
}
}
function generate (
ast,
options
) {
const state = new CodegenState(options);
const code = ast ? genElement(ast, state) : '_c("div")';
return {
render: `with(this){return ${code}}`,
staticRenderFns: state.staticRenderFns
}
}
function genElement (el, state) {
if (el.parent) {
el.pre = el.pre || el.parent.pre;
}
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el, state)
} else if (el.once && !el.onceProcessed) {
return genOnce(el, state)
} else if (el.for && !el.forProcessed) {
return genFor(el, state)
} else if (el.if && !el.ifProcessed) {
return genIf(el, state)
} else if (el.tag === 'template' && !el.slotTarget && !state.pre) {
return genChildren(el, state) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el, state)
} else {
// component or element
let code;
if (el.component) {
code = genComponent(el.component, el, state);
} else {
let data;
if (!el.plain || (el.pre && state.maybeComponent(el))) {
data = genData$2(el, state);
}
const children = el.inlineTemplate ? null : genChildren(el, state, true);
code = `_c('${el.tag}'${
data ? `,${data}` : '' // data
}${
children ? `,${children}` : '' // children
})`;
}
// module transforms
for (let i = 0; i < state.transforms.length; i++) {
code = state.transforms[i](el, code);
}
return code
}
}
// hoist static sub-trees out
function genStatic (el, state) {
el.staticProcessed = true;
// Some elements (templates) need to behave differently inside of a v-pre
// node. All pre nodes are static roots, so we can use this as a location to
// wrap a state change and reset it upon exiting the pre node.
const originalPreState = state.pre;
if (el.pre) {
state.pre = el.pre;
}
state.staticRenderFns.push(`with(this){return ${genElement(el, state)}}`);
state.pre = originalPreState;
return `_m(${
state.staticRenderFns.length - 1
}${
el.staticInFor ? ',true' : ''
})`
}
// v-once
function genOnce (el, state) {
el.onceProcessed = true;
if (el.if && !el.ifProcessed) {
return genIf(el, state)
} else if (el.staticInFor) {
let key = '';
let parent = el.parent;
while (parent) {
if (parent.for) {
key = parent.key;
break
}
parent = parent.parent;
}
if (!key) {
state.warn(
`v-once can only be used inside v-for that is keyed. `,
el.rawAttrsMap['v-once']
);
return genElement(el, state)
}
return `_o(${genElement(el, state)},${state.onceId++},${key})`
} else {
return genStatic(el, state)
}
}
function genIf (
el,
state,
altGen,
altEmpty
) {
el.ifProcessed = true; // avoid recursion
return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)
}
function genIfConditions (
conditions,
state,
altGen,
altEmpty
) {
if (!conditions.length) {
return altEmpty || '_e()'
}
const condition = conditions.shift();
if (condition.exp) {
return `(${condition.exp})?${
genTernaryExp(condition.block)
}:${
genIfConditions(conditions, state, altGen, altEmpty)
}`
} else {
return `${genTernaryExp(condition.block)}`
}
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return altGen
? altGen(el, state)
: el.once
? genOnce(el, state)
: genElement(el, state)
}
}
function genFor (
el,
state,
altGen,
altHelper
) {
const exp = el.for;
const alias = el.alias;
const iterator1 = el.iterator1 ? `,${el.iterator1}` : '';
const iterator2 = el.iterator2 ? `,${el.iterator2}` : '';
if (state.maybeComponent(el) &&
el.tag !== 'slot' &&
el.tag !== 'template' &&
!el.key
) {
state.warn(
`<${el.tag} v-for="${alias} in ${exp}">: component lists rendered with ` +
`v-for should have explicit keys. ` +
`See https://vuejs.org/guide/list.html#key for more info.`,
el.rawAttrsMap['v-for'],
true /* tip */
);
}
el.forProcessed = true; // avoid recursion
return `${altHelper || '_l'}((${exp}),` +
`function(${alias}${iterator1}${iterator2}){` +
`return ${(altGen || genElement)(el, state)}` +
'})'
}
function genData$2 (el, state) {
let data = '{';
// directives first.
// directives may mutate the el's other properties before they are generated.
const dirs = genDirectives(el, state);
if (dirs) data += dirs + ',';
// key
if (el.key) {
data += `key:${el.key},`;
}
// ref
if (el.ref) {
data += `ref:${el.ref},`;
}
if (el.refInFor) {
data += `refInFor:true,`;
}
// pre
if (el.pre) {
data += `pre:true,`;
}
// record original tag name for components using "is" attribute
if (el.component) {
data += `tag:"${el.tag}",`;
}
// module data generation functions
for (let i = 0; i < state.dataGenFns.length; i++) {
data += state.dataGenFns[i](el);
}
// attributes
if (el.attrs) {
data += `attrs:${genProps(el.attrs)},`;
}
// DOM props
if (el.props) {
data += `domProps:${genProps(el.props)},`;
}
// event handlers
if (el.events) {
data += `${genHandlers(el.events, false)},`;
}
if (el.nativeEvents) {
data += `${genHandlers(el.nativeEvents, true)},`;
}
// slot target
// only for non-scoped slots
if (el.slotTarget && !el.slotScope) {
data += `slot:${el.slotTarget},`;
}
// scoped slots
if (el.scopedSlots) {
data += `${genScopedSlots(el.scopedSlots, state)},`;
}
// component v-model
if (el.model) {
data += `model:{value:${
el.model.value
},callback:${
el.model.callback
},expression:${
el.model.expression
}},`;
}
// inline-template
if (el.inlineTemplate) {
const inlineTemplate = genInlineTemplate(el, state);
if (inlineTemplate) {
data += `${inlineTemplate},`;
}
}
data = data.replace(/,$/, '') + '}';
// v-bind dynamic argument wrap
// v-bind with dynamic arguments must be applied using the same v-bind object
// merge helper so that class/style/mustUseProp attrs are handled correctly.
if (el.dynamicAttrs) {
data = `_b(${data},"${el.tag}",${genProps(el.dynamicAttrs)})`;
}
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data);
}
// v-on data wrap
if (el.wrapListeners) {
data = el.wrapListeners(data);
}
return data
}
function genDirectives (el, state) {
const dirs = el.directives;
if (!dirs) return
let res = 'directives:[';
let hasRuntime = false;
let i, l, dir, needRuntime;
for (i = 0, l = dirs.length; i < l; i++) {
dir = dirs[i];
needRuntime = true;
const gen = state.directives[dir.name];
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, state.warn);
}
if (needRuntime) {
hasRuntime = true;
res += `{name:"${dir.name}",rawName:"${dir.rawName}"${
dir.value ? `,value:(${dir.value}),expression:${JSON.stringify(dir.value)}` : ''
}${
dir.arg ? `,arg:${dir.isDynamicArg ? dir.arg : `"${dir.arg}"`}` : ''
}${
dir.modifiers ? `,modifiers:${JSON.stringify(dir.modifiers)}` : ''
}},`;
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
}
function genInlineTemplate (el, state) {
const ast = el.children[0];
if (el.children.length !== 1 || ast.type !== 1) {
state.warn(
'Inline-template components must have exactly one child element.',
{ start: el.start }
);
}
if (ast && ast.type === 1) {
const inlineRenderFns = generate(ast, state.options);
return `inlineTemplate:{render:function(){${
inlineRenderFns.render
}},staticRenderFns:[${
inlineRenderFns.staticRenderFns.map(code => `function(){${code}}`).join(',')
}]}`
}
}
function genScopedSlots (
slots,
state
) {
const hasDynamicKeys = Object.keys(slots).some(key => {
const slot = slots[key];
return slot.slotTargetDynamic || slot.if || slot.for
});
return `scopedSlots:_u([${
Object.keys(slots).map(key => {
return genScopedSlot(slots[key], state)
}).join(',')
}]${hasDynamicKeys ? `,true` : ``})`
}
function genScopedSlot (
el,
state
) {
if (el.if && !el.ifProcessed) {
return genIf(el, state, genScopedSlot, `null`)
}
if (el.for && !el.forProcessed) {
return genFor(el, state, genScopedSlot)
}
const fn = `function(${String(el.slotScope)}){` +
`return ${el.tag === 'template'
? genChildren(el, state) || 'undefined'
: genElement(el, state)
}}`;
return `{key:${el.slotTarget || `"default"`},fn:${fn}}`
}
function genChildren (
el,
state,
checkSkip,
altGenElement,
altGenNode
) {
const children = el.children;
if (children.length) {
const el = children[0];
// optimize single v-for
if (children.length === 1 &&
el.for &&
el.tag !== 'template' &&
el.tag !== 'slot'
) {
const normalizationType = checkSkip
? state.maybeComponent(el) ? `,1` : `,0`
: ``;
return `${(altGenElement || genElement)(el, state)}${normalizationType}`
}
const normalizationType = checkSkip
? getNormalizationType(children, state.maybeComponent)
: 0;
const gen = altGenNode || genNode;
return `[${children.map(c => gen(c, state)).join(',')}]${
normalizationType ? `,${normalizationType}` : ''
}`
}
}
// determine the normalization needed for the children array.
// 0: no normalization needed
// 1: simple normalization needed (possible 1-level deep nested array)
// 2: full normalization needed
function getNormalizationType (
children,
maybeComponent
) {
let res = 0;
for (let i = 0; i < children.length; i++) {
const el = children[i];
if (el.type !== 1) {
continue
}
if (needsNormalization(el) ||
(el.ifConditions && el.ifConditions.some(c => needsNormalization(c.block)))) {
res = 2;
break
}
if (maybeComponent(el) ||
(el.ifConditions && el.ifConditions.some(c => maybeComponent(c.block)))) {
res = 1;
}
}
return res
}
function needsNormalization (el) {
return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
}
function genNode (node, state) {
if (node.type === 1) {
return genElement(node, state)
} else if (node.type === 3 && node.isComment) {
return genComment(node)
} else {
return genText(node)
}
}
function genText (text) {
return `_v(${text.type === 2
? text.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(text.text))
})`
}
function genComment (comment) {
return `_e(${JSON.stringify(comment.text)})`
}
function genSlot (el, state) {
const slotName = el.slotName || '"default"';
const children = genChildren(el, state);
let res = `_t(${slotName}${children ? `,${children}` : ''}`;
const attrs = el.attrs && `{${el.attrs.map(a => `${camelize(a.name)}:${a.value}`).join(',')}}`;
const bind$$1 = el.attrsMap['v-bind'];
if ((attrs || bind$$1) && !children) {
res += `,null`;
}
if (attrs) {
res += `,${attrs}`;
}
if (bind$$1) {
res += `${attrs ? '' : ',null'},${bind$$1}`;
}
return res + ')'
}
// componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (
componentName,
el,
state
) {
const children = el.inlineTemplate ? null : genChildren(el, state, true);
return `_c(${componentName},${genData$2(el, state)}${
children ? `,${children}` : ''
})`
}
function genProps (props) {
let staticProps = ``;
let dynamicProps = ``;
for (let i = 0; i < props.length; i++) {
const prop = props[i];
const value = transformSpecialNewlines(prop.value);
if (prop.dynamic) {
dynamicProps += `${prop.name},${value},`;
} else {
staticProps += `"${prop.name}":${value},`;
}
}
staticProps = `{${staticProps.slice(0, -1)}}`;
if (dynamicProps) {
return `_d(${staticProps},[${dynamicProps.slice(0, -1)}])`
} else {
return staticProps
}
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
// these keywords should not appear inside expressions, but operators like
// typeof, instanceof and in are allowed
const prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b');
// these unary operators should not be used as property/method names
const unaryOperatorsRE = new RegExp('\\b' + (
'delete,typeof,void'
).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)');
// strip strings in expressions
const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast, warn) {
if (ast) {
checkNode(ast, warn);
}
}
function checkNode (node, warn) {
if (node.type === 1) {
for (const name in node.attrsMap) {
if (dirRE.test(name)) {
const value = node.attrsMap[name];
if (value) {
const range = node.rawAttrsMap[name];
if (name === 'v-for') {
checkFor(node, `v-for="${value}"`, warn, range);
} else if (onRE.test(name)) {
checkEvent(value, `${name}="${value}"`, warn, range);
} else {
checkExpression(value, `${name}="${value}"`, warn, range);
}
}
}
}
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
checkNode(node.children[i], warn);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, warn, node);
}
}
function checkEvent (exp, text, warn, range) {
const stipped = exp.replace(stripStringRE, '');
const keywordMatch = stipped.match(unaryOperatorsRE);
if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') {
warn(
`avoid using JavaScript unary operator as property name: ` +
`"${keywordMatch[0]}" in expression ${text.trim()}`,
range
);
}
checkExpression(exp, text, warn, range);
}
function checkFor (node, text, warn, range) {
checkExpression(node.for || '', text, warn, range);
checkIdentifier(node.alias, 'v-for alias', text, warn, range);
checkIdentifier(node.iterator1, 'v-for iterator', text, warn, range);
checkIdentifier(node.iterator2, 'v-for iterator', text, warn, range);
}
function checkIdentifier (
ident,
type,
text,
warn,
range
) {
if (typeof ident === 'string') {
try {
new Function(`var ${ident}=_`);
} catch (e) {
warn(`invalid ${type} "${ident}" in expression: ${text.trim()}`, range);
}
}
}
function checkExpression (exp, text, warn, range) {
try {
new Function(`return ${exp}`);
} catch (e) {
const keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
warn(
`avoid using JavaScript keyword as property name: ` +
`"${keywordMatch[0]}"\n Raw expression: ${text.trim()}`,
range
);
} else {
warn(
`invalid expression: ${e.message} in\n\n` +
` ${exp}\n\n` +
` Raw expression: ${text.trim()}\n`,
range
);
}
}
}
/* */
const range = 2;
function generateCodeFrame (
source,
start = 0,
end = source.length
) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (let j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length) continue
res.push(`${j + 1}${repeat(` `, 3 - String(j + 1).length)}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1;
const length = end > count ? lineLength - pad : end - start;
res.push(` | ` + repeat(` `, pad) + repeat(`^`, length));
} else if (j > i) {
if (end > count) {
const length = Math.min(end - count, lineLength);
res.push(` | ` + repeat(`^`, length));
}
count += lineLength + 1;
}
}
break
}
}
return res.join('\n')
}
function repeat (str, n) {
let result = '';
while (true) { // eslint-disable-line
if (n & 1) result += str;
n >>>= 1;
if (n <= 0) break
str += str;
}
return result
}
/* */
function createFunction (code, errors) {
try {
return new Function(code)
} catch (err) {
errors.push({ err, code });
return noop
}
}
function createCompileToFunctionFn (compile) {
const cache = Object.create(null);
return function compileToFunctions (
template,
options,
vm
) {
options = extend({}, options);
const warn$$1 = options.warn || warn;
delete options.warn;
/* istanbul ignore if */
{
// detect possible CSP restriction
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
warn$$1(
'It seems you are using the standalone build of Vue.js in an ' +
'environment with Content Security Policy that prohibits unsafe-eval. ' +
'The template compiler cannot work in this environment. Consider ' +
'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
'templates into render functions.'
);
}
}
}
// check cache
const key = options.delimiters
? String(options.delimiters) + template
: template;
if (cache[key]) {
return cache[key]
}
// compile
const compiled = compile(template, options);
// check compilation errors/tips
{
if (compiled.errors && compiled.errors.length) {
if (options.outputSourceRange) {
compiled.errors.forEach(e => {
warn$$1(
`Error compiling template:\n\n${e.msg}\n\n` +
generateCodeFrame(template, e.start, e.end),
vm
);
});
} else {
warn$$1(
`Error compiling template:\n\n${template}\n\n` +
compiled.errors.map(e => `- ${e}`).join('\n') + '\n',
vm
);
}
}
if (compiled.tips && compiled.tips.length) {
if (options.outputSourceRange) {
compiled.tips.forEach(e => tip(e.msg, vm));
} else {
compiled.tips.forEach(msg => tip(msg, vm));
}
}
}
// turn code into functions
const res = {};
const fnGenErrors = [];
res.render = createFunction(compiled.render, fnGenErrors);
res.staticRenderFns = compiled.staticRenderFns.map(code => {
return createFunction(code, fnGenErrors)
});
// check function generation errors.
// this should only happen if there is a bug in the compiler itself.
// mostly for codegen development use
/* istanbul ignore if */
{
if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
warn$$1(
`Failed to generate render function:\n\n` +
fnGenErrors.map(({ err, code }) => `${err.toString()} in\n\n${code}\n`).join('\n'),
vm
);
}
}
return (cache[key] = res)
}
}
/* */
function createCompilerCreator (baseCompile) {
return function createCompiler (baseOptions) {
function compile (
template,
options
) {
const finalOptions = Object.create(baseOptions);
const errors = [];
const tips = [];
let warn = (msg, range, tip) => {
(tip ? tips : errors).push(msg);
};
if (options) {
if (options.outputSourceRange) {
// $flow-disable-line
const leadingSpaceLength = template.match(/^\s*/)[0].length;
warn = (msg, range, tip) => {
const data = { msg };
if (range) {
if (range.start != null) {
data.start = range.start + leadingSpaceLength;
}
if (range.end != null) {
data.end = range.end + leadingSpaceLength;
}
}
(tip ? tips : errors).push(data);
};
}
// merge custom modules
if (options.modules) {
finalOptions.modules =
(baseOptions.modules || []).concat(options.modules);
}
// merge custom directives
if (options.directives) {
finalOptions.directives = extend(
Object.create(baseOptions.directives || null),
options.directives
);
}
// copy other options
for (const key in options) {
if (key !== 'modules' && key !== 'directives') {
finalOptions[key] = options[key];
}
}
}
finalOptions.warn = warn;
const compiled = baseCompile(template.trim(), finalOptions);
{
detectErrors(compiled.ast, warn);
}
compiled.errors = errors;
compiled.tips = tips;
return compiled
}
return {
compile,
compileToFunctions: createCompileToFunctionFn(compile)
}
}
}
/* */
// `createCompilerCreator` allows creating compilers that use alternative
// parser/optimizer/codegen, e.g the SSR optimizing compiler.
// Here we just export a default compiler using the default parts.
const createCompiler = createCompilerCreator(function baseCompile (
template,
options
) {
const ast = parse(template.trim(), options);
if (options.optimize !== false) {
optimize(ast, options);
}
const code = generate(ast, options);
return {
ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
});
/* */
const { compile, compileToFunctions } = createCompiler(baseOptions);
/* */
// check whether current browser encodes a char inside attribute values
let div;
function getShouldDecode (href) {
div = div || document.createElement('div');
div.innerHTML = href ? `<a href="\n"/>` : `<div a="\n"/>`;
return div.innerHTML.indexOf(' ') > 0
}
// #3663: IE encodes newlines inside attribute values while other browsers don't
const shouldDecodeNewlines = inBrowser ? getShouldDecode(false) : false;
// #6828: chrome encodes content in a[href]
const shouldDecodeNewlinesForHref = inBrowser ? getShouldDecode(true) : false;
/* */
const idToTemplate = cached(id => {
const el = query(id);
return el && el.innerHTML
});
const mount = Vue.prototype.$mount;
Vue.prototype.$mount = function (
el,
hydrating
) {
el = el && query(el);
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
);
return this
}
const options = this.$options;
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template;
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template);
/* istanbul ignore if */
if (!template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
);
}
}
} else if (template.nodeType) {
template = template.innerHTML;
} else {
{
warn('invalid template option:' + template, this);
}
return this
}
} else if (el) {
template = getOuterHTML(el);
}
if (template) {
/* istanbul ignore if */
if (config.performance && mark) {
mark('compile');
}
const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: "development" !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this);
options.render = render;
options.staticRenderFns = staticRenderFns;
/* istanbul ignore if */
if (config.performance && mark) {
mark('compile end');
measure(`vue ${this._name} compile`, 'compile', 'compile end');
}
}
}
return mount.call(this, el, hydrating)
};
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el) {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div');
container.appendChild(el.cloneNode(true));
return container.innerHTML
}
}
Vue.compile = compileToFunctions;
export default Vue;
|
'use strict';
var React = require('react');
var PureRenderMixin = require('react-addons-pure-render-mixin');
var SvgIcon = require('../../svg-icon');
var HardwareTabletMac = React.createClass({
displayName: 'HardwareTabletMac',
mixins: [PureRenderMixin],
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M18.5 0h-14C3.12 0 2 1.12 2 2.5v19C2 22.88 3.12 24 4.5 24h14c1.38 0 2.5-1.12 2.5-2.5v-19C21 1.12 19.88 0 18.5 0zm-7 23c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm7.5-4H4V3h15v16z' })
);
}
});
module.exports = HardwareTabletMac;
|
/*
Copyright (c) 2017 NAVER Corp.
@egjs/axes project is licensed under the MIT license
@egjs/axes JavaScript library
https://github.com/naver/egjs-axes
@version 2.5.10
All-in-one packaged file for ease use of '@egjs/axes' with below dependencies.
NOTE: This is not an official distribution file and is only for user convenience.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.eg = global.eg || {}, global.eg.Axes = factory());
}(this, (function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
};
function __extends(d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
/*
Copyright (c) 2017 NAVER Corp.
@egjs/component project is licensed under the MIT license
@egjs/component JavaScript library
https://naver.github.io/egjs-component
@version 2.1.2
*/
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
function isUndefined(value) {
return typeof value === "undefined";
}
/**
* A class used to manage events in a component
* @ko 컴포넌트의 이벤트을 관리할 수 있게 하는 클래스
* @alias eg.Component
*/
var Component =
/*#__PURE__*/
function () {
var Component =
/*#__PURE__*/
function () {
/**
* Version info string
* @ko 버전정보 문자열
* @name VERSION
* @static
* @type {String}
* @example
* eg.Component.VERSION; // ex) 2.0.0
* @memberof eg.Component
*/
/**
* @support {"ie": "7+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.1+ (except 3.x)"}
*/
function Component() {
this._eventHandler = {};
this.options = {};
}
/**
* Triggers a custom event.
* @ko 커스텀 이벤트를 발생시킨다
* @param {String} eventName The name of the custom event to be triggered <ko>발생할 커스텀 이벤트의 이름</ko>
* @param {Object} customEvent Event data to be sent when triggering a custom event <ko>커스텀 이벤트가 발생할 때 전달할 데이터</ko>
* @return {Boolean} Indicates whether the event has occurred. If the stop() method is called by a custom event handler, it will return false and prevent the event from occurring. <a href="https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F">Ref</a> <ko>이벤트 발생 여부. 커스텀 이벤트 핸들러에서 stop() 메서드를 호출하면 'false'를 반환하고 이벤트 발생을 중단한다. <a href="https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F">참고</a></ko>
* @example
class Some extends eg.Component {
some(){
if(this.trigger("beforeHi")){ // When event call to stop return false.
this.trigger("hi");// fire hi event.
}
}
}
const some = new Some();
some.on("beforeHi", (e) => {
if(condition){
e.stop(); // When event call to stop, `hi` event not call.
}
});
some.on("hi", (e) => {
// `currentTarget` is component instance.
console.log(some === e.currentTarget); // true
});
// If you want to more know event design. You can see article.
// https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F
*/
var _proto = Component.prototype;
_proto.trigger = function trigger(eventName, customEvent) {
if (customEvent === void 0) {
customEvent = {};
}
var handlerList = this._eventHandler[eventName] || [];
var hasHandlerList = handlerList.length > 0;
if (!hasHandlerList) {
return true;
} // If detach method call in handler in first time then handler list calls.
handlerList = handlerList.concat();
customEvent.eventType = eventName;
var isCanceled = false;
var arg = [customEvent];
var i = 0;
customEvent.stop = function () {
isCanceled = true;
};
customEvent.currentTarget = this;
for (var _len = arguments.length, restParam = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
restParam[_key - 2] = arguments[_key];
}
if (restParam.length >= 1) {
arg = arg.concat(restParam);
}
for (i = 0; handlerList[i]; i++) {
handlerList[i].apply(this, arg);
}
return !isCanceled;
};
/**
* Executed event just one time.
* @ko 이벤트가 한번만 실행된다.
* @param {eventName} eventName The name of the event to be attached <ko>등록할 이벤트의 이름</ko>
* @param {Function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return {eg.Component} An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
class Some extends eg.Component {
hi() {
alert("hi");
}
thing() {
this.once("hi", this.hi);
}
}
var some = new Some();
some.thing();
some.trigger("hi");
// fire alert("hi");
some.trigger("hi");
// Nothing happens
*/
_proto.once = function once(eventName, handlerToAttach) {
if (typeof eventName === "object" && isUndefined(handlerToAttach)) {
var eventHash = eventName;
var i;
for (i in eventHash) {
this.once(i, eventHash[i]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var self = this;
this.on(eventName, function listener() {
for (var _len2 = arguments.length, arg = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
arg[_key2] = arguments[_key2];
}
handlerToAttach.apply(self, arg);
self.off(eventName, listener);
});
}
return this;
};
/**
* Checks whether an event has been attached to a component.
* @ko 컴포넌트에 이벤트가 등록됐는지 확인한다.
* @param {String} eventName The name of the event to be attached <ko>등록 여부를 확인할 이벤트의 이름</ko>
* @return {Boolean} Indicates whether the event is attached. <ko>이벤트 등록 여부</ko>
* @example
class Some extends eg.Component {
some() {
this.hasOn("hi");// check hi event.
}
}
*/
_proto.hasOn = function hasOn(eventName) {
return !!this._eventHandler[eventName];
};
/**
* Attaches an event to a component.
* @ko 컴포넌트에 이벤트를 등록한다.
* @param {eventName} eventName The name of the event to be attached <ko>등록할 이벤트의 이름</ko>
* @param {Function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return {eg.Component} An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
class Some extends eg.Component {
hi() {
console.log("hi");
}
some() {
this.on("hi",this.hi); //attach event
}
}
*/
_proto.on = function on(eventName, handlerToAttach) {
if (typeof eventName === "object" && isUndefined(handlerToAttach)) {
var eventHash = eventName;
var name;
for (name in eventHash) {
this.on(name, eventHash[name]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var handlerList = this._eventHandler[eventName];
if (isUndefined(handlerList)) {
this._eventHandler[eventName] = [];
handlerList = this._eventHandler[eventName];
}
handlerList.push(handlerToAttach);
}
return this;
};
/**
* Detaches an event from the component.
* @ko 컴포넌트에 등록된 이벤트를 해제한다
* @param {eventName} eventName The name of the event to be detached <ko>해제할 이벤트의 이름</ko>
* @param {Function} handlerToDetach The handler function of the event to be detached <ko>해제할 이벤트의 핸들러 함수</ko>
* @return {eg.Component} An instance of a component itself <ko>컴포넌트 자신의 인스턴스</ko>
* @example
class Some extends eg.Component {
hi() {
console.log("hi");
}
some() {
this.off("hi",this.hi); //detach event
}
}
*/
_proto.off = function off(eventName, handlerToDetach) {
// All event detach.
if (isUndefined(eventName)) {
this._eventHandler = {};
return this;
} // All handler of specific event detach.
if (isUndefined(handlerToDetach)) {
if (typeof eventName === "string") {
this._eventHandler[eventName] = undefined;
return this;
} else {
var eventHash = eventName;
var name;
for (name in eventHash) {
this.off(name, eventHash[name]);
}
return this;
}
} // The handler of specific event detach.
var handlerList = this._eventHandler[eventName];
if (handlerList) {
var k;
var handlerFunction;
for (k = 0; (handlerFunction = handlerList[k]) !== undefined; k++) {
if (handlerFunction === handlerToDetach) {
handlerList = handlerList.splice(k, 1);
break;
}
}
}
return this;
};
return Component;
}();
Component.VERSION = "2.1.2";
return Component;
}();
/* eslint-disable no-new-func, no-nested-ternary */
var win;
if (typeof window === "undefined") {
// window is undefined in node.js
win = {};
} else {
win = window;
}
/*! Hammer.JS - v2.0.12-snapshot - 2018-10-29
* http://naver.github.io/egjs
*
* Forked By Naver egjs
* Copyright (c) hammerjs
* Licensed under the MIT license */
function _extends() {
_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;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
/**
* @private
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} target
* @param {...Object} objects_to_assign
* @returns {Object} target
*/
var assign;
if (typeof Object.assign !== 'function') {
assign = function assign(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
} else {
assign = Object.assign;
}
var assign$1 = assign;
var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = typeof document === "undefined" ? {
style: {}
} : document.createElement('div');
var TYPE_FUNCTION = 'function';
var round = Math.round,
abs = Math.abs;
var now = Date.now;
/**
* @private
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix;
var prop;
var camelProp = property[0].toUpperCase() + property.slice(1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = prefix ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined;
}
/* eslint-disable no-new-func, no-nested-ternary */
var win$1;
if (typeof window === "undefined") {
// window is undefined in node.js
win$1 = {};
} else {
win$1 = window;
}
var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
function getTouchActionProps() {
if (!NATIVE_TOUCH_ACTION) {
return false;
}
var touchMap = {};
var cssSupports = win$1.CSS && win$1.CSS.supports;
['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function (val) {
// If css.supports is not supported but there is native touch-action assume it supports
// all values. This is the case for IE 10 and 11.
return touchMap[val] = cssSupports ? win$1.CSS.supports('touch-action', val) : true;
});
return touchMap;
}
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
var TOUCH_ACTION_MAP = getTouchActionProps();
var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
var SUPPORT_TOUCH = 'ontouchstart' in win$1;
var SUPPORT_POINTER_EVENTS = prefixed(win$1, 'PointerEvent') !== undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';
var COMPUTE_INTERVAL = 25;
var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;
var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;
var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];
/**
* @private
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
}
/**
* @private
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val === TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
}
/**
* @private
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return str.indexOf(find) > -1;
}
/**
* @private
* when the touchActions are collected they are not a valid value, so we need to clean things up. *
* @param {String} actions
* @returns {*}
*/
function cleanTouchActions(actions) {
// none
if (inStr(actions, TOUCH_ACTION_NONE)) {
return TOUCH_ACTION_NONE;
}
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // if both pan-x and pan-y are set (different recognizers
// for different directions, e.g. horizontal pan but vertical swipe?)
// we need none (as otherwise with pan-x pan-y combined none of these
// recognizers will work, since the browser would handle all panning
if (hasPanX && hasPanY) {
return TOUCH_ACTION_NONE;
} // pan-x OR pan-y
if (hasPanX || hasPanY) {
return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
} // manipulation
if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
return TOUCH_ACTION_MANIPULATION;
}
return TOUCH_ACTION_AUTO;
}
/**
* @private
* Touch Action
* sets the touchAction property or uses the js alternative
* @param {Manager} manager
* @param {String} value
* @constructor
*/
var TouchAction =
/*#__PURE__*/
function () {
function TouchAction(manager, value) {
this.manager = manager;
this.set(value);
}
/**
* @private
* set the touchAction value on the element or enable the polyfill
* @param {String} value
*/
var _proto = TouchAction.prototype;
_proto.set = function set(value) {
// find out the touch-action by the event handlers
if (value === TOUCH_ACTION_COMPUTE) {
value = this.compute();
}
if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
}
this.actions = value.toLowerCase().trim();
};
/**
* @private
* just re-set the touchAction value
*/
_proto.update = function update() {
this.set(this.manager.options.touchAction);
};
/**
* @private
* compute the value for the touchAction property based on the recognizer's settings
* @returns {String} value
*/
_proto.compute = function compute() {
var actions = [];
each(this.manager.recognizers, function (recognizer) {
if (boolOrFn(recognizer.options.enable, [recognizer])) {
actions = actions.concat(recognizer.getTouchAction());
}
});
return cleanTouchActions(actions.join(' '));
};
/**
* @private
* this method is called on each input cycle and provides the preventing of the browser behavior
* @param {Object} input
*/
_proto.preventDefaults = function preventDefaults(input) {
var srcEvent = input.srcEvent;
var direction = input.offsetDirection; // if the touch action did prevented once this session
if (this.manager.session.prevented) {
srcEvent.preventDefault();
return;
}
var actions = this.actions;
var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
if (hasNone) {
// do not prevent defaults if this is a tap gesture
var isTapPointer = input.pointers.length === 1;
var isTapMovement = input.distance < 2;
var isTapTouchTime = input.deltaTime < 250;
if (isTapPointer && isTapMovement && isTapTouchTime) {
return;
}
}
if (hasPanX && hasPanY) {
// `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
return;
}
if (hasNone || hasPanY && direction & DIRECTION_HORIZONTAL || hasPanX && direction & DIRECTION_VERTICAL) {
return this.preventSrc(srcEvent);
}
};
/**
* @private
* call preventDefault to prevent the browser's default behavior (scrolling in most cases)
* @param {Object} srcEvent
*/
_proto.preventSrc = function preventSrc(srcEvent) {
this.manager.session.prevented = true;
srcEvent.preventDefault();
};
return TouchAction;
}();
/**
* @private
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* @private
* get the center of all the pointers
* @param {Array} pointers
* @return {Object} center contains `x` and `y` properties
*/
function getCenter(pointers) {
var pointersLength = pointers.length; // no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0;
var y = 0;
var i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
/**
* @private
* create a simple clone from the input used for storage of firstInput and firstMultiple
* @param {Object} input
* @returns {Object} clonedInputData
*/
function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
}
/**
* @private
* calculate the absolute distance between two points
* @param {Object} p1 {x, y}
* @param {Object} p2 {x, y}
* @param {Array} [props] containing x and y keys
* @return {Number} distance
*/
function getDistance(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]];
var y = p2[props[1]] - p1[props[1]];
return Math.sqrt(x * x + y * y);
}
/**
* @private
* calculate the angle between two coordinates
* @param {Object} p1
* @param {Object} p2
* @param {Array} [props] containing x and y keys
* @return {Number} angle
*/
function getAngle(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]];
var y = p2[props[1]] - p1[props[1]];
return Math.atan2(y, x) * 180 / Math.PI;
}
/**
* @private
* get the direction between two points
* @param {Number} x
* @param {Number} y
* @return {Number} direction
*/
function getDirection(x, y) {
if (x === y) {
return DIRECTION_NONE;
}
if (abs(x) >= abs(y)) {
return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
}
function computeDeltaXY(session, input) {
var center = input.center; // let { offsetDelta:offset = {}, prevDelta = {}, prevInput = {} } = session;
// jscs throwing error on defalut destructured values and without defaults tests fail
var offset = session.offsetDelta || {};
var prevDelta = session.prevDelta || {};
var prevInput = session.prevInput || {};
if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
prevDelta = session.prevDelta = {
x: prevInput.deltaX || 0,
y: prevInput.deltaY || 0
};
offset = session.offsetDelta = {
x: center.x,
y: center.y
};
}
input.deltaX = prevDelta.x + (center.x - offset.x);
input.deltaY = prevDelta.y + (center.y - offset.y);
}
/**
* @private
* calculate the velocity between two points. unit is in px per ms.
* @param {Number} deltaTime
* @param {Number} x
* @param {Number} y
* @return {Object} velocity `x` and `y`
*/
function getVelocity(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
/**
* @private
* calculate the scale factor between two pointersets
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} scale
*/
function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}
/**
* @private
* calculate the rotation degrees between two pointersets
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} rotation
*/
function getRotation(start, end) {
return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
}
/**
* @private
* velocity is calculated every x ms
* @param {Object} session
* @param {Object} input
*/
function computeIntervalInputData(session, input) {
var last = session.lastInterval || input;
var deltaTime = input.timeStamp - last.timeStamp;
var velocity;
var velocityX;
var velocityY;
var direction;
if (input.eventType !== INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
var deltaX = input.deltaX - last.deltaX;
var deltaY = input.deltaY - last.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = abs(v.x) > abs(v.y) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
}
/**
* @private
* extend the data with some usable properties like scale, rotate, velocity etc
* @param {Object} manager
* @param {Object} input
*/
function computeInputData(manager, input) {
var session = manager.session;
var pointers = input.pointers;
var pointersLength = pointers.length; // store the first input to calculate the distance and direction
if (!session.firstInput) {
session.firstInput = simpleCloneInputData(input);
} // to compute scale and rotation we need to store the multiple touches
if (pointersLength > 1 && !session.firstMultiple) {
session.firstMultiple = simpleCloneInputData(input);
} else if (pointersLength === 1) {
session.firstMultiple = false;
}
var firstInput = session.firstInput,
firstMultiple = session.firstMultiple;
var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
var center = input.center = getCenter(pointers);
input.timeStamp = now();
input.deltaTime = input.timeStamp - firstInput.timeStamp;
input.angle = getAngle(offsetCenter, center);
input.distance = getDistance(offsetCenter, center);
computeDeltaXY(session, input);
input.offsetDirection = getDirection(input.deltaX, input.deltaY);
var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
input.overallVelocityX = overallVelocity.x;
input.overallVelocityY = overallVelocity.y;
input.overallVelocity = abs(overallVelocity.x) > abs(overallVelocity.y) ? overallVelocity.x : overallVelocity.y;
input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
input.maxPointers = !session.prevInput ? input.pointers.length : input.pointers.length > session.prevInput.maxPointers ? input.pointers.length : session.prevInput.maxPointers;
computeIntervalInputData(session, input); // find the correct target
var target = manager.element;
if (hasParent(input.srcEvent.target, target)) {
target = input.srcEvent.target;
}
input.target = target;
}
/**
* @private
* handle input events
* @param {Manager} manager
* @param {String} eventType
* @param {Object} input
*/
function inputHandler(manager, eventType, input) {
var pointersLen = input.pointers.length;
var changedPointersLen = input.changedPointers.length;
var isFirst = eventType & INPUT_START && pointersLen - changedPointersLen === 0;
var isFinal = eventType & (INPUT_END | INPUT_CANCEL) && pointersLen - changedPointersLen === 0;
input.isFirst = !!isFirst;
input.isFinal = !!isFinal;
if (isFirst) {
manager.session = {};
} // source event is the normalized value of the domEvents
// like 'touchstart, mouseup, pointerdown'
input.eventType = eventType; // compute scale, rotation etc
computeInputData(manager, input); // emit secret event
manager.emit('hammer.input', input);
manager.recognize(input);
manager.session.prevInput = input;
}
/**
* @private
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return str.trim().split(/\s+/g);
}
/**
* @private
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function (type) {
target.addEventListener(type, handler, false);
});
}
/**
* @private
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function (type) {
target.removeEventListener(type, handler, false);
});
}
/**
* @private
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = element.ownerDocument || element;
return doc.defaultView || doc.parentWindow || window;
}
/**
* @private
* create new input type manager
* @param {Manager} manager
* @param {Function} callback
* @returns {Input}
* @constructor
*/
var Input =
/*#__PURE__*/
function () {
function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function (ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
}
/**
* @private
* should handle the inputEvent data and trigger the callback
* @virtual
*/
var _proto = Input.prototype;
_proto.handler = function handler() {};
/**
* @private
* bind the events
*/
_proto.init = function init() {
this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
};
/**
* @private
* unbind the events
*/
_proto.destroy = function destroy() {
this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
};
return Input;
}();
/**
* @private
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if (findByKey && src[i][findByKey] == find || !findByKey && src[i] === find) {
// do not use === here, test fails
return i;
}
i++;
}
return -1;
}
}
var POINTER_INPUT_MAP = {
pointerdown: INPUT_START,
pointermove: INPUT_MOVE,
pointerup: INPUT_END,
pointercancel: INPUT_CANCEL,
pointerout: INPUT_CANCEL
}; // in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
2: INPUT_TYPE_TOUCH,
3: INPUT_TYPE_PEN,
4: INPUT_TYPE_MOUSE,
5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};
var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive
if (win$1.MSPointerEvent && !win$1.PointerEvent) {
POINTER_ELEMENT_EVENTS = 'MSPointerDown';
POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}
/**
* @private
* Pointer events input
* @constructor
* @extends Input
*/
var PointerEventInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(PointerEventInput, _Input);
function PointerEventInput() {
var _this;
var proto = PointerEventInput.prototype;
proto.evEl = POINTER_ELEMENT_EVENTS;
proto.evWin = POINTER_WINDOW_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.store = _this.manager.session.pointerEvents = [];
return _this;
}
/**
* @private
* handle mouse events
* @param {Object} ev
*/
var _proto = PointerEventInput.prototype;
_proto.handler = function handler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
var isTouch = pointerType === INPUT_TYPE_TOUCH; // get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId'); // start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
} // it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
} // update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
};
return PointerEventInput;
}(Input);
/**
* @private
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray(obj) {
return Array.prototype.slice.call(obj, 0);
}
/**
* @private
* unique array with objects based on a key (like 'id') or just by the array's value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
while (i < src.length) {
var val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort(function (a, b) {
return a[key] > b[key];
});
}
}
return results;
}
var TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* @private
* Multi-user touch events input
* @constructor
* @extends Input
*/
var TouchInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(TouchInput, _Input);
function TouchInput() {
TouchInput.prototype.evTarget = TOUCH_TARGET_EVENTS;
TouchInput.prototype.targetIds = {};
return _Input.apply(this, arguments) || this; // this.evTarget = TOUCH_TARGET_EVENTS;
// this.targetIds = {};
}
var _proto = TouchInput.prototype;
_proto.handler = function handler(ev) {
var type = TOUCH_INPUT_MAP[ev.type];
var touches = getTouches.call(this, ev, type);
if (!touches) {
return;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
};
return TouchInput;
}(Input);
function getTouches(ev, type) {
var allTouches = toArray(ev.touches);
var targetIds = this.targetIds; // when there is only one touch, the process can be simplified
if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
targetIds[allTouches[0].identifier] = true;
return [allTouches, allTouches];
}
var i;
var targetTouches;
var changedTouches = toArray(ev.changedTouches);
var changedTargetTouches = [];
var target = this.target; // get target touches from touches
targetTouches = allTouches.filter(function (touch) {
return hasParent(touch.target, target);
}); // collect touches
if (type === INPUT_START) {
i = 0;
while (i < targetTouches.length) {
targetIds[targetTouches[i].identifier] = true;
i++;
}
} // filter changed touches to only contain touches that exist in the collected target ids
i = 0;
while (i < changedTouches.length) {
if (targetIds[changedTouches[i].identifier]) {
changedTargetTouches.push(changedTouches[i]);
} // cleanup removed touches
if (type & (INPUT_END | INPUT_CANCEL)) {
delete targetIds[changedTouches[i].identifier];
}
i++;
}
if (!changedTargetTouches.length) {
return;
}
return [// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches];
}
var MOUSE_INPUT_MAP = {
mousedown: INPUT_START,
mousemove: INPUT_MOVE,
mouseup: INPUT_END
};
var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
/**
* @private
* Mouse events input
* @constructor
* @extends Input
*/
var MouseInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(MouseInput, _Input);
function MouseInput() {
var _this;
var proto = MouseInput.prototype;
proto.evEl = MOUSE_ELEMENT_EVENTS;
proto.evWin = MOUSE_WINDOW_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.pressed = false; // mousedown state
return _this;
}
/**
* @private
* handle mouse events
* @param {Object} ev
*/
var _proto = MouseInput.prototype;
_proto.handler = function handler(ev) {
var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down
if (eventType & INPUT_START && ev.button === 0) {
this.pressed = true;
}
if (eventType & INPUT_MOVE && ev.which !== 1) {
eventType = INPUT_END;
} // mouse must be down
if (!this.pressed) {
return;
}
if (eventType & INPUT_END) {
this.pressed = false;
}
this.callback(this.manager, eventType, {
pointers: [ev],
changedPointers: [ev],
pointerType: INPUT_TYPE_MOUSE,
srcEvent: ev
});
};
return MouseInput;
}(Input);
/**
* @private
* Combined touch and mouse input
*
* Touch has a higher priority then mouse, and while touching no mouse events are allowed.
* This because touch devices also emit mouse events while doing a touch.
*
* @constructor
* @extends Input
*/
var DEDUP_TIMEOUT = 2500;
var DEDUP_DISTANCE = 25;
function setLastTouch(eventData) {
var _eventData$changedPoi = eventData.changedPointers,
touch = _eventData$changedPoi[0];
if (touch.identifier === this.primaryTouch) {
var lastTouch = {
x: touch.clientX,
y: touch.clientY
};
var lts = this.lastTouches;
this.lastTouches.push(lastTouch);
var removeLastTouch = function removeLastTouch() {
var i = lts.indexOf(lastTouch);
if (i > -1) {
lts.splice(i, 1);
}
};
setTimeout(removeLastTouch, DEDUP_TIMEOUT);
}
}
function recordTouches(eventType, eventData) {
if (eventType & INPUT_START) {
this.primaryTouch = eventData.changedPointers[0].identifier;
setLastTouch.call(this, eventData);
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
setLastTouch.call(this, eventData);
}
}
function isSyntheticEvent(eventData) {
var x = eventData.srcEvent.clientX;
var y = eventData.srcEvent.clientY;
for (var i = 0; i < this.lastTouches.length; i++) {
var t = this.lastTouches[i];
var dx = Math.abs(x - t.x);
var dy = Math.abs(y - t.y);
if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
return true;
}
}
return false;
}
var TouchMouseInput =
/*#__PURE__*/
function () {
var TouchMouseInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(TouchMouseInput, _Input);
function TouchMouseInput(_manager, callback) {
var _this;
_this = _Input.call(this, _manager, callback) || this;
_this.handler = function (manager, inputEvent, inputData) {
var isTouch = inputData.pointerType === INPUT_TYPE_TOUCH;
var isMouse = inputData.pointerType === INPUT_TYPE_MOUSE;
if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
return;
} // when we're in a touch event, record touches to de-dupe synthetic mouse event
if (isTouch) {
recordTouches.call(_assertThisInitialized(_assertThisInitialized(_this)), inputEvent, inputData);
} else if (isMouse && isSyntheticEvent.call(_assertThisInitialized(_assertThisInitialized(_this)), inputData)) {
return;
}
_this.callback(manager, inputEvent, inputData);
};
_this.touch = new TouchInput(_this.manager, _this.handler);
_this.mouse = new MouseInput(_this.manager, _this.handler);
_this.primaryTouch = null;
_this.lastTouches = [];
return _this;
}
/**
* @private
* handle mouse and touch events
* @param {Hammer} manager
* @param {String} inputEvent
* @param {Object} inputData
*/
var _proto = TouchMouseInput.prototype;
/**
* @private
* remove the event listeners
*/
_proto.destroy = function destroy() {
this.touch.destroy();
this.mouse.destroy();
};
return TouchMouseInput;
}(Input);
return TouchMouseInput;
}();
/**
* @private
* create new input type manager
* called by the Manager constructor
* @param {Hammer} manager
* @returns {Input}
*/
function createInputInstance(manager) {
var Type; // let inputClass = manager.options.inputClass;
var inputClass = manager.options.inputClass;
if (inputClass) {
Type = inputClass;
} else if (SUPPORT_POINTER_EVENTS) {
Type = PointerEventInput;
} else if (SUPPORT_ONLY_TOUCH) {
Type = TouchInput;
} else if (!SUPPORT_TOUCH) {
Type = MouseInput;
} else {
Type = TouchMouseInput;
}
return new Type(manager, inputHandler);
}
/**
* @private
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if (Array.isArray(arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;
/**
* @private
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* @private
* get a recognizer by name if it is bound to a manager
* @param {Recognizer|String} otherRecognizer
* @param {Recognizer} recognizer
* @returns {Recognizer}
*/
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = recognizer.manager;
if (manager) {
return manager.get(otherRecognizer);
}
return otherRecognizer;
}
/**
* @private
* get a usable string, used as event postfix
* @param {constant} state
* @returns {String} state
*/
function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
}
/**
* @private
* Recognizer flow explained; *
* All recognizers have the initial state of POSSIBLE when a input session starts.
* The definition of a input session is from the first input until the last input, with all it's movement in it. *
* Example session for mouse-input: mousedown -> mousemove -> mouseup
*
* On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
* which determines with state it should be.
*
* If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
* POSSIBLE to give it another change on the next cycle.
*
* Possible
* |
* +-----+---------------+
* | |
* +-----+-----+ |
* | | |
* Failed Cancelled |
* +-------+------+
* | |
* Recognized Began
* |
* Changed
* |
* Ended/Recognized
*/
/**
* @private
* Recognizer
* Every recognizer needs to extend from this class.
* @constructor
* @param {Object} options
*/
var Recognizer =
/*#__PURE__*/
function () {
function Recognizer(options) {
if (options === void 0) {
options = {};
}
this.options = _extends({
enable: true
}, options);
this.id = uniqueId();
this.manager = null; // default is enable true
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
}
/**
* @private
* set options
* @param {Object} options
* @return {Recognizer}
*/
var _proto = Recognizer.prototype;
_proto.set = function set(options) {
assign$1(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state
this.manager && this.manager.touchAction.update();
return this;
};
/**
* @private
* recognize simultaneous with an other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.recognizeWith = function recognizeWith(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
};
/**
* @private
* drop the simultaneous link. it doesnt remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.dropRecognizeWith = function dropRecognizeWith(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
delete this.simultaneous[otherRecognizer.id];
return this;
};
/**
* @private
* recognizer can only run when an other is failing
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.requireFailure = function requireFailure(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
return this;
}
var requireFail = this.requireFail;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (inArray(requireFail, otherRecognizer) === -1) {
requireFail.push(otherRecognizer);
otherRecognizer.requireFailure(this);
}
return this;
};
/**
* @private
* drop the requireFailure link. it does not remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.dropRequireFailure = function dropRequireFailure(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
var index = inArray(this.requireFail, otherRecognizer);
if (index > -1) {
this.requireFail.splice(index, 1);
}
return this;
};
/**
* @private
* has require failures boolean
* @returns {boolean}
*/
_proto.hasRequireFailures = function hasRequireFailures() {
return this.requireFail.length > 0;
};
/**
* @private
* if the recognizer can recognize simultaneous with an other recognizer
* @param {Recognizer} otherRecognizer
* @returns {Boolean}
*/
_proto.canRecognizeWith = function canRecognizeWith(otherRecognizer) {
return !!this.simultaneous[otherRecognizer.id];
};
/**
* @private
* You should use `tryEmit` instead of `emit` directly to check
* that all the needed recognizers has failed before emitting.
* @param {Object} input
*/
_proto.emit = function emit(input) {
var self = this;
var state = this.state;
function emit(event) {
self.manager.emit(event, input);
} // 'panstart' and 'panmove'
if (state < STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
emit(self.options.event); // simple 'eventName' events
if (input.additionalEvent) {
// additional event(panleft, panright, pinchin, pinchout...)
emit(input.additionalEvent);
} // panend and pancancel
if (state >= STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
};
/**
* @private
* Check that all the require failure recognizers has failed,
* if true, it emits a gesture event,
* otherwise, setup the state to FAILED.
* @param {Object} input
*/
_proto.tryEmit = function tryEmit(input) {
if (this.canEmit()) {
return this.emit(input);
} // it's failing anyway
this.state = STATE_FAILED;
};
/**
* @private
* can we emit?
* @returns {boolean}
*/
_proto.canEmit = function canEmit() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
};
/**
* @private
* update the recognizer
* @param {Object} inputData
*/
_proto.recognize = function recognize(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign$1({}, inputData); // is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
} // reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone); // the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
};
/**
* @private
* return the state of the recognizer
* the actual recognizing happens in this method
* @virtual
* @param {Object} inputData
* @returns {constant} STATE
*/
/* jshint ignore:start */
_proto.process = function process(inputData) {};
/* jshint ignore:end */
/**
* @private
* return the preferred touch-action
* @virtual
* @returns {Array}
*/
_proto.getTouchAction = function getTouchAction() {};
/**
* @private
* called when the gesture isn't allowed to recognize
* like when another is being recognized or it is disabled
* @virtual
*/
_proto.reset = function reset() {};
return Recognizer;
}();
var defaults = {
/**
* @private
* set if DOM events are being triggered.
* But this is slower and unused by simple implementations, so disabled by default.
* @type {Boolean}
* @default false
*/
domEvents: false,
/**
* @private
* The value for the touchAction property/fallback.
* When set to `compute` it will magically set the correct value based on the added recognizers.
* @type {String}
* @default compute
*/
touchAction: TOUCH_ACTION_COMPUTE,
/**
* @private
* @type {Boolean}
* @default true
*/
enable: true,
/**
* @private
* EXPERIMENTAL FEATURE -- can be removed/changed
* Change the parent input target element.
* If Null, then it is being set the to main element.
* @type {Null|EventTarget}
* @default null
*/
inputTarget: null,
/**
* @private
* force an input class
* @type {Null|Function}
* @default null
*/
inputClass: null,
/**
* @private
* Default recognizer setup when calling `Hammer()`
* When creating a new Manager these will be skipped.
* @type {Array}
*/
preset: [],
/**
* @private
* Some CSS properties can be used to improve the working of Hammer.
* Add them to this method and they will be set when creating a new Manager.
* @namespace
*/
cssProps: {
/**
* @private
* Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userSelect: "none",
/**
* @private
* Disable the Windows Phone grippers when pressing an element.
* @type {String}
* @default 'none'
*/
touchSelect: "none",
/**
* @private
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari displays
* a callout containing information about the link. This property allows you to disable that callout.
* @type {String}
* @default 'none'
*/
touchCallout: "none",
/**
* @private
* Specifies whether zooming is enabled. Used by IE10>
* @type {String}
* @default 'none'
*/
contentZooming: "none",
/**
* @private
* Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userDrag: "none",
/**
* @private
* Overrides the highlight color shown when the user taps a link or a JavaScript
* clickable element in iOS. This property obeys the alpha value, if specified.
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: "rgba(0,0,0,0)"
}
};
var STOP = 1;
var FORCED_STOP = 2;
/**
* @private
* add/remove the css properties as defined in manager.options.cssProps
* @param {Manager} manager
* @param {Boolean} add
*/
function toggleCssProps(manager, add) {
var element = manager.element;
if (!element.style) {
return;
}
var prop;
each(manager.options.cssProps, function (value, name) {
prop = prefixed(element.style, name);
if (add) {
manager.oldCssProps[prop] = element.style[prop];
element.style[prop] = value;
} else {
element.style[prop] = manager.oldCssProps[prop] || "";
}
});
if (!add) {
manager.oldCssProps = {};
}
}
/**
* @private
* trigger dom event
* @param {String} event
* @param {Object} data
*/
function triggerDomEvent(event, data) {
var gestureEvent = document.createEvent("Event");
gestureEvent.initEvent(event, true, true);
gestureEvent.gesture = data;
data.target.dispatchEvent(gestureEvent);
}
/**
* @private
* Manager
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
var Manager =
/*#__PURE__*/
function () {
function Manager(element, options) {
var _this = this;
this.options = assign$1({}, defaults, options || {});
this.options.inputTarget = this.options.inputTarget || element;
this.handlers = {};
this.session = {};
this.recognizers = [];
this.oldCssProps = {};
this.element = element;
this.input = createInputInstance(this);
this.touchAction = new TouchAction(this, this.options.touchAction);
toggleCssProps(this, true);
each(this.options.recognizers, function (item) {
var recognizer = _this.add(new item[0](item[1]));
item[2] && recognizer.recognizeWith(item[2]);
item[3] && recognizer.requireFailure(item[3]);
}, this);
}
/**
* @private
* set options
* @param {Object} options
* @returns {Manager}
*/
var _proto = Manager.prototype;
_proto.set = function set(options) {
assign$1(this.options, options); // Options that need a little more setup
if (options.touchAction) {
this.touchAction.update();
}
if (options.inputTarget) {
// Clean up existing event listeners and reinitialize
this.input.destroy();
this.input.target = options.inputTarget;
this.input.init();
}
return this;
};
/**
* @private
* stop recognizing for this session.
* This session will be discarded, when a new [input]start event is fired.
* When forced, the recognizer cycle is stopped immediately.
* @param {Boolean} [force]
*/
_proto.stop = function stop(force) {
this.session.stopped = force ? FORCED_STOP : STOP;
};
/**
* @private
* run the recognizers!
* called by the inputHandler function on every movement of the pointers (touches)
* it walks through all the recognizers and tries to detect the gesture that is being made
* @param {Object} inputData
*/
_proto.recognize = function recognize(inputData) {
var session = this.session;
if (session.stopped) {
return;
} // run the touch-action polyfill
this.touchAction.preventDefaults(inputData);
var recognizer;
var recognizers = this.recognizers; // this holds the recognizer that is being recognized.
// so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
// if no recognizer is detecting a thing, it is set to `null`
var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized
// or when we're in a new session
if (!curRecognizer || curRecognizer && curRecognizer.state & STATE_RECOGNIZED) {
session.curRecognizer = null;
curRecognizer = null;
}
var i = 0;
while (i < recognizers.length) {
recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one.
// 1. allow if the session is NOT forced stopped (see the .stop() method)
// 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
// that is being recognized.
// 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
// this can be setup with the `recognizeWith()` method on the recognizer.
if (session.stopped !== FORCED_STOP && ( // 1
!curRecognizer || recognizer === curRecognizer || // 2
recognizer.canRecognizeWith(curRecognizer))) {
// 3
recognizer.recognize(inputData);
} else {
recognizer.reset();
} // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
// current active recognizer. but only if we don't already have an active recognizer
if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
session.curRecognizer = recognizer;
curRecognizer = recognizer;
}
i++;
}
};
/**
* @private
* get a recognizer by its event name.
* @param {Recognizer|String} recognizer
* @returns {Recognizer|Null}
*/
_proto.get = function get(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
var recognizers = this.recognizers;
for (var i = 0; i < recognizers.length; i++) {
if (recognizers[i].options.event === recognizer) {
return recognizers[i];
}
}
return null;
};
/**
* @private add a recognizer to the manager
* existing recognizers with the same event name will be removed
* @param {Recognizer} recognizer
* @returns {Recognizer|Manager}
*/
_proto.add = function add(recognizer) {
if (invokeArrayArg(recognizer, "add", this)) {
return this;
} // remove existing
var existing = this.get(recognizer.options.event);
if (existing) {
this.remove(existing);
}
this.recognizers.push(recognizer);
recognizer.manager = this;
this.touchAction.update();
return recognizer;
};
/**
* @private
* remove a recognizer by name or instance
* @param {Recognizer|String} recognizer
* @returns {Manager}
*/
_proto.remove = function remove(recognizer) {
if (invokeArrayArg(recognizer, "remove", this)) {
return this;
}
var targetRecognizer = this.get(recognizer); // let's make sure this recognizer exists
if (recognizer) {
var recognizers = this.recognizers;
var index = inArray(recognizers, targetRecognizer);
if (index !== -1) {
recognizers.splice(index, 1);
this.touchAction.update();
}
}
return this;
};
/**
* @private
* bind event
* @param {String} events
* @param {Function} handler
* @returns {EventEmitter} this
*/
_proto.on = function on(events, handler) {
if (events === undefined || handler === undefined) {
return this;
}
var handlers = this.handlers;
each(splitStr(events), function (event) {
handlers[event] = handlers[event] || [];
handlers[event].push(handler);
});
return this;
};
/**
* @private unbind event, leave emit blank to remove all handlers
* @param {String} events
* @param {Function} [handler]
* @returns {EventEmitter} this
*/
_proto.off = function off(events, handler) {
if (events === undefined) {
return this;
}
var handlers = this.handlers;
each(splitStr(events), function (event) {
if (!handler) {
delete handlers[event];
} else {
handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
}
});
return this;
};
/**
* @private emit event to the listeners
* @param {String} event
* @param {Object} data
*/
_proto.emit = function emit(event, data) {
// we also want to trigger dom events
if (this.options.domEvents) {
triggerDomEvent(event, data);
} // no handlers, so skip it all
var handlers = this.handlers[event] && this.handlers[event].slice();
if (!handlers || !handlers.length) {
return;
}
data.type = event;
data.preventDefault = function () {
data.srcEvent.preventDefault();
};
var i = 0;
while (i < handlers.length) {
handlers[i](data);
i++;
}
};
/**
* @private
* destroy the manager and unbinds all events
* it doesn't unbind dom events, that is the user own responsibility
*/
_proto.destroy = function destroy() {
this.element && toggleCssProps(this, false);
this.handlers = {};
this.session = {};
this.input.destroy();
this.element = null;
};
return Manager;
}();
var SINGLE_TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* @private
* Touch events input
* @constructor
* @extends Input
*/
var SingleTouchInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(SingleTouchInput, _Input);
function SingleTouchInput() {
var _this;
var proto = SingleTouchInput.prototype;
proto.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
proto.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.started = false;
return _this;
}
var _proto = SingleTouchInput.prototype;
_proto.handler = function handler(ev) {
var type = SINGLE_TOUCH_INPUT_MAP[ev.type]; // should we handle the touch events?
if (type === INPUT_START) {
this.started = true;
}
if (!this.started) {
return;
}
var touches = normalizeSingleTouches.call(this, ev, type); // when done, reset the started state
if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
this.started = false;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
};
return SingleTouchInput;
}(Input);
function normalizeSingleTouches(ev, type) {
var all = toArray(ev.touches);
var changed = toArray(ev.changedTouches);
if (type & (INPUT_END | INPUT_CANCEL)) {
all = uniqueArray(all.concat(changed), 'identifier', true);
}
return [all, changed];
}
/**
* @private
* This recognizer is just used as a base for the simple attribute recognizers.
* @constructor
* @extends Recognizer
*/
var AttrRecognizer =
/*#__PURE__*/
function (_Recognizer) {
_inheritsLoose(AttrRecognizer, _Recognizer);
function AttrRecognizer(options) {
if (options === void 0) {
options = {};
}
return _Recognizer.call(this, _extends({
pointers: 1
}, options)) || this;
}
/**
* @private
* Used to check if it the recognizer receives valid input, like input.distance > 10.
* @memberof AttrRecognizer
* @param {Object} input
* @returns {Boolean} recognized
*/
var _proto = AttrRecognizer.prototype;
_proto.attrTest = function attrTest(input) {
var optionPointers = this.options.pointers;
return optionPointers === 0 || input.pointers.length === optionPointers;
};
/**
* @private
* Process the input and return the state for the recognizer
* @memberof AttrRecognizer
* @param {Object} input
* @returns {*} State
*/
_proto.process = function process(input) {
var state = this.state;
var eventType = input.eventType;
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED
if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
return state | STATE_CANCELLED;
} else if (isRecognized || isValid) {
if (eventType & INPUT_END) {
return state | STATE_ENDED;
} else if (!(state & STATE_BEGAN)) {
return STATE_BEGAN;
}
return state | STATE_CHANGED;
}
return STATE_FAILED;
};
return AttrRecognizer;
}(Recognizer);
/**
* @private
* A tap is recognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
* between the given interval and position. The delay option can be used to recognize multi-taps without firing
* a single tap.
*
* The eventData from the emitted event contains the property `tapCount`, which contains the amount of
* multi-taps being recognized.
* @constructor
* @extends Recognizer
*/
var TapRecognizer =
/*#__PURE__*/
function (_Recognizer) {
_inheritsLoose(TapRecognizer, _Recognizer);
function TapRecognizer(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _Recognizer.call(this, _extends({
event: 'tap',
pointers: 1,
taps: 1,
interval: 300,
// max time between the multi-tap taps
time: 250,
// max time of the pointer to be down (like finger on the screen)
threshold: 9,
// a minimal movement is ok, but keep it low
posThreshold: 10
}, options)) || this; // previous time and center,
// used for tap counting
_this.pTime = false;
_this.pCenter = false;
_this._timer = null;
_this._input = null;
_this.count = 0;
return _this;
}
var _proto = TapRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return [TOUCH_ACTION_MANIPULATION];
};
_proto.process = function process(input) {
var _this2 = this;
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTouchTime = input.deltaTime < options.time;
this.reset();
if (input.eventType & INPUT_START && this.count === 0) {
return this.failTimeout();
} // we only allow little movement
// and we've reached an end event, so a tap is possible
if (validMovement && validTouchTime && validPointers) {
if (input.eventType !== INPUT_END) {
return this.failTimeout();
}
var validInterval = this.pTime ? input.timeStamp - this.pTime < options.interval : true;
var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;
this.pTime = input.timeStamp;
this.pCenter = input.center;
if (!validMultiTap || !validInterval) {
this.count = 1;
} else {
this.count += 1;
}
this._input = input; // if tap count matches we have recognized it,
// else it has began recognizing...
var tapCount = this.count % options.taps;
if (tapCount === 0) {
// no failing requirements, immediately trigger the tap event
// or wait as long as the multitap interval to trigger
if (!this.hasRequireFailures()) {
return STATE_RECOGNIZED;
} else {
this._timer = setTimeout(function () {
_this2.state = STATE_RECOGNIZED;
_this2.tryEmit();
}, options.interval);
return STATE_BEGAN;
}
}
}
return STATE_FAILED;
};
_proto.failTimeout = function failTimeout() {
var _this3 = this;
this._timer = setTimeout(function () {
_this3.state = STATE_FAILED;
}, this.options.interval);
return STATE_FAILED;
};
_proto.reset = function reset() {
clearTimeout(this._timer);
};
_proto.emit = function emit() {
if (this.state === STATE_RECOGNIZED) {
this._input.tapCount = this.count;
this.manager.emit(this.options.event, this._input);
}
};
return TapRecognizer;
}(Recognizer);
/**
* @private
* direction cons to string
* @param {constant} direction
* @returns {String}
*/
function directionStr(direction) {
if (direction === DIRECTION_DOWN) {
return 'down';
} else if (direction === DIRECTION_UP) {
return 'up';
} else if (direction === DIRECTION_LEFT) {
return 'left';
} else if (direction === DIRECTION_RIGHT) {
return 'right';
}
return '';
}
/**
* @private
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
var PanRecognizer =
/*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(PanRecognizer, _AttrRecognizer);
function PanRecognizer(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _AttrRecognizer.call(this, _extends({
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL
}, options)) || this;
_this.pX = null;
_this.pY = null;
return _this;
}
var _proto = PanRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
var direction = this.options.direction;
var actions = [];
if (direction & DIRECTION_HORIZONTAL) {
actions.push(TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
actions.push(TOUCH_ACTION_PAN_X);
}
return actions;
};
_proto.directionTest = function directionTest(input) {
var options = this.options;
var hasMoved = true;
var distance = input.distance;
var direction = input.direction;
var x = input.deltaX;
var y = input.deltaY; // lock to axis?
if (!(direction & options.direction)) {
if (options.direction & DIRECTION_HORIZONTAL) {
direction = x === 0 ? DIRECTION_NONE : x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
hasMoved = x !== this.pX;
distance = Math.abs(input.deltaX);
} else {
direction = y === 0 ? DIRECTION_NONE : y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
hasMoved = y !== this.pY;
distance = Math.abs(input.deltaY);
}
}
input.direction = direction;
return hasMoved && distance > options.threshold && direction & options.direction;
};
_proto.attrTest = function attrTest(input) {
return AttrRecognizer.prototype.attrTest.call(this, input) && ( // replace with a super call
this.state & STATE_BEGAN || !(this.state & STATE_BEGAN) && this.directionTest(input));
};
_proto.emit = function emit(input) {
this.pX = input.deltaX;
this.pY = input.deltaY;
var direction = directionStr(input.direction);
if (direction) {
input.additionalEvent = this.options.event + direction;
}
_AttrRecognizer.prototype.emit.call(this, input);
};
return PanRecognizer;
}(AttrRecognizer);
/**
* @private
* Swipe
* Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
var SwipeRecognizer =
/*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(SwipeRecognizer, _AttrRecognizer);
function SwipeRecognizer(options) {
if (options === void 0) {
options = {};
}
return _AttrRecognizer.call(this, _extends({
event: 'swipe',
threshold: 10,
velocity: 0.3,
direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
pointers: 1
}, options)) || this;
}
var _proto = SwipeRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return PanRecognizer.prototype.getTouchAction.call(this);
};
_proto.attrTest = function attrTest(input) {
var direction = this.options.direction;
var velocity;
if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
velocity = input.overallVelocity;
} else if (direction & DIRECTION_HORIZONTAL) {
velocity = input.overallVelocityX;
} else if (direction & DIRECTION_VERTICAL) {
velocity = input.overallVelocityY;
}
return _AttrRecognizer.prototype.attrTest.call(this, input) && direction & input.offsetDirection && input.distance > this.options.threshold && input.maxPointers === this.options.pointers && abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
};
_proto.emit = function emit(input) {
var direction = directionStr(input.offsetDirection);
if (direction) {
this.manager.emit(this.options.event + direction, input);
}
this.manager.emit(this.options.event, input);
};
return SwipeRecognizer;
}(AttrRecognizer);
/**
* @private
* Pinch
* Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
* @constructor
* @extends AttrRecognizer
*/
var PinchRecognizer =
/*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(PinchRecognizer, _AttrRecognizer);
function PinchRecognizer(options) {
if (options === void 0) {
options = {};
}
return _AttrRecognizer.call(this, _extends({
event: 'pinch',
threshold: 0,
pointers: 2
}, options)) || this;
}
var _proto = PinchRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return [TOUCH_ACTION_NONE];
};
_proto.attrTest = function attrTest(input) {
return _AttrRecognizer.prototype.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
};
_proto.emit = function emit(input) {
if (input.scale !== 1) {
var inOut = input.scale < 1 ? 'in' : 'out';
input.additionalEvent = this.options.event + inOut;
}
_AttrRecognizer.prototype.emit.call(this, input);
};
return PinchRecognizer;
}(AttrRecognizer);
/**
* @private
* Rotate
* Recognized when two or more pointer are moving in a circular motion.
* @constructor
* @extends AttrRecognizer
*/
var RotateRecognizer =
/*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(RotateRecognizer, _AttrRecognizer);
function RotateRecognizer(options) {
if (options === void 0) {
options = {};
}
return _AttrRecognizer.call(this, _extends({
event: 'rotate',
threshold: 0,
pointers: 2
}, options)) || this;
}
var _proto = RotateRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return [TOUCH_ACTION_NONE];
};
_proto.attrTest = function attrTest(input) {
return _AttrRecognizer.prototype.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
};
return RotateRecognizer;
}(AttrRecognizer);
/**
* @private
* Press
* Recognized when the pointer is down for x ms without any movement.
* @constructor
* @extends Recognizer
*/
var PressRecognizer =
/*#__PURE__*/
function (_Recognizer) {
_inheritsLoose(PressRecognizer, _Recognizer);
function PressRecognizer(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _Recognizer.call(this, _extends({
event: 'press',
pointers: 1,
time: 251,
// minimal time of the pointer to be pressed
threshold: 9
}, options)) || this;
_this._timer = null;
_this._input = null;
return _this;
}
var _proto = PressRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
return [TOUCH_ACTION_AUTO];
};
_proto.process = function process(input) {
var _this2 = this;
var options = this.options;
var validPointers = input.pointers.length === options.pointers;
var validMovement = input.distance < options.threshold;
var validTime = input.deltaTime > options.time;
this._input = input; // we only allow little movement
// and we've reached an end event, so a tap is possible
if (!validMovement || !validPointers || input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime) {
this.reset();
} else if (input.eventType & INPUT_START) {
this.reset();
this._timer = setTimeout(function () {
_this2.state = STATE_RECOGNIZED;
_this2.tryEmit();
}, options.time);
} else if (input.eventType & INPUT_END) {
return STATE_RECOGNIZED;
}
return STATE_FAILED;
};
_proto.reset = function reset() {
clearTimeout(this._timer);
};
_proto.emit = function emit(input) {
if (this.state !== STATE_RECOGNIZED) {
return;
}
if (input && input.eventType & INPUT_END) {
this.manager.emit(this.options.event + "up", input);
} else {
this._input.timeStamp = now();
this.manager.emit(this.options.event, this._input);
}
};
return PressRecognizer;
}(Recognizer);
// export const DIRECTION_NONE = 1;
var FIXED_DIGIT = 100000;
var TRANSFORM = function () {
if (typeof document === "undefined") {
return "";
}
var bodyStyle = (document.head || document.getElementsByTagName("head")[0]).style;
var target = ["transform", "webkitTransform", "msTransform", "mozTransform"];
for (var i = 0, len = target.length; i < len; i++) {
if (target[i] in bodyStyle) {
return target[i];
}
}
return "";
}();
function toArray$1(nodes) {
// const el = Array.prototype.slice.call(nodes);
// for IE8
var el = [];
for (var i = 0, len = nodes.length; i < len; i++) {
el.push(nodes[i]);
}
return el;
}
function $(param, multi) {
if (multi === void 0) {
multi = false;
}
var el;
if (typeof param === "string") {
// String (HTML, Selector)
// check if string is HTML tag format
var match = param.match(/^<([a-z]+)\s*([^>]*)>/); // creating element
if (match) {
// HTML
var dummy = document.createElement("div");
dummy.innerHTML = param;
el = toArray$1(dummy.childNodes);
} else {
// Selector
el = toArray$1(document.querySelectorAll(param));
}
if (!multi) {
el = el.length >= 1 ? el[0] : undefined;
}
} else if (param === win) {
// window
el = param;
} else if (param.nodeName && (param.nodeType === 1 || param.nodeType === 9)) {
// HTMLElement, Document
el = param;
} else if ("jQuery" in win && param instanceof jQuery || param.constructor.prototype.jquery) {
// jQuery
el = multi ? param.toArray() : param.get(0);
} else if (Array.isArray(param)) {
el = param.map(function (v) {
return $(v);
});
if (!multi) {
el = el.length >= 1 ? el[0] : undefined;
}
}
return el;
}
var raf = win.requestAnimationFrame || win.webkitRequestAnimationFrame;
var caf = win.cancelAnimationFrame || win.webkitCancelAnimationFrame;
if (raf && !caf) {
var keyInfo_1 = {};
var oldraf_1 = raf;
raf = function (callback) {
function wrapCallback(timestamp) {
if (keyInfo_1[key]) {
callback(timestamp);
}
}
var key = oldraf_1(wrapCallback);
keyInfo_1[key] = true;
return key;
};
caf = function (key) {
delete keyInfo_1[key];
};
} else if (!(raf && caf)) {
raf = function (callback) {
return win.setTimeout(function () {
callback(win.performance && win.performance.now && win.performance.now() || new Date().getTime());
}, 16);
};
caf = win.clearTimeout;
}
/**
* A polyfill for the window.requestAnimationFrame() method.
* @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
* @private
*/
function requestAnimationFrame(fp) {
return raf(fp);
}
/**
* A polyfill for the window.cancelAnimationFrame() method. It cancels an animation executed through a call to the requestAnimationFrame() method.
* @param {Number} key − The ID value returned through a call to the requestAnimationFrame() method. <ko>requestAnimationFrame() 메서드가 반환한 아이디 값</ko>
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
* @private
*/
function cancelAnimationFrame(key) {
caf(key);
}
function map(obj, callback) {
var tranformed = {};
for (var k in obj) {
k && (tranformed[k] = callback(obj[k], k));
}
return tranformed;
}
function filter(obj, callback) {
var filtered = {};
for (var k in obj) {
k && callback(obj[k], k) && (filtered[k] = obj[k]);
}
return filtered;
}
function every(obj, callback) {
for (var k in obj) {
if (k && !callback(obj[k], k)) {
return false;
}
}
return true;
}
function equal(target, base) {
return every(target, function (v, k) {
return v === base[k];
});
}
function toFixed(num) {
return Math.round(num * FIXED_DIGIT) / FIXED_DIGIT;
}
function getInsidePosition(destPos, range, circular, bounce) {
var toDestPos = destPos;
var targetRange = [circular[0] ? range[0] : bounce ? range[0] - bounce[0] : range[0], circular[1] ? range[1] : bounce ? range[1] + bounce[1] : range[1]];
toDestPos = Math.max(targetRange[0], toDestPos);
toDestPos = Math.min(targetRange[1], toDestPos);
return +toFixed(toDestPos);
} // determine outside
function isOutside(pos, range) {
return pos < range[0] || pos > range[1];
}
function getDuration(distance, deceleration) {
var duration = Math.sqrt(distance / deceleration * 2); // when duration is under 100, then value is zero
return duration < 100 ? 0 : duration;
}
function isCircularable(destPos, range, circular) {
return circular[1] && destPos > range[1] || circular[0] && destPos < range[0];
}
function getCirculatedPos(pos, range, circular) {
var toPos = pos;
var min = range[0];
var max = range[1];
var length = max - min;
if (circular[1] && pos > max) {
// right
toPos = (toPos - max) % length + min;
}
if (circular[0] && pos < min) {
// left
toPos = (toPos - min) % length + max;
}
return +toFixed(toPos);
}
function minMax(value, min, max) {
return Math.max(Math.min(value, max), min);
}
var AnimationManager =
/*#__PURE__*/
function () {
function AnimationManager(_a) {
var options = _a.options,
itm = _a.itm,
em = _a.em,
axm = _a.axm;
this.options = options;
this.itm = itm;
this.em = em;
this.axm = axm;
this.animationEnd = this.animationEnd.bind(this);
}
var __proto = AnimationManager.prototype;
__proto.getDuration = function (depaPos, destPos, wishDuration) {
var _this = this;
var duration;
if (typeof wishDuration !== "undefined") {
duration = wishDuration;
} else {
var durations_1 = map(destPos, function (v, k) {
return getDuration(Math.abs(Math.abs(v) - Math.abs(depaPos[k])), _this.options.deceleration);
});
duration = Object.keys(durations_1).reduce(function (max, v) {
return Math.max(max, durations_1[v]);
}, -Infinity);
}
return minMax(duration, this.options.minimumDuration, this.options.maximumDuration);
};
__proto.createAnimationParam = function (pos, duration, option) {
var depaPos = this.axm.get();
var destPos = pos;
var inputEvent = option && option.event || null;
return {
depaPos: depaPos,
destPos: destPos,
duration: minMax(duration, this.options.minimumDuration, this.options.maximumDuration),
delta: this.axm.getDelta(depaPos, destPos),
inputEvent: inputEvent,
input: option && option.input || null,
isTrusted: !!inputEvent,
done: this.animationEnd
};
};
__proto.grab = function (axes, option) {
if (this._animateParam && axes.length) {
var orgPos_1 = this.axm.get(axes);
var pos = this.axm.map(orgPos_1, function (v, opt) {
return getCirculatedPos(v, opt.range, opt.circular);
});
if (!every(pos, function (v, k) {
return orgPos_1[k] === v;
})) {
this.em.triggerChange(pos, orgPos_1, option, !!option);
}
this._animateParam = null;
this._raf && cancelAnimationFrame(this._raf);
this._raf = null;
this.em.triggerAnimationEnd(!!(option && option.event));
}
};
__proto.getEventInfo = function () {
if (this._animateParam && this._animateParam.input && this._animateParam.inputEvent) {
return {
input: this._animateParam.input,
event: this._animateParam.inputEvent
};
} else {
return null;
}
};
__proto.restore = function (option) {
var pos = this.axm.get();
var destPos = this.axm.map(pos, function (v, opt) {
return Math.min(opt.range[1], Math.max(opt.range[0], v));
});
this.animateTo(destPos, this.getDuration(pos, destPos), option);
};
__proto.animationEnd = function () {
var beforeParam = this.getEventInfo();
this._animateParam = null; // for Circular
var circularTargets = this.axm.filter(this.axm.get(), function (v, opt) {
return isCircularable(v, opt.range, opt.circular);
});
Object.keys(circularTargets).length > 0 && this.setTo(this.axm.map(circularTargets, function (v, opt) {
return getCirculatedPos(v, opt.range, opt.circular);
}));
this.itm.setInterrupt(false);
this.em.triggerAnimationEnd(!!beforeParam);
if (this.axm.isOutside()) {
this.restore(beforeParam);
} else {
this.finish(!!beforeParam);
}
};
__proto.finish = function (isTrusted) {
this._animateParam = null;
this.itm.setInterrupt(false);
this.em.triggerFinish(isTrusted);
};
__proto.animateLoop = function (param, complete) {
if (param.duration) {
this._animateParam = __assign({}, param);
var info_1 = this._animateParam;
var self_1 = this;
var prevPos_1 = info_1.depaPos;
info_1.startTime = new Date().getTime();
(function loop() {
self_1._raf = null;
var easingPer = self_1.easing((new Date().getTime() - info_1.startTime) / param.duration);
var toPos = map(info_1.depaPos, function (pos, key) {
return pos + info_1.delta[key] * easingPer;
});
var isCanceled = !self_1.em.triggerChange(toPos, prevPos_1);
prevPos_1 = map(toPos, function (v) {
return toFixed(v);
});
if (easingPer >= 1) {
var destPos = param.destPos;
if (!equal(destPos, self_1.axm.get(Object.keys(destPos)))) {
self_1.em.triggerChange(destPos, prevPos_1);
}
complete();
return;
} else if (isCanceled) {
self_1.finish(false);
} else {
// animationEnd
self_1._raf = requestAnimationFrame(loop);
}
})();
} else {
this.em.triggerChange(param.destPos);
complete();
}
};
__proto.getUserControll = function (param) {
var userWish = param.setTo();
userWish.destPos = this.axm.get(userWish.destPos);
userWish.duration = minMax(userWish.duration, this.options.minimumDuration, this.options.maximumDuration);
return userWish;
};
__proto.animateTo = function (destPos, duration, option) {
var _this = this;
var param = this.createAnimationParam(destPos, duration, option);
var depaPos = __assign({}, param.depaPos);
var retTrigger = this.em.triggerAnimationStart(param); // to control
var userWish = this.getUserControll(param); // You can't stop the 'animationStart' event when 'circular' is true.
if (!retTrigger && this.axm.every(userWish.destPos, function (v, opt) {
return isCircularable(v, opt.range, opt.circular);
})) {
console.warn("You can't stop the 'animation' event when 'circular' is true.");
}
if (retTrigger && !equal(userWish.destPos, depaPos)) {
var inputEvent = option && option.event || null;
this.animateLoop({
depaPos: depaPos,
destPos: userWish.destPos,
duration: userWish.duration,
delta: this.axm.getDelta(depaPos, userWish.destPos),
isTrusted: !!inputEvent,
inputEvent: inputEvent,
input: option && option.input || null
}, function () {
return _this.animationEnd();
});
}
};
__proto.easing = function (p) {
return p > 1 ? 1 : this.options.easing(p);
};
__proto.setTo = function (pos, duration) {
if (duration === void 0) {
duration = 0;
}
var axes = Object.keys(pos);
this.grab(axes);
var orgPos = this.axm.get(axes);
if (equal(pos, orgPos)) {
return this;
}
this.itm.setInterrupt(true);
var movedPos = filter(pos, function (v, k) {
return orgPos[k] !== v;
});
if (!Object.keys(movedPos).length) {
return this;
}
movedPos = this.axm.map(movedPos, function (v, opt) {
var range = opt.range,
circular = opt.circular;
if (circular && (circular[0] || circular[1])) {
return v;
} else {
return getInsidePosition(v, range, circular);
}
});
if (equal(movedPos, orgPos)) {
return this;
}
if (duration > 0) {
this.animateTo(movedPos, duration);
} else {
this.em.triggerChange(movedPos);
this.finish(false);
}
return this;
};
__proto.setBy = function (pos, duration) {
if (duration === void 0) {
duration = 0;
}
return this.setTo(map(this.axm.get(Object.keys(pos)), function (v, k) {
return v + pos[k];
}), duration);
};
return AnimationManager;
}();
var EventManager =
/*#__PURE__*/
function () {
function EventManager(axes) {
this.axes = axes;
}
/**
* This event is fired when a user holds an element on the screen of the device.
* @ko 사용자가 기기의 화면에 손을 대고 있을 때 발생하는 이벤트
* @name eg.Axes#hold
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Object.<string, number>} pos coordinate <ko>좌표 정보</ko>
* @property {Object} input The instance of inputType where the event occurred<ko>이벤트가 발생한 inputType 인스턴스</ko>
* @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("hold", function(event) {
* // event.pos
* // event.input
* // event.inputEvent
* // isTrusted
* });
*/
var __proto = EventManager.prototype;
__proto.triggerHold = function (pos, option) {
this.axes.trigger("hold", {
pos: pos,
input: option.input || null,
inputEvent: option.event || null,
isTrusted: true
});
};
/**
* Specifies the coordinates to move after the 'change' event. It works when the holding value of the change event is true.
* @ko 'change' 이벤트 이후 이동할 좌표를 지정한다. change이벤트의 holding 값이 true일 경우에 동작한다
* @name set
* @function
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("change", function(event) {
* event.holding && event.set({x: 10});
* });
*/
/** Specifies the animation coordinates to move after the 'release' or 'animationStart' events.
* @ko 'release' 또는 'animationStart' 이벤트 이후 이동할 좌표를 지정한다.
* @name setTo
* @function
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @param {Number} [duration] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("animationStart", function(event) {
* event.setTo({x: 10}, 2000);
* });
*/
/**
* This event is fired when a user release an element on the screen of the device.
* @ko 사용자가 기기의 화면에서 손을 뗐을 때 발생하는 이벤트
* @name eg.Axes#release
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Object.<string, number>} depaPos The coordinates when releasing an element<ko>손을 뗐을 때의 좌표 </ko>
* @property {Object.<string, number>} destPos The coordinates to move to after releasing an element<ko>손을 뗀 뒤에 이동할 좌표</ko>
* @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko>
* @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko>
* @property {Object} input The instance of inputType where the event occurred<ko>이벤트가 발생한 inputType 인스턴스</ko>
* @property {setTo} setTo Specifies the animation coordinates to move after the event <ko>이벤트 이후 이동할 애니메이션 좌표를 지정한다</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("release", function(event) {
* // event.depaPos
* // event.destPos
* // event.delta
* // event.input
* // event.inputEvent
* // event.setTo
* // event.isTrusted
*
* // if you want to change the animation coordinates to move after the 'release' event.
* event.setTo({x: 10}, 2000);
* });
*/
__proto.triggerRelease = function (param) {
param.setTo = this.createUserControll(param.destPos, param.duration);
this.axes.trigger("release", param);
};
/**
* This event is fired when coordinate changes.
* @ko 좌표가 변경됐을 때 발생하는 이벤트
* @name eg.Axes#change
* @event
* @type {object} The object of data to be sent when the event is fired <ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Object.<string, number>} pos The coordinate <ko>좌표</ko>
* @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko>
* @property {Boolean} holding Indicates whether a user holds an element on the screen of the device.<ko>사용자가 기기의 화면을 누르고 있는지 여부</ko>
* @property {Object} input The instance of inputType where the event occurred. If the value is changed by animation, it returns 'null'.<ko>이벤트가 발생한 inputType 인스턴스. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko>
* @property {Object} inputEvent The event object received from inputType. If the value is changed by animation, it returns 'null'.<ko>inputType으로 부터 받은 이벤트 객체. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko>
* @property {set} set Specifies the coordinates to move after the event. It works when the holding value is true <ko>이벤트 이후 이동할 좌표를 지정한다. holding 값이 true일 경우에 동작한다.</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("change", function(event) {
* // event.pos
* // event.delta
* // event.input
* // event.inputEvent
* // event.holding
* // event.set
* // event.isTrusted
*
* // if you want to change the coordinates to move after the 'change' event.
* // it works when the holding value of the change event is true.
* event.holding && event.set({x: 10});
* });
*/
__proto.triggerChange = function (pos, depaPos, option, holding) {
if (holding === void 0) {
holding = false;
}
var am = this.am;
var axm = am.axm;
var eventInfo = am.getEventInfo();
var moveTo = axm.moveTo(pos, depaPos);
var inputEvent = option && option.event || eventInfo && eventInfo.event || null;
var param = {
pos: moveTo.pos,
delta: moveTo.delta,
holding: holding,
inputEvent: inputEvent,
isTrusted: !!inputEvent,
input: option && option.input || eventInfo && eventInfo.input || null,
set: inputEvent ? this.createUserControll(moveTo.pos) : function () {}
};
var result = this.axes.trigger("change", param);
inputEvent && axm.set(param.set()["destPos"]);
return result;
};
/**
* This event is fired when animation starts.
* @ko 에니메이션이 시작할 때 발생한다.
* @name eg.Axes#animationStart
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Object.<string, number>} depaPos The coordinates when animation starts<ko>애니메이션이 시작 되었을 때의 좌표 </ko>
* @property {Object.<string, number>} destPos The coordinates to move to. If you change this value, you can run the animation<ko>이동할 좌표. 이값을 변경하여 애니메이션을 동작시킬수 있다</ko>
* @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko>
* @property {Number} duration Duration of the animation (unit: ms). If you change this value, you can control the animation duration time.<ko>애니메이션 진행 시간(단위: ms). 이값을 변경하여 애니메이션의 이동시간을 조절할 수 있다.</ko>
* @property {Object} input The instance of inputType where the event occurred. If the value is changed by animation, it returns 'null'.<ko>이벤트가 발생한 inputType 인스턴스. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko>
* @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko>
* @property {setTo} setTo Specifies the animation coordinates to move after the event <ko>이벤트 이후 이동할 애니메이션 좌표를 지정한다</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("release", function(event) {
* // event.depaPos
* // event.destPos
* // event.delta
* // event.input
* // event.inputEvent
* // event.setTo
* // event.isTrusted
*
* // if you want to change the animation coordinates to move after the 'animationStart' event.
* event.setTo({x: 10}, 2000);
* });
*/
__proto.triggerAnimationStart = function (param) {
param.setTo = this.createUserControll(param.destPos, param.duration);
return this.axes.trigger("animationStart", param);
};
/**
* This event is fired when animation ends.
* @ko 에니메이션이 끝났을 때 발생한다.
* @name eg.Axes#animationEnd
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("animationEnd", function(event) {
* // event.isTrusted
* });
*/
__proto.triggerAnimationEnd = function (isTrusted) {
if (isTrusted === void 0) {
isTrusted = false;
}
this.axes.trigger("animationEnd", {
isTrusted: isTrusted
});
};
/**
* This event is fired when all actions have been completed.
* @ko 에니메이션이 끝났을 때 발생한다.
* @name eg.Axes#finish
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("finish", function(event) {
* // event.isTrusted
* });
*/
__proto.triggerFinish = function (isTrusted) {
if (isTrusted === void 0) {
isTrusted = false;
}
this.axes.trigger("finish", {
isTrusted: isTrusted
});
};
__proto.createUserControll = function (pos, duration) {
if (duration === void 0) {
duration = 0;
} // to controll
var userControl = {
destPos: __assign({}, pos),
duration: duration
};
return function (toPos, userDuration) {
toPos && (userControl.destPos = __assign({}, toPos));
userDuration !== undefined && (userControl.duration = userDuration);
return userControl;
};
};
__proto.setAnimationManager = function (am) {
this.am = am;
};
__proto.destroy = function () {
this.axes.off();
};
return EventManager;
}();
var InterruptManager =
/*#__PURE__*/
function () {
function InterruptManager(options) {
this.options = options;
this._prevented = false; // check whether the animation event was prevented
}
var __proto = InterruptManager.prototype;
__proto.isInterrupting = function () {
// when interruptable is 'true', return value is always 'true'.
return this.options.interruptable || this._prevented;
};
__proto.isInterrupted = function () {
return !this.options.interruptable && this._prevented;
};
__proto.setInterrupt = function (prevented) {
!this.options.interruptable && (this._prevented = prevented);
};
return InterruptManager;
}();
var AxisManager =
/*#__PURE__*/
function () {
function AxisManager(axis, options) {
var _this = this;
this.axis = axis;
this.options = options;
this._complementOptions();
this._pos = Object.keys(this.axis).reduce(function (acc, v) {
acc[v] = _this.axis[v].range[0];
return acc;
}, {});
}
/**
* set up 'css' expression
* @private
*/
var __proto = AxisManager.prototype;
__proto._complementOptions = function () {
var _this = this;
Object.keys(this.axis).forEach(function (axis) {
_this.axis[axis] = __assign({
range: [0, 100],
bounce: [0, 0],
circular: [false, false]
}, _this.axis[axis]);
["bounce", "circular"].forEach(function (v) {
var axisOption = _this.axis;
var key = axisOption[axis][v];
if (/string|number|boolean/.test(typeof key)) {
axisOption[axis][v] = [key, key];
}
});
});
};
__proto.getDelta = function (depaPos, destPos) {
var fullDepaPos = this.get(depaPos);
return map(this.get(destPos), function (v, k) {
return v - fullDepaPos[k];
});
};
__proto.get = function (axes) {
var _this = this;
if (axes && Array.isArray(axes)) {
return axes.reduce(function (acc, v) {
if (v && v in _this._pos) {
acc[v] = _this._pos[v];
}
return acc;
}, {});
} else {
return __assign({}, this._pos, axes || {});
}
};
__proto.moveTo = function (pos, depaPos) {
if (depaPos === void 0) {
depaPos = this._pos;
}
var delta = map(this._pos, function (v, key) {
return key in pos && key in depaPos ? pos[key] - depaPos[key] : 0;
});
this.set(this.map(pos, function (v, opt) {
return opt ? getCirculatedPos(v, opt.range, opt.circular) : 0;
}));
return {
pos: __assign({}, this._pos),
delta: delta
};
};
__proto.set = function (pos) {
for (var k in pos) {
if (k && k in this._pos) {
this._pos[k] = pos[k];
}
}
};
__proto.every = function (pos, callback) {
var axisOptions = this.axis;
return every(pos, function (value, key) {
return callback(value, axisOptions[key], key);
});
};
__proto.filter = function (pos, callback) {
var axisOptions = this.axis;
return filter(pos, function (value, key) {
return callback(value, axisOptions[key], key);
});
};
__proto.map = function (pos, callback) {
var axisOptions = this.axis;
return map(pos, function (value, key) {
return callback(value, axisOptions[key], key);
});
};
__proto.isOutside = function (axes) {
return !this.every(axes ? this.get(axes) : this._pos, function (v, opt) {
return !isOutside(v, opt.range);
});
};
return AxisManager;
}();
var InputObserver =
/*#__PURE__*/
function () {
function InputObserver(_a) {
var options = _a.options,
itm = _a.itm,
em = _a.em,
axm = _a.axm,
am = _a.am;
this.isOutside = false;
this.moveDistance = null;
this.isStopped = false;
this.options = options;
this.itm = itm;
this.em = em;
this.axm = axm;
this.am = am;
} // when move pointer is held in outside
var __proto = InputObserver.prototype;
__proto.atOutside = function (pos) {
var _this = this;
if (this.isOutside) {
return this.axm.map(pos, function (v, opt) {
var tn = opt.range[0] - opt.bounce[0];
var tx = opt.range[1] + opt.bounce[1];
return v > tx ? tx : v < tn ? tn : v;
});
} else {
// when start pointer is held in inside
// get a initialization slope value to prevent smooth animation.
var initSlope_1 = this.am.easing(0.00001) / 0.00001;
return this.axm.map(pos, function (v, opt) {
var min = opt.range[0];
var max = opt.range[1];
var out = opt.bounce;
if (v < min) {
// left
return min - _this.am.easing((min - v) / (out[0] * initSlope_1)) * out[0];
} else if (v > max) {
// right
return max + _this.am.easing((v - max) / (out[1] * initSlope_1)) * out[1];
}
return v;
});
}
};
__proto.get = function (input) {
return this.axm.get(input.axes);
};
__proto.hold = function (input, event) {
if (this.itm.isInterrupted() || !input.axes.length) {
return;
}
var changeOption = {
input: input,
event: event
};
this.isStopped = false;
this.itm.setInterrupt(true);
this.am.grab(input.axes, changeOption);
!this.moveDistance && this.em.triggerHold(this.axm.get(), changeOption);
this.isOutside = this.axm.isOutside(input.axes);
this.moveDistance = this.axm.get(input.axes);
};
__proto.change = function (input, event, offset) {
if (this.isStopped || !this.itm.isInterrupting() || this.axm.every(offset, function (v) {
return v === 0;
})) {
return;
}
var depaPos = this.axm.get(input.axes);
var destPos; // for outside logic
destPos = map(this.moveDistance || depaPos, function (v, k) {
return v + (offset[k] || 0);
});
this.moveDistance && (this.moveDistance = destPos); // from outside to inside
if (this.isOutside && this.axm.every(depaPos, function (v, opt) {
return !isOutside(v, opt.range);
})) {
this.isOutside = false;
}
destPos = this.atOutside(destPos);
var isCanceled = !this.em.triggerChange(destPos, depaPos, {
input: input,
event: event
}, true);
if (isCanceled) {
this.isStopped = true;
this.moveDistance = null;
this.am.finish(false);
}
};
__proto.release = function (input, event, offset, inputDuration) {
if (this.isStopped || !this.itm.isInterrupting() || !this.moveDistance) {
return;
}
var pos = this.axm.get(input.axes);
var depaPos = this.axm.get();
var destPos = this.axm.get(this.axm.map(offset, function (v, opt, k) {
if (opt.circular && (opt.circular[0] || opt.circular[1])) {
return pos[k] + v;
} else {
return getInsidePosition(pos[k] + v, opt.range, opt.circular, opt.bounce);
}
}));
var duration = this.am.getDuration(destPos, pos, inputDuration);
if (duration === 0) {
destPos = __assign({}, depaPos);
} // prepare params
var param = {
depaPos: depaPos,
destPos: destPos,
duration: duration,
delta: this.axm.getDelta(depaPos, destPos),
inputEvent: event,
input: input,
isTrusted: true
};
this.em.triggerRelease(param);
this.moveDistance = null; // to contol
var userWish = this.am.getUserControll(param);
var isEqual = equal(userWish.destPos, depaPos);
var changeOption = {
input: input,
event: event
};
if (isEqual || userWish.duration === 0) {
!isEqual && this.em.triggerChange(userWish.destPos, depaPos, changeOption, true);
this.itm.setInterrupt(false);
if (this.axm.isOutside()) {
this.am.restore(changeOption);
} else {
this.em.triggerFinish(true);
}
} else {
this.am.animateTo(userWish.destPos, userWish.duration, changeOption);
}
};
return InputObserver;
}();
/**
* @typedef {Object} AxisOption The Axis information. The key of the axis specifies the name to use as the logical virtual coordinate system.
* @ko 축 정보. 축의 키는 논리적인 가상 좌표계로 사용할 이름을 지정한다.
* @property {Number[]} [range] The coordinate of range <ko>좌표 범위</ko>
* @property {Number} [range.0=0] The coordinate of the minimum <ko>최소 좌표</ko>
* @property {Number} [range.1=0] The coordinate of the maximum <ko>최대 좌표</ko>
* @property {Number[]} [bounce] The size of bouncing area. The coordinates can exceed the coordinate area as much as the bouncing area based on user action. If the coordinates does not exceed the bouncing area when an element is dragged, the coordinates where bouncing effects are applied are retuned back into the coordinate area<ko>바운스 영역의 크기. 사용자의 동작에 따라 좌표가 좌표 영역을 넘어 바운스 영역의 크기만큼 더 이동할 수 있다. 사용자가 끌어다 놓는 동작을 했을 때 좌표가 바운스 영역에 있으면, 바운스 효과가 적용된 좌표가 다시 좌표 영역 안으로 들어온다</ko>
* @property {Number} [bounce.0=0] The size of coordinate of the minimum area <ko>최소 좌표 바운스 영역의 크기</ko>
* @property {Number} [bounce.1=0] The size of coordinate of the maximum area <ko>최대 좌표 바운스 영역의 크기</ko>
* @property {Boolean[]} [circular] Indicates whether a circular element is available. If it is set to "true" and an element is dragged outside the coordinate area, the element will appear on the other side.<ko>순환 여부. 'true'로 설정한 방향의 좌표 영역 밖으로 엘리먼트가 이동하면 반대 방향에서 엘리먼트가 나타난다</ko>
* @property {Boolean} [circular.0=false] Indicates whether to circulate to the coordinate of the minimum <ko>최소 좌표 방향의 순환 여부</ko>
* @property {Boolean} [circular.1=false] Indicates whether to circulate to the coordinate of the maximum <ko>최대 좌표 방향의 순환 여부</ko>
**/
/**
* @typedef {Object} AxesOption The option object of the eg.Axes module
* @ko eg.Axes 모듈의 옵션 객체
* @property {Function} [easing=easing.easeOutCubic] The easing function to apply to an animation <ko>애니메이션에 적용할 easing 함수</ko>
* @property {Number} [maximumDuration=Infinity] Maximum duration of the animation <ko>가속도에 의해 애니메이션이 동작할 때의 최대 좌표 이동 시간</ko>
* @property {Number} [minimumDuration=0] Minimum duration of the animation <ko>가속도에 의해 애니메이션이 동작할 때의 최소 좌표 이동 시간</ko>
* @property {Number} [deceleration=0.0006] Deceleration of the animation where acceleration is manually enabled by user. A higher value indicates shorter running time. <ko>사용자의 동작으로 가속도가 적용된 애니메이션의 감속도. 값이 높을수록 애니메이션 실행 시간이 짧아진다</ko>
* @property {Boolean} [interruptable=true] Indicates whether an animation is interruptible.<br>- true: It can be paused or stopped by user action or the API.<br>- false: It cannot be paused or stopped by user action or the API while it is running.<ko>진행 중인 애니메이션 중지 가능 여부.<br>- true: 사용자의 동작이나 API로 애니메이션을 중지할 수 있다.<br>- false: 애니메이션이 진행 중일 때는 사용자의 동작이나 API가 적용되지 않는다</ko>
**/
/**
* @class eg.Axes
* @classdesc A module used to change the information of user action entered by various input devices such as touch screen or mouse into the logical virtual coordinates. You can easily create a UI that responds to user actions.
* @ko 터치 입력 장치나 마우스와 같은 다양한 입력 장치를 통해 전달 받은 사용자의 동작을 논리적인 가상 좌표로 변경하는 모듈이다. 사용자 동작에 반응하는 UI를 손쉽게 만들수 있다.
* @extends eg.Component
*
* @param {Object.<string, AxisOption>} axis Axis information managed by eg.Axes. The key of the axis specifies the name to use as the logical virtual coordinate system. <ko>eg.Axes가 관리하는 축 정보. 축의 키는 논리적인 가상 좌표계로 사용할 이름을 지정한다.</ko>
* @param {AxesOption} [options] The option object of the eg.Axes module<ko>eg.Axes 모듈의 옵션 객체</ko>
* @param {Object.<string, number>} [startPos] The coordinates to be moved when creating an instance. not triggering change event.<ko>인스턴스 생성시 이동할 좌표, change 이벤트는 발생하지 않음.</ko>
*
* @support {"ie": "10+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.3+ (except 3.x)"}
* @example
*
* // 1. Initialize eg.Axes
* const axes = new eg.Axes({
* something1: {
* range: [0, 150],
* bounce: 50
* },
* something2: {
* range: [0, 200],
* bounce: 100
* },
* somethingN: {
* range: [1, 10],
* }
* }, {
* deceleration : 0.0024
* });
*
* // 2. attach event handler
* axes.on({
* "hold" : function(evt) {
* },
* "release" : function(evt) {
* },
* "animationStart" : function(evt) {
* },
* "animationEnd" : function(evt) {
* },
* "change" : function(evt) {
* }
* });
*
* // 3. Initialize inputTypes
* const panInputArea = new eg.Axes.PanInput("#area", {
* scale: [0.5, 1]
* });
* const panInputHmove = new eg.Axes.PanInput("#hmove");
* const panInputVmove = new eg.Axes.PanInput("#vmove");
* const pinchInputArea = new eg.Axes.PinchInput("#area", {
* scale: 1.5
* });
*
* // 4. Connect eg.Axes and InputTypes
* // [PanInput] When the mouse or touchscreen is down and moved.
* // Connect the 'something2' axis to the mouse or touchscreen x position and
* // connect the 'somethingN' axis to the mouse or touchscreen y position.
* axes.connect(["something2", "somethingN"], panInputArea); // or axes.connect("something2 somethingN", panInputArea);
*
* // Connect only one 'something1' axis to the mouse or touchscreen x position.
* axes.connect(["something1"], panInputHmove); // or axes.connect("something1", panInputHmove);
*
* // Connect only one 'something2' axis to the mouse or touchscreen y position.
* axes.connect(["", "something2"], panInputVmove); // or axes.connect(" something2", panInputVmove);
*
* // [PinchInput] Connect 'something2' axis when two pointers are moving toward (zoom-in) or away from each other (zoom-out).
* axes.connect("something2", pinchInputArea);
*/
var Axes =
/*#__PURE__*/
function (_super) {
__extends(Axes, _super);
function Axes(axis, options, startPos) {
if (axis === void 0) {
axis = {};
}
var _this = _super.call(this) || this;
_this.axis = axis;
_this._inputs = [];
_this.options = __assign({
easing: function easeOutCubic(x) {
return 1 - Math.pow(1 - x, 3);
},
interruptable: true,
maximumDuration: Infinity,
minimumDuration: 0,
deceleration: 0.0006
}, options);
_this.itm = new InterruptManager(_this.options);
_this.axm = new AxisManager(_this.axis, _this.options);
_this.em = new EventManager(_this);
_this.am = new AnimationManager(_this);
_this.io = new InputObserver(_this);
_this.em.setAnimationManager(_this.am);
startPos && _this.em.triggerChange(startPos);
return _this;
}
/**
* Connect the axis of eg.Axes to the inputType.
* @ko eg.Axes의 축과 inputType을 연결한다
* @method eg.Axes#connect
* @param {(String[]|String)} axes The name of the axis to associate with inputType <ko>inputType과 연결할 축의 이름</ko>
* @param {Object} inputType The inputType instance to associate with the axis of eg.Axes <ko>eg.Axes의 축과 연결할 inputType 인스턴스<ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* }
* });
*
* axes.connect("x", new eg.Axes.PanInput("#area1"))
* .connect("x xOther", new eg.Axes.PanInput("#area2"))
* .connect(" xOther", new eg.Axes.PanInput("#area3"))
* .connect(["x"], new eg.Axes.PanInput("#area4"))
* .connect(["xOther", "x"], new eg.Axes.PanInput("#area5"))
* .connect(["", "xOther"], new eg.Axes.PanInput("#area6"));
*/
var __proto = Axes.prototype;
__proto.connect = function (axes, inputType) {
var mapped;
if (typeof axes === "string") {
mapped = axes.split(" ");
} else {
mapped = axes.concat();
} // check same instance
if (~this._inputs.indexOf(inputType)) {
this.disconnect(inputType);
} // check same element in hammer type for share
if ("hammer" in inputType) {
var targets = this._inputs.filter(function (v) {
return v.hammer && v.element === inputType.element;
});
if (targets.length) {
inputType.hammer = targets[0].hammer;
}
}
inputType.mapAxes(mapped);
inputType.connect(this.io);
this._inputs.push(inputType);
return this;
};
/**
* Disconnect the axis of eg.Axes from the inputType.
* @ko eg.Axes의 축과 inputType의 연결을 끊는다.
* @method eg.Axes#disconnect
* @param {Object} [inputType] An inputType instance associated with the axis of eg.Axes <ko>eg.Axes의 축과 연결한 inputType 인스턴스<ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* }
* });
*
* const input1 = new eg.Axes.PanInput("#area1");
* const input2 = new eg.Axes.PanInput("#area2");
* const input3 = new eg.Axes.PanInput("#area3");
*
* axes.connect("x", input1);
* .connect("x xOther", input2)
* .connect(["xOther", "x"], input3);
*
* axes.disconnect(input1); // disconnects input1
* axes.disconnect(); // disconnects all of them
*/
__proto.disconnect = function (inputType) {
if (inputType) {
var index = this._inputs.indexOf(inputType);
if (index >= 0) {
this._inputs[index].disconnect();
this._inputs.splice(index, 1);
}
} else {
this._inputs.forEach(function (v) {
return v.disconnect();
});
this._inputs = [];
}
return this;
};
/**
* Returns the current position of the coordinates.
* @ko 좌표의 현재 위치를 반환한다
* @method eg.Axes#get
* @param {Object} [axes] The names of the axis <ko>축 이름들</ko>
* @return {Object.<string, number>} Axis coordinate information <ko>축 좌표 정보</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.get(); // {"x": 0, "xOther": -100, "zoom": 50}
* axes.get(["x", "zoom"]); // {"x": 0, "zoom": 50}
*/
__proto.get = function (axes) {
return this.axm.get(axes);
};
/**
* Moves an axis to specific coordinates.
* @ko 좌표를 이동한다.
* @method eg.Axes#setTo
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @param {Number} [duration=0] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.setTo({"x": 30, "zoom": 60});
* axes.get(); // {"x": 30, "xOther": -100, "zoom": 60}
*
* axes.setTo({"x": 100, "xOther": 60}, 1000); // animatation
*
* // after 1000 ms
* axes.get(); // {"x": 100, "xOther": 60, "zoom": 60}
*/
__proto.setTo = function (pos, duration) {
if (duration === void 0) {
duration = 0;
}
this.am.setTo(pos, duration);
return this;
};
/**
* Moves an axis from the current coordinates to specific coordinates.
* @ko 현재 좌표를 기준으로 좌표를 이동한다.
* @method eg.Axes#setBy
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @param {Number} [duration=0] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.setBy({"x": 30, "zoom": 10});
* axes.get(); // {"x": 30, "xOther": -100, "zoom": 60}
*
* axes.setBy({"x": 70, "xOther": 60}, 1000); // animatation
*
* // after 1000 ms
* axes.get(); // {"x": 100, "xOther": -40, "zoom": 60}
*/
__proto.setBy = function (pos, duration) {
if (duration === void 0) {
duration = 0;
}
this.am.setBy(pos, duration);
return this;
};
/**
* Returns whether there is a coordinate in the bounce area of the target axis.
* @ko 대상 축 중 bounce영역에 좌표가 존재하는지를 반환한다
* @method eg.Axes#isBounceArea
* @param {Object} [axes] The names of the axis <ko>축 이름들</ko>
* @return {Boolen} Whether the bounce area exists. <ko>bounce 영역 존재 여부</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.isBounceArea(["x"]);
* axes.isBounceArea(["x", "zoom"]);
* axes.isBounceArea();
*/
__proto.isBounceArea = function (axes) {
return this.axm.isOutside(axes);
};
/**
* Destroys properties, and events used in a module and disconnect all connections to inputTypes.
* @ko 모듈에 사용한 속성, 이벤트를 해제한다. 모든 inputType과의 연결을 끊는다.
* @method eg.Axes#destroy
*/
__proto.destroy = function () {
this.disconnect();
this.em.destroy();
};
/**
* Version info string
* @ko 버전정보 문자열
* @name VERSION
* @static
* @type {String}
* @example
* eg.Axes.VERSION; // ex) 3.3.3
* @memberof eg.Axes
*/
Axes.VERSION = "2.5.10";
/**
* @name eg.Axes.TRANSFORM
* @desc Returns the transform attribute with CSS vendor prefixes.
* @ko CSS vendor prefixes를 붙인 transform 속성을 반환한다.
*
* @constant
* @type {String}
* @example
* eg.Axes.TRANSFORM; // "transform" or "webkitTransform"
*/
Axes.TRANSFORM = TRANSFORM;
/**
* @name eg.Axes.DIRECTION_NONE
* @constant
* @type {Number}
*/
Axes.DIRECTION_NONE = DIRECTION_NONE;
/**
* @name eg.Axes.DIRECTION_LEFT
* @constant
* @type {Number}
*/
Axes.DIRECTION_LEFT = DIRECTION_LEFT;
/**
* @name eg.Axes.DIRECTION_RIGHT
* @constant
* @type {Number}
*/
Axes.DIRECTION_RIGHT = DIRECTION_RIGHT;
/**
* @name eg.Axes.DIRECTION_UP
* @constant
* @type {Number}
*/
Axes.DIRECTION_UP = DIRECTION_UP;
/**
* @name eg.Axes.DIRECTION_DOWN
* @constant
* @type {Number}
*/
Axes.DIRECTION_DOWN = DIRECTION_DOWN;
/**
* @name eg.Axes.DIRECTION_HORIZONTAL
* @constant
* @type {Number}
*/
Axes.DIRECTION_HORIZONTAL = DIRECTION_HORIZONTAL;
/**
* @name eg.Axes.DIRECTION_VERTICAL
* @constant
* @type {Number}
*/
Axes.DIRECTION_VERTICAL = DIRECTION_VERTICAL;
/**
* @name eg.Axes.DIRECTION_ALL
* @constant
* @type {Number}
*/
Axes.DIRECTION_ALL = DIRECTION_ALL;
return Axes;
}(Component);
var SUPPORT_POINTER_EVENTS$1 = "PointerEvent" in win || "MSPointerEvent" in win;
var SUPPORT_TOUCH$1 = "ontouchstart" in win;
var UNIQUEKEY = "_EGJS_AXES_INPUTTYPE_";
function toAxis(source, offset) {
return offset.reduce(function (acc, v, i) {
if (source[i]) {
acc[source[i]] = v;
}
return acc;
}, {});
}
function createHammer(element, options) {
try {
// create Hammer
return new Manager(element, __assign({}, options));
} catch (e) {
return null;
}
}
function convertInputType(inputType) {
if (inputType === void 0) {
inputType = [];
}
var hasTouch = false;
var hasMouse = false;
var hasPointer = false;
inputType.forEach(function (v) {
switch (v) {
case "mouse":
hasMouse = true;
break;
case "touch":
hasTouch = SUPPORT_TOUCH$1;
break;
case "pointer":
hasPointer = SUPPORT_POINTER_EVENTS$1;
// no default
}
});
if (hasPointer) {
return PointerEventInput;
} else if (hasTouch && hasMouse) {
return TouchMouseInput;
} else if (hasTouch) {
return TouchInput;
} else if (hasMouse) {
return MouseInput;
}
return null;
}
function getDirectionByAngle(angle, thresholdAngle) {
if (thresholdAngle < 0 || thresholdAngle > 90) {
return DIRECTION_NONE;
}
var toAngle = Math.abs(angle);
return toAngle > thresholdAngle && toAngle < 180 - thresholdAngle ? DIRECTION_VERTICAL : DIRECTION_HORIZONTAL;
}
function getNextOffset(speeds, deceleration) {
var normalSpeed = Math.sqrt(speeds[0] * speeds[0] + speeds[1] * speeds[1]);
var duration = Math.abs(normalSpeed / -deceleration);
return [speeds[0] / 2 * duration, speeds[1] / 2 * duration];
}
function useDirection(checkType, direction, userDirection) {
if (userDirection) {
return !!(direction === DIRECTION_ALL || direction & checkType && userDirection & checkType);
} else {
return !!(direction & checkType);
}
}
/**
* @typedef {Object} PanInputOption The option object of the eg.Axes.PanInput module.
* @ko eg.Axes.PanInput 모듈의 옵션 객체
* @property {String[]} [inputType=["touch","mouse", "pointer"]] Types of input devices.<br>- touch: Touch screen<br>- mouse: Mouse <ko>입력 장치 종류.<br>- touch: 터치 입력 장치<br>- mouse: 마우스</ko>
* @property {Number[]} [scale] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko>
* @property {Number} [scale.0=1] horizontal axis scale <ko>수평축 배율</ko>
* @property {Number} [scale.1=1] vertical axis scale <ko>수직축 배율</ko>
* @property {Number} [thresholdAngle=45] The threshold value that determines whether user action is horizontal or vertical (0~90) <ko>사용자의 동작이 가로 방향인지 세로 방향인지 판단하는 기준 각도(0~90)</ko>
* @property {Number} [threshold=0] Minimal pan distance required before recognizing <ko>사용자의 Pan 동작을 인식하기 위해산 최소한의 거리</ko>
* @property {Object} [hammerManagerOptions={cssProps: {userSelect: "none",touchSelect: "none",touchCallout: "none",userDrag: "none"}] Options of Hammer.Manager <ko>Hammer.Manager의 옵션</ko>
**/
/**
* @class eg.Axes.PanInput
* @classdesc A module that passes the amount of change to eg.Axes when the mouse or touchscreen is down and moved. use less than two axes.
* @ko 마우스나 터치 스크린을 누르고 움직일때의 변화량을 eg.Axes에 전달하는 모듈. 두개 이하의 축을 사용한다.
*
* @example
* const pan = new eg.Axes.PanInput("#area", {
* inputType: ["touch"],
* scale: [1, 1.3],
* });
*
* // Connect the 'something2' axis to the mouse or touchscreen x position when the mouse or touchscreen is down and moved.
* // Connect the 'somethingN' axis to the mouse or touchscreen y position when the mouse or touchscreen is down and moved.
* axes.connect(["something2", "somethingN"], pan); // or axes.connect("something2 somethingN", pan);
*
* // Connect only one 'something1' axis to the mouse or touchscreen x position when the mouse or touchscreen is down and moved.
* axes.connect(["something1"], pan); // or axes.connect("something1", pan);
*
* // Connect only one 'something2' axis to the mouse or touchscreen y position when the mouse or touchscreen is down and moved.
* axes.connect(["", "something2"], pan); // or axes.connect(" something2", pan);
*
* @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.PanInput module <ko>eg.Axes.PanInput 모듈을 사용할 엘리먼트</ko>
* @param {PanInputOption} [options] The option object of the eg.Axes.PanInput module<ko>eg.Axes.PanInput 모듈의 옵션 객체</ko>
*/
var PanInput =
/*#__PURE__*/
function () {
function PanInput(el, options) {
this.axes = [];
this.hammer = null;
this.element = null;
this.panRecognizer = null;
/**
* Hammer helps you add support for touch gestures to your page
*
* @external Hammer
* @see {@link http://hammerjs.github.io|Hammer.JS}
* @see {@link http://hammerjs.github.io/jsdoc/Hammer.html|Hammer.JS API documents}
* @see Hammer.JS applies specific CSS properties by {@link http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html|default} when creating an instance. The eg.Axes module removes all default CSS properties provided by Hammer.JS
*/
if (typeof Manager === "undefined") {
throw new Error("The Hammerjs must be loaded before eg.Axes.PanInput.\nhttp://hammerjs.github.io/");
}
this.element = $(el);
this.options = __assign({
inputType: ["touch", "mouse", "pointer"],
scale: [1, 1],
thresholdAngle: 45,
threshold: 0,
hammerManagerOptions: {
// css properties were removed due to usablility issue
// http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html
cssProps: {
userSelect: "none",
touchSelect: "none",
touchCallout: "none",
userDrag: "none"
}
}
}, options);
this.onHammerInput = this.onHammerInput.bind(this);
this.onPanmove = this.onPanmove.bind(this);
this.onPanend = this.onPanend.bind(this);
}
var __proto = PanInput.prototype;
__proto.mapAxes = function (axes) {
var useHorizontal = !!axes[0];
var useVertical = !!axes[1];
if (useHorizontal && useVertical) {
this._direction = DIRECTION_ALL;
} else if (useHorizontal) {
this._direction = DIRECTION_HORIZONTAL;
} else if (useVertical) {
this._direction = DIRECTION_VERTICAL;
} else {
this._direction = DIRECTION_NONE;
}
this.axes = axes;
};
__proto.connect = function (observer) {
var hammerOption = {
direction: this._direction,
threshold: this.options.threshold
};
if (this.hammer) {
// for sharing hammer instance.
// hammer remove previous PanRecognizer.
this.removeRecognizer();
this.dettachEvent();
} else {
var keyValue = this.element[UNIQUEKEY];
if (!keyValue) {
keyValue = String(Math.round(Math.random() * new Date().getTime()));
}
var inputClass = convertInputType(this.options.inputType);
if (!inputClass) {
throw new Error("Wrong inputType parameter!");
}
this.hammer = createHammer(this.element, __assign({
inputClass: inputClass
}, this.options.hammerManagerOptions));
this.element[UNIQUEKEY] = keyValue;
}
this.panRecognizer = new PanRecognizer(hammerOption);
this.hammer.add(this.panRecognizer);
this.attachEvent(observer);
return this;
};
__proto.disconnect = function () {
this.removeRecognizer();
if (this.hammer) {
this.dettachEvent();
}
this._direction = DIRECTION_NONE;
return this;
};
/**
* Destroys elements, properties, and events used in a module.
* @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다.
* @method eg.Axes.PanInput#destroy
*/
__proto.destroy = function () {
this.disconnect();
if (this.hammer && this.hammer.recognizers.length === 0) {
this.hammer.destroy();
}
delete this.element[UNIQUEKEY];
this.element = null;
this.hammer = null;
};
/**
* Enables input devices
* @ko 입력 장치를 사용할 수 있게 한다
* @method eg.Axes.PanInput#enable
* @return {eg.Axes.PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.enable = function () {
this.hammer && (this.hammer.get("pan").options.enable = true);
return this;
};
/**
* Disables input devices
* @ko 입력 장치를 사용할 수 없게 한다.
* @method eg.Axes.PanInput#disable
* @return {eg.Axes.PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.disable = function () {
this.hammer && (this.hammer.get("pan").options.enable = false);
return this;
};
/**
* Returns whether to use an input device
* @ko 입력 장치를 사용 여부를 반환한다.
* @method eg.Axes.PanInput#isEnable
* @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko>
*/
__proto.isEnable = function () {
return !!(this.hammer && this.hammer.get("pan").options.enable);
};
__proto.removeRecognizer = function () {
if (this.hammer && this.panRecognizer) {
this.hammer.remove(this.panRecognizer);
this.panRecognizer = null;
}
};
__proto.onHammerInput = function (event) {
if (this.isEnable()) {
if (event.isFirst) {
this.observer.hold(this, event);
} else if (event.isFinal) {
this.onPanend(event);
}
}
};
__proto.onPanmove = function (event) {
var userDirection = getDirectionByAngle(event.angle, this.options.thresholdAngle); // not support offset properties in Hammerjs - start
var prevInput = this.hammer.session.prevInput;
/* eslint-disable no-param-reassign */
if (prevInput) {
event.offsetX = event.deltaX - prevInput.deltaX;
event.offsetY = event.deltaY - prevInput.deltaY;
} else {
event.offsetX = 0;
event.offsetY = 0;
}
var offset = this.getOffset([event.offsetX, event.offsetY], [useDirection(DIRECTION_HORIZONTAL, this._direction, userDirection), useDirection(DIRECTION_VERTICAL, this._direction, userDirection)]);
var prevent = offset.some(function (v) {
return v !== 0;
});
if (prevent) {
event.srcEvent.preventDefault();
event.srcEvent.stopPropagation();
}
event.preventSystemEvent = prevent;
prevent && this.observer.change(this, event, toAxis(this.axes, offset));
};
__proto.onPanend = function (event) {
var offset = this.getOffset([Math.abs(event.velocityX) * (event.deltaX < 0 ? -1 : 1), Math.abs(event.velocityY) * (event.deltaY < 0 ? -1 : 1)], [useDirection(DIRECTION_HORIZONTAL, this._direction), useDirection(DIRECTION_VERTICAL, this._direction)]);
offset = getNextOffset(offset, this.observer.options.deceleration);
this.observer.release(this, event, toAxis(this.axes, offset));
};
__proto.attachEvent = function (observer) {
this.observer = observer;
this.hammer.on("hammer.input", this.onHammerInput).on("panstart panmove", this.onPanmove);
};
__proto.dettachEvent = function () {
this.hammer.off("hammer.input", this.onHammerInput).off("panstart panmove", this.onPanmove);
this.observer = null;
};
__proto.getOffset = function (properties, direction) {
var offset = [0, 0];
var scale = this.options.scale;
if (direction[0]) {
offset[0] = properties[0] * scale[0];
}
if (direction[1]) {
offset[1] = properties[1] * scale[1];
}
return offset;
};
return PanInput;
}();
/**
* @typedef {Object} PinchInputOption The option object of the eg.Axes.PinchInput module
* @ko eg.Axes.PinchInput 모듈의 옵션 객체
* @property {Number} [scale=1] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko>
* @property {Number} [threshold=0] Minimal scale before recognizing <ko>사용자의 Pinch 동작을 인식하기 위해산 최소한의 배율</ko>
* @property {Object} [hammerManagerOptions={cssProps: {userSelect: "none",touchSelect: "none",touchCallout: "none",userDrag: "none"}] Options of Hammer.Manager <ko>Hammer.Manager의 옵션</ko>
**/
/**
* @class eg.Axes.PinchInput
* @classdesc A module that passes the amount of change to eg.Axes when two pointers are moving toward (zoom-in) or away from each other (zoom-out). use one axis.
* @ko 2개의 pointer를 이용하여 zoom-in하거나 zoom-out 하는 동작의 변화량을 eg.Axes에 전달하는 모듈. 한 개 의 축을 사용한다.
* @example
* const pinch = new eg.Axes.PinchInput("#area", {
* scale: 1
* });
*
* // Connect 'something' axis when two pointers are moving toward (zoom-in) or away from each other (zoom-out).
* axes.connect("something", pinch);
*
* @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.PinchInput module <ko>eg.Axes.PinchInput 모듈을 사용할 엘리먼트</ko>
* @param {PinchInputOption} [options] The option object of the eg.Axes.PinchInput module<ko>eg.Axes.PinchInput 모듈의 옵션 객체</ko>
*/
var PinchInput =
/*#__PURE__*/
function () {
function PinchInput(el, options) {
this.axes = [];
this.hammer = null;
this.element = null;
this._base = null;
this._prev = null;
this.pinchRecognizer = null;
/**
* Hammer helps you add support for touch gestures to your page
*
* @external Hammer
* @see {@link http://hammerjs.github.io|Hammer.JS}
* @see {@link http://hammerjs.github.io/jsdoc/Hammer.html|Hammer.JS API documents}
* @see Hammer.JS applies specific CSS properties by {@link http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html|default} when creating an instance. The eg.Axes module removes all default CSS properties provided by Hammer.JS
*/
if (typeof Manager === "undefined") {
throw new Error("The Hammerjs must be loaded before eg.Axes.PinchInput.\nhttp://hammerjs.github.io/");
}
this.element = $(el);
this.options = __assign({
scale: 1,
threshold: 0,
inputType: ["touch", "pointer"],
hammerManagerOptions: {
// css properties were removed due to usablility issue
// http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html
cssProps: {
userSelect: "none",
touchSelect: "none",
touchCallout: "none",
userDrag: "none"
}
}
}, options);
this.onPinchStart = this.onPinchStart.bind(this);
this.onPinchMove = this.onPinchMove.bind(this);
this.onPinchEnd = this.onPinchEnd.bind(this);
}
var __proto = PinchInput.prototype;
__proto.mapAxes = function (axes) {
this.axes = axes;
};
__proto.connect = function (observer) {
var hammerOption = {
threshold: this.options.threshold
};
if (this.hammer) {
// for sharing hammer instance.
// hammer remove previous PinchRecognizer.
this.removeRecognizer();
this.dettachEvent();
} else {
var keyValue = this.element[UNIQUEKEY];
if (!keyValue) {
keyValue = String(Math.round(Math.random() * new Date().getTime()));
}
var inputClass = convertInputType(this.options.inputType);
if (!inputClass) {
throw new Error("Wrong inputType parameter!");
}
this.hammer = createHammer(this.element, __assign({
inputClass: inputClass
}, this.options.hammerManagerOptions));
this.element[UNIQUEKEY] = keyValue;
}
this.pinchRecognizer = new PinchRecognizer(hammerOption);
this.hammer.add(this.pinchRecognizer);
this.attachEvent(observer);
return this;
};
__proto.disconnect = function () {
this.removeRecognizer();
if (this.hammer) {
this.hammer.remove(this.pinchRecognizer);
this.pinchRecognizer = null;
this.dettachEvent();
}
return this;
};
/**
* Destroys elements, properties, and events used in a module.
* @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다.
* @method eg.Axes.PinchInput#destroy
*/
__proto.destroy = function () {
this.disconnect();
if (this.hammer && this.hammer.recognizers.length === 0) {
this.hammer.destroy();
}
delete this.element[UNIQUEKEY];
this.element = null;
this.hammer = null;
};
__proto.removeRecognizer = function () {
if (this.hammer && this.pinchRecognizer) {
this.hammer.remove(this.pinchRecognizer);
this.pinchRecognizer = null;
}
};
__proto.onPinchStart = function (event) {
this._base = this.observer.get(this)[this.axes[0]];
var offset = this.getOffset(event.scale);
this.observer.hold(this, event);
this.observer.change(this, event, toAxis(this.axes, [offset]));
this._prev = event.scale;
};
__proto.onPinchMove = function (event) {
var offset = this.getOffset(event.scale, this._prev);
this.observer.change(this, event, toAxis(this.axes, [offset]));
this._prev = event.scale;
};
__proto.onPinchEnd = function (event) {
var offset = this.getOffset(event.scale, this._prev);
this.observer.change(this, event, toAxis(this.axes, [offset]));
this.observer.release(this, event, toAxis(this.axes, [0]), 0);
this._base = null;
this._prev = null;
};
__proto.getOffset = function (pinchScale, prev) {
if (prev === void 0) {
prev = 1;
}
return this._base * (pinchScale - prev) * this.options.scale;
};
__proto.attachEvent = function (observer) {
this.observer = observer;
this.hammer.on("pinchstart", this.onPinchStart).on("pinchmove", this.onPinchMove).on("pinchend", this.onPinchEnd);
};
__proto.dettachEvent = function () {
this.hammer.off("pinchstart", this.onPinchStart).off("pinchmove", this.onPinchMove).off("pinchend", this.onPinchEnd);
this.observer = null;
this._prev = null;
};
/**
* Enables input devices
* @ko 입력 장치를 사용할 수 있게 한다
* @method eg.Axes.PinchInput#enable
* @return {eg.Axes.PinchInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.enable = function () {
this.hammer && (this.hammer.get("pinch").options.enable = true);
return this;
};
/**
* Disables input devices
* @ko 입력 장치를 사용할 수 없게 한다.
* @method eg.Axes.PinchInput#disable
* @return {eg.Axes.PinchInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.disable = function () {
this.hammer && (this.hammer.get("pinch").options.enable = false);
return this;
};
/**
* Returns whether to use an input device
* @ko 입력 장치를 사용 여부를 반환한다.
* @method eg.Axes.PinchInput#isEnable
* @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko>
*/
__proto.isEnable = function () {
return !!(this.hammer && this.hammer.get("pinch").options.enable);
};
return PinchInput;
}();
/**
* @typedef {Object} WheelInputOption The option object of the eg.Axes.WheelInput module
* @ko eg.Axes.WheelInput 모듈의 옵션 객체
* @property {Number} [scale=1] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko>
**/
/**
* @class eg.Axes.WheelInput
* @classdesc A module that passes the amount of change to eg.Axes when the mouse wheel is moved. use one axis.
* @ko 마우스 휠이 움직일때의 변화량을 eg.Axes에 전달하는 모듈. 한 개 의 축을 사용한다.
*
* @example
* const wheel = new eg.Axes.WheelInput("#area", {
* scale: 1
* });
*
* // Connect 'something' axis when the mousewheel is moved.
* axes.connect("something", wheel);
*
* @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.WheelInput module <ko>eg.Axes.WheelInput 모듈을 사용할 엘리먼트</ko>
* @param {WheelInputOption} [options] The option object of the eg.Axes.WheelInput module<ko>eg.Axes.WheelInput 모듈의 옵션 객체</ko>
*/
var WheelInput =
/*#__PURE__*/
function () {
function WheelInput(el, options) {
this.axes = [];
this.element = null;
this._isEnabled = false;
this._isHolded = false;
this._timer = null;
this.element = $(el);
this.options = __assign({
scale: 1,
useNormalized: true
}, options);
this.onWheel = this.onWheel.bind(this);
}
var __proto = WheelInput.prototype;
__proto.mapAxes = function (axes) {
this.axes = axes;
};
__proto.connect = function (observer) {
this.dettachEvent();
this.attachEvent(observer);
return this;
};
__proto.disconnect = function () {
this.dettachEvent();
return this;
};
/**
* Destroys elements, properties, and events used in a module.
* @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다.
* @method eg.Axes.WheelInput#destroy
*/
__proto.destroy = function () {
this.disconnect();
this.element = null;
};
__proto.onWheel = function (event) {
var _this = this;
if (!this._isEnabled) {
return;
}
event.preventDefault();
if (event.deltaY === 0) {
return;
}
if (!this._isHolded) {
this.observer.hold(this, event);
this._isHolded = true;
}
var offset = (event.deltaY > 0 ? -1 : 1) * this.options.scale * (this.options.useNormalized ? 1 : Math.abs(event.deltaY));
this.observer.change(this, event, toAxis(this.axes, [offset]));
clearTimeout(this._timer);
this._timer = setTimeout(function () {
if (_this._isHolded) {
_this._isHolded = false;
_this.observer.release(_this, event, toAxis(_this.axes, [0]));
}
}, 50);
};
__proto.attachEvent = function (observer) {
this.observer = observer;
this.element.addEventListener("wheel", this.onWheel);
this._isEnabled = true;
};
__proto.dettachEvent = function () {
this.element.removeEventListener("wheel", this.onWheel);
this._isEnabled = false;
this.observer = null;
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
};
/**
* Enables input devices
* @ko 입력 장치를 사용할 수 있게 한다
* @method eg.Axes.WheelInput#enable
* @return {eg.Axes.WheelInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.enable = function () {
this._isEnabled = true;
return this;
};
/**
* Disables input devices
* @ko 입력 장치를 사용할 수 없게 한다.
* @method eg.Axes.WheelInput#disable
* @return {eg.Axes.WheelInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.disable = function () {
this._isEnabled = false;
return this;
};
/**
* Returns whether to use an input device
* @ko 입력 장치를 사용 여부를 반환한다.
* @method eg.Axes.WheelInput#isEnable
* @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko>
*/
__proto.isEnable = function () {
return this._isEnabled;
};
return WheelInput;
}();
var KEY_LEFT_ARROW = 37;
var KEY_A = 65;
var KEY_UP_ARROW = 38;
var KEY_W = 87;
var KEY_RIGHT_ARROW = 39;
var KEY_D = 68;
var KEY_DOWN_ARROW = 40;
var KEY_S = 83;
var DIRECTION_REVERSE = -1;
var DIRECTION_FORWARD = 1;
var DIRECTION_HORIZONTAL$1 = -1;
var DIRECTION_VERTICAL$1 = 1;
var DELAY = 80;
/**
* @typedef {Object} MoveKeyInputOption The option object of the eg.Axes.MoveKeyInput module
* @ko eg.Axes.MoveKeyInput 모듈의 옵션 객체
* @property {Array<Number>} [scale] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko>
* @property {Number} [scale[0]=1] Coordinate scale for the first axis<ko>첫번째 축의 배율</ko>
* @property {Number} [scale[1]=1] Coordinate scale for the decond axis<ko>두번째 축의 배율</ko>
**/
/**
* @class eg.Axes.MoveKeyInput
* @classdesc A module that passes the amount of change to eg.Axes when the move key stroke is occured. use two axis.
* @ko 이동키 입력이 발생했을 때의 변화량을 eg.Axes에 전달하는 모듈. 두 개 의 축을 사용한다.
*
* @example
* const moveKey = new eg.Axes.MoveKeyInput("#area", {
* scale: [1, 1]
* });
*
* // Connect 'x', 'y' axes when the moveKey is pressed.
* axes.connect(["x", "y"], moveKey);
*
* @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.MoveKeyInput module <ko>eg.Axes.MoveKeyInput 모듈을 사용할 엘리먼트</ko>
* @param {MoveKeyInputOption} [options] The option object of the eg.Axes.MoveKeyInput module<ko>eg.Axes.MoveKeyInput 모듈의 옵션 객체</ko>
*/
var MoveKeyInput =
/*#__PURE__*/
function () {
function MoveKeyInput(el, options) {
this.axes = [];
this.element = null;
this._isEnabled = false;
this._isHolded = false;
this._timer = null;
this.element = $(el);
this.options = __assign({
scale: [1, 1]
}, options);
this.onKeydown = this.onKeydown.bind(this);
this.onKeyup = this.onKeyup.bind(this);
}
var __proto = MoveKeyInput.prototype;
__proto.mapAxes = function (axes) {
this.axes = axes;
};
__proto.connect = function (observer) {
this.dettachEvent(); // add tabindex="0" to the container for making it focusable
if (this.element.getAttribute("tabindex") !== "0") {
this.element.setAttribute("tabindex", "0");
}
this.attachEvent(observer);
return this;
};
__proto.disconnect = function () {
this.dettachEvent();
return this;
};
/**
* Destroys elements, properties, and events used in a module.
* @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다.
* @method eg.Axes.MoveKeyInput#destroy
*/
__proto.destroy = function () {
this.disconnect();
this.element = null;
};
__proto.onKeydown = function (e) {
if (!this._isEnabled) {
return;
}
var isMoveKey = true;
var direction = DIRECTION_FORWARD;
var move = DIRECTION_HORIZONTAL$1;
switch (e.keyCode) {
case KEY_LEFT_ARROW:
case KEY_A:
direction = DIRECTION_REVERSE;
break;
case KEY_RIGHT_ARROW:
case KEY_D:
break;
case KEY_DOWN_ARROW:
case KEY_S:
direction = DIRECTION_REVERSE;
move = DIRECTION_VERTICAL$1;
break;
case KEY_UP_ARROW:
case KEY_W:
move = DIRECTION_VERTICAL$1;
break;
default:
isMoveKey = false;
}
if (move === DIRECTION_HORIZONTAL$1 && !this.axes[0] || move === DIRECTION_VERTICAL$1 && !this.axes[1]) {
isMoveKey = false;
}
if (!isMoveKey) {
return;
}
var offsets = move === DIRECTION_HORIZONTAL$1 ? [+this.options.scale[0] * direction, 0] : [0, +this.options.scale[1] * direction];
if (!this._isHolded) {
this.observer.hold(this, event);
this._isHolded = true;
}
clearTimeout(this._timer);
this.observer.change(this, event, toAxis(this.axes, offsets));
};
__proto.onKeyup = function (e) {
var _this = this;
if (!this._isHolded) {
return;
}
clearTimeout(this._timer);
this._timer = setTimeout(function () {
_this.observer.release(_this, e, toAxis(_this.axes, [0, 0]));
_this._isHolded = false;
}, DELAY);
};
__proto.attachEvent = function (observer) {
this.observer = observer;
this.element.addEventListener("keydown", this.onKeydown, false);
this.element.addEventListener("keypress", this.onKeydown, false);
this.element.addEventListener("keyup", this.onKeyup, false);
this._isEnabled = true;
};
__proto.dettachEvent = function () {
this.element.removeEventListener("keydown", this.onKeydown, false);
this.element.removeEventListener("keypress", this.onKeydown, false);
this.element.removeEventListener("keyup", this.onKeyup, false);
this._isEnabled = false;
this.observer = null;
};
/**
* Enables input devices
* @ko 입력 장치를 사용할 수 있게 한다
* @method eg.Axes.MoveKeyInput#enable
* @return {eg.Axes.MoveKeyInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.enable = function () {
this._isEnabled = true;
return this;
};
/**
* Disables input devices
* @ko 입력 장치를 사용할 수 없게 한다.
* @method eg.Axes.MoveKeyInput#disable
* @return {eg.Axes.MoveKeyInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.disable = function () {
this._isEnabled = false;
return this;
};
/**
* Returns whether to use an input device
* @ko 입력 장치를 사용 여부를 반환한다.
* @method eg.Axes.MoveKeyInput#isEnable
* @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko>
*/
__proto.isEnable = function () {
return this._isEnabled;
};
return MoveKeyInput;
}();
Axes.PanInput = PanInput;
Axes.PinchInput = PinchInput;
Axes.WheelInput = WheelInput;
Axes.MoveKeyInput = MoveKeyInput;
return Axes;
})));
//# sourceMappingURL=axes.pkgd.js.map
|
!function(e,_){"object"==typeof exports&&"undefined"!=typeof module?module.exports=_(require("dayjs")):"function"==typeof define&&define.amd?define(["dayjs"],_):e.dayjs_locale_it_ch=_(e.dayjs)}(this,function(e){"use strict";e=e&&e.hasOwnProperty("default")?e.default:e;var _={name:"it-ch",weekdays:"domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato".split("_"),months:"gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre".split("_"),weekStart:1,weekdaysShort:"dom_lun_mar_mer_gio_ven_sab".split("_"),monthsShort:"gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic".split("_"),weekdaysMin:"do_lu_ma_me_gi_ve_sa".split("_"),ordinal:function(e){return e}};return e.locale(_,null,!0),_});
|
/**! Qoopido.demand 5.2.0-rc.5 | https://github.com/dlueth/qoopido.demand | (c) 2018 Dirk Lueth */
!function(){"use strict";provide(["/demand/abstract/handler"],function(e){function t(){}var n=".html",r=/^text\/html/,o=document.createElement("body");return t.prototype={validate:function(e){return r.test(e)},onPreRequest:function(e){var t=e.url.pathname;e.url.pathname=t.slice(-n.length)!==n?t+n:t},process:function(e){provide(function(){return function(e){var t,n=document.createDocumentFragment();for(o.innerHTML=e;t=o.firstElementChild;)n.appendChild(t);return n}(e.source)})}},new(t.extends(e))})}();
//# sourceMappingURL=html.js.map
|
!function(e,_){"object"==typeof exports&&"undefined"!=typeof module?module.exports=_(require("dayjs")):"function"==typeof define&&define.amd?define(["dayjs"],_):e.dayjs_locale_de_ch=_(e.dayjs)}(this,function(e){"use strict";e=e&&e.hasOwnProperty("default")?e.default:e;var _={name:"de-ch",weekdays:"Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"),months:"Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"),weekStart:1,weekdaysShort:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),monthsShort:"Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.".split("_"),weekdaysMin:"So_Mo_Di_Mi_Do_Fr_Sa".split("_"),ordinal:function(e){return e}};return e.locale(_,null,!0),_});
|
/*!
* Start Bootstrap - Creative v5.1.2 (https://startbootstrap.com/template-overviews/creative)
* Copyright 2013-2019 Start Bootstrap
* Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-creative/blob/master/LICENSE)
*/
!function(e){"use strict";e('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function(){if(location.pathname.replace(/^\//,"")==this.pathname.replace(/^\//,"")&&location.hostname==this.hostname){var a=e(this.hash);if((a=a.length?a:e("[name="+this.hash.slice(1)+"]")).length)return e("html, body").animate({scrollTop:a.offset().top-72},1e3,"easeInOutExpo"),!1}}),e(".js-scroll-trigger").click(function(){e(".navbar-collapse").collapse("hide")}),e("body").scrollspy({target:"#mainNav",offset:75});var a=function(){100<e("#mainNav").offset().top?e("#mainNav").addClass("navbar-scrolled"):e("#mainNav").removeClass("navbar-scrolled")};a(),e(window).scroll(a),e("#portfolio").magnificPopup({delegate:"a",type:"image",tLoading:"Loading image #%curr%...",mainClass:"mfp-img-mobile",gallery:{enabled:!0,navigateByImgClick:!0,preload:[0,1]},image:{tError:'<a href="%url%">The image #%curr%</a> could not be loaded.'}})}(jQuery);
|
const ContainerBuilder = require("@enhavo/dependency-injection/container/ContainerBuilder");
class ContainerBuilderBucket
{
constructor() {
/** @type {Entry[]} */
this.entries = [];
this.current = null;
}
createBuilder(name) {
if (this.hasBuilder(name)) {
return this.getBuilder(name);
}
this.entries.push(new Entry(name, new ContainerBuilder()));
this.setCurrentBuilder(name);
return this.getCurrentBuilder();
}
setCurrentBuilder(name) {
this.current = name;
}
getCurrentBuilder() {
return this.getBuilder(this.current);
}
getCurrentName() {
return this.current;
}
hasBuilder(name) {
for (let entry of this.entries) {
if (entry.name === name) {
return true;
}
}
return false;
}
getBuilder(name) {
for (let entry of this.entries) {
if (entry.name === name) {
return entry.builder;
}
}
throw 'Can\'t find any builder'
}
}
class Entry
{
constructor(name, builder) {
/** @type {string} */
this.name = name;
/** @type {ContainerBuilder} */
this.builder = builder;
}
}
module.exports = ContainerBuilderBucket;
|
var theme_infographic = {
// 默认色板
color: [
'#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
'#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
'#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
],
// 图表标题
title: {
itemGap: 8,
textStyle: {
fontWeight: 'normal',
color: '#27727B' // 主标题文字颜色
}
},
// 图例
legend: {
itemGap: 8
},
// 值域
dataRange: {
x:'right',
y:'center',
itemWidth: 5,
itemHeight:25,
color:['#C1232B','#FCCE10']
},
toolbox: {
color : [
'#C1232B','#B5C334','#FCCE10','#E87C25','#27727B',
'#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
],
effectiveColor : '#ff4500',
itemGap: 8
},
// 提示框
tooltip: {
backgroundColor: 'rgba(50,50,50,0.5)', // 提示背景颜色,默认为透明度为0.7的黑色
axisPointer : { // 坐标轴指示器,坐标轴触发有效
type : 'line', // 默认为直线,可选为:'line' | 'shadow'
lineStyle : { // 直线指示器样式设置
color: '#27727B',
type: 'dashed'
},
crossStyle: {
color: '#27727B'
},
shadowStyle : { // 阴影指示器样式设置
color: 'rgba(200,200,200,0.3)'
}
}
},
// 区域缩放控制器
dataZoom: {
dataBackgroundColor: 'rgba(181,195,52,0.3)', // 数据背景颜色
fillerColor: 'rgba(181,195,52,0.2)', // 填充颜色
handleColor: '#27727B', // 手柄颜色
},
// 网格
grid: {
borderWidth:0
},
// 类目轴
categoryAxis: {
axisLine: { // 坐标轴线
lineStyle: { // 属性lineStyle控制线条样式
color: '#27727B'
}
},
splitLine: { // 分隔线
show: false
}
},
// 数值型坐标轴默认参数
valueAxis: {
axisLine: { // 坐标轴线
show: false
},
splitArea : {
show: false
},
splitLine: { // 分隔线
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: ['#ccc'],
type: 'dashed'
}
}
},
polar : {
axisLine: { // 坐标轴线
lineStyle: { // 属性lineStyle控制线条样式
color: '#ddd'
}
},
splitArea : {
show : true,
areaStyle : {
color: ['rgba(250,250,250,0.2)','rgba(200,200,200,0.2)']
}
},
splitLine : {
lineStyle : {
color : '#ddd'
}
}
},
timeline : {
lineStyle : {
color : '#27727B'
},
controlStyle : {
normal : { color : '#27727B'},
emphasis : { color : '#27727B'}
},
symbol : 'emptyCircle',
symbolSize : 3
},
// 柱形图默认参数
bar: {
itemStyle: {
normal: {
barBorderRadius: 0
},
emphasis: {
barBorderRadius: 0
}
}
},
// 折线图默认参数
line: {
itemStyle: {
normal: {
borderWidth:2,
borderColor:'#fff',
lineStyle: {
width: 3
}
},
emphasis: {
borderWidth:0
}
},
symbol: 'circle', // 拐点图形类型
symbolSize: 3.5 // 拐点图形大小
},
// K线图默认参数
k: {
itemStyle: {
normal: {
color: '#C1232B', // 阳线填充颜色
color0: '#B5C334', // 阴线填充颜色
lineStyle: {
width: 1,
color: '#C1232B', // 阳线边框颜色
color0: '#B5C334' // 阴线边框颜色
}
}
}
},
// 散点图默认参数
scatter: {
itemdStyle: {
normal: {
borderWidth:1,
borderColor:'rgba(200,200,200,0.5)'
},
emphasis: {
borderWidth:0
}
},
symbol: 'star4', // 图形类型
symbolSize: 4 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
},
// 雷达图默认参数
radar : {
symbol: 'emptyCircle', // 图形类型
symbolSize:3
//symbol: null, // 拐点图形类型
//symbolRotate : null, // 图形旋转控制
},
map: {
itemStyle: {
normal: {
areaStyle: {
color: '#ddd'
},
label: {
textStyle: {
color: '#C1232B'
}
}
},
emphasis: { // 也是选中样式
areaStyle: {
color: '#fe994e'
},
label: {
textStyle: {
color: 'rgb(100,0,0)'
}
}
}
}
},
force : {
itemStyle: {
normal: {
linkStyle : {
strokeColor : '#27727B'
}
}
}
},
chord : {
padding : 4,
itemStyle : {
normal : {
lineStyle : {
width : 1,
color : 'rgba(128, 128, 128, 0.5)'
},
chordStyle : {
lineStyle : {
width : 1,
color : 'rgba(128, 128, 128, 0.5)'
}
}
},
emphasis : {
lineStyle : {
width : 1,
color : 'rgba(128, 128, 128, 0.5)'
},
chordStyle : {
lineStyle : {
width : 1,
color : 'rgba(128, 128, 128, 0.5)'
}
}
}
}
},
gauge : {
center:['50%','80%'],
radius:'100%',
startAngle: 180,
endAngle : 0,
axisLine: { // 坐标轴线
show: true, // 默认显示,属性show控制显示与否
lineStyle: { // 属性lineStyle控制线条样式
color: [[0.2, '#B5C334'],[0.8, '#27727B'],[1, '#C1232B']],
width: '40%'
}
},
axisTick: { // 坐标轴小标记
splitNumber: 2, // 每份split细分多少段
length: 5, // 属性length控制线长
lineStyle: { // 属性lineStyle控制线条样式
color: '#fff'
}
},
axisLabel: { // 坐标轴文本标签,详见axis.axisLabel
textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE
color: '#fff',
fontWeight:'bolder'
}
},
splitLine: { // 分隔线
length: '5%', // 属性length控制线长
lineStyle: { // 属性lineStyle(详见lineStyle)控制线条样式
color: '#fff'
}
},
pointer : {
width : '40%',
length: '80%',
color: '#fff'
},
title : {
offsetCenter: [0, -20], // x, y,单位px
textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE
color: 'auto',
fontSize: 20
}
},
detail : {
offsetCenter: [0, 00], // x, y,单位px
textStyle: { // 其余属性默认使用全局文本样式,详见TEXTSTYLE
color: 'auto',
fontSize: 40
}
}
},
textStyle: {
fontFamily: '微软雅黑, Arial, Verdana, sans-serif'
}
}
|
var parent = require('../../actual/typed-array/fill');
module.exports = parent;
|
/*
* html2canvas v0.25 <http://html2canvas.hertzen.com>
* Copyright (c) 2011 Niklas von Hertzen. All rights reserved.
* http://www.twitter.com/niklasvh
*
* Released under MIT License
*/
/*
* The MIT License
* 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.
*/
/*
* jQuery helper plugin for examples and tests
*/
(function( $ ){
$.fn.html2canvas = function(options) {
var date = new Date();
var message,
timeoutTimer,
timer = date.getTime();
var object = $.extend({},{
logging: false,
proxyUrl: "http://html2canvas.appspot.com/", // running html2canvas-python proxy
ready: function(renderer) {
var finishTime = new Date();
// console.log((finishTime.getTime()-timer)/1000);
document.body.appendChild(renderer.canvas);
var canvas = $(renderer.canvas);
canvas.css('position','absolute')
.css('left',0).css('top',0);
// $('body').append(canvas);
$(canvas).siblings().toggle();
throwMessage('Screenshot created in '+ ((finishTime.getTime()-timer)/1000) + " seconds<br />Total of "+renderer.numDraws+" draws performed",4000);
$(window).click(function(){
if (!canvas.is(':visible')){
$(canvas).toggle().siblings().toggle();
throwMessage("Canvas Render visible");
} else{
$(canvas).siblings().toggle();
$(canvas).toggle();
throwMessage("Canvas Render hidden");
}
});
}
},options)
new html2canvas(this.get(0), object);
function throwMessage(msg,duration){
window.clearTimeout(timeoutTimer);
timeoutTimer = window.setTimeout(function(){
message.fadeOut(function(){
message.remove();
});
},duration || 2000);
$(message).remove();
message = $('<div />').html(msg).css({
margin:0,
padding:10,
background: "#000",
opacity:0.7,
position:"fixed",
top:10,
right:10,
fontFamily: 'Tahoma' ,
color:'#fff',
fontSize:12,
borderRadius:12,
width:'auto',
height:'auto',
textAlign:'center',
textDecoration:'none'
}).hide().fadeIn().appendTo('body');
}
};
})( jQuery );
|
import {Router} from 'aurelia-router';
import bootstrap from 'bootstrap';
export class App {
static inject() { return [Router]; }
constructor(router) {
this.router = router;
this.router.configure(config => {
config.title = 'Aurelia';
config.map([
{ route: ['','welcome'], moduleId: 'welcome', nav: true, title:'Welcome' },
{ route: 'flickr', moduleId: 'flickr', nav: true },
{ route: 'child-router', moduleId: 'child-router', nav: true, title:'Child Router' }
]);
});
}
}
|
import {create} from "ember-metal/platform";
import {get} from "ember-metal/property_get";
import run from "ember-metal/run_loop";
import ObjectProxy from "ember-runtime/system/object_proxy";
import PromiseProxyMixin from "ember-runtime/mixins/promise_proxy";
import EmberRSVP from "ember-runtime/ext/rsvp";
var RSVP = requireModule("rsvp"); // jshint ignore:line
var ObjectPromiseProxy;
test("present on ember namespace", function(){
ok(PromiseProxyMixin, "expected PromiseProxyMixin to exist");
});
QUnit.module("Ember.PromiseProxy - ObjectProxy", {
setup: function() {
ObjectPromiseProxy = ObjectProxy.extend(PromiseProxyMixin);
}
});
test("no promise, invoking then should raise", function(){
var proxy = ObjectPromiseProxy.create();
raises(function(){
proxy.then(function() { return this; }, function() { return this; });
}, new RegExp("PromiseProxy's promise must be set"));
});
test("fulfillment", function(){
var value = {
firstName: 'stef',
lastName: 'penner'
};
var deferred = RSVP.defer();
var proxy = ObjectPromiseProxy.create({
promise: deferred.promise
});
var didFulfillCount = 0;
var didRejectCount = 0;
proxy.then(function(){
didFulfillCount++;
}, function(){
didRejectCount++;
});
equal(get(proxy, 'content'), undefined, 'expects the proxy to have no content');
equal(get(proxy, 'reason'), undefined, 'expects the proxy to have no reason');
equal(get(proxy, 'isPending'), true, 'expects the proxy to indicate that it is loading');
equal(get(proxy, 'isSettled'), false, 'expects the proxy to indicate that it is not settled');
equal(get(proxy, 'isRejected'), false, 'expects the proxy to indicate that it is not rejected');
equal(get(proxy, 'isFulfilled'), false, 'expects the proxy to indicate that it is not fulfilled');
equal(didFulfillCount, 0, 'should not yet have been fulfilled');
equal(didRejectCount, 0, 'should not yet have been rejected');
run(deferred, 'resolve', value);
equal(didFulfillCount, 1, 'should have been fulfilled');
equal(didRejectCount, 0, 'should not have been rejected');
equal(get(proxy, 'content'), value, 'expects the proxy to have content');
equal(get(proxy, 'reason'), undefined, 'expects the proxy to still have no reason');
equal(get(proxy, 'isPending'), false, 'expects the proxy to indicate that it is no longer loading');
equal(get(proxy, 'isSettled'), true, 'expects the proxy to indicate that it is settled');
equal(get(proxy, 'isRejected'), false, 'expects the proxy to indicate that it is not rejected');
equal(get(proxy, 'isFulfilled'), true, 'expects the proxy to indicate that it is fulfilled');
run(deferred, 'resolve', value);
equal(didFulfillCount, 1, 'should still have been only fulfilled once');
equal(didRejectCount, 0, 'should still not have been rejected');
run(deferred, 'reject', value);
equal(didFulfillCount, 1, 'should still have been only fulfilled once');
equal(didRejectCount, 0, 'should still not have been rejected');
equal(get(proxy, 'content'), value, 'expects the proxy to have still have same content');
equal(get(proxy, 'reason'), undefined, 'expects the proxy still to have no reason');
equal(get(proxy, 'isPending'), false, 'expects the proxy to indicate that it is no longer loading');
equal(get(proxy, 'isSettled'), true, 'expects the proxy to indicate that it is settled');
equal(get(proxy, 'isRejected'), false, 'expects the proxy to indicate that it is not rejected');
equal(get(proxy, 'isFulfilled'), true, 'expects the proxy to indicate that it is fulfilled');
// rest of the promise semantics are tested in directly in RSVP
});
test("rejection", function(){
var reason = new Error("failure");
var deferred = RSVP.defer();
var proxy = ObjectPromiseProxy.create({
promise: deferred.promise
});
var didFulfillCount = 0;
var didRejectCount = 0;
proxy.then(function(){
didFulfillCount++;
}, function(){
didRejectCount++;
});
equal(get(proxy, 'content'), undefined, 'expects the proxy to have no content');
equal(get(proxy, 'reason'), undefined, 'expects the proxy to have no reason');
equal(get(proxy, 'isPending'), true, 'expects the proxy to indicate that it is loading');
equal(get(proxy, 'isSettled'), false, 'expects the proxy to indicate that it is not settled');
equal(get(proxy, 'isRejected'), false, 'expects the proxy to indicate that it is not rejected');
equal(get(proxy, 'isFulfilled'), false, 'expects the proxy to indicate that it is not fulfilled');
equal(didFulfillCount, 0, 'should not yet have been fulfilled');
equal(didRejectCount, 0, 'should not yet have been rejected');
run(deferred, 'reject', reason);
equal(didFulfillCount, 0, 'should not yet have been fulfilled');
equal(didRejectCount, 1, 'should have been rejected');
equal(get(proxy, 'content'), undefined, 'expects the proxy to have no content');
equal(get(proxy, 'reason'), reason, 'expects the proxy to have a reason');
equal(get(proxy, 'isPending'), false, 'expects the proxy to indicate that it is not longer loading');
equal(get(proxy, 'isSettled'), true, 'expects the proxy to indicate that it is settled');
equal(get(proxy, 'isRejected'), true, 'expects the proxy to indicate that it is rejected');
equal(get(proxy, 'isFulfilled'), false, 'expects the proxy to indicate that it is not fulfilled');
run(deferred, 'reject', reason);
equal(didFulfillCount, 0, 'should stll not yet have been fulfilled');
equal(didRejectCount, 1, 'should still remain rejected');
run(deferred, 'resolve', 1);
equal(didFulfillCount, 0, 'should stll not yet have been fulfilled');
equal(didRejectCount, 1, 'should still remain rejected');
equal(get(proxy, 'content'), undefined, 'expects the proxy to have no content');
equal(get(proxy, 'reason'), reason, 'expects the proxy to have a reason');
equal(get(proxy, 'isPending'), false, 'expects the proxy to indicate that it is not longer loading');
equal(get(proxy, 'isSettled'), true, 'expects the proxy to indicate that it is settled');
equal(get(proxy, 'isRejected'), true, 'expects the proxy to indicate that it is rejected');
equal(get(proxy, 'isFulfilled'), false, 'expects the proxy to indicate that it is not fulfilled');
});
test("unhandled rejects still propogate to RSVP.on('error', ...) ", function(){
expect(1);
RSVP.on('error', onerror);
RSVP.off('error', RSVP.onerrorDefault);
var expectedReason = new Error("failure");
var deferred = RSVP.defer();
var proxy = ObjectPromiseProxy.create({
promise: deferred.promise
});
proxy.get('promise');
function onerror(reason) {
equal(reason, expectedReason, 'expected reason');
}
RSVP.on('error', onerror);
RSVP.off('error', RSVP.onerrorDefault);
run(deferred, 'reject', expectedReason);
RSVP.on('error', RSVP.onerrorDefault);
RSVP.off('error', onerror);
run(deferred, 'reject', expectedReason);
RSVP.on('error', RSVP.onerrorDefault);
RSVP.off('error', onerror);
});
test("should work with promise inheritance", function(){
function PromiseSubclass() {
RSVP.Promise.apply(this, arguments);
}
PromiseSubclass.prototype = create(RSVP.Promise.prototype);
PromiseSubclass.prototype.constructor = PromiseSubclass;
PromiseSubclass.cast = RSVP.Promise.cast;
var proxy = ObjectPromiseProxy.create({
promise: new PromiseSubclass(function(){ })
});
ok(proxy.then() instanceof PromiseSubclass, 'promise proxy respected inheritence');
});
test("should reset isFulfilled and isRejected when promise is reset", function() {
var deferred = EmberRSVP.defer();
var proxy = ObjectPromiseProxy.create({
promise: deferred.promise
});
equal(get(proxy, 'isPending'), true, 'expects the proxy to indicate that it is loading');
equal(get(proxy, 'isSettled'), false, 'expects the proxy to indicate that it is not settled');
equal(get(proxy, 'isRejected'), false, 'expects the proxy to indicate that it is not rejected');
equal(get(proxy, 'isFulfilled'), false, 'expects the proxy to indicate that it is not fulfilled');
run(deferred, 'resolve');
equal(get(proxy, 'isPending'), false, 'expects the proxy to indicate that it is no longer loading');
equal(get(proxy, 'isSettled'), true, 'expects the proxy to indicate that it is settled');
equal(get(proxy, 'isRejected'), false, 'expects the proxy to indicate that it is not rejected');
equal(get(proxy, 'isFulfilled'), true, 'expects the proxy to indicate that it is fulfilled');
var anotherDeferred = EmberRSVP.defer();
proxy.set('promise', anotherDeferred.promise);
equal(get(proxy, 'isPending'), true, 'expects the proxy to indicate that it is loading');
equal(get(proxy, 'isSettled'), false, 'expects the proxy to indicate that it is not settled');
equal(get(proxy, 'isRejected'), false, 'expects the proxy to indicate that it is not rejected');
equal(get(proxy, 'isFulfilled'), false, 'expects the proxy to indicate that it is not fulfilled');
run(anotherDeferred, 'reject');
equal(get(proxy, 'isPending'), false, 'expects the proxy to indicate that it is not longer loading');
equal(get(proxy, 'isSettled'), true, 'expects the proxy to indicate that it is settled');
equal(get(proxy, 'isRejected'), true, 'expects the proxy to indicate that it is rejected');
equal(get(proxy, 'isFulfilled'), false, 'expects the proxy to indicate that it is not fulfilled');
});
test("should have content when isFulfilled is set", function() {
var deferred = EmberRSVP.defer();
var proxy = ObjectPromiseProxy.create({
promise: deferred.promise
});
proxy.addObserver('isFulfilled', function() {
equal(get(proxy, 'content'), true);
});
run(deferred, 'resolve', true);
});
test("should have reason when isRejected is set", function() {
var error = new Error('Y U REJECT?!?');
var deferred = EmberRSVP.defer();
var proxy = ObjectPromiseProxy.create({
promise: deferred.promise
});
proxy.addObserver('isRejected', function() {
equal(get(proxy, 'reason'), error);
});
try {
run(deferred, 'reject', error);
} catch(e) {
equal(e, error);
}
});
|
import Ember from 'ember';
import DroppableMixin from 'client/mixins/droppable';
const { computed } = Ember;
export default Ember.Component.extend(DroppableMixin, {
files: [],
progress: '',
filesPresent: computed('files.length', function() {
return `You have ${this.get('files.length')} file(s) ready to upload.`;
}).readOnly(),
total: 0,
// expand this module so that it waits
uploadFiles() {
var uploaded = 0;
var files = this.get('files');
var total = this.get('total') + files.length;
this.set('total', total);
var uploader = this.fileUploader;
uploader.url = this.get('url');
uploader.paramName = 'upload';
var uploadRecord = {};
uploadRecord[this.get('type')] = JSON.stringify(this.get('record')._attributes);
if (!Ember.isEmpty(files)) {
uploader.upload(files, uploadRecord);
}
// uploader.on('progress', function(e) {
// Handle progress changes
// Use `e.percent` to get percentag
// TODO this no longer makes sense till i can make individual file progress bars
// $('.upload-progress').html(e.percent + '%');
// });
uploader.on('didUpload', (e) => {
// Handle finished upload
uploaded++;
console.log('total down', total);
console.log(e);
this.set('progress', `Upload ${uploaded} of ${total} finished`);
this.set('files', []);
});
},
drop(e) {
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault();
var files = e.dataTransfer.files;
this.set('files', files);
},
actions: {
upload() {
this.uploadFiles();
}
}
});
|
describe('Image', function() {
var image
beforeEach(function() {
image = draw.image(imageUrl, 100, 100)
})
afterEach(function() {
draw.clear()
})
describe('x()', function() {
it('should return the value of x without an argument', function() {
expect(image.x()).toBe(0)
})
it('should set the value of x with the first argument', function() {
image.x(123)
var box = image.bbox()
expect(box.x).toBe(123)
})
})
describe('y()', function() {
it('should return the value of y without an argument', function() {
expect(image.y()).toBe(0)
})
it('should set the value of y with the first argument', function() {
image.y(345)
var box = image.bbox()
expect(box.y).toBe(345)
})
})
describe('cx()', function() {
it('should return the value of cx without an argument', function() {
expect(image.cx()).toBe(50)
})
it('should set the value of cx with the first argument', function() {
image.cx(123)
var box = image.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('should return the value of cy without an argument', function() {
expect(image.cy()).toBe(50)
})
it('should set the value of cy with the first argument', function() {
image.cy(345)
var box = image.bbox()
expect(box.cy).toBe(345)
})
})
describe('move()', function() {
it('should set the x and y position', function() {
image.move(123,456)
expect(image.node.getAttribute('x')).toBe('123')
expect(image.node.getAttribute('y')).toBe('456')
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
image.move(50,60)
image.dx(100)
expect(image.node.getAttribute('x')).toBe('150')
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
image.move(50,60)
image.dy(120)
expect(image.node.getAttribute('y')).toBe('180')
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
image.move(50,60)
image.dmove(80, 25)
expect(image.node.getAttribute('x')).toBe('130')
expect(image.node.getAttribute('y')).toBe('85')
})
})
describe('center()', function() {
it('should set the cx and cy position', function() {
image.center(321,567)
var box = image.bbox()
expect(box.cx).toBe(321)
expect(box.cy).toBe(567)
})
})
describe('width()', function() {
it('sets the width of the element', function() {
image.width(789)
expect(image.node.getAttribute('width')).toBe('789')
})
it('gets the width of the element if the argument is null', function() {
expect(image.width().toString()).toBe(image.node.getAttribute('width'))
})
})
describe('height()', function() {
it('sets the height of the element', function() {
image.height(1236)
expect(image.node.getAttribute('height')).toBe('1236')
})
it('gets the height of the element if the argument is null', function() {
expect(image.height().toString()).toBe(image.node.getAttribute('height'))
})
})
describe('size()', function() {
it('should define the width and height of the element', function() {
image.size(987,654)
expect(image.node.getAttribute('width')).toBe('987')
expect(image.node.getAttribute('height')).toBe('654')
})
it('defines the width and height proportionally with only the width value given', function() {
var box = image.bbox()
image.size(500)
expect(image.width()).toBe(500)
expect(image.width() / image.height()).toBe(box.width / box.height)
})
it('defines the width and height proportionally with only the height value given', function() {
var box = image.bbox()
image.size(null, 525)
expect(image.height()).toBe(525)
expect(image.width() / image.height()).toBe(box.width / box.height)
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box = image.scale(2).bbox()
expect(box.width).toBe(image.attr('width') * 2)
expect(box.height).toBe(image.attr('height') * 2)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box = image.scale(2, 3.5).bbox()
expect(box.width).toBe(image.attr('width') * 2)
expect(box.height).toBe(image.attr('height') * 3.5)
})
})
describe('translate()', function() {
it('should set the translation of an element', function() {
image.transform({ x: 12, y: 12 })
expect(image.node.getAttribute('transform')).toBe('translate(12 12)')
})
})
})
|
var docker = require('docker-browser-console')
var websocket = require('websocket-stream')
var pump = require('pump')
var url = require('url')
var u = url.parse(location.toString(), true)
var terminal = docker()
var url = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host+'/'+(u.query.id || '')
pump(terminal, websocket(url), terminal)
terminal.appendTo(document.getElementById('console'))
|
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);
};
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { OverlayModule, CompatibilityModule } from '../core';
import { MdMenu } from './menu-directive';
import { MdMenuItem } from './menu-item';
import { MdMenuTrigger } from './menu-trigger';
import { MdRippleModule } from '../core/ripple/ripple';
export { MdMenu } from './menu-directive';
export { MdMenuItem } from './menu-item';
export { MdMenuTrigger } from './menu-trigger';
export var MdMenuModule = (function () {
function MdMenuModule() {
}
/** @deprecated */
MdMenuModule.forRoot = function () {
return {
ngModule: MdMenuModule,
providers: [],
};
};
MdMenuModule = __decorate([
NgModule({
imports: [OverlayModule, CommonModule, MdRippleModule, CompatibilityModule],
exports: [MdMenu, MdMenuItem, MdMenuTrigger, CompatibilityModule],
declarations: [MdMenu, MdMenuItem, MdMenuTrigger],
}),
__metadata('design:paramtypes', [])
], MdMenuModule);
return MdMenuModule;
}());
//# sourceMappingURL=menu.js.map
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof exports !== "undefined") {
factory();
} else {
var mod = {
exports: {}
};
factory();
global.bootstrapTableFiFI = mod.exports;
}
})(this, function () {
'use strict';
/**
* Bootstrap Table Finnish translations
* Author: Minna Lehtomäki <minna.j.lehtomaki@gmail.com>
*/
(function ($) {
'use strict';
$.fn.bootstrapTable.locales['fi-FI'] = {
formatLoadingMessage: function formatLoadingMessage() {
return 'Ladataan, ole hyvä ja odota...';
},
formatRecordsPerPage: function formatRecordsPerPage(pageNumber) {
return pageNumber + ' riviä sivulla';
},
formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows) {
return 'Näytetään rivit ' + pageFrom + ' - ' + pageTo + ' / ' + totalRows;
},
formatSearch: function formatSearch() {
return 'Hae';
},
formatNoMatches: function formatNoMatches() {
return 'Hakuehtoja vastaavia tuloksia ei löytynyt';
},
formatPaginationSwitch: function formatPaginationSwitch() {
return 'Näytä/Piilota sivutus';
},
formatRefresh: function formatRefresh() {
return 'Päivitä';
},
formatToggle: function formatToggle() {
return 'Valitse';
},
formatColumns: function formatColumns() {
return 'Sarakkeet';
},
formatAllRows: function formatAllRows() {
return 'Kaikki';
},
formatExport: function formatExport() {
return 'Vie tiedot';
},
formatClearFilters: function formatClearFilters() {
return 'Poista suodattimet';
}
};
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['fi-FI']);
})(jQuery);
});
|
'use strict';
var YUITest = require('yuitest');
var Assert = YUITest.Assert;
var ArrayAssert = YUITest.ArrayAssert;
var path = require('path');
var fs = require('fs');
var Y = require(path.join(__dirname, '../', 'lib', 'index'));
//Move to the test dir before running the tests.
process.chdir(__dirname);
var existsSync = fs.existsSync || path.existsSync;
var suite = new YUITest.TestSuite({
name: 'Parser Test Suite',
setUp: function () {
process.chdir(__dirname);
var json = (new Y.YUIDoc({
quiet: true,
paths: [
'input/charts',
'input/inherit',
'input/namespace',
'input/test',
'input/test2'
],
outdir: './out'
})).run();
this.project = json.project;
this.data = json;
}
});
suite.add(new YUITest.TestCase({
name: 'Project Data',
setUp: function () {
this.project = suite.project;
this.data = suite.data;
},
findByName: function (name, cl) {
var items = this.data.classitems,
ret;
items.forEach(function (i) {
if (i.name === name && i.class === cl) {
ret = i;
}
});
return ret;
},
'test: out directory': function () {
Assert.isTrue(existsSync(path.join(__dirname, 'out')), 'Out directory was not created');
},
'test: data.json creation': function () {
Assert.isTrue(existsSync(path.join(__dirname, 'out', 'data.json')), 'data.json file was not created');
},
'test: parser': function () {
var keys = Object.keys(this.data);
Assert.areEqual(7, keys.length, 'Failed to populate all fields');
ArrayAssert.itemsAreSame(['project', 'files', 'modules', 'classes', 'elements', 'classitems', 'warnings'], keys, 'Object keys are wrong');
},
'test: project data': function () {
Assert.areSame(path.normalize('input/test/test.js'), this.project.file, 'Project data loaded from wrong file');
Assert.areSame(2, this.project.line, 'Line number is off');
Assert.areSame('The test project', this.project.description, 'Description not set properly');
Assert.areSame('The Tester', this.project.title, 'Title not set');
Assert.areSame('admo', this.project.author, 'Author not set');
Assert.areSame('entropy', this.project.contributor, 'Contributor not set');
Assert.areSame('http://a.img', this.project.icon[0], 'Icon not set');
Assert.areSame(1, this.project.icon.length, 'Found wring number of icons');
Assert.areSame(2, this.project.url.length, 'Found wrong number of urls');
Assert.areSame('http://one.url', this.project.url[0], 'URL #1 is wrong');
Assert.areSame('http://two.url', this.project.url[1], 'URL #2 is wrong');
},
'test: files parsing': function () {
var files = this.data.files,
one, two, three, four;
// 1 module, 3 classes
one = files[path.normalize('input/test/anim.js')];
Assert.isObject(one, 'Failed to parse input/test/anim.js');
Assert.areSame(1, Object.keys(one.modules).length, '1 module should be found');
Assert.areSame(3, Object.keys(one.classes).length, '3 classes should be found');
// 2 modules, 3 classes
two = files[path.normalize('input/test/test.js')];
Assert.isObject(two, 'Failed to parse input/test/test.js');
Assert.areSame(2, Object.keys(two.modules).length, '2 modules should be found');
Assert.areSame(3, Object.keys(two.classes).length, '3 classes should be found');
//Module -> class association
three = files[path.normalize('input/test2/dump/dump.js')];
Assert.isObject(three, 'Failed to parse input/test2/dump/dump.js');
Assert.areSame(1, three.modules.dump, 'dump module not found');
Assert.areSame(1, three.classes['YUI~dump'], 'YUI~dump class not found');
//Module -> class association
four = files[path.normalize('input/test2/oop/oop.js')];
Assert.isObject(four, 'Failed to parse input/test2/oop/oop.js');
Assert.areSame(1, four.modules.oop, 'oop module not found');
Assert.areSame(1, four.classes['YUI~oop'], 'YUI~oop class not found');
},
'test: namespace parsing': function () {
var item = this.data.files[path.normalize('input/test2/namespace.js')];
Assert.isObject(item, 'Failed to parse input/test2/namespace.js');
Assert.areSame(3, Object.keys(item.classes).length, 'Failed to parse all classes');
ArrayAssert.itemsAreSame(['P.storage', 'P'], Object.keys(item.namespaces), 'Namespace failed to parse');
ArrayAssert.itemsAreSame(['P.storage.Store', 'P.storage.LocalStore', 'P.storage'], Object.keys(item.classes), 'Classes failed to parse');
},
'test: module parsing': function () {
var mods = this.data.modules;
//anim Module
Assert.isObject(mods.anim, 'Failed to parse Anim module');
Assert.areSame(2, Object.keys(mods.anim.submodules).length, 'Should have 2 submodules');
Assert.areSame(3, Object.keys(mods.anim.classes).length, 'Should have 3 classes');
Assert.areSame('This is the Anim MODULE description', mods.anim.description, 'Description parse');
Assert.areSame('main', mods.anim.itemtype, 'Failed to parse @main itemtype');
Assert.areSame('module', mods.anim.tag, 'Tag parse failed');
},
'test: main module association': function () {
var mod = this.data.modules.charts,
d = 'The Charts widget provides an api for displaying data\ngraphically.';
Assert.isObject(mod, 'Failed to parse charts module');
Assert.areSame(d, mod.description, 'Incorrect description for charts module');
Assert.areSame('main', mod.tag, 'Tagname is not main');
Assert.areSame('main', mod.itemtype, 'ItemType should be main');
},
'test: submodule parsing': function () {
var mods = this.data.modules,
m, desc;
//anim-easing submodule
m = mods['anim-easing'];
Assert.isObject(m, 'Failed to parse anim-easing module');
desc = 'The easing module provides methods for customizing\nhow an animation behaves during each run.';
Assert.areSame(desc, m.description, 'Failed to parse submodule description');
Assert.areSame(0, Object.keys(m.submodules).length, 'Should have 0 submodules');
Assert.areSame(1, Object.keys(m.classes).length, 'Should have 1 class');
Assert.areSame(1, m.is_submodule, 'Submodule association failed');
Assert.areSame('anim', m.module, 'Failed to associate module');
//anim-easing-foo submodule
m = mods['anim-easing-foo'];
Assert.isObject(m, 'Failed to parse anim-easing-foo module');
desc = 'FOO FOO FOO FOO FOO The easing module provides methods for customizing';
Assert.areSame(desc, m.description, 'Failed to parse submodule description');
Assert.areSame(0, Object.keys(m.submodules).length, 'Should have 0 submodules');
Assert.areSame(1, Object.keys(m.classes).length, 'Should have 1 class');
Assert.areSame(1, m.is_submodule, 'Submodule association failed');
Assert.areSame('anim', m.module, 'Failed to associate module');
},
'test: extra module data parsing': function () {
var mods = this.data.modules,
m;
m = mods.mymodule;
Assert.isObject(m, 'Failed to parse mymodule module');
Assert.areSame(1, Object.keys(m.submodules).length, 'Should have 1 submodules');
Assert.areSame(3, Object.keys(m.classes).length, 'Should have 3 class');
Assert.areSame('The module', m.description, 'Description parse failed');
ArrayAssert.itemsAreSame(['one', 'two', 'three'], m.category, 'Category parsing failed');
ArrayAssert.itemsAreSame(['one', 'two'], m.requires, 'Requires parsing failed');
ArrayAssert.itemsAreSame(['three', 'four'], m.uses, 'Uses parsing failed');
m = mods.mysubmodule;
Assert.isObject(m, 'Failed to parse mysubmodule module');
Assert.areSame(0, Object.keys(m.submodules).length, 'Should have 0 submodules');
Assert.areSame(3, Object.keys(m.classes).length, 'Should have 3 class');
Assert.areSame(1, m.is_submodule, 'Submodule association failed');
ArrayAssert.itemsAreSame(['three', 'four'], m.category, 'Category parsing failed');
//Testing modules with slashes in them
m = mods['myapp/views/index'];
Assert.isObject(m, 'Failed to parse myapp/views/index module');
Assert.areSame(1, Object.keys(m.classes).length, 'Should have 1 class');
m = mods['P.storage'];
Assert.isObject(m, 'Failed to parse P.storage module');
ArrayAssert.itemsAreSame(['P.storage.Store', 'P.storage.LocalStore', 'P.storage'], Object.keys(m.classes), 'Failed to parse classes');
ArrayAssert.itemsAreSame(['P.storage', 'P'], Object.keys(m.namespaces), 'Namespace failed to parse');
},
'test: element parsing': function () {
var els = this.data.elements,
foo = els['x-foo'],
bar = els['x-bar'];
Assert.isObject(foo, 'Failed to find <x-foo> element');
Assert.areSame('x-foo', foo.name, 'Failed to set name');
Assert.areSame('anim', foo.module, 'Failed to set module');
Assert.isObject(bar, 'Failed to find <x-bar> element');
Assert.areSame('x-bar', bar.name, 'Failed to set name');
Assert.areSame('anim', bar.module, 'Failed to set module');
},
'test: element details parsing': function () {
var baz = this.data.elements['x-baz'];
Assert.isObject(baz, 'Failed to find <x-baz> element');
Assert.areSame('x-baz', baz.name, 'Failed to set name');
Assert.areSame('Element 3', baz.description, 'Failed to set description');
Assert.areSame('<body>, <x-foo>', baz.parents, 'Failed to set parents');
Assert.areSame('<x-bar>', baz.contents, 'Failed to set contents');
Assert.areSame('XBazElement', baz.interface, 'Failed to set interface');
},
'test: element attributes parsing': function () {
var baz = this.data.elements['x-baz'];
Assert.isObject(baz, 'Failed to find <x-baz> element');
Assert.areSame(3, baz.attributes.length, 'Failed to parse all the attributes');
Assert.areSame('first', baz.attributes[0].name, 'Failed to set first attribute name');
Assert.areSame('first attribute test', baz.attributes[0].description, 'Failed to set first attribute description');
Assert.areSame('second', baz.attributes[1].name, 'Failed to set second attribute name');
Assert.areSame('second attribute test', baz.attributes[1].description.replace(/\s+/g, ' '), 'Failed to set second attribute description');
Assert.areSame('third', baz.attributes[2].name, 'Failed to set third attribute name');
Assert.areSame('third attribute test', baz.attributes[2].description.replace(/\s+/g, ' '), 'Failed to set third attribute description');
},
'test: class parsing': function () {
var cl = this.data.classes,
anim, easing, my, other, m;
anim = cl.Anim;
Assert.isObject(anim, 'Failed to find Anim class');
Assert.areSame('Anim', anim.name, 'Failed to set name');
Assert.areSame('Anim', anim.shortname, 'Failed to set shortname');
Assert.areSame('anim', anim.module, 'Failed to test module.');
easing = cl.Easing;
Assert.isObject(easing, 'Failed to find Easing class');
Assert.areSame('Easing', easing.name, 'Failed to set name');
Assert.areSame('Easing', easing.shortname, 'Failed to set shortname');
Assert.areSame('anim', easing.module, 'Failed to test module.');
Assert.areSame('anim-easing', easing.submodule, 'Failed to test submodule.');
my = cl.myclass;
Assert.isObject(my, 'Failed to find myclass class');
Assert.areSame('myclass', my.name, 'Failed to set name');
Assert.areSame('myclass', my.shortname, 'Failed to set shortname');
Assert.areSame('mymodule', my.module, 'Failed to test module.');
Assert.areSame('mysubmodule', my.submodule, 'Failed to test submodule.');
Assert.areSame(1, my.is_constructor, 'Failed to register constructor.');
other = cl.OtherClass;
Assert.isObject(other, 'Failed to find myclass class');
Assert.areSame('OtherClass', other.name, 'Failed to set name');
Assert.areSame('OtherClass', other.shortname, 'Failed to set shortname');
Assert.areSame('mymodule', other.module, 'Failed to test module.');
Assert.areSame('mysubmodule', other.submodule, 'Failed to test submodule.');
Assert.areSame(1, Object.keys(other.extension_for).length, 'Failed to assign extension_for');
Assert.areSame('myclass', other.extension_for[0], 'Failed to assign extension_for');
m = cl['P.storage.P.storage'];
Assert.isUndefined(m, 'Should not have double namespaces');
Assert.isNotUndefined(cl['P.storage'], 'Should not have double namespaces');
Assert.isNotUndefined(cl['P.storage.Store'], 'Should not have double namespaces');
Assert.isNotUndefined(cl['P.storage.LocalStore'], 'Should not have double namespaces');
},
'test: classitems parsing': function () {
Assert.isArray(this.data.classitems, 'Failed to populate classitems array');
var keys, item, item2;
item = this.findByName('testoptional', 'myclass');
Assert.areSame('testoptional', item.name, 'Failed to find item: testoptional');
Assert.areSame('myclass', item.class, 'Failed to find class: testoptional');
Assert.areSame('mymodule', item.module, 'Failed to find module: testoptional');
Assert.areSame('mysubmodule', item.submodule, 'Failed to find submodule: testoptional');
Assert.areSame('method', item.itemtype, 'Should be a method');
keys = [
'file',
'line',
'description',
'itemtype',
'name',
'params',
'evil',
'injects',
'return',
'throws',
'example',
'class',
'module',
'submodule'
];
ArrayAssert.itemsAreSame(keys, Object.keys(item), 'Item missing from output');
Assert.areSame('', item.evil, 'Single tag not found');
Assert.areSame('HTML', item.injects.type, 'Injection type not found');
Assert.isUndefined(item.return.type, 'Type should be missing');
Assert.isUndefined(item.throws.type, 'Type should be missing');
Assert.areSame(2, item.example.length, 'Should have 2 example snippets');
item2 = this.findByName('testobjectparam', 'myclass');
Assert.areSame('String', item2.return.type, 'Type should not be missing');
Assert.areSame('Error', item2.throws.type, 'Type should not be missing');
},
'test: parameter parsing': function () {
var item, item2, item3, item4;
item = this.findByName('testoptional', 'myclass');
Assert.isArray(item.params, 'Params should be an array');
Assert.areSame(6, item.params.length, 'Failed to parse all 6 parameters');
Assert.areSame('notype', item.params[0].name, 'Name missing');
Assert.isUndefined(item.params[0].type, 'Type should be missing');
Assert.areSame('namesecond', item.params[1].name, 'Name missing');
Assert.areSame('Int', item.params[1].type, 'Type should be Int');
Assert.areSame('optionalvar', item.params[3].name, 'Name missing');
Assert.isTrue(item.params[3].optional, 'Parameter should be optional');
Assert.isUndefined(item.params[3].optdefault, 'Optional Default value should be undefined');
Assert.areSame('optionalDefault1', item.params[4].name, 'Name missing');
Assert.isTrue(item.params[4].optional, 'Parameter should be optional');
Assert.areSame('"defaultVal"', item.params[4].optdefault, 'Optional Default value is incorrect');
Assert.areSame('optionalDefault2', item.params[5].name, 'Name missing');
Assert.isTrue(item.params[5].optional, 'Parameter should be optional');
Assert.areSame('"defaultVal1 defaultVal2"', item.params[5].optdefault, 'Optional Default value is incorrect');
item2 = this.findByName('test0ton', 'myclass');
Assert.isArray(item2.params, 'Params should be an array');
Assert.areSame(1, item2.params.length, 'Failed to parse all 5 parameters');
Assert.isTrue(item2.params[0].optional, 'Optional not set');
Assert.isTrue(item2.params[0].multiple, 'Multiple not set');
Assert.isUndefined(item2.return.type, 'Type should be missing');
Assert.isUndefined(item2.throws.type, 'Type should be missing');
item2 = this.findByName('test1ton', 'myclass');
Assert.isArray(item2.params, 'Params should be an array');
Assert.areSame(1, item2.params.length, 'Failed to parse all 5 parameters');
Assert.isUndefined(item2.params[0].optional, 'Optional should not be set');
Assert.isTrue(item2.params[0].multiple, 'Multiple not set');
Assert.isUndefined(item2.return.type, 'Type should be missing');
Assert.isUndefined(item2.throws.type, 'Type should be missing');
item3 = this.findByName('testrestparam0n', 'myclass');
Assert.isArray(item3.params, 'Params should be an array');
Assert.areSame(1, item3.params.length, 'Failed to parse all 5 parameters');
Assert.isTrue(item3.params[0].optional, 'Optional not set');
Assert.isTrue(item3.params[0].multiple, 'Multiple not set');
Assert.isUndefined(item3.return.type, 'Type should be missing');
Assert.isUndefined(item3.throws.type, 'Type should be missing');
item4 = this.findByName('testrestparam1n', 'myclass');
Assert.isArray(item4.params, 'Params should be an array');
Assert.areSame(1, item4.params.length, 'Failed to parse all 5 parameters');
Assert.isUndefined(item4.params[0].optional, 'Optional should not be set');
Assert.isTrue(item4.params[0].multiple, 'Multiple not set');
Assert.isUndefined(item4.return.type, 'Type should be missing');
Assert.isUndefined(item4.throws.type, 'Type should be missing');
item = this.findByName('testNewlineBeforeDescription', 'myclass');
Assert.isArray(item.params, 'Params should be an array.');
Assert.areSame(2, item.params.length, 'Should parse two params.');
Assert.areSame('foo', item.params[0].name, 'Param 0 should have the correct name.');
Assert.areSame('bar', item.params[1].name, 'Param 1 should have the correct name.');
Assert.areSame(
'This parameter is foo.',
item.params[0].description,
'Param 0 should have the correct description.'
);
Assert.areSame(
'This parameter is bar.\n\n It does useful things.',
item.params[1].description,
'Param 1 should have the correct description.'
);
},
'test: indented description': function () {
var item = this.findByName('testNewlineBeforeDescription', 'myclass');
Assert.areSame('Boolean', item.return.type, 'Type should be correct.');
Assert.areSame(
'Sometimes true, sometimes false.\nNobody knows!',
item.return.description,
'Description indentation should be normalized to the first line.'
);
Assert.areSame('Error', item.throws.type, 'Type should be correct.');
Assert.areSame(
'Throws an error.\nCatch me.',
item.throws.description,
'Description indentation should be normalized to the first line.'
);
},
'test: object parameters': function () {
var item, props;
item = this.findByName('testobjectparam', 'myclass');
Assert.areSame('testobjectparam', item.name, 'Failed to find item: testobjectparam');
Assert.areSame('myclass', item.class, 'Failed to find class: testobjectparam');
Assert.areSame('mymodule', item.module, 'Failed to find module: testobjectparam');
Assert.areSame('mysubmodule', item.submodule, 'Failed to find submodule: testobjectparam');
Assert.areSame('method', item.itemtype, 'Should be a method');
Assert.areSame(1, item.params.length, 'More than one param found');
props = item.params[0].props;
Assert.areSame(2, props.length, 'First param should have props');
Assert.areSame('prop1', props[0].name, 'Invalid item');
Assert.areSame('prop1', props[0].description, 'Invalid item');
Assert.areSame('String', props[0].type, 'Invalid item');
Assert.areSame('prop2', props[1].name, 'Invalid item');
Assert.areSame('prop2', props[1].description, 'Invalid item');
Assert.areSame('Bool', props[1].type, 'Invalid item');
},
'test: tag fixing': function () {
var item = this.findByName('testoptional', 'myclass');
Assert.isObject(item, 'failed to find item');
Assert.isNotUndefined(item.return, 'Failed to replace returns with return');
item = this.findByName('_positionChangeHandler', 'Axis');
Assert.isObject(item, 'failed to find item');
Assert.areEqual(1, item.params.length, 'Failed to replace parma with param');
item = this.findByName('crashTest', 'OtherClass2');
Assert.isObject(item, 'failed to find item');
Assert.areEqual(1, item.params.length, 'Failed to replace params with param');
},
'test: double namespaces': function () {
var cls = this.data.classes,
mod_bad = cls['Foo.Bar.Foo.Bar'],
mod_good = cls['Foo.Bar'];
Assert.isUndefined(mod_bad, 'Found class Foo.Bar.Foo.Bar');
Assert.isObject(mod_good, 'Failed to parse Foo.Bar namespace');
},
'test: inherited methods': function () {
var item = this.findByName('myMethod', 'mywidget.SubWidget');
Assert.isObject(item, 'Failed to parse second method');
},
'test: case tags': function () {
var item = this.findByName('testMethod', 'OtherClass2');
Assert.isObject(item, 'Failed to parse second method');
Assert.areSame('method', item.itemtype, 'Failed to parse Cased Method tag');
Assert.isArray(item.params, 'Failed to parse Cased Params');
Assert.areSame(1, item.params.length, 'Failed to parse number of cased params');
},
'test: required attribute': function () {
var item = this.findByName('requiredAttr', 'OtherClass2');
Assert.isObject(item, 'Failed to parse attribute');
Assert.areSame('attribute', item.itemtype, 'Failed to parse itemtype');
Assert.areSame(1, item.required, 'Failed to find required short tag');
},
'test: optional attribute': function () {
var item = this.findByName('optionalAttr', 'OtherClass2');
Assert.isObject(item, 'Failed to parse attribute');
Assert.areSame('attribute', item.itemtype, 'Failed to parse itemtype');
Assert.areSame(1, item.optional, 'Failed to find optional short tag');
},
'test: module with example meta': function () {
var item = this.data.modules.ExampleModule;
Assert.isObject(item, 'Failed to parse module');
Assert.isArray(item.example, 'Failed to parse module example data');
},
'test: class with example meta': function () {
var item = this.data.classes['mywidget.SuperWidget'];
Assert.isObject(item, 'Failed to parse class');
Assert.isArray(item.example, 'Failed to parse class example data');
},
'test: event with optional items': function () {
var item = this.findByName('changeWithOptional', 'OtherClass2');
Assert.isObject(item, 'Failed to locate event object');
Assert.isArray(item.params);
Assert.areSame(item.params[0].name, 'ev');
Assert.areSame(item.params[0].type, 'EventFacade');
Assert.isArray(item.params[0].props);
Assert.areSame(item.params[0].props[0].name, 'name');
Assert.isTrue(item.params[0].props[0].optional);
},
'test: markdown example': function () {
var item = this.findByName('foo2', 'myclass');
Assert.areSame(item.example[0], '\n @media screen and (max-width: 767px) {\n }');
}
}));
YUITest.TestRunner.add(suite);
|
var isExist = ClipMenu.require('v8cgi/util');
if (!isExist) {
throw new Error('Could not find the library');
}
return Util.base64decode(clipText);
|
var fieldTests = require('./commonFieldTestUtils.js');
var ModelTestConfig = require('../../../modelTestConfig/PasswordModelTestConfig');
module.exports = {
// '@disabled': true, // TODO: enable after https://github.com/keystonejs/keystone/issues/3428 is fixed
before: function (browser) {
fieldTests.before(browser);
browser.adminUIInitialFormScreen.setDefaultModelTestConfig(ModelTestConfig);
browser.adminUIItemScreen.setDefaultModelTestConfig(ModelTestConfig);
browser.adminUIListScreen.setDefaultModelTestConfig(ModelTestConfig);
},
after: fieldTests.after,
'Password field should show correctly in the initial modal': function (browser) {
browser.adminUIApp.openList({ section: 'fields', list: 'Password' });
browser.adminUIListScreen.clickCreateItemButton();
browser.adminUIApp.waitForInitialFormScreen();
browser.adminUIInitialFormScreen.assertFieldUIVisible({
fields: [
{ name: 'name', },
{ name: 'fieldA', options: { passwordShown: true }, }
],
});
browser.adminUIInitialFormScreen.cancel();
browser.adminUIApp.waitForListScreen();
},
'Password field can be filled via the initial modal': function (browser) {
browser.adminUIApp.openList({ section: 'fields', list: 'Password' });
browser.adminUIListScreen.clickCreateItemButton();
browser.adminUIApp.waitForInitialFormScreen();
browser.adminUIInitialFormScreen.fillFieldInputs({
fields: [
{ name: 'name', input: { value: 'Password Field Test 1' }, },
{ name: 'fieldA', input: { value: 'CorrectH0rseB@tteryStapl1', confirm: 'wrongCorrectH0rseB@tteryStapl1' }, },
],
});
browser.adminUIInitialFormScreen.save();
browser.adminUIInitialFormScreen.assertElementTextEquals({ element: '@flashError', text: 'Passwords must match.' });
browser.adminUIInitialFormScreen.fillFieldInputs({
fields: [
{ name: 'fieldA', input: { value: 'CorrectH0rseB@tteryStapl1', confirm: 'CorrectH0rseB@tteryStapl1' }, },
],
});
browser.adminUIInitialFormScreen.assertFieldInputs({
fields: [
{ name: 'fieldA', input: { value: 'CorrectH0rseB@tteryStapl1', confirm: 'CorrectH0rseB@tteryStapl1' }, },
],
});
browser.adminUIInitialFormScreen.save();
browser.adminUIApp.waitForItemScreen();
},
'Password field should show correctly in the edit form': function (browser) {
browser.adminUIItemScreen.assertFieldUIVisible({
fields: [
{ name: 'fieldA', options: { passwordShown: false }, },
{ name: 'fieldB', options: { passwordShown: false }, }
],
});
browser.adminUIItemScreen.assertFieldInputs({
fields: [
{ name: 'name', input: { value: 'Password Field Test 1' }, },
],
})
},
'Password field can be filled via the edit form': function (browser) {
browser.adminUIItemScreen.clickFieldUI({
fields: [
{ name: 'fieldB', 'click': 'setPasswordButton', },
],
});
browser.adminUIItemScreen.assertFieldUIVisible({
fields: [
{ name: 'fieldA', options: { passwordShown: false }, },
{ name: 'fieldB', options: { passwordShown: true }, }
],
});
browser.adminUIItemScreen.fillFieldInputs({
fields: [
{ name: 'fieldB', input: { value: 'CorrectH0rseB@tteryStapl2', confirm: 'wrongCorrectH0rseB@tteryStapl2' }, },
],
});
browser.adminUIItemScreen.save();
browser.adminUIApp.waitForItemScreen();
browser.adminUIItemScreen.assertElementTextEquals({ element: '@flashError', text: 'Passwords must match.' });
browser.adminUIItemScreen.fillFieldInputs({
fields: [
{ name: 'fieldB', input: { value: 'CorrectH0rseB@tteryStapl2', confirm: 'CorrectH0rseB@tteryStapl2' }, },
],
});
browser.adminUIItemScreen.save();
browser.adminUIApp.waitForItemScreen();
browser.adminUIItemScreen.assertElementTextEquals({ element: '@flashMessage', text: 'Your changes have been saved successfully' });
browser.adminUIItemScreen.assertFieldInputs({
fields: [
{ name: 'name', input: { value: 'Password Field Test 1' }, },
],
})
},
};
|
/*! jQuery Validation Plugin - v1.18.0 - 9/9/2018
* https://jqueryvalidation.org/
* Copyright (c) 2018 Jörn Zaefferer; Licensed MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery","../jquery.validate.min"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){return a.extend(a.validator.messages,{required:"Hãy nhập.",remote:"Hãy sửa cho đúng.",email:"Hãy nhập email.",url:"Hãy nhập URL.",date:"Hãy nhập ngày.",dateISO:"Hãy nhập ngày (ISO).",number:"Hãy nhập số.",digits:"Hãy nhập chữ số.",creditcard:"Hãy nhập số thẻ tín dụng.",equalTo:"Hãy nhập thêm lần nữa.",extension:"Phần mở rộng không đúng.",maxlength:a.validator.format("Hãy nhập từ {0} kí tự trở xuống."),minlength:a.validator.format("Hãy nhập từ {0} kí tự trở lên."),rangelength:a.validator.format("Hãy nhập từ {0} đến {1} kí tự."),range:a.validator.format("Hãy nhập từ {0} đến {1}."),max:a.validator.format("Hãy nhập từ {0} trở xuống."),min:a.validator.format("Hãy nhập từ {0} trở lên.")}),a});
|
import expect, { spyOn } from 'expect'
import React, { Component } from 'react'
import { Simulate } from 'react-addons-test-utils'
import { render } from 'react-dom'
import execSteps from './execSteps'
import createHistory from 'history/lib/createMemoryHistory'
import Router from '../Router'
import Route from '../Route'
import Link from '../Link'
const { click } = Simulate
describe('v1 Link', function () {
class Hello extends Component {
render() {
return <div>Hello {this.props.params.name}!</div>
}
}
let node
beforeEach(function () {
node = document.createElement('div')
})
it('knows how to make its href', function () {
class LinkWrapper extends Component {
render() {
return <Link to="/hello/michael" query={{ the: 'query' }} hash="#the-hash">Link</Link>
}
}
render((
<Router history={createHistory('/')}>
<Route path="/" component={LinkWrapper} />
</Router>
), node, function () {
const a = node.querySelector('a')
expect(a.getAttribute('href')).toEqual('/hello/michael?the=query#the-hash')
})
})
describe('with params', function () {
class App extends Component {
render() {
return (
<div>
<Link
to="/hello/michael"
activeClassName="active"
>
Michael
</Link>
<Link
to="hello/ryan" query={{ the: 'query' }}
activeClassName="active"
>
Ryan
</Link>
</div>
)
}
}
it('is active when its params match', function (done) {
render((
<Router history={createHistory('/hello/michael')}>
<Route path="/" component={App}>
<Route path="hello/:name" component={Hello} />
</Route>
</Router>
), node, function () {
const a = node.querySelectorAll('a')[0]
expect(a.className.trim()).toEqual('active')
done()
})
})
it('is not active when its params do not match', function (done) {
render((
<Router history={createHistory('/hello/michael')}>
<Route path="/" component={App}>
<Route path="hello/:name" component={Hello} />
</Route>
</Router>
), node, function () {
const a = node.querySelectorAll('a')[1]
expect(a.className.trim()).toEqual('')
done()
})
})
it('is active when its params and query match', function (done) {
render((
<Router history={createHistory('/hello/ryan?the=query')}>
<Route path="/" component={App}>
<Route path="hello/:name" component={Hello} />
</Route>
</Router>
), node, function () {
const a = node.querySelectorAll('a')[1]
expect(a.className.trim()).toEqual('active')
done()
})
})
it('is not active when its query does not match', function (done) {
render((
<Router history={createHistory('/hello/ryan?the=other+query')}>
<Route path="/" component={App}>
<Route path="hello/:name" component={Hello} />
</Route>
</Router>
), node, function () {
const a = node.querySelectorAll('a')[1]
expect(a.className.trim()).toEqual('')
done()
})
})
})
it('transitions to the correct route with deprecated props', function (done) {
class LinkWrapper extends Component {
handleClick() {
// just here to make sure click handlers don't prevent it from happening
}
render() {
return <Link to="/hello" hash="#world" query={{ how: 'are' }} state={{ you: 'doing?' }} onClick={(e) => this.handleClick(e)}>Link</Link>
}
}
const history = createHistory('/')
const spy = spyOn(history, 'push').andCallThrough()
const steps = [
function () {
click(node.querySelector('a'), { button: 0 })
},
function () {
expect(node.innerHTML).toMatch(/Hello/)
expect(spy).toHaveBeenCalled()
const { location } = this.state
expect(location.pathname).toEqual('/hello')
expect(location.search).toEqual('?how=are')
expect(location.hash).toEqual('#world')
expect(location.state).toEqual({ you: 'doing?' })
}
]
const execNextStep = execSteps(steps, done)
render((
<Router history={history} onUpdate={execNextStep}>
<Route path="/" component={LinkWrapper} />
<Route path="/hello" component={Hello} />
</Router>
), node, execNextStep)
})
})
|
define(["$data","$spec"],function(){
var body = document.body
describe('data', {
data: function(){
//使用了data方法的元素或对象都会添加一个叫uniqueNumber的数字属性
$.data( body,"test1",[1,2,3]);
expect(typeof body.uniqueNumber === "number").ok();
expect($.data( body,"test1")).same([1,2,3]);
//现在数据缓存系统是不能为文本节点,注释节点储存任何数据
var textNode = document.createTextNode("文本节点");
body.appendChild( textNode );
$.data( textNode,"text","text");
expect($.data( textNode,"test1")).eq( void 0 );
body.removeChild( textNode );
var el = $("<div data-aaa=1 data-bbb=2 data-ccc-ddd=3 />").appendTo(body)
expect(el.data()).same({
aaa:1,
bbb:2,
cccDdd:3
});
var val = $.data( body,"test2",{
aa:"aa",
bb:"bb"
});
//测试返回值
expect(val).same({
aa:"aa",
bb:"bb"
});
},
mergeData: function(){
var a = {};
//写入数揣
$.data(a,"name","司徒正美");
//写入一个复杂的数据
$.data(a,"obj",{
ee:[1,2,3,{
aa:"aa",
bb:"bb"
}],
dd:function(){},
date:new Date
});
var b = {};
$.data(b,"sex","man");
//合并数据
$.mergeData(b,a);
// alert($.data(b))
expect($.data(a)).log()
expect($.data(b)).log()
delete $.data(b).sex;
expect($.data(a)).same($.data(b))
},
removeData: function(){
$.data( body,"test1",[1,2,3]);
var val = $.removeData( body,"test1");
expect(val).same([1,2,3]);
$.removeData( body );
expect( $.data( body )).same({});
},
parseData: function(){
body.setAttribute("data-object","{a:1,b:2,c:3}")
var data = $.parseData( body, "object")
expect(data).same({
a:1,
b:2,
c:3
});
body.setAttribute("data-array","[1,2,3]")
data = $.parseData( body, "array");
expect(data).same([1,2,3]);
body.setAttribute("data-null","null");
data = $.parseData( body, "null");
expect(data).eq(null);
body.setAttribute("data-num","20120429");
data = $.parseData( body, "num");
expect(data).eq(20120429);
}
});
//2012.4.29 添加$.parseData测试
})
|
/* eslint-disable complexity */
/* eslint-env mocha */
import 'babel-polyfill';
import assert from 'assert';
import s from 'underscore.string';
import { _getURL } from './getURL';
const testPaths = (o, _processPath) => {
let processPath = _processPath;
if (o._root_url_path_prefix !== '') {
processPath = (path) => _processPath(o._root_url_path_prefix + path);
}
assert.equal(_getURL('', o), processPath(''));
assert.equal(_getURL('/', o), processPath(''));
assert.equal(_getURL('//', o), processPath(''));
assert.equal(_getURL('///', o), processPath(''));
assert.equal(_getURL('/channel', o), processPath('/channel'));
assert.equal(_getURL('/channel/', o), processPath('/channel'));
assert.equal(_getURL('/channel//', o), processPath('/channel'));
assert.equal(_getURL('/channel/123', o), processPath('/channel/123'));
assert.equal(_getURL('/channel/123/', o), processPath('/channel/123'));
assert.equal(_getURL('/channel/123?id=456&name=test', o), processPath('/channel/123?id=456&name=test'));
assert.equal(_getURL('/channel/123/?id=456&name=test', o), processPath('/channel/123?id=456&name=test'));
};
const getCloudUrl = (_site_url, path) => {
path = s.ltrim(path, '/');
const url = `https://go.rocket.chat/?host=${ encodeURIComponent(_site_url.replace(/https?:\/\//, '')) }&path=${ encodeURIComponent(path) }`;
if (_site_url.includes('http://')) {
return `${ url }&secure=no`;
}
return url;
};
const testCases = (options) => {
const _site_url = s.rtrim(options._site_url, '/');
if (!options.cloud) {
if (options._cdn_prefix === '') {
if (options.full && !options.cdn) {
it('should return with host if full: true', () => {
testPaths(options, (path) => _site_url + path);
});
}
if (!options.full && options.cdn) {
it('should return without cdn prefix if cdn: true', () => {
testPaths(options, (path) => path);
});
}
if (!options.full && !options.cdn) {
it('should return without host by default', () => {
testPaths(options, (path) => path);
});
}
if (options.full && options.cdn) {
it('should return with host if full: true and cdn: true', () => {
testPaths(options, (path) => _site_url + path);
});
}
} else {
if (options.full && !options.cdn) {
it('should return with host if full: true', () => {
testPaths(options, (path) => _site_url + path);
});
}
if (!options.full && options.cdn) {
it('should return with cdn prefix if cdn: true', () => {
testPaths(options, (path) => options._cdn_prefix + path);
});
}
if (!options.full && !options.cdn) {
it('should return without host by default', () => {
testPaths(options, (path) => path);
});
}
if (options.full && options.cdn) {
it('should return with cdn prefix if full: true and cdn: true', () => {
testPaths(options, (path) => options._cdn_prefix + path);
});
}
}
} else if (options._cdn_prefix === '') {
if (options.full && !options.cdn && !options.cloud) {
it('should return with host if full: true', () => {
testPaths(options, (path) => _site_url + path);
});
}
if (!options.full && options.cdn) {
it('should return with cloud host if cdn: true', () => {
testPaths(options, (path) => getCloudUrl(_site_url, path));
});
}
if (!options.full && !options.cdn) {
it('should return with cloud host if full: fase and cdn: false', () => {
testPaths(options, (path) => getCloudUrl(_site_url, path));
});
}
if (options.full && options.cdn && !options.cloud) {
it('should return with host if full: true and cdn: true', () => {
testPaths(options, (path) => _site_url + path);
});
}
} else {
if (options.full && !options.cdn && !options.cloud) {
it('should return with host if full: true', () => {
testPaths(options, (path) => _site_url + path);
});
}
if (!options.full && options.cdn && !options.cloud) {
it('should return with cdn prefix if cdn: true', () => {
testPaths(options, (path) => options._cdn_prefix + path);
});
}
if (!options.full && !options.cdn) {
it('should return with cloud host if full: fase and cdn: false', () => {
testPaths(options, (path) => getCloudUrl(_site_url, path));
});
}
if (options.full && options.cdn && !options.cloud) {
it('should return with host if full: true and cdn: true', () => {
testPaths(options, (path) => options._cdn_prefix + path);
});
}
}
};
const testOptions = (options) => {
testCases({ ...options, cdn: false, full: false, cloud: false });
testCases({ ...options, cdn: true, full: false, cloud: false });
testCases({ ...options, cdn: false, full: true, cloud: false });
testCases({ ...options, cdn: false, full: false, cloud: true });
testCases({ ...options, cdn: true, full: true, cloud: false });
testCases({ ...options, cdn: false, full: true, cloud: true });
testCases({ ...options, cdn: true, full: false, cloud: true });
testCases({ ...options, cdn: true, full: true, cloud: true });
};
describe('getURL', () => {
describe('getURL with no CDN, no PREFIX for http://localhost:3000/', () => {
testOptions({
_cdn_prefix: '',
_root_url_path_prefix: '',
_site_url: 'http://localhost:3000/',
});
});
describe('getURL with no CDN, no PREFIX for http://localhost:3000', () => {
testOptions({
_cdn_prefix: '',
_root_url_path_prefix: '',
_site_url: 'http://localhost:3000',
});
});
describe('getURL with CDN, no PREFIX for http://localhost:3000/', () => {
testOptions({
_cdn_prefix: 'https://cdn.com',
_root_url_path_prefix: '',
_site_url: 'http://localhost:3000/',
});
});
describe('getURL with CDN, PREFIX for http://localhost:3000/', () => {
testOptions({
_cdn_prefix: 'https://cdn.com',
_root_url_path_prefix: 'sub',
_site_url: 'http://localhost:3000/',
});
});
describe('getURL with CDN, PREFIX for https://localhost:3000/', () => {
testOptions({
_cdn_prefix: 'https://cdn.com',
_root_url_path_prefix: 'sub',
_site_url: 'https://localhost:3000/',
});
});
});
|
/*!
* Datepicker for Bootstrap v1.7.1 (https://github.com/uxsolutions/bootstrap-datepicker)
*
* Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0)
*/
(function(factory){
if (typeof define === "function" && define.amd) {
define(["jquery"], factory);
} else if (typeof exports === 'object') {
factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($, undefined){
function UTCDate(){
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday(){
var today = new Date();
return UTCDate(today.getFullYear(), today.getMonth(), today.getDate());
}
function isUTCEquals(date1, date2) {
return (
date1.getUTCFullYear() === date2.getUTCFullYear() &&
date1.getUTCMonth() === date2.getUTCMonth() &&
date1.getUTCDate() === date2.getUTCDate()
);
}
function alias(method, deprecationMsg){
return function(){
if (deprecationMsg !== undefined) {
$.fn.datepicker.deprecated(deprecationMsg);
}
return this[method].apply(this, arguments);
};
}
function isValidDate(d) {
return d && !isNaN(d.getTime());
}
var DateArray = (function(){
var extras = {
get: function(i){
return this.slice(i)[0];
},
contains: function(d){
// Array.indexOf is not cross-browser;
// $.inArray doesn't work with Dates
var val = d && d.valueOf();
for (var i=0, l=this.length; i < l; i++)
// Use date arithmetic to allow dates with different times to match
if (0 <= this[i].valueOf() - val && this[i].valueOf() - val < 1000*60*60*24)
return i;
return -1;
},
remove: function(i){
this.splice(i,1);
},
replace: function(new_array){
if (!new_array)
return;
if (!$.isArray(new_array))
new_array = [new_array];
this.clear();
this.push.apply(this, new_array);
},
clear: function(){
this.length = 0;
},
copy: function(){
var a = new DateArray();
a.replace(this);
return a;
}
};
return function(){
var a = [];
a.push.apply(a, arguments);
$.extend(a, extras);
return a;
};
})();
// Picker object
var Datepicker = function(element, options){
$.data(element, 'datepicker', this);
this._process_options(options);
this.dates = new DateArray();
this.viewDate = this.o.defaultViewDate;
this.focusDate = null;
this.element = $(element);
this.isInput = this.element.is('input');
this.inputField = this.isInput ? this.element : this.element.find('input');
this.component = this.element.hasClass('date') ? this.element.find('.add-on, .input-group-addon, .btn') : false;
if (this.component && this.component.length === 0)
this.component = false;
this.isInline = !this.component && this.element.is('div');
this.picker = $(DPGlobal.template);
// Checking templates and inserting
if (this._check_template(this.o.templates.leftArrow)) {
this.picker.find('.prev').html(this.o.templates.leftArrow);
}
if (this._check_template(this.o.templates.rightArrow)) {
this.picker.find('.next').html(this.o.templates.rightArrow);
}
this._buildEvents();
this._attachEvents();
if (this.isInline){
this.picker.addClass('datepicker-inline').appendTo(this.element);
}
else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.o.rtl){
this.picker.addClass('datepicker-rtl');
}
if (this.o.calendarWeeks) {
this.picker.find('.datepicker-days .datepicker-switch, thead .datepicker-title, tfoot .today, tfoot .clear')
.attr('colspan', function(i, val){
return Number(val) + 1;
});
}
this._process_options({
startDate: this._o.startDate,
endDate: this._o.endDate,
daysOfWeekDisabled: this.o.daysOfWeekDisabled,
daysOfWeekHighlighted: this.o.daysOfWeekHighlighted,
datesDisabled: this.o.datesDisabled
});
this._allow_update = false;
this.setViewMode(this.o.startView);
this._allow_update = true;
this.fillDow();
this.fillMonths();
this.update();
if (this.isInline){
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_resolveViewName: function(view){
$.each(DPGlobal.viewModes, function(i, viewMode){
if (view === i || $.inArray(view, viewMode.names) !== -1){
view = i;
return false;
}
});
return view;
},
_resolveDaysOfWeek: function(daysOfWeek){
if (!$.isArray(daysOfWeek))
daysOfWeek = daysOfWeek.split(/[,\s]*/);
return $.map(daysOfWeek, Number);
},
_check_template: function(tmp){
try {
// If empty
if (tmp === undefined || tmp === "") {
return false;
}
// If no html, everything ok
if ((tmp.match(/[<>]/g) || []).length <= 0) {
return true;
}
// Checking if html is fine
var jDom = $(tmp);
return jDom.length > 0;
}
catch (ex) {
return false;
}
},
_process_options: function(opts){
// Store raw options for reference
this._o = $.extend({}, this._o, opts);
// Processed options
var o = this.o = $.extend({}, this._o);
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
var lang = o.language;
if (!dates[lang]){
lang = lang.split('-')[0];
if (!dates[lang])
lang = defaults.language;
}
o.language = lang;
// Retrieve view index from any aliases
o.startView = this._resolveViewName(o.startView);
o.minViewMode = this._resolveViewName(o.minViewMode);
o.maxViewMode = this._resolveViewName(o.maxViewMode);
// Check view is between min and max
o.startView = Math.max(this.o.minViewMode, Math.min(this.o.maxViewMode, o.startView));
// true, false, or Number > 0
if (o.multidate !== true){
o.multidate = Number(o.multidate) || false;
if (o.multidate !== false)
o.multidate = Math.max(0, o.multidate);
}
o.multidateSeparator = String(o.multidateSeparator);
o.weekStart %= 7;
o.weekEnd = (o.weekStart + 6) % 7;
var format = DPGlobal.parseFormat(o.format);
if (o.startDate !== -Infinity){
if (!!o.startDate){
if (o.startDate instanceof Date)
o.startDate = this._local_to_utc(this._zero_time(o.startDate));
else
o.startDate = DPGlobal.parseDate(o.startDate, format, o.language, o.assumeNearbyYear);
}
else {
o.startDate = -Infinity;
}
}
if (o.endDate !== Infinity){
if (!!o.endDate){
if (o.endDate instanceof Date)
o.endDate = this._local_to_utc(this._zero_time(o.endDate));
else
o.endDate = DPGlobal.parseDate(o.endDate, format, o.language, o.assumeNearbyYear);
}
else {
o.endDate = Infinity;
}
}
o.daysOfWeekDisabled = this._resolveDaysOfWeek(o.daysOfWeekDisabled||[]);
o.daysOfWeekHighlighted = this._resolveDaysOfWeek(o.daysOfWeekHighlighted||[]);
o.datesDisabled = o.datesDisabled||[];
if (!$.isArray(o.datesDisabled)) {
o.datesDisabled = o.datesDisabled.split(',');
}
o.datesDisabled = $.map(o.datesDisabled, function(d){
return DPGlobal.parseDate(d, format, o.language, o.assumeNearbyYear);
});
var plc = String(o.orientation).toLowerCase().split(/\s+/g),
_plc = o.orientation.toLowerCase();
plc = $.grep(plc, function(word){
return /^auto|left|right|top|bottom$/.test(word);
});
o.orientation = {x: 'auto', y: 'auto'};
if (!_plc || _plc === 'auto')
; // no action
else if (plc.length === 1){
switch (plc[0]){
case 'top':
case 'bottom':
o.orientation.y = plc[0];
break;
case 'left':
case 'right':
o.orientation.x = plc[0];
break;
}
}
else {
_plc = $.grep(plc, function(word){
return /^left|right$/.test(word);
});
o.orientation.x = _plc[0] || 'auto';
_plc = $.grep(plc, function(word){
return /^top|bottom$/.test(word);
});
o.orientation.y = _plc[0] || 'auto';
}
if (o.defaultViewDate instanceof Date || typeof o.defaultViewDate === 'string') {
o.defaultViewDate = DPGlobal.parseDate(o.defaultViewDate, format, o.language, o.assumeNearbyYear);
} else if (o.defaultViewDate) {
var year = o.defaultViewDate.year || new Date().getFullYear();
var month = o.defaultViewDate.month || 0;
var day = o.defaultViewDate.day || 1;
o.defaultViewDate = UTCDate(year, month, day);
} else {
o.defaultViewDate = UTCToday();
}
},
_events: [],
_secondaryEvents: [],
_applyEvents: function(evs){
for (var i=0, el, ch, ev; i < evs.length; i++){
el = evs[i][0];
if (evs[i].length === 2){
ch = undefined;
ev = evs[i][1];
} else if (evs[i].length === 3){
ch = evs[i][1];
ev = evs[i][2];
}
el.on(ev, ch);
}
},
_unapplyEvents: function(evs){
for (var i=0, el, ev, ch; i < evs.length; i++){
el = evs[i][0];
if (evs[i].length === 2){
ch = undefined;
ev = evs[i][1];
} else if (evs[i].length === 3){
ch = evs[i][1];
ev = evs[i][2];
}
el.off(ev, ch);
}
},
_buildEvents: function(){
var events = {
keyup: $.proxy(function(e){
if ($.inArray(e.keyCode, [27, 37, 39, 38, 40, 32, 13, 9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this),
paste: $.proxy(this.paste, this)
};
if (this.o.showOnFocus === true) {
events.focus = $.proxy(this.show, this);
}
if (this.isInput) { // single input
this._events = [
[this.element, events]
];
}
// component: input + button
else if (this.component && this.inputField.length) {
this._events = [
// For components that are not readonly, allow keyboard nav
[this.inputField, events],
[this.component, {
click: $.proxy(this.show, this)
}]
];
}
else {
this._events = [
[this.element, {
click: $.proxy(this.show, this),
keydown: $.proxy(this.keydown, this)
}]
];
}
this._events.push(
// Component: listen for blur on element descendants
[this.element, '*', {
blur: $.proxy(function(e){
this._focused_from = e.target;
}, this)
}],
// Input: listen for blur on element
[this.element, {
blur: $.proxy(function(e){
this._focused_from = e.target;
}, this)
}]
);
if (this.o.immediateUpdates) {
// Trigger input updates immediately on changed year/month
this._events.push([this.element, {
'changeYear changeMonth': $.proxy(function(e){
this.update(e.date);
}, this)
}]);
}
this._secondaryEvents = [
[this.picker, {
click: $.proxy(this.click, this)
}],
[this.picker, '.prev, .next', {
click: $.proxy(this.navArrowsClick, this)
}],
[this.picker, '.day:not(.disabled)', {
click: $.proxy(this.dayCellClick, this)
}],
[$(window), {
resize: $.proxy(this.place, this)
}],
[$(document), {
'mousedown touchstart': $.proxy(function(e){
// Clicked outside the datepicker, hide it
if (!(
this.element.is(e.target) ||
this.element.find(e.target).length ||
this.picker.is(e.target) ||
this.picker.find(e.target).length ||
this.isInline
)){
this.hide();
}
}, this)
}]
];
},
_attachEvents: function(){
this._detachEvents();
this._applyEvents(this._events);
},
_detachEvents: function(){
this._unapplyEvents(this._events);
},
_attachSecondaryEvents: function(){
this._detachSecondaryEvents();
this._applyEvents(this._secondaryEvents);
},
_detachSecondaryEvents: function(){
this._unapplyEvents(this._secondaryEvents);
},
_trigger: function(event, altdate){
var date = altdate || this.dates.get(-1),
local_date = this._utc_to_local(date);
this.element.trigger({
type: event,
date: local_date,
viewMode: this.viewMode,
dates: $.map(this.dates, this._utc_to_local),
format: $.proxy(function(ix, format){
if (arguments.length === 0){
ix = this.dates.length - 1;
format = this.o.format;
} else if (typeof ix === 'string'){
format = ix;
ix = this.dates.length - 1;
}
format = format || this.o.format;
var date = this.dates.get(ix);
return DPGlobal.formatDate(date, format, this.o.language);
}, this)
});
},
show: function(){
if (this.inputField.prop('disabled') || (this.inputField.prop('readonly') && this.o.enableOnReadonly === false))
return;
if (!this.isInline)
this.picker.appendTo(this.o.container);
this.place();
this.picker.show();
this._attachSecondaryEvents();
this._trigger('show');
if ((window.navigator.msMaxTouchPoints || 'ontouchstart' in document) && this.o.disableTouchKeyboard) {
$(this.element).blur();
}
return this;
},
hide: function(){
if (this.isInline || !this.picker.is(':visible'))
return this;
this.focusDate = null;
this.picker.hide().detach();
this._detachSecondaryEvents();
this.setViewMode(this.o.startView);
if (this.o.forceParse && this.inputField.val())
this.setValue();
this._trigger('hide');
return this;
},
destroy: function(){
this.hide();
this._detachEvents();
this._detachSecondaryEvents();
this.picker.remove();
delete this.element.data().datepicker;
if (!this.isInput){
delete this.element.data().date;
}
return this;
},
paste: function(e){
var dateString;
if (e.originalEvent.clipboardData && e.originalEvent.clipboardData.types
&& $.inArray('text/plain', e.originalEvent.clipboardData.types) !== -1) {
dateString = e.originalEvent.clipboardData.getData('text/plain');
} else if (window.clipboardData) {
dateString = window.clipboardData.getData('Text');
} else {
return;
}
this.setDate(dateString);
this.update();
e.preventDefault();
},
_utc_to_local: function(utc){
if (!utc) {
return utc;
}
var local = new Date(utc.getTime() + (utc.getTimezoneOffset() * 60000));
if (local.getTimezoneOffset() !== utc.getTimezoneOffset()) {
local = new Date(utc.getTime() + (local.getTimezoneOffset() * 60000));
}
return local;
},
_local_to_utc: function(local){
return local && new Date(local.getTime() - (local.getTimezoneOffset()*60000));
},
_zero_time: function(local){
return local && new Date(local.getFullYear(), local.getMonth(), local.getDate());
},
_zero_utc_time: function(utc){
return utc && UTCDate(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate());
},
getDates: function(){
return $.map(this.dates, this._utc_to_local);
},
getUTCDates: function(){
return $.map(this.dates, function(d){
return new Date(d);
});
},
getDate: function(){
return this._utc_to_local(this.getUTCDate());
},
getUTCDate: function(){
var selected_date = this.dates.get(-1);
if (selected_date !== undefined) {
return new Date(selected_date);
} else {
return null;
}
},
clearDates: function(){
this.inputField.val('');
this.update();
this._trigger('changeDate');
if (this.o.autoclose) {
this.hide();
}
},
setDates: function(){
var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
this.update.apply(this, args);
this._trigger('changeDate');
this.setValue();
return this;
},
setUTCDates: function(){
var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
this.setDates.apply(this, $.map(args, this._utc_to_local));
return this;
},
setDate: alias('setDates'),
setUTCDate: alias('setUTCDates'),
remove: alias('destroy', 'Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead'),
setValue: function(){
var formatted = this.getFormattedDate();
this.inputField.val(formatted);
return this;
},
getFormattedDate: function(format){
if (format === undefined)
format = this.o.format;
var lang = this.o.language;
return $.map(this.dates, function(d){
return DPGlobal.formatDate(d, format, lang);
}).join(this.o.multidateSeparator);
},
getStartDate: function(){
return this.o.startDate;
},
setStartDate: function(startDate){
this._process_options({startDate: startDate});
this.update();
this.updateNavArrows();
return this;
},
getEndDate: function(){
return this.o.endDate;
},
setEndDate: function(endDate){
this._process_options({endDate: endDate});
this.update();
this.updateNavArrows();
return this;
},
setDaysOfWeekDisabled: function(daysOfWeekDisabled){
this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
this.update();
return this;
},
setDaysOfWeekHighlighted: function(daysOfWeekHighlighted){
this._process_options({daysOfWeekHighlighted: daysOfWeekHighlighted});
this.update();
return this;
},
setDatesDisabled: function(datesDisabled){
this._process_options({datesDisabled: datesDisabled});
this.update();
return this;
},
place: function(){
if (this.isInline)
return this;
var calendarWidth = this.picker.outerWidth(),
calendarHeight = this.picker.outerHeight(),
visualPadding = 10,
container = $(this.o.container),
windowWidth = container.width(),
scrollTop = this.o.container === 'body' ? $(document).scrollTop() : container.scrollTop(),
appendOffset = container.offset();
var parentsZindex = [0];
this.element.parents().each(function(){
var itemZIndex = $(this).css('z-index');
if (itemZIndex !== 'auto' && Number(itemZIndex) !== 0) parentsZindex.push(Number(itemZIndex));
});
var zIndex = Math.max.apply(Math, parentsZindex) + this.o.zIndexOffset;
var offset = this.component ? this.component.parent().offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
var left = offset.left - appendOffset.left;
var top = offset.top - appendOffset.top;
if (this.o.container !== 'body') {
top += scrollTop;
}
this.picker.removeClass(
'datepicker-orient-top datepicker-orient-bottom '+
'datepicker-orient-right datepicker-orient-left'
);
if (this.o.orientation.x !== 'auto'){
this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
if (this.o.orientation.x === 'right')
left -= calendarWidth - width;
}
// auto x orientation is best-placement: if it crosses a window
// edge, fudge it sideways
else {
if (offset.left < 0) {
// component is outside the window on the left side. Move it into visible range
this.picker.addClass('datepicker-orient-left');
left -= offset.left - visualPadding;
} else if (left + calendarWidth > windowWidth) {
// the calendar passes the widow right edge. Align it to component right side
this.picker.addClass('datepicker-orient-right');
left += width - calendarWidth;
} else {
if (this.o.rtl) {
// Default to right
this.picker.addClass('datepicker-orient-right');
} else {
// Default to left
this.picker.addClass('datepicker-orient-left');
}
}
}
// auto y orientation is best-situation: top or bottom, no fudging,
// decision based on which shows more of the calendar
var yorient = this.o.orientation.y,
top_overflow;
if (yorient === 'auto'){
top_overflow = -scrollTop + top - calendarHeight;
yorient = top_overflow < 0 ? 'bottom' : 'top';
}
this.picker.addClass('datepicker-orient-' + yorient);
if (yorient === 'top')
top -= calendarHeight + parseInt(this.picker.css('padding-top'));
else
top += height;
if (this.o.rtl) {
var right = windowWidth - (left + width);
this.picker.css({
top: top,
right: right,
zIndex: zIndex
});
} else {
this.picker.css({
top: top,
left: left,
zIndex: zIndex
});
}
return this;
},
_allow_update: true,
update: function(){
if (!this._allow_update)
return this;
var oldDates = this.dates.copy(),
dates = [],
fromArgs = false;
if (arguments.length){
$.each(arguments, $.proxy(function(i, date){
if (date instanceof Date)
date = this._local_to_utc(date);
dates.push(date);
}, this));
fromArgs = true;
} else {
dates = this.isInput
? this.element.val()
: this.element.data('date') || this.inputField.val();
if (dates && this.o.multidate)
dates = dates.split(this.o.multidateSeparator);
else
dates = [dates];
delete this.element.data().date;
}
dates = $.map(dates, $.proxy(function(date){
return DPGlobal.parseDate(date, this.o.format, this.o.language, this.o.assumeNearbyYear);
}, this));
dates = $.grep(dates, $.proxy(function(date){
return (
!this.dateWithinRange(date) ||
!date
);
}, this), true);
this.dates.replace(dates);
if (this.o.updateViewDate) {
if (this.dates.length)
this.viewDate = new Date(this.dates.get(-1));
else if (this.viewDate < this.o.startDate)
this.viewDate = new Date(this.o.startDate);
else if (this.viewDate > this.o.endDate)
this.viewDate = new Date(this.o.endDate);
else
this.viewDate = this.o.defaultViewDate;
}
if (fromArgs){
// setting date by clicking
this.setValue();
this.element.change();
}
else if (this.dates.length){
// setting date by typing
if (String(oldDates) !== String(this.dates) && fromArgs) {
this._trigger('changeDate');
this.element.change();
}
}
if (!this.dates.length && oldDates.length) {
this._trigger('clearDate');
this.element.change();
}
this.fill();
return this;
},
fillDow: function(){
if (this.o.showWeekDays) {
var dowCnt = this.o.weekStart,
html = '<tr>';
if (this.o.calendarWeeks){
html += '<th class="cw"> </th>';
}
while (dowCnt < this.o.weekStart + 7){
html += '<th class="dow';
if ($.inArray(dowCnt, this.o.daysOfWeekDisabled) !== -1)
html += ' disabled';
html += '">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
}
},
fillMonths: function(){
var localDate = this._utc_to_local(this.viewDate);
var html = '';
var focused;
for (var i = 0; i < 12; i++){
focused = localDate && localDate.getMonth() === i ? ' focused' : '';
html += '<span class="month' + focused + '">' + dates[this.o.language].monthsShort[i] + '</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
setRange: function(range){
if (!range || !range.length)
delete this.range;
else
this.range = $.map(range, function(d){
return d.valueOf();
});
this.fill();
},
getClassNames: function(date){
var cls = [],
year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth(),
today = UTCToday();
if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)){
cls.push('old');
} else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)){
cls.push('new');
}
if (this.focusDate && date.valueOf() === this.focusDate.valueOf())
cls.push('focused');
// Compare internal UTC date with UTC today, not local today
if (this.o.todayHighlight && isUTCEquals(date, today)) {
cls.push('today');
}
if (this.dates.contains(date) !== -1)
cls.push('active');
if (!this.dateWithinRange(date)){
cls.push('disabled');
}
if (this.dateIsDisabled(date)){
cls.push('disabled', 'disabled-date');
}
if ($.inArray(date.getUTCDay(), this.o.daysOfWeekHighlighted) !== -1){
cls.push('highlighted');
}
if (this.range){
if (date > this.range[0] && date < this.range[this.range.length-1]){
cls.push('range');
}
if ($.inArray(date.valueOf(), this.range) !== -1){
cls.push('selected');
}
if (date.valueOf() === this.range[0]){
cls.push('range-start');
}
if (date.valueOf() === this.range[this.range.length-1]){
cls.push('range-end');
}
}
return cls;
},
_fill_yearsView: function(selector, cssClass, factor, year, startYear, endYear, beforeFn){
var html = '';
var step = factor / 10;
var view = this.picker.find(selector);
var startVal = Math.floor(year / factor) * factor;
var endVal = startVal + step * 9;
var focusedVal = Math.floor(this.viewDate.getFullYear() / step) * step;
var selected = $.map(this.dates, function(d){
return Math.floor(d.getUTCFullYear() / step) * step;
});
var classes, tooltip, before;
for (var currVal = startVal - step; currVal <= endVal + step; currVal += step) {
classes = [cssClass];
tooltip = null;
if (currVal === startVal - step) {
classes.push('old');
} else if (currVal === endVal + step) {
classes.push('new');
}
if ($.inArray(currVal, selected) !== -1) {
classes.push('active');
}
if (currVal < startYear || currVal > endYear) {
classes.push('disabled');
}
if (currVal === focusedVal) {
classes.push('focused');
}
if (beforeFn !== $.noop) {
before = beforeFn(new Date(currVal, 0, 1));
if (before === undefined) {
before = {};
} else if (typeof before === 'boolean') {
before = {enabled: before};
} else if (typeof before === 'string') {
before = {classes: before};
}
if (before.enabled === false) {
classes.push('disabled');
}
if (before.classes) {
classes = classes.concat(before.classes.split(/\s+/));
}
if (before.tooltip) {
tooltip = before.tooltip;
}
}
html += '<span class="' + classes.join(' ') + '"' + (tooltip ? ' title="' + tooltip + '"' : '') + '>' + currVal + '</span>';
}
view.find('.datepicker-switch').text(startVal + '-' + endVal);
view.find('td').html(html);
},
fill: function(){
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
todaytxt = dates[this.o.language].today || dates['en'].today || '',
cleartxt = dates[this.o.language].clear || dates['en'].clear || '',
titleFormat = dates[this.o.language].titleFormat || dates['en'].titleFormat,
tooltip,
before;
if (isNaN(year) || isNaN(month))
return;
this.picker.find('.datepicker-days .datepicker-switch')
.text(DPGlobal.formatDate(d, titleFormat, this.o.language));
this.picker.find('tfoot .today')
.text(todaytxt)
.css('display', this.o.todayBtn === true || this.o.todayBtn === 'linked' ? 'table-cell' : 'none');
this.picker.find('tfoot .clear')
.text(cleartxt)
.css('display', this.o.clearBtn === true ? 'table-cell' : 'none');
this.picker.find('thead .datepicker-title')
.text(this.o.title)
.css('display', typeof this.o.title === 'string' && this.o.title !== '' ? 'table-cell' : 'none');
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month, 0),
day = prevMonth.getUTCDate();
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
if (prevMonth.getUTCFullYear() < 100){
nextMonth.setUTCFullYear(prevMonth.getUTCFullYear());
}
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var weekDay, clsName;
while (prevMonth.valueOf() < nextMonth){
weekDay = prevMonth.getUTCDay();
if (weekDay === this.o.weekStart){
html.push('<tr>');
if (this.o.calendarWeeks){
// ISO 8601: First week contains first thursday.
// ISO also states week starts on Monday, but we can be more abstract here.
var
// Start of current week: based on weekstart/current date
ws = new Date(+prevMonth + (this.o.weekStart - weekDay - 7) % 7 * 864e5),
// Thursday of this week
th = new Date(Number(ws) + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
// First Thursday of year, year from thursday
yth = new Date(Number(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay()) % 7 * 864e5),
// Calendar week: ms between thursdays, div ms per day, div 7 days
calWeek = (th - yth) / 864e5 / 7 + 1;
html.push('<td class="cw">'+ calWeek +'</td>');
}
}
clsName = this.getClassNames(prevMonth);
clsName.push('day');
var content = prevMonth.getUTCDate();
if (this.o.beforeShowDay !== $.noop){
before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
if (before === undefined)
before = {};
else if (typeof before === 'boolean')
before = {enabled: before};
else if (typeof before === 'string')
before = {classes: before};
if (before.enabled === false)
clsName.push('disabled');
if (before.classes)
clsName = clsName.concat(before.classes.split(/\s+/));
if (before.tooltip)
tooltip = before.tooltip;
if (before.content)
content = before.content;
}
//Check if uniqueSort exists (supported by jquery >=1.12 and >=2.2)
//Fallback to unique function for older jquery versions
if ($.isFunction($.uniqueSort)) {
clsName = $.uniqueSort(clsName);
} else {
clsName = $.unique(clsName);
}
html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + ' data-date="' + prevMonth.getTime().toString() + '">' + content + '</td>');
tooltip = null;
if (weekDay === this.o.weekEnd){
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
}
this.picker.find('.datepicker-days tbody').html(html.join(''));
var monthsTitle = dates[this.o.language].monthsTitle || dates['en'].monthsTitle || 'Months';
var months = this.picker.find('.datepicker-months')
.find('.datepicker-switch')
.text(this.o.maxViewMode < 2 ? monthsTitle : year)
.end()
.find('tbody span').removeClass('active');
$.each(this.dates, function(i, d){
if (d.getUTCFullYear() === year)
months.eq(d.getUTCMonth()).addClass('active');
});
if (year < startYear || year > endYear){
months.addClass('disabled');
}
if (year === startYear){
months.slice(0, startMonth).addClass('disabled');
}
if (year === endYear){
months.slice(endMonth+1).addClass('disabled');
}
if (this.o.beforeShowMonth !== $.noop){
var that = this;
$.each(months, function(i, month){
var moDate = new Date(year, i, 1);
var before = that.o.beforeShowMonth(moDate);
if (before === undefined)
before = {};
else if (typeof before === 'boolean')
before = {enabled: before};
else if (typeof before === 'string')
before = {classes: before};
if (before.enabled === false && !$(month).hasClass('disabled'))
$(month).addClass('disabled');
if (before.classes)
$(month).addClass(before.classes);
if (before.tooltip)
$(month).prop('title', before.tooltip);
});
}
// Generating decade/years picker
this._fill_yearsView(
'.datepicker-years',
'year',
10,
year,
startYear,
endYear,
this.o.beforeShowYear
);
// Generating century/decades picker
this._fill_yearsView(
'.datepicker-decades',
'decade',
100,
year,
startYear,
endYear,
this.o.beforeShowDecade
);
// Generating millennium/centuries picker
this._fill_yearsView(
'.datepicker-centuries',
'century',
1000,
year,
startYear,
endYear,
this.o.beforeShowCentury
);
},
updateNavArrows: function(){
if (!this._allow_update)
return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
prevIsDisabled,
nextIsDisabled,
factor = 1;
switch (this.viewMode){
case 0:
prevIsDisabled = year <= startYear && month <= startMonth;
nextIsDisabled = year >= endYear && month >= endMonth;
break;
case 4:
factor *= 10;
/* falls through */
case 3:
factor *= 10;
/* falls through */
case 2:
factor *= 10;
/* falls through */
case 1:
prevIsDisabled = Math.floor(year / factor) * factor <= startYear;
nextIsDisabled = Math.floor(year / factor) * factor + factor >= endYear;
break;
}
this.picker.find('.prev').toggleClass('disabled', prevIsDisabled);
this.picker.find('.next').toggleClass('disabled', nextIsDisabled);
},
click: function(e){
e.preventDefault();
e.stopPropagation();
var target, dir, day, year, month;
target = $(e.target);
// Clicked on the switch
if (target.hasClass('datepicker-switch') && this.viewMode !== this.o.maxViewMode){
this.setViewMode(this.viewMode + 1);
}
// Clicked on today button
if (target.hasClass('today') && !target.hasClass('day')){
this.setViewMode(0);
this._setDate(UTCToday(), this.o.todayBtn === 'linked' ? null : 'view');
}
// Clicked on clear button
if (target.hasClass('clear')){
this.clearDates();
}
if (!target.hasClass('disabled')){
// Clicked on a month, year, decade, century
if (target.hasClass('month')
|| target.hasClass('year')
|| target.hasClass('decade')
|| target.hasClass('century')) {
this.viewDate.setUTCDate(1);
day = 1;
if (this.viewMode === 1){
month = target.parent().find('span').index(target);
year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
} else {
month = 0;
year = Number(target.text());
this.viewDate.setUTCFullYear(year);
}
this._trigger(DPGlobal.viewModes[this.viewMode - 1].e, this.viewDate);
if (this.viewMode === this.o.minViewMode){
this._setDate(UTCDate(year, month, day));
} else {
this.setViewMode(this.viewMode - 1);
this.fill();
}
}
}
if (this.picker.is(':visible') && this._focused_from){
this._focused_from.focus();
}
delete this._focused_from;
},
dayCellClick: function(e){
var $target = $(e.currentTarget);
var timestamp = $target.data('date');
var date = new Date(timestamp);
if (this.o.updateViewDate) {
if (date.getUTCFullYear() !== this.viewDate.getUTCFullYear()) {
this._trigger('changeYear', this.viewDate);
}
if (date.getUTCMonth() !== this.viewDate.getUTCMonth()) {
this._trigger('changeMonth', this.viewDate);
}
}
this._setDate(date);
},
// Clicked on prev or next
navArrowsClick: function(e){
var $target = $(e.currentTarget);
var dir = $target.hasClass('prev') ? -1 : 1;
if (this.viewMode !== 0){
dir *= DPGlobal.viewModes[this.viewMode].navStep * 12;
}
this.viewDate = this.moveMonth(this.viewDate, dir);
this._trigger(DPGlobal.viewModes[this.viewMode].e, this.viewDate);
this.fill();
},
_toggle_multidate: function(date){
var ix = this.dates.contains(date);
if (!date){
this.dates.clear();
}
if (ix !== -1){
if (this.o.multidate === true || this.o.multidate > 1 || this.o.toggleActive){
this.dates.remove(ix);
}
} else if (this.o.multidate === false) {
this.dates.clear();
this.dates.push(date);
}
else {
this.dates.push(date);
}
if (typeof this.o.multidate === 'number')
while (this.dates.length > this.o.multidate)
this.dates.remove(0);
},
_setDate: function(date, which){
if (!which || which === 'date')
this._toggle_multidate(date && new Date(date));
if ((!which && this.o.updateViewDate) || which === 'view')
this.viewDate = date && new Date(date);
this.fill();
this.setValue();
if (!which || which !== 'view') {
this._trigger('changeDate');
}
this.inputField.trigger('change');
if (this.o.autoclose && (!which || which === 'date')){
this.hide();
}
},
moveDay: function(date, dir){
var newDate = new Date(date);
newDate.setUTCDate(date.getUTCDate() + dir);
return newDate;
},
moveWeek: function(date, dir){
return this.moveDay(date, dir * 7);
},
moveMonth: function(date, dir){
if (!isValidDate(date))
return this.o.defaultViewDate;
if (!dir)
return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag === 1){
test = dir === -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function(){
return new_date.getUTCMonth() === month;
}
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function(){
return new_date.getUTCMonth() !== new_month;
};
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
new_month = (new_month + 12) % 12;
}
else {
// For magnitudes >1, move one month at a time...
for (var i=0; i < mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function(){
return new_month !== new_date.getUTCMonth();
};
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()){
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function(date, dir){
return this.moveMonth(date, dir*12);
},
moveAvailableDate: function(date, dir, fn){
do {
date = this[fn](date, dir);
if (!this.dateWithinRange(date))
return false;
fn = 'moveDay';
}
while (this.dateIsDisabled(date));
return date;
},
weekOfDateIsDisabled: function(date){
return $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1;
},
dateIsDisabled: function(date){
return (
this.weekOfDateIsDisabled(date) ||
$.grep(this.o.datesDisabled, function(d){
return isUTCEquals(date, d);
}).length > 0
);
},
dateWithinRange: function(date){
return date >= this.o.startDate && date <= this.o.endDate;
},
keydown: function(e){
if (!this.picker.is(':visible')){
if (e.keyCode === 40 || e.keyCode === 27) { // allow down to re-show picker
this.show();
e.stopPropagation();
}
return;
}
var dateChanged = false,
dir, newViewDate,
focusDate = this.focusDate || this.viewDate;
switch (e.keyCode){
case 27: // escape
if (this.focusDate){
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
}
else
this.hide();
e.preventDefault();
e.stopPropagation();
break;
case 37: // left
case 38: // up
case 39: // right
case 40: // down
if (!this.o.keyboardNavigation || this.o.daysOfWeekDisabled.length === 7)
break;
dir = e.keyCode === 37 || e.keyCode === 38 ? -1 : 1;
if (this.viewMode === 0) {
if (e.ctrlKey){
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveYear');
if (newViewDate)
this._trigger('changeYear', this.viewDate);
} else if (e.shiftKey){
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveMonth');
if (newViewDate)
this._trigger('changeMonth', this.viewDate);
} else if (e.keyCode === 37 || e.keyCode === 39){
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveDay');
} else if (!this.weekOfDateIsDisabled(focusDate)){
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveWeek');
}
} else if (this.viewMode === 1) {
if (e.keyCode === 38 || e.keyCode === 40) {
dir = dir * 4;
}
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveMonth');
} else if (this.viewMode === 2) {
if (e.keyCode === 38 || e.keyCode === 40) {
dir = dir * 4;
}
newViewDate = this.moveAvailableDate(focusDate, dir, 'moveYear');
}
if (newViewDate){
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 13: // enter
if (!this.o.forceParse)
break;
focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
if (this.o.keyboardNavigation) {
this._toggle_multidate(focusDate);
dateChanged = true;
}
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.setValue();
this.fill();
if (this.picker.is(':visible')){
e.preventDefault();
e.stopPropagation();
if (this.o.autoclose)
this.hide();
}
break;
case 9: // tab
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
this.hide();
break;
}
if (dateChanged){
if (this.dates.length)
this._trigger('changeDate');
else
this._trigger('clearDate');
this.inputField.trigger('change');
}
},
setViewMode: function(viewMode){
this.viewMode = viewMode;
this.picker
.children('div')
.hide()
.filter('.datepicker-' + DPGlobal.viewModes[this.viewMode].clsName)
.show();
this.updateNavArrows();
this._trigger('changeViewMode', new Date(this.viewDate));
}
};
var DateRangePicker = function(element, options){
$.data(element, 'datepicker', this);
this.element = $(element);
this.inputs = $.map(options.inputs, function(i){
return i.jquery ? i[0] : i;
});
delete options.inputs;
this.keepEmptyValues = options.keepEmptyValues;
delete options.keepEmptyValues;
datepickerPlugin.call($(this.inputs), options)
.on('changeDate', $.proxy(this.dateUpdated, this));
this.pickers = $.map(this.inputs, function(i){
return $.data(i, 'datepicker');
});
this.updateDates();
};
DateRangePicker.prototype = {
updateDates: function(){
this.dates = $.map(this.pickers, function(i){
return i.getUTCDate();
});
this.updateRanges();
},
updateRanges: function(){
var range = $.map(this.dates, function(d){
return d.valueOf();
});
$.each(this.pickers, function(i, p){
p.setRange(range);
});
},
dateUpdated: function(e){
// `this.updating` is a workaround for preventing infinite recursion
// between `changeDate` triggering and `setUTCDate` calling. Until
// there is a better mechanism.
if (this.updating)
return;
this.updating = true;
var dp = $.data(e.target, 'datepicker');
if (dp === undefined) {
return;
}
var new_date = dp.getUTCDate(),
keep_empty_values = this.keepEmptyValues,
i = $.inArray(e.target, this.inputs),
j = i - 1,
k = i + 1,
l = this.inputs.length;
if (i === -1)
return;
$.each(this.pickers, function(i, p){
if (!p.getUTCDate() && (p === dp || !keep_empty_values))
p.setUTCDate(new_date);
});
if (new_date < this.dates[j]){
// Date being moved earlier/left
while (j >= 0 && new_date < this.dates[j]){
this.pickers[j--].setUTCDate(new_date);
}
} else if (new_date > this.dates[k]){
// Date being moved later/right
while (k < l && new_date > this.dates[k]){
this.pickers[k++].setUTCDate(new_date);
}
}
this.updateDates();
delete this.updating;
},
destroy: function(){
$.map(this.pickers, function(p){ p.destroy(); });
$(this.inputs).off('changeDate', this.dateUpdated);
delete this.element.data().datepicker;
},
remove: alias('destroy', 'Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead')
};
function opts_from_el(el, prefix){
// Derive options from element data-attrs
var data = $(el).data(),
out = {}, inkey,
replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
prefix = new RegExp('^' + prefix.toLowerCase());
function re_lower(_,a){
return a.toLowerCase();
}
for (var key in data)
if (prefix.test(key)){
inkey = key.replace(replace, re_lower);
out[inkey] = data[key];
}
return out;
}
function opts_from_locale(lang){
// Derive options from locale plugins
var out = {};
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
if (!dates[lang]){
lang = lang.split('-')[0];
if (!dates[lang])
return;
}
var d = dates[lang];
$.each(locale_opts, function(i,k){
if (k in d)
out[k] = d[k];
});
return out;
}
var old = $.fn.datepicker;
var datepickerPlugin = function(option){
var args = Array.apply(null, arguments);
args.shift();
var internal_return;
this.each(function(){
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option === 'object' && option;
if (!data){
var elopts = opts_from_el(this, 'date'),
// Preliminary otions
xopts = $.extend({}, defaults, elopts, options),
locopts = opts_from_locale(xopts.language),
// Options priority: js args, data-attrs, locales, defaults
opts = $.extend({}, defaults, locopts, elopts, options);
if ($this.hasClass('input-daterange') || opts.inputs){
$.extend(opts, {
inputs: opts.inputs || $this.find('input').toArray()
});
data = new DateRangePicker(this, opts);
}
else {
data = new Datepicker(this, opts);
}
$this.data('datepicker', data);
}
if (typeof option === 'string' && typeof data[option] === 'function'){
internal_return = data[option].apply(data, args);
}
});
if (
internal_return === undefined ||
internal_return instanceof Datepicker ||
internal_return instanceof DateRangePicker
)
return this;
if (this.length > 1)
throw new Error('Using only allowed for the collection of a single element (' + option + ' function)');
else
return internal_return;
};
$.fn.datepicker = datepickerPlugin;
var defaults = $.fn.datepicker.defaults = {
assumeNearbyYear: false,
autoclose: false,
beforeShowDay: $.noop,
beforeShowMonth: $.noop,
beforeShowYear: $.noop,
beforeShowDecade: $.noop,
beforeShowCentury: $.noop,
calendarWeeks: false,
clearBtn: false,
toggleActive: false,
daysOfWeekDisabled: [],
daysOfWeekHighlighted: [],
datesDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'mm/dd/yyyy',
keepEmptyValues: false,
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
maxViewMode: 4,
multidate: false,
multidateSeparator: ',',
orientation: "auto",
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
updateViewDate: true,
weekStart: 0,
disableTouchKeyboard: false,
enableOnReadonly: true,
showOnFocus: true,
zIndexOffset: 10,
container: 'body',
immediateUpdates: false,
title: '',
templates: {
leftArrow: '«',
rightArrow: '»'
},
showWeekDays: true
};
var locale_opts = $.fn.datepicker.locale_opts = [
'format',
'rtl',
'weekStart'
];
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear",
titleFormat: "MM yyyy"
}
};
var DPGlobal = {
viewModes: [
{
names: ['days', 'month'],
clsName: 'days',
e: 'changeMonth'
},
{
names: ['months', 'year'],
clsName: 'months',
e: 'changeYear',
navStep: 1
},
{
names: ['years', 'decade'],
clsName: 'years',
e: 'changeDecade',
navStep: 10
},
{
names: ['decades', 'century'],
clsName: 'decades',
e: 'changeCentury',
navStep: 100
},
{
names: ['centuries', 'millennium'],
clsName: 'centuries',
e: 'changeMillennium',
navStep: 1000
}
],
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,
parseFormat: function(format){
if (typeof format.toValue === 'function' && typeof format.toDisplay === 'function')
return format;
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function(date, format, language, assumeNearby){
if (!date)
return undefined;
if (date instanceof Date)
return date;
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
if (format.toValue)
return format.toValue(date, format, language);
var fn_map = {
d: 'moveDay',
m: 'moveMonth',
w: 'moveWeek',
y: 'moveYear'
},
dateAliases = {
yesterday: '-1d',
today: '+0d',
tomorrow: '+1d'
},
parts, part, dir, i, fn;
if (date in dateAliases){
date = dateAliases[date];
}
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/i.test(date)){
parts = date.match(/([\-+]\d+)([dmwy])/gi);
date = new Date();
for (i=0; i < parts.length; i++){
part = parts[i].match(/([\-+]\d+)([dmwy])/i);
dir = Number(part[1]);
fn = fn_map[part[2].toLowerCase()];
date = Datepicker.prototype[fn](date, dir);
}
return Datepicker.prototype._zero_utc_time(date);
}
parts = date && date.match(this.nonpunctuation) || [];
function applyNearbyYear(year, threshold){
if (threshold === true)
threshold = 10;
// if year is 2 digits or less, than the user most likely is trying to get a recent century
if (year < 100){
year += 2000;
// if the new year is more than threshold years in advance, use last century
if (year > ((new Date()).getFullYear()+threshold)){
year -= 100;
}
}
return year;
}
var parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function(d,v){
return d.setUTCFullYear(assumeNearby ? applyNearbyYear(v, assumeNearby) : v);
},
m: function(d,v){
if (isNaN(d))
return d;
v -= 1;
while (v < 0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() !== v)
d.setUTCDate(d.getUTCDate()-1);
return d;
},
d: function(d,v){
return d.setUTCDate(v);
}
},
val, filtered;
setters_map['yy'] = setters_map['yyyy'];
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCToday();
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length !== fparts.length){
fparts = $(fparts).filter(function(i,p){
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
function match_part(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m.toLowerCase() === p.toLowerCase();
}
if (parts.length === fparts.length){
var cnt;
for (i=0, cnt = fparts.length; i < cnt; i++){
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)){
switch (part){
case 'MM':
filtered = $(dates[language].months).filter(match_part);
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(match_part);
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
var _date, s;
for (i=0; i < setters_order.length; i++){
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s])){
_date = new Date(date);
setters_map[s](_date, parsed[s]);
if (!isNaN(_date))
date = _date;
}
}
}
return date;
},
formatDate: function(date, format, language){
if (!date)
return '';
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
if (format.toDisplay)
return format.toDisplay(date, format, language);
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
date = [];
var seps = $.extend([], format.separators);
for (var i=0, cnt = format.parts.length; i <= cnt; i++){
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>'+
'<tr>'+
'<th colspan="7" class="datepicker-title"></th>'+
'</tr>'+
'<tr>'+
'<th class="prev">'+defaults.templates.leftArrow+'</th>'+
'<th colspan="5" class="datepicker-switch"></th>'+
'<th class="next">'+defaults.templates.rightArrow+'</th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot>'+
'<tr>'+
'<th colspan="7" class="today"></th>'+
'</tr>'+
'<tr>'+
'<th colspan="7" class="clear"></th>'+
'</tr>'+
'</tfoot>'
};
DPGlobal.template = '<div class="datepicker">'+
'<div class="datepicker-days">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-decades">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-centuries">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
/* DATEPICKER NO CONFLICT
* =================== */
$.fn.datepicker.noConflict = function(){
$.fn.datepicker = old;
return this;
};
/* DATEPICKER VERSION
* =================== */
$.fn.datepicker.version = '1.7.1';
$.fn.datepicker.deprecated = function(msg){
var console = window.console;
if (console && console.warn) {
console.warn('DEPRECATED: ' + msg);
}
};
/* DATEPICKER DATA-API
* ================== */
$(document).on(
'focus.datepicker.data-api click.datepicker.data-api',
'[data-provide="datepicker"]',
function(e){
var $this = $(this);
if ($this.data('datepicker'))
return;
e.preventDefault();
// component click requires us to explicitly show it
datepickerPlugin.call($this, 'show');
}
);
$(function(){
datepickerPlugin.call($('[data-provide="datepicker-inline"]'));
});
}));
|
var parent = require('../../actual/typed-array/every');
module.exports = parent;
|
// This is (almost) directly from Node.js utils
// https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js
var getName = require('./getName');
module.exports = inspect;
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Boolean} showHidden Flag that shows hidden (not enumerable)
* properties of objects.
* @param {Number} depth Depth in which to descend in object. Default is 2.
* @param {Boolean} colors Flag to turn on ANSI escape codes to color the
* output. Default is false (no coloring).
*/
function inspect(obj, showHidden, depth, colors) {
var ctx = {
showHidden: showHidden,
seen: [],
stylize: function (str) { return str; }
};
return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth));
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (value && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
return value.inspect(recurseTimes);
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var visibleKeys = Object.keys(value);
var keys = ctx.showHidden ? Object.getOwnPropertyNames(value) : visibleKeys;
// Some type of object without properties can be shortcutted.
// In IE, errors have a single `stack` property, or if they are vanilla `Error`,
// a `stack` plus `description` property; ignore those for consistency.
if (keys.length === 0 || (isError(value) && (
(keys.length === 1 && keys[0] === 'stack') ||
(keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack')
))) {
if (typeof value === 'function') {
var name = getName(value);
var nameSuffix = name ? ': ' + name : '';
return ctx.stylize('[Function' + nameSuffix + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toUTCString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (typeof value === 'function') {
var name = getName(value);
var nameSuffix = name ? ': ' + name : '';
base = ' [Function' + nameSuffix + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
return formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
switch (typeof value) {
case 'undefined':
return ctx.stylize('undefined', 'undefined');
case 'string':
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
case 'number':
return ctx.stylize('' + value, 'number');
case 'boolean':
return ctx.stylize('' + value, 'boolean');
}
// For some reason typeof null is "object", so special case here.
if (value === null) {
return ctx.stylize('null', 'null');
}
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (Object.prototype.hasOwnProperty.call(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str;
if (value.__lookupGetter__) {
if (value.__lookupGetter__(key)) {
if (value.__lookupSetter__(key)) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (value.__lookupSetter__(key)) {
str = ctx.stylize('[Setter]', 'special');
}
}
}
if (visibleKeys.indexOf(key) < 0) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(value[key]) < 0) {
if (recurseTimes === null) {
str = formatValue(ctx, value[key], null);
} else {
str = formatValue(ctx, value[key], recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (typeof name === 'undefined') {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
function isArray(ar) {
return Array.isArray(ar) ||
(typeof ar === 'object' && objectToString(ar) === '[object Array]');
}
function isRegExp(re) {
return typeof re === 'object' && objectToString(re) === '[object RegExp]';
}
function isDate(d) {
return typeof d === 'object' && objectToString(d) === '[object Date]';
}
function isError(e) {
return typeof e === 'object' && objectToString(e) === '[object Error]';
}
function objectToString(o) {
return Object.prototype.toString.call(o);
}
|
import { DEBUG } from '@glimmer/env';
import { moduleFor, RenderingTestCase, runTask } from 'internal-test-helpers';
import { set } from '@ember/-internals/metal';
import { Component } from '../../utils/helpers';
moduleFor(
'Errors thrown during render',
class extends RenderingTestCase {
['@test it can recover resets the transaction when an error is thrown during initial render'](
assert
) {
let shouldThrow = true;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
if (shouldThrow) {
throw new Error('silly mistake in init!');
}
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
assert.throws(() => {
this.render('{{#if this.switch}}{{#foo-bar}}{{foo-bar}}{{/foo-bar}}{{/if}}', {
switch: true,
});
}, /silly mistake in init/);
assert.equal(
this.renderer._inRenderTransaction,
false,
'should not be in a transaction even though an error was thrown'
);
this.assertText('');
runTask(() => set(this.context, 'switch', false));
shouldThrow = false;
runTask(() => set(this.context, 'switch', true));
if (DEBUG) {
this.assertText('', 'it does not rerender after error in development');
} else {
this.assertText('hello', 'it rerenders after error in production');
}
}
['@skip it can recover resets the transaction when an error is thrown during rerender'](
assert
) {
let shouldThrow = false;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
if (shouldThrow) {
throw new Error('silly mistake in init!');
}
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{#if this.switch}}{{#foo-bar}}{{foo-bar}}{{/foo-bar}}{{/if}}', {
switch: true,
});
this.assertText('hello');
runTask(() => set(this.context, 'switch', false));
shouldThrow = true;
assert.throws(() => {
runTask(() => set(this.context, 'switch', true));
}, /silly mistake in init/);
assert.equal(
this.renderer._inRenderTransaction,
false,
'should not be in a transaction even though an error was thrown'
);
this.assertText('');
runTask(() => set(this.context, 'switch', false));
shouldThrow = false;
runTask(() => set(this.context, 'switch', true));
if (DEBUG) {
this.assertText('', 'it does not rerender after error in development');
} else {
this.assertText('hello', 'it does rerender after error in production');
}
}
['@test it can recover resets the transaction when an error is thrown during didInsertElement'](
assert
) {
let shouldThrow = true;
let FooBarComponent = Component.extend({
didInsertElement() {
this._super(...arguments);
if (shouldThrow) {
throw new Error('silly mistake!');
}
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
assert.throws(() => {
this.render('{{#if this.switch}}{{#foo-bar}}{{foo-bar}}{{/foo-bar}}{{/if}}', {
switch: true,
});
}, /silly mistake/);
assert.equal(
this.renderer._inRenderTransaction,
false,
'should not be in a transaction even though an error was thrown'
);
this.assertText('hello');
runTask(() => set(this.context, 'switch', false));
this.assertText('');
}
['@test it can recover resets the transaction when an error is thrown during destroy'](assert) {
let shouldThrow = true;
let FooBarComponent = Component.extend({
destroy() {
this._super(...arguments);
if (shouldThrow) {
throw new Error('silly mistake!');
}
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{#if this.switch}}{{#foo-bar}}{{foo-bar}}{{/foo-bar}}{{/if}}', {
switch: true,
});
this.assertText('hello');
assert.throws(() => {
runTask(() => set(this.context, 'switch', false));
}, /silly mistake/);
this.assertText('');
shouldThrow = false;
runTask(() => set(this.context, 'switch', true));
this.assertText('hello');
}
}
);
|
/*!
* jQuery UI Effects Size @VERSION
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Size Effect
//>>group: Effects
//>>description: Resize an element to a specified width and height.
//>>docs: http://api.jqueryui.com/size-effect/
//>>demos: http://jqueryui.com/effect/
( function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [
"jquery",
"../version",
"../effect"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}( function( $ ) {
return $.effects.define( "size", function( options, done ) {
// Create element
var baseline, factor, temp,
element = $( this ),
// Copy for children
cProps = [ "fontSize" ],
vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],
// Set options
mode = options.mode,
restore = mode !== "effect",
scale = options.scale || "both",
origin = options.origin || [ "middle", "center" ],
position = element.css( "position" ),
pos = element.position(),
original = $.effects.scaledDimensions( element ),
from = options.from || original,
to = options.to || $.effects.scaledDimensions( element, 0 );
$.effects.createPlaceholder( element );
if ( mode === "show" ) {
temp = from;
from = to;
to = temp;
}
// Set scaling factor
factor = {
from: {
y: from.height / original.height,
x: from.width / original.width
},
to: {
y: to.height / original.height,
x: to.width / original.width
}
};
// Scale the css box
if ( scale === "box" || scale === "both" ) {
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
from = $.effects.setTransition( element, vProps, factor.from.y, from );
to = $.effects.setTransition( element, vProps, factor.to.y, to );
}
// Horizontal props scaling
if ( factor.from.x !== factor.to.x ) {
from = $.effects.setTransition( element, hProps, factor.from.x, from );
to = $.effects.setTransition( element, hProps, factor.to.x, to );
}
}
// Scale the content
if ( scale === "content" || scale === "both" ) {
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
from = $.effects.setTransition( element, cProps, factor.from.y, from );
to = $.effects.setTransition( element, cProps, factor.to.y, to );
}
}
// Adjust the position properties based on the provided origin points
if ( origin ) {
baseline = $.effects.getBaseline( origin, original );
from.top = ( original.outerHeight - from.outerHeight ) * baseline.y + pos.top;
from.left = ( original.outerWidth - from.outerWidth ) * baseline.x + pos.left;
to.top = ( original.outerHeight - to.outerHeight ) * baseline.y + pos.top;
to.left = ( original.outerWidth - to.outerWidth ) * baseline.x + pos.left;
}
element.css( from );
// Animate the children if desired
if ( scale === "content" || scale === "both" ) {
vProps = vProps.concat( [ "marginTop", "marginBottom" ] ).concat( cProps );
hProps = hProps.concat( [ "marginLeft", "marginRight" ] );
// Only animate children with width attributes specified
// TODO: is this right? should we include anything with css width specified as well
element.find( "*[width]" ).each( function() {
var child = $( this ),
childOriginal = $.effects.scaledDimensions( child ),
childFrom = {
height: childOriginal.height * factor.from.y,
width: childOriginal.width * factor.from.x,
outerHeight: childOriginal.outerHeight * factor.from.y,
outerWidth: childOriginal.outerWidth * factor.from.x
},
childTo = {
height: childOriginal.height * factor.to.y,
width: childOriginal.width * factor.to.x,
outerHeight: childOriginal.height * factor.to.y,
outerWidth: childOriginal.width * factor.to.x
};
// Vertical props scaling
if ( factor.from.y !== factor.to.y ) {
childFrom = $.effects.setTransition( child, vProps, factor.from.y, childFrom );
childTo = $.effects.setTransition( child, vProps, factor.to.y, childTo );
}
// Horizontal props scaling
if ( factor.from.x !== factor.to.x ) {
childFrom = $.effects.setTransition( child, hProps, factor.from.x, childFrom );
childTo = $.effects.setTransition( child, hProps, factor.to.x, childTo );
}
if ( restore ) {
$.effects.saveStyle( child );
}
// Animate children
child.css( childFrom );
child.animate( childTo, options.duration, options.easing, function() {
// Restore children
if ( restore ) {
$.effects.restoreStyle( child );
}
} );
} );
}
// Animate
element.animate( to, {
queue: false,
duration: options.duration,
easing: options.easing,
complete: function() {
var offset = element.offset();
if ( to.opacity === 0 ) {
element.css( "opacity", from.opacity );
}
if ( !restore ) {
element
.css( "position", position === "static" ? "relative" : position )
.offset( offset );
// Need to save style here so that automatic style restoration
// doesn't restore to the original styles from before the animation.
$.effects.saveStyle( element );
}
done();
}
} );
} );
} ) );
|
/*
* Copyright (C) 2014 rafa
*
* This program 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 2
* of the License, or (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
function fRedsocialperfilRoutes() {
// Path.map("#/redsocialperfil").to(function () {
// $('#indexContenidoJsp').spinner();
// control('redsocialperfil').list($('#indexContenido'), param().defaultizeUrlObjectParameters({}), null);
// //redsocialperfilControl.modalListEventsLoading(redsocialperfilObject, redsocialperfilView, $('#indexContenido'), param().defaultizeUrlObjectParameters({}), null);
// $('#indexContenidoJsp').empty();
// return false;
// });
Path.map("#/redsocialperfil").to(function () {
$('#indexContenidoJsp').spinner();
oRedsocialperfilControl.list($('#indexContenido'), param().defaultizeUrlObjectParameters({}), null, oRedsocialperfilModel, oRedsocialperfilView);
//redsocialperfilControl.modalListEventsLoading(redsocialperfilObject, redsocialperfilView, $('#indexContenido'), param().defaultizeUrlObjectParameters({}), null);
$('#indexContenidoJsp').empty();
$('#indexContenidoJsp').append(oRedsocialperfilControl.getClassNameRedsocialperfil());
return false;
});
Path.map("#/redsocialperfil/list/:url").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oRedsocialperfilControl.list($('#indexContenido'), paramsObject, null, oRedsocialperfilModel, oRedsocialperfilView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/redsocialperfil/view/:id").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oRedsocialperfilControl.view($('#indexContenido'), paramsObject['id'], oRedsocialperfilModel, oRedsocialperfilView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/redsocialperfil/edit/:id").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oRedsocialperfilControl.edit($('#indexContenido'), paramsObject['id'], oRedsocialperfilModel, oRedsocialperfilView);
$('#indexContenidoJsp').empty();
});
Path.map("#/redsocialperfil/new").to(function () {
$('#indexContenidoJsp').spinner();
//var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oRedsocialperfilControl.new($('#indexContenido'), null, oRedsocialperfilModel, oRedsocialperfilView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/redsocialperfil/new/:url").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oRedsocialperfilControl.new($('#indexContenido'), paramsObject, oRedsocialperfilModel, oRedsocialperfilView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/redsocialperfil/remove/:id").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oRedsocialperfilControl.remove($('#indexContenido'), paramsObject['id'], oRedsocialperfilModel, oRedsocialperfilView);
$('#indexContenidoJsp').empty();
return false;
});
Path.map("#/redsocialperfil/duplicate/:id").to(function () {
$('#indexContenidoJsp').spinner();
var paramsObject = param().defaultizeUrlObjectParameters(param().getUrlObjectFromUrlString(this.params['url']));
oRedsocialperfilControl.duplicate($('#indexContenido'), paramsObject['id'], oRedsocialperfilModel, oRedsocialperfilView);
$('#indexContenidoJsp').empty();
return false;
});
}
|
steal('can/util/can.js', 'mootools', 'can/util/event.js','can/util/fragment.js', 'can/util/deferred.js',
'can/util/array/each.js', 'can/util/object/isplain', "can/util/inserted",function(can) {
// mootools.js
// ---------
// _MooTools node list._
//
// Map string helpers.
can.trim = function(s){
return s && s.trim()
}
// This extend() function is ruthlessly and shamelessly stolen from
// jQuery 1.8.2:, lines 291-353.
var extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !can.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( can.isPlainObject(copy) || (copyIsArray = can.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && can.isArray(src) ? src : [];
} else {
clone = src && can.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = can.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
can.extend = extend;
// Map array helpers.
can.makeArray = function(item) {
// All other libraries return a copy if item is an array.
// The original Mootools Array.from returned the same item so we need to slightly modify it
if (item == null) return [];
try {
return (Type.isEnumerable(item) && typeof item != 'string') ? Array.prototype.slice.call(item) : [item];
} catch(ex) {
// some things like DOMNodeChildCollections don't slice so good.
// This pains me, but it has to be done.
var arr = [],
i;
for( i = 0; i < item.length; ++i) {
arr.push(item[i]);
}
return arr;
}
}
can.isArray = function(arr) {
return typeOf(arr) === 'array'
};
can.inArray = function(item,arr,fromIndex) {
if(!arr) {
return -1;
}
return Array.prototype.indexOf.call(arr, item, fromIndex);
}
can.map = function(arr, fn){
return Array.from(arr||[]).map(fn);
}
// Map object helpers.
can.param = function(object){
return Object.toQueryString(object)
}
can.isEmptyObject = function(object){
return Object.keys(object).length === 0;
}
// Map function helpers.
can.proxy = function(func){
var args = can.makeArray(arguments),
func = args.shift();
return func.bind.apply(func, args)
}
can.isFunction = function(f){
return typeOf(f) == 'function'
}
// Make this object so you can bind on it.
can.bind = function( ev, cb){
// If we can bind to it...
if(this.bind && this.bind !== can.bind){
this.bind(ev, cb)
} else if(this.addEvent) {
this.addEvent(ev, cb);
} else if(this.nodeName && this.nodeType == 1) {
$(this).addEvent(ev, cb)
} else {
// Make it bind-able...
can.addEvent.call(this, ev, cb)
}
return this;
}
can.unbind = function(ev, cb){
// If we can bind to it...
if(this.unbind && this.unbind !== can.unbind){
this.unbind(ev, cb)
} else if(this.removeEvent) {
this.removeEvent(ev, cb)
} if(this.nodeName && this.nodeType == 1) {
$(this).removeEvent(ev, cb)
} else {
// Make it bind-able...
can.removeEvent.call(this, ev, cb)
}
return this;
}
// Alias on/off to bind/unbind respectively
can.on = can.bind;
can.off = can.unbind;
can.trigger = function(item, event, args, bubble){
// Defaults to `true`.
bubble = (bubble === undefined ? true : bubble);
args = args || [];
var propagating = true;
if(item.fireEvent){
item = item[0] || item;
// walk up parents to simulate bubbling .
while(item && propagating) {
// Handle walking yourself.
if(!event.type){
event = {
type : event,
target : item,
stopPropagation: function(){
propagating = false;
}
}
}
var events = (item !== window ?
can.$(item).retrieve('events')[0] :
item.retrieve('events') );
if (events && events[event.type]) {
events[event.type].keys.each(function(fn){
fn.apply(item, [event].concat(args));
}, this);
}
// If we are bubbling, get parent node.
if(bubble && item.parentNode && item.parentNode.nodeType != 11){
item = item.parentNode
} else {
item = null;
}
}
} else {
if(typeof event === 'string'){
event = {type: event}
}
event.target = event.target || item;
can.dispatch.call(item, event, args)
}
}
can.delegate = function(selector, ev , cb){
if(this.delegate) {
this.delegate(selector, ev , cb)
}
else if(this.addEvent) {
this.addEvent(ev+":relay("+selector+")", cb)
} else {
// make it bind-able ...
}
return this;
}
can.undelegate = function(selector, ev , cb){
if(this.undelegate) {
this.undelegate(selector, ev , cb)
}
else if(this.removeEvent) {
this.removeEvent(ev+":relay("+selector+")", cb)
} else {
// make it bind-able ...
}
return this;
}
var optionsMap = {
type:"method",
success : undefined,
error: undefined
}
var updateDeferred = function(xhr, d){
for(var prop in xhr){
if(typeof d[prop] == 'function'){
d[prop] = function(){
xhr[prop].apply(xhr, arguments)
}
} else {
d[prop] = prop[xhr]
}
}
}
can.ajax = function(options){
var d = can.Deferred(),
requestOptions = can.extend({}, options),
request;
// Map jQuery options to MooTools options.
for(var option in optionsMap){
if(requestOptions[option] !== undefined){
requestOptions[optionsMap[option]] = requestOptions[option];
delete requestOptions[option]
}
}
// Mootools defaults to 'post', but Can expects a default of 'get'
requestOptions.method = requestOptions.method || 'get';
requestOptions.url = requestOptions.url.toString();
var success = options.onSuccess || options.success,
error = options.onFailure || options.error;
requestOptions.onSuccess = function(response, xml){
var data = response;
updateDeferred(request.xhr, d);
d.resolve(data,"success",request.xhr);
success && success(data,"success",request.xhr);
}
requestOptions.onFailure = function(){
updateDeferred(request.xhr, d);
d.reject(request.xhr,"error");
error && error(request.xhr,"error");
}
if(options.dataType ==='json'){
request = new Request.JSON(requestOptions);
} else {
request = new Request(requestOptions);
}
request.send();
updateDeferred(request.xhr, d);
return d;
}
// Element -- get the wrapped helper.
can.$ = function(selector){
if(selector === window){
return window;
}
return $$(selector)
}
// Add `document` fragment support.
var old = document.id;
document.id = function(el){
if(el && el.nodeType === 11){
return el
} else{
return old.apply(document, arguments);
}
};
can.append = function(wrapped, html){
if(typeof html === 'string'){
html = can.buildFragment(html)
}
return wrapped.grab(html)
}
can.filter = function(wrapped, filter){
return wrapped.filter(filter);
}
can.data = function(wrapped, key, value){
if(value === undefined){
return wrapped[0].retrieve(key)
} else {
return wrapped.store(key, value)
}
}
can.addClass = function(wrapped, className){
return wrapped.addClass(className);
}
can.remove = function(wrapped){
// We need to remove text nodes ourselves.
var filtered = wrapped.filter(function(node){
if(node.nodeType !== 1){
node.parentNode.removeChild(node);
} else {
return true;
}
})
filtered.destroy();
return filtered;
}
can.has = function(wrapped, element){
// this way work in mootools
if( Slick.contains(wrapped[0], element) ){
return wrapped
} else {
return []
}
}
// Destroyed method.
var destroy = Element.prototype.destroy,
grab = Element.prototype.grab;
Element.implement({
destroy : function(){
can.trigger(this,"removed",[],false)
var elems = this.getElementsByTagName("*");
for ( var i = 0, elem; (elem = elems[i]) !== undefined; i++ ) {
can.trigger(elem,"removed",[],false);
}
destroy.apply(this, arguments)
},
grab: function(el){
var elems;
if(el && el.nodeType === 11){
elems = can.makeArray(el.childNodes);
} else {
elems = [el]
}
var ret = grab.apply(this,arguments);
can.inserted( elems );
return ret;
}
});
can.get = function(wrapped, index){
return wrapped[index];
}
// Overwrite to handle IE not having an id.
// IE barfs if text node.
var idOf = Slick.uidOf;
Slick.uidOf = function(node){
// for some reason, in IE8, node will be the window but not equal it.
if(node.nodeType === 1 || node === window || node.document === document ) {
return idOf(node);
} else {
return Math.random();
}
}
Element.NativeEvents["hashchange"] = 2;
return can;
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.3.4_A4;
* @section: 15.3.4;
* @assertion: The Function prototype object does not have a valueOf property of its own. however, it inherits the valueOf property from the Object prototype Object;
* @description: Checking valueOf property at Function.prototype;
*/
//CHECK#1
if (Function.prototype.hasOwnProperty("valueOf") !== false) {
$ERROR('#1: The Function prototype object does not have a valueOf property of its own');
}
//CHECK#2
if (typeof Function.prototype.valueOf === "undefined") {
$ERROR('#2: however, it inherits the valueOf property from the Object prototype Object');
}
//CHECK#3
if (Function.prototype.valueOf !== Object.prototype.valueOf) {
$ERROR('#3: however, it inherits the valueOf property from the Object prototype Object');
}
|
var auto = require('run-auto')
var DHT = require('bittorrent-dht/server')
var fs = require('fs')
var parseTorrent = require('parse-torrent')
var test = require('tape')
var WebTorrent = require('../')
var leavesPath = __dirname + '/content/Leaves of Grass by Walt Whitman.epub'
var leavesFile = fs.readFileSync(leavesPath)
var leavesTorrent = fs.readFileSync(__dirname + '/torrents/leaves.torrent')
var leavesParsed = parseTorrent(leavesTorrent)
// remove trackers from .torrent file
leavesParsed.announce = []
test('Download using DHT (via magnet uri)', function (t) {
t.plan(10)
var dhtServer = new DHT({ bootstrap: false })
dhtServer.on('error', function (err) { t.fail(err) })
dhtServer.on('warning', function (err) { t.fail(err) })
var magnetUri = 'magnet:?xt=urn:btih:' + leavesParsed.infoHash
auto({
dhtPort: function (cb) {
dhtServer.listen(function () {
var port = dhtServer.address().port
cb(null, port)
})
},
client1: ['dhtPort', function (cb, r) {
var client1 = new WebTorrent({
tracker: false,
dht: { bootstrap: '127.0.0.1:' + r.dhtPort }
})
client1.on('error', function (err) { t.fail(err) })
client1.on('warning', function (err) { t.fail(err) })
var announced = false
var wroteStorage = false
function maybeDone () {
if (announced && wroteStorage) cb(null, client1)
}
client1.add(leavesParsed, function (torrent) {
// torrent metadata has been fetched -- sanity check it
t.equal(torrent.name, 'Leaves of Grass by Walt Whitman.epub')
var names = [ 'Leaves of Grass by Walt Whitman.epub' ]
t.deepEqual(torrent.files.map(function (file) { return file.name }), names)
torrent.on('dhtAnnounce', function () {
announced = true
maybeDone()
})
torrent.storage.load(fs.createReadStream(leavesPath), function (err) {
t.error(err)
wroteStorage = true
maybeDone()
})
})
}],
client2: ['client1', function (cb, r) {
var client2 = new WebTorrent({
tracker: false,
dht: { bootstrap: '127.0.0.1:' + r.dhtPort }
})
client2.on('error', function (err) { t.fail(err) })
client2.on('warning', function (err) { t.fail(err) })
var gotBuffer = false
var gotDone = false
function maybeDone () {
if (gotBuffer && gotDone) cb(null, client2)
}
client2.add(magnetUri, function (torrent) {
torrent.files[0].getBuffer(function (err, buf) {
t.error(err)
t.deepEqual(buf, leavesFile, 'downloaded correct content')
gotBuffer = true
maybeDone()
})
torrent.once('done', function () {
t.pass('client2 downloaded torrent from client1')
gotDone = true
maybeDone()
})
})
}]
}, function (err, r) {
t.error(err)
r.client1.destroy(function () {
t.pass('client1 destroyed')
})
r.client2.destroy(function () {
t.pass('client2 destroyed')
})
dhtServer.destroy(function () {
t.pass('dht server destroyed')
})
})
})
|
import m from 'mithril';
import projectContributions from '../../src/c/project-contributions';
describe('projectContributions', () => {
let $output, projectContribution;
describe('view', () => {
beforeAll(() => {
jasmine.Ajax.stubRequest(new RegExp("("+apiPrefix + '\/contributors)'+'(.*)')).andReturn({
'responseText' : JSON.stringify(ContributorMockery())
});
spyOn(m, 'component').and.callThrough();
projectContribution = ContributorMockery()[0];
const project = m.prop({
id: 1231
});
const component = m.component(projectContributions, {
project: project
}),
view = component.view(component.controller({
project: project
}));
$output = mq(view);
});
it('should render project contributions list', () => {
expect($output.contains(projectContribution.data.name)).toEqual(true);
});
});
});
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*
* @providesModule SplitViewWindows
*/
'use strict';
module.exports = require('UnimplementedView');
|
(function (root, factory) {
// Node.
if(typeof module === 'object' && typeof module.exports === 'object') {
exports = module.exports = factory();
}
// AMD.
if(typeof define === 'function' && define.amd) {
define(factory);
}
// Browser Global.
if(typeof window === "object") {
if (typeof root.Terraformer === "undefined"){
root.Terraformer = {};
}
root.Terraformer.RTree = factory().RTree;
}
}(this, function() {
var exports = { };
var Terraformer;
// Local Reference To Browser Global
if(typeof this.navigator === "object") {
Terraformer = this.Terraformer;
}
// Setup Node Dependencies
if(typeof module === 'object' && typeof module.exports === 'object') {
Terraformer = require('terraformer');
}
function Deferred () {
this._thens = [];
}
Deferred.prototype = {
/* This is the "front end" API. */
// then(onResolve, onReject): Code waiting for this promise uses the
// then() method to be notified when the promise is complete. There
// are two completion callbacks: onReject and onResolve. A more
// robust promise implementation will also have an onProgress handler.
then: function (onResolve, onReject) {
// capture calls to then()
this._thens.push({ resolve: onResolve, reject: onReject });
},
// Some promise implementations also have a cancel() front end API that
// calls all of the onReject() callbacks (aka a "cancelable promise").
// cancel: function (reason) {},
/* This is the "back end" API. */
// resolve(resolvedValue): The resolve() method is called when a promise
// is resolved (duh). The resolved value (if any) is passed by the resolver
// to this method. All waiting onResolve callbacks are called
// and any future ones are, too, each being passed the resolved value.
resolve: function (val) {
this._complete('resolve', val);
},
// reject(exception): The reject() method is called when a promise cannot
// be resolved. Typically, you'd pass an exception as the single parameter,
// but any other argument, including none at all, is acceptable.
// All waiting and all future onReject callbacks are called when reject()
// is called and are passed the exception parameter.
reject: function (ex) {
this._complete('reject', ex);
},
// Some promises may have a progress handler. The back end API to signal a
// progress "event" has a single parameter. The contents of this parameter
// could be just about anything and is specific to your implementation.
// progress: function (data) {},
/* "Private" methods. */
_complete: function (which, arg) {
// switch over to sync then()
this.then = (which === 'resolve') ?
function (resolve, reject) { resolve(arg); } :
function (resolve, reject) { reject(arg); };
// disallow multiple calls to resolve or reject
this.resolve = this.reject =
function () { throw new Error('Deferred already completed.'); };
// complete all waiting (async) then()s
for (var i = 0; i < this._thens.length; i++) {
var aThen = this._thens[i];
if(aThen[which]) {
aThen[which](arg);
}
}
delete this._thens;
}
};
/******************************************************************************
rtree.js - General-Purpose Non-Recursive Javascript R-Tree Library
Version 0.6.2, December 5st 2009
Copyright (c) 2009 Jon-Carlos Rivera
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.
Jon-Carlos Rivera - imbcmdth@hotmail.com
******************************************************************************/
/*
* RTree - A simple r-tree structure for great results.
* @constructor
*/
var RTree = function (width) {
// Variables to control tree-dimensions
var _Min_Width = 3; // Minimum width of any node before a merge
var _Max_Width = 6; // Maximum width of any node before a split
if (!isNaN(width)) {
_Min_Width = Math.floor(width / 2.0);
_Max_Width = width;
}
// Start with an empty root-tree
var _T = {
x: 0,
y: 0,
w: 0,
h: 0,
id: "root",
nodes: []
};
/* @function
* @description Function to generate unique strings for element IDs
* @param {String} n The prefix to use for the IDs generated.
* @return {String} A guarenteed unique ID.
*/
var _name_to_id = (function() {
// hide our idCache inside this closure
var idCache = {};
// return the api: our function that returns a unique string with incrementing number appended to given idPrefix
return function(idPrefix) {
var idVal = 0;
if (idPrefix in idCache) {
idVal = idCache[idPrefix]++;
} else {
idCache[idPrefix] = 0;
}
return idPrefix + "_" + idVal;
};
})();
// This is my special addition to the world of r-trees
// every other (simple) method I found produced crap trees
// this skews insertions to prefering squarer and emptier nodes
RTree.Rectangle.squarified_ratio = function(l, w, fill) {
// Area of new enlarged rectangle
var lperi = (l + w) / 2.0; // Average size of a side of the new rectangle
var larea = l * w; // Area of new rectangle
// return the ratio of the perimeter to the area - the closer to 1 we are,
// the more "square" a rectangle is. conversly, when approaching zero the
// more elongated a rectangle is
var lgeo = larea / (lperi * lperi);
return (larea * fill / lgeo);
};
/* find the best specific node(s) for object to be deleted from
* [ leaf node parent ] = _remove_subtree(rectangle, object, root)
* @private
*/
var _remove_subtree = function(rect, obj, root) {
var hit_stack = []; // Contains the elements that overlap
var count_stack = []; // Contains the elements that overlap
var ret_array = [];
var current_depth = 1;
if (!rect || !RTree.Rectangle.overlap_rectangle(rect, root)) {
return ret_array;
}
var ret_obj = {
x: rect.x,
y: rect.y,
w: rect.w,
h: rect.h,
target: obj
};
count_stack.push(root.nodes.length);
hit_stack.push(root);
do {
var tree = hit_stack.pop();
var i = count_stack.pop() - 1;
if ("target" in ret_obj) { // We are searching for a target
while (i >= 0) {
var ltree = tree.nodes[i];
if (RTree.Rectangle.overlap_rectangle(ret_obj, ltree)) {
if ((ret_obj.target && "leaf" in ltree && ltree.leaf === ret_obj.target) || (!ret_obj.target && ("leaf" in ltree || RTree.Rectangle.contains_rectangle(ltree, ret_obj)))) { // A Match !!
// Yup we found a match...
// we can cancel search and start walking up the list
if ("nodes" in ltree) { // If we are deleting a node not a leaf...
ret_array = _search_subtree(ltree, true, [], ltree);
tree.nodes.splice(i, 1);
} else {
ret_array = tree.nodes.splice(i, 1);
}
// Resize MBR down...
RTree.Rectangle.make_MBR(tree.nodes, tree);
delete ret_obj.target;
if (tree.nodes.length < _Min_Width) { // Underflow
ret_obj.nodes = _search_subtree(tree, true, [], tree);
}
break;
}
/* else if("load" in ltree) { // A load
}*/
else if ("nodes" in ltree) { // Not a Leaf
current_depth += 1;
count_stack.push(i);
hit_stack.push(tree);
tree = ltree;
i = ltree.nodes.length;
}
}
i -= 1;
}
} else if ("nodes" in ret_obj) { // We are unsplitting
tree.nodes.splice(i + 1, 1); // Remove unsplit node
// ret_obj.nodes contains a list of elements removed from the tree so far
if (tree.nodes.length > 0) {
RTree.Rectangle.make_MBR(tree.nodes, tree);
}
for (var t = 0; t < ret_obj.nodes.length; t++) {
_insert_subtree(ret_obj.nodes[t], tree);
}
ret_obj.nodes.length = 0;
if (hit_stack.length === 0 && tree.nodes.length <= 1) { // Underflow..on root!
ret_obj.nodes = _search_subtree(tree, true, ret_obj.nodes, tree);
tree.nodes.length = 0;
hit_stack.push(tree);
count_stack.push(1);
} else if (hit_stack.length > 0 && tree.nodes.length < _Min_Width) { // Underflow..AGAIN!
ret_obj.nodes = _search_subtree(tree, true, ret_obj.nodes, tree);
tree.nodes.length = 0;
} else {
delete ret_obj.nodes; // Just start resizing
}
} else { // we are just resizing
RTree.Rectangle.make_MBR(tree.nodes, tree);
}
current_depth -= 1;
} while (hit_stack.length > 0);
return (ret_array);
};
/* choose the best damn node for rectangle to be inserted into
* [ leaf node parent ] = _choose_leaf_subtree(rectangle, root to start search at)
* @private
*/
var _choose_leaf_subtree = function(rect, root) {
var best_choice_index = -1;
var best_choice_stack = [];
var best_choice_area;
var load_callback = function(local_tree, local_node) {
return function(data) {
local_tree._attach_data(local_node, data);
};
};
best_choice_stack.push(root);
var nodes = root.nodes;
do {
if (best_choice_index !== -1) {
best_choice_stack.push(nodes[best_choice_index]);
nodes = nodes[best_choice_index].nodes;
best_choice_index = -1;
}
for (var i = nodes.length - 1; i >= 0; i--) {
var ltree = nodes[i];
if ("leaf" in ltree) {
// Bail out of everything and start inserting
best_choice_index = -1;
break;
}
// Area of new enlarged rectangle
var old_lratio = RTree.Rectangle.squarified_ratio(ltree.w, ltree.h, ltree.nodes.length + 1);
// Enlarge rectangle to fit new rectangle
var nw = Math.max(ltree.x + ltree.w, rect.x + rect.w) - Math.min(ltree.x, rect.x);
var nh = Math.max(ltree.y + ltree.h, rect.y + rect.h) - Math.min(ltree.y, rect.y);
// Area of new enlarged rectangle
var lratio = RTree.Rectangle.squarified_ratio(nw, nh, ltree.nodes.length + 2);
if (best_choice_index < 0 || Math.abs(lratio - old_lratio) < best_choice_area) {
best_choice_area = Math.abs(lratio - old_lratio);
best_choice_index = i;
}
}
} while (best_choice_index !== -1);
return (best_choice_stack);
};
/* split a set of nodes into two roughly equally-filled nodes
* [ an array of two new arrays of nodes ] = linear_split(array of nodes)
* @private
*/
var _linear_split = function(nodes) {
var n = _pick_linear(nodes);
while (nodes.length > 0) {
_pick_next(nodes, n[0], n[1]);
}
return (n);
};
/* insert the best source rectangle into the best fitting parent node: a or b
* [] = pick_next(array of source nodes, target node array a, target node array b)
* @private
*/
var _pick_next = function(nodes, a, b) {
// Area of new enlarged rectangle
var area_a = RTree.Rectangle.squarified_ratio(a.w, a.h, a.nodes.length + 1);
var area_b = RTree.Rectangle.squarified_ratio(b.w, b.h, b.nodes.length + 1);
var high_area_delta;
var high_area_node;
var lowest_growth_group;
for (var i = nodes.length - 1; i >= 0; i--) {
var l = nodes[i];
var new_area_a = {};
new_area_a.x = Math.min(a.x, l.x);
new_area_a.y = Math.min(a.y, l.y);
new_area_a.w = Math.max(a.x + a.w, l.x + l.w) - new_area_a.x;
new_area_a.h = Math.max(a.y + a.h, l.y + l.h) - new_area_a.y;
var change_new_area_a = Math.abs(RTree.Rectangle.squarified_ratio(new_area_a.w, new_area_a.h, a.nodes.length + 2) - area_a);
var new_area_b = {};
new_area_b.x = Math.min(b.x, l.x);
new_area_b.y = Math.min(b.y, l.y);
new_area_b.w = Math.max(b.x + b.w, l.x + l.w) - new_area_b.x;
new_area_b.h = Math.max(b.y + b.h, l.y + l.h) - new_area_b.y;
var change_new_area_b = Math.abs(RTree.Rectangle.squarified_ratio(new_area_b.w, new_area_b.h, b.nodes.length + 2) - area_b);
if (!high_area_node || !high_area_delta || Math.abs(change_new_area_b - change_new_area_a) < high_area_delta) {
high_area_node = i;
high_area_delta = Math.abs(change_new_area_b - change_new_area_a);
lowest_growth_group = change_new_area_b < change_new_area_a ? b : a;
}
}
var temp_node = nodes.splice(high_area_node, 1)[0];
if (a.nodes.length + nodes.length + 1 <= _Min_Width) {
a.nodes.push(temp_node);
RTree.Rectangle.expand_rectangle(a, temp_node);
} else if (b.nodes.length + nodes.length + 1 <= _Min_Width) {
b.nodes.push(temp_node);
RTree.Rectangle.expand_rectangle(b, temp_node);
} else {
lowest_growth_group.nodes.push(temp_node);
RTree.Rectangle.expand_rectangle(lowest_growth_group, temp_node);
}
};
/* pick the "best" two starter nodes to use as seeds using the "linear" criteria
* [ an array of two new arrays of nodes ] = pick_linear(array of source nodes)
* @private
*/
var _pick_linear = function(nodes) {
var lowest_high_x = nodes.length - 1;
var highest_low_x = 0;
var lowest_high_y = nodes.length - 1;
var highest_low_y = 0;
var t1, t2;
for (var i = nodes.length - 2; i >= 0; i--) {
var l = nodes[i];
if (l.x > nodes[highest_low_x].x) {
highest_low_x = i;
} else if (l.x + l.w < nodes[lowest_high_x].x + nodes[lowest_high_x].w) {
lowest_high_x = i;
}
if (l.y > nodes[highest_low_y].y) {
highest_low_y = i;
} else if (l.y + l.h < nodes[lowest_high_y].y + nodes[lowest_high_y].h) {
lowest_high_y = i;
}
}
var dx = Math.abs((nodes[lowest_high_x].x + nodes[lowest_high_x].w) - nodes[highest_low_x].x);
var dy = Math.abs((nodes[lowest_high_y].y + nodes[lowest_high_y].h) - nodes[highest_low_y].y);
if (dx > dy) {
if (lowest_high_x > highest_low_x) {
t1 = nodes.splice(lowest_high_x, 1)[0];
t2 = nodes.splice(highest_low_x, 1)[0];
} else {
t2 = nodes.splice(highest_low_x, 1)[0];
t1 = nodes.splice(lowest_high_x, 1)[0];
}
} else {
if (lowest_high_y > highest_low_y) {
t1 = nodes.splice(lowest_high_y, 1)[0];
t2 = nodes.splice(highest_low_y, 1)[0];
} else {
t2 = nodes.splice(highest_low_y, 1)[0];
t1 = nodes.splice(lowest_high_y, 1)[0];
}
}
return ([{
x: t1.x,
y: t1.y,
w: t1.w,
h: t1.h,
nodes: [t1]
}, {
x: t2.x,
y: t2.y,
w: t2.w,
h: t2.h,
nodes: [t2]
}]);
};
var _attach_data = function(node, more_tree) {
node.nodes = more_tree.nodes;
node.x = more_tree.x;
node.y = more_tree.y;
node.w = more_tree.w;
node.h = more_tree.h;
return (node);
};
/* non-recursive internal search function
* [ nodes | objects ] = _search_subtree(rectangle, [return node data], [array to fill], root to begin search at)
* @private
*/
var _search_subtree = function(rect, return_node, return_array, root) {
var hit_stack = []; // Contains the elements that overlap
if (!RTree.Rectangle.overlap_rectangle(rect, root)) {
return return_array;
}
var load_callback = function(local_tree, local_node) {
return function(data) {
local_tree._attach_data(local_node, data);
};
};
hit_stack.push(root.nodes);
do {
var nodes = hit_stack.pop();
for (var i = nodes.length - 1; i >= 0; i--) {
var ltree = nodes[i];
if (RTree.Rectangle.overlap_rectangle(rect, ltree)) {
if ("nodes" in ltree) { // Not a Leaf
hit_stack.push(ltree.nodes);
} else if ("leaf" in ltree) { // A Leaf !!
if (!return_node) {
return_array.push(ltree.leaf);
} else {
return_array.push(ltree);
}
}
}
}
} while (hit_stack.length > 0);
return return_array;
};
/* non-recursive internal insert function
* [] = _insert_subtree(rectangle, object to insert, root to begin insertion at)
* @private
*/
var _insert_subtree = function(node, root) {
var bc; // Best Current node
// Initial insertion is special because we resize the Tree and we don't
// care about any overflow (seriously, how can the first object overflow?)
if (root.nodes.length === 0) {
root.x = node.x;
root.y = node.y;
root.w = node.w;
root.h = node.h;
root.nodes.push(node);
return;
}
// Find the best fitting leaf node
// choose_leaf returns an array of all tree levels (including root)
// that were traversed while trying to find the leaf
var tree_stack = _choose_leaf_subtree(node, root);
var ret_obj = node; //{x:rect.x,y:rect.y,w:rect.w,h:rect.h, leaf:obj};
// Walk back up the tree resizing and inserting as needed
do {
//handle the case of an empty node (from a split)
if (bc && "nodes" in bc && bc.nodes.length === 0) {
var pbc = bc; // Past bc
bc = tree_stack.pop();
for (var t = 0; t < bc.nodes.length; t++) {
if (bc.nodes[t] === pbc || bc.nodes[t].nodes.length === 0) {
bc.nodes.splice(t, 1);
break;
}
}
} else {
bc = tree_stack.pop();
}
// If there is data attached to this ret_obj
if ("leaf" in ret_obj || "nodes" in ret_obj || Array.isArray(ret_obj)) {
// Do Insert
if (Array.isArray(ret_obj)) {
for (var ai = 0; ai < ret_obj.length; ai++) {
RTree.Rectangle.expand_rectangle(bc, ret_obj[ai]);
}
bc.nodes = bc.nodes.concat(ret_obj);
} else {
RTree.Rectangle.expand_rectangle(bc, ret_obj);
bc.nodes.push(ret_obj); // Do Insert
}
if (bc.nodes.length <= _Max_Width) { // Start Resizeing Up the Tree
ret_obj = {
x: bc.x,
y: bc.y,
w: bc.w,
h: bc.h
};
} else { // Otherwise Split this Node
// linear_split() returns an array containing two new nodes
// formed from the split of the previous node's overflow
var a = _linear_split(bc.nodes);
ret_obj = a; //[1];
if (tree_stack.length < 1) { // If are splitting the root..
bc.nodes.push(a[0]);
tree_stack.push(bc); // Reconsider the root element
ret_obj = a[1];
}
}
} else { // Otherwise Do Resize
//Just keep applying the new bounding rectangle to the parents..
RTree.Rectangle.expand_rectangle(bc, ret_obj);
ret_obj = {
x: bc.x,
y: bc.y,
w: bc.w,
h: bc.h
};
}
} while (tree_stack.length > 0);
};
/* returns a JSON representation of the tree
* @public
*/
this.serialize = function(callback) {
var dfd = new Deferred();
if(callback){
dfd.then(function(result){
callback(null, result);
}, function(error){
callback(error, null);
});
}
dfd.resolve(_T);
return dfd;
};
/* accepts a JSON representation of the tree and inserts it
* @public
*/
this.deserialize = function(new_tree, where, callback) {
var args = Array.prototype.slice.call(arguments);
var dfd = new Deferred();
switch (args.length) {
case 1:
where = _T;
break;
case 2:
if(typeof args[1] === "function"){
where = _T;
callback = args[1];
}
break;
}
if(callback){
dfd.then(function(result){
callback(null, result);
}, function(error){
callback(error, null);
});
}
dfd.resolve(_attach_data(where, new_tree));
return dfd;
};
/* non-recursive search function
* [ nodes | objects ] = RTree.search(rectangle, [return node data], [array to fill])
* @public
*/
this.search = function(shape, callback) {
var rect;
if(shape.type){
var b = Terraformer.Tools.calculateBounds(shape);
rect = {
x: b[0],
y: b[1],
w: Math.abs(b[0] - b[2]),
h: Math.abs(b[1] - b[3])
};
} else {
rect = shape;
}
var dfd = new Deferred();
var args = [ rect, false, [ ], _T ];
if (rect === undefined) {
throw "Wrong number of arguments. RT.Search requires at least a bounding rectangle.";
}
if(callback){
dfd.then(function(result){
callback(null, result);
}, function(error){
callback(error, null);
});
}
dfd.resolve(_search_subtree.apply(this, args));
return dfd;
};
/* partially-recursive toJSON function
* [ string ] = RTree.toJSON([rectangle], [tree])
* @public
*/
this.toJSON = function(rect, tree) {
var hit_stack = []; // Contains the elements that overlap
var count_stack = []; // Contains the elements that overlap
var return_stack = {}; // Contains the elements that overlap
var max_depth = 3; // This triggers recursion and tree-splitting
var current_depth = 1;
var return_string = "";
if (rect && !RTree.Rectangle.overlap_rectangle(rect, _T)) {
return "";
}
if (!tree) {
count_stack.push(_T.nodes.length);
hit_stack.push(_T.nodes);
return_string += "var main_tree = {x:" + _T.x.toFixed() + ",y:" + _T.y.toFixed() + ",w:" + _T.w.toFixed() + ",h:" + _T.h.toFixed() + ",nodes:[";
} else {
max_depth += 4;
count_stack.push(tree.nodes.length);
hit_stack.push(tree.nodes);
return_string += "var main_tree = {x:" + tree.x.toFixed() + ",y:" + tree.y.toFixed() + ",w:" + tree.w.toFixed() + ",h:" + tree.h.toFixed() + ",nodes:[";
}
do {
var nodes = hit_stack.pop();
var i = count_stack.pop() - 1;
if (i >= 0 && i < nodes.length - 1) {
return_string += ",";
}
while (i >= 0) {
var ltree = nodes[i];
if (!rect || RTree.Rectangle.overlap_rectangle(rect, ltree)) {
if (ltree.nodes) { // Not a Leaf
if (current_depth >= max_depth) {
var len = return_stack.length;
var nam = _name_to_id("saved_subtree");
return_string += "{x:" + ltree.x.toFixed() + ",y:" + ltree.y.toFixed() + ",w:" + ltree.w.toFixed() + ",h:" + ltree.h.toFixed() + ",load:'" + nam + ".js'}";
return_stack[nam] = this.toJSON(rect, ltree);
if (i > 0) {
return_string += ",";
}
} else {
return_string += "{x:" + ltree.x.toFixed() + ",y:" + ltree.y.toFixed() + ",w:" + ltree.w.toFixed() + ",h:" + ltree.h.toFixed() + ",nodes:[";
current_depth += 1;
count_stack.push(i);
hit_stack.push(nodes);
nodes = ltree.nodes;
i = ltree.nodes.length;
}
} else if (ltree.leaf) { // A Leaf !!
var data = ltree.leaf.toJSON ? ltree.leaf.toJSON() : JSON.stringify(ltree.leaf);
return_string += "{x:" + ltree.x.toFixed() + ",y:" + ltree.y.toFixed() + ",w:" + ltree.w.toFixed() + ",h:" + ltree.h.toFixed() + ",leaf:" + data + "}";
if (i > 0) {
return_string += ",";
}
} else if (ltree.load) { // A load
return_string += "{x:" + ltree.x.toFixed() + ",y:" + ltree.y.toFixed() + ",w:" + ltree.w.toFixed() + ",h:" + ltree.h.toFixed() + ",load:'" + ltree.load + "'}";
if (i > 0) {
return_string += ",";
}
}
}
i -= 1;
}
if (i < 0) {
return_string += "]}";
current_depth -= 1;
}
} while (hit_stack.length > 0);
return_string += ";";
for (var my_key in return_stack) {
return_string += "\nvar " + my_key + " = function(){" + return_stack[my_key] + " return(main_tree);};";
}
return (return_string);
};
/* non-recursive function that deletes a specific
* [ number ] = RTree.remove(rectangle, obj)
*/
this.remove = function(shape, obj, callback) {
var args = Array.prototype.slice.call(arguments);
var conditional;
if(args[0].type){
var b = Terraformer.Tools.calculateBounds(shape);
args[0] = {
x: b[0],
y: b[1],
w: Math.abs(b[0] - b[2]),
h: Math.abs(b[1] - b[3])
};
}
var dfd = new Deferred();
if (args.length < 1) {
throw "Wrong number of arguments. RT.remove requires at least a bounding rectangle or GeoJSON.";
}
switch (args.length) {
case 1:
conditional = false;
break;
case 2:
if(typeof args[1] === "function"){
conditional = false;
callback = args[1];
} else {
conditional = args[1];
}
break;
}
if(callback){
dfd.then(function(result){
callback(null, result);
}, function(error){
callback(error, null);
});
}
args = [args[0], conditional, _T];
if (args[1] === false) { // Do area-wide delete
var numberdeleted = 0;
var ret_array = [];
do {
numberdeleted = ret_array.length;
ret_array = ret_array.concat(_remove_subtree.apply(this, args));
} while (numberdeleted !== ret_array.length);
dfd.resolve(ret_array);
} else { // Delete a specific item
dfd.resolve(_remove_subtree.apply(this, args));
}
return dfd;
};
/* non-recursive insert function
* [] = RTree.insert(rectangle, object to insert)
*/
this.insert = function(shape, obj, callback) {
var rect;
if(shape.type){
var b = Terraformer.Tools.calculateBounds(shape);
rect = {
x: b[0],
y: b[1],
w: Math.abs(b[0] - b[2]),
h: Math.abs(b[1] - b[3])
};
} else {
rect = shape;
}
var dfd = new Deferred();
if (arguments.length < 2) {
throw "Wrong number of arguments. RT.Insert requires at least a bounding rectangle or GeoJSON and an object.";
}
if(callback){
dfd.then(function(result){
callback(null, result);
}, function(error){
callback(error, null);
});
}
dfd.resolve(_insert_subtree({
x: rect.x,
y: rect.y,
w: rect.w,
h: rect.h,
leaf: obj
}, _T));
return dfd;
};
/* non-recursive delete function
* [deleted object] = RTree.remove(rectangle, [object to delete])
*/
//End of RTree
};
/* Rectangle - Generic rectangle object - Not yet used */
RTree.Rectangle = function(ix, iy, iw, ih) { // new Rectangle(bounds) or new Rectangle(x, y, w, h)
var x, x2, y, y2, w, h;
if (ix.x) {
x = ix.x;
y = ix.y;
if (ix.w !== 0 && !ix.w && ix.x2) {
w = ix.x2 - ix.x;
h = ix.y2 - ix.y;
} else {
w = ix.w;
h = ix.h;
}
x2 = x + w;
y2 = y + h; // For extra fastitude
} else {
x = ix;
y = iy;
w = iw;
h = ih;
x2 = x + w;
y2 = y + h; // For extra fastitude
}
this.x1 = this.x = function() {
return x;
};
this.y1 = this.y = function() {
return y;
};
this.x2 = function() {
return x2;
};
this.y2 = function() {
return y2;
};
this.w = function() {
return w;
};
this.h = function() {
return h;
};
this.toJSON = function() {
return ('{"x":' + x.toString() + ', "y":' + y.toString() + ', "w":' + w.toString() + ', "h":' + h.toString() + '}');
};
this.overlap = function(a) {
return (this.x() < a.x2() && this.x2() > a.x() && this.y() < a.y2() && this.y2() > a.y());
};
this.expand = function(a) {
var nx = Math.min(this.x(), a.x());
var ny = Math.min(this.y(), a.y());
w = Math.max(this.x2(), a.x2()) - nx;
h = Math.max(this.y2(), a.y2()) - ny;
x = nx;
y = ny;
return (this);
};
this.setRect = function(ix, iy, iw, ih) {
var x, x2, y, y2, w, h;
if (ix.x) {
x = ix.x;
y = ix.y;
if (ix.w !== 0 && !ix.w && ix.x2) {
w = ix.x2 - ix.x;
h = ix.y2 - ix.y;
} else {
w = ix.w;
h = ix.h;
}
x2 = x + w;
y2 = y + h; // For extra fastitude
} else {
x = ix;
y = iy;
w = iw;
h = ih;
x2 = x + w;
y2 = y + h; // For extra fastitude
}
};
//End of RTree.Rectangle
};
/* returns true if rectangle 1 overlaps rectangle 2
* [ boolean ] = overlap_rectangle(rectangle a, rectangle b)
* @static function
*/
RTree.Rectangle.overlap_rectangle = function(a, b) {
return (a.x < (b.x + b.w) && (a.x + a.w) > b.x && a.y < (b.y + b.h) && (a.y + a.h) > b.y);
};
/* returns true if rectangle a is contained in rectangle b
* [ boolean ] = contains_rectangle(rectangle a, rectangle b)
* @static function
*/
RTree.Rectangle.contains_rectangle = function(a, b) {
return ((a.x + a.w) <= (b.x + b.w) && a.x >= b.x && (a.y + a.h) <= (b.y + b.h) && a.y >= b.y);
};
/* expands rectangle A to include rectangle B, rectangle B is untouched
* [ rectangle a ] = expand_rectangle(rectangle a, rectangle b)
* @static function
*/
RTree.Rectangle.expand_rectangle = function(a, b) {
var nx, ny;
// unintuitively, this is way way faster than max/min
if (a.x < b.x) {
nx = a.x;
} else {
nx = b.x;
}
if (a.y < b.y) {
ny = a.y;
} else {
ny = b.y;
}
if (a.x + a.w > b.x + b.w) {
a.w = (a.x + a.w) - nx;
} else {
a.w = (b.x + b.w) - nx;
}
if (a.y + a.h > b.y + b.h) {
a.h = (a.y + a.h) - ny;
} else {
a.h = (b.y + b.h) - ny;
}
a.x = nx;
a.y = ny;
return (a);
};
/* generates a minimally bounding rectangle for all rectangles in
* array "nodes". If rect is set, it is modified into the MBR. Otherwise,
* a new rectangle is generated and returned.
* [ rectangle a ] = make_MBR(rectangle array nodes, rectangle rect)
* @static function
*/
RTree.Rectangle.make_MBR = function(nodes, rect) {
if (nodes.length < 1) {
return ({
x: 0,
y: 0,
w: 0,
h: 0
});
}
//throw "make_MBR: nodes must contain at least one rectangle!";
if (!rect) {
rect = {
x: nodes[0].x,
y: nodes[0].y,
w: nodes[0].w,
h: nodes[0].h
};
} else {
rect.x = nodes[0].x;
rect.y = nodes[0].y;
rect.w = nodes[0].w;
rect.h = nodes[0].h;
}
for (var i = nodes.length - 1; i > 0; i--) {
RTree.Rectangle.expand_rectangle(rect, nodes[i]);
}
return (rect);
};
exports.RTree = RTree;
return exports;
}));
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _underscore = require('underscore');
var _gulpUtil = require('gulp-util');
var _gulpUtil2 = _interopRequireDefault(_gulpUtil);
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"); } }
var GulpBuilder = function () {
/**
* Create a new instance.
*
* @param {Task} task
*/
function GulpBuilder(task) {
_classCallCheck(this, GulpBuilder);
this.task = task;
}
/**
* Named constructor to prep a Elixir -> Gulp conversion.
*
* @param {Task} task
* @return {GulpTask}
*/
_createClass(GulpBuilder, [{
key: 'build',
/**
* Convert the Elixir task to a Gulp task.
*/
value: function build() {
var _this = this;
var name = this.task.name;
if ((0, _underscore.has)(gulp.tasks, name)) return;
this.task.loadDependencies && this.task.loadDependencies();
gulp.task(name, function () {
if (_this.shouldRunAllTasksNamed(name)) {
return Elixir.tasks.byName(name).forEach(function (task) {
return task.run();
});
}
return Elixir.tasks.findIncompleteByName(name)[0].run();
});
}
/**
* See if we should run all mixins for the given task name.
*
* @param {string} name
* @return {Boolean}
*/
}, {
key: 'shouldRunAllTasksNamed',
value: function shouldRunAllTasksNamed(name) {
return (0, _underscore.intersection)(_gulpUtil2.default.env._, [name, 'watch', 'tdd']).length;
}
}], [{
key: 'fromElixirTask',
value: function fromElixirTask(task) {
return new GulpBuilder(task).build();
}
}]);
return GulpBuilder;
}();
exports.default = GulpBuilder;
|
version https://git-lfs.github.com/spec/v1
oid sha256:ad571493c40a8480bfb7447020dd74ac4b0fdaefd7484c48f862997cef7fb34b
size 25608
|
/*
Highcharts JS v6.1.2 (2018-08-31)
Gantt series
(c) 2016 Lars A. V. Cabrera
--- WORK IN PROGRESS ---
License: www.highcharts.com/license
*/
(function(m){"object"===typeof module&&module.exports?module.exports=m:"function"===typeof define&&define.amd?define(function(){return m}):m(Highcharts)})(function(m){(function(h){var m=h.each,r=h.isObject,u=h.pick,n=h.wrap,l=h.Axis,v=h.Chart,p=h.Tick;l.prototype.isOuterAxis=function(){var b=this,e=-1,c=!0;m(this.chart.axes,function(f,g){f.side===b.side&&(f===b?e=g:0<=e&&g>e&&(c=!1))});return c};p.prototype.getLabelWidth=function(){return this.label.getBBox().width};l.prototype.getMaxLabelLength=
function(b){var e=this.tickPositions,c=this.ticks,f=0;if(!this.maxLabelLength||b)m(e,function(b){(b=c[b])&&b.labelLength>f&&(f=b.labelLength)}),this.maxLabelLength=f;return this.maxLabelLength};l.prototype.addTitle=function(){var b=this.chart.renderer,e=this.axisParent,c=this.horiz,f=this.opposite,g=this.options,d=g.title,a;this.showAxis=a=this.hasData()||u(g.showEmpty,!0);g.title="";this.axisTitle||((g=d.textAlign)||(g=(c?{low:"left",middle:"center",high:"right"}:{low:f?"right":"left",middle:"center",
high:f?"left":"right"})[d.align]),this.axisTitle=b.text(d.text,0,0,d.useHTML).attr({zIndex:7,rotation:d.rotation||0,align:g}).addClass("highcharts-axis-title").css(d.style).add(e),this.axisTitle.isNew=!0);this.axisTitle[a?"show":"hide"](!0)};h.dateFormats={W:function(b){b=new this.Date(b);var e=0===this.get("Day",b)?7:this.get("Day",b),c=b.getTime(),f=new Date(this.get("FullYear",b),0,1,-6);this.set("Date",b,this.get("Date",b)+4-e);return 1+Math.floor(Math.floor((c-f)/864E5)/7)},E:function(b){return this.dateFormat("%a",
b,!0).charAt(0)}};n(p.prototype,"addLabel",function(b){var e=this.axis,c=void 0!==e.options.categories,f=e.tickPositions,f=this.pos!==f[f.length-1];(!e.options.grid||c||f)&&b.apply(this)});n(p.prototype,"getLabelPosition",function(b,e,c,f){var g=b.apply(this,Array.prototype.slice.call(arguments,1)),d=this.axis,a=d.options,k=a.tickInterval||1,q,t;a.grid&&(q=a.labels.style.fontSize,t=d.chart.renderer.fontMetrics(q,f),q=t.b,t=t.h,d.horiz&&void 0===a.categories?(a=d.axisGroup.getBBox().height,k=this.pos+
k/2,g.x=d.translate(k)+d.left,k=a/2+t/2-Math.abs(t-q),g.y=0===d.side?c-k:c+k):(void 0===a.categories&&(k=this.pos+k/2,g.y=d.translate(k)+d.top+q/2),k=this.getLabelWidth()/2-d.maxLabelLength/2,g.x=3===d.side?g.x+k:g.x-k));return g});n(l.prototype,"tickSize",function(b){var e=b.apply(this,Array.prototype.slice.call(arguments,1)),c;this.options.grid&&!this.horiz&&(c=2*Math.abs(this.defaultLeftAxisOptions.labels.x),this.maxLabelLength||(this.maxLabelLength=this.getMaxLabelLength()),c=this.maxLabelLength+
c,e[0]=c);return e});n(l.prototype,"getOffset",function(b){var e=this.chart.axisOffset,c=this.side,f,g,d=this.options,a=d.title,k=a&&a.text&&!1!==a.enabled;this.options.grid&&r(this.options.title)?(g=this.tickSize("tick")[0],e[c]&&g&&(f=e[c]+g),k&&this.addTitle(),b.apply(this,Array.prototype.slice.call(arguments,1)),e[c]=u(f,e[c]),d.title=a):b.apply(this,Array.prototype.slice.call(arguments,1))});n(l.prototype,"renderUnsquish",function(b){this.options.grid&&(this.labelRotation=0,this.options.labels.rotation=
0);b.apply(this)});n(l.prototype,"setOptions",function(b,e){e.grid&&this.horiz&&(e.startOnTick=!0,e.minPadding=0,e.endOnTick=!0);b.apply(this,Array.prototype.slice.call(arguments,1))});n(l.prototype,"render",function(b){var e=this.options,c,f,g,d,a,k,q=this.chart.renderer;if(e.grid){if(c=2*Math.abs(this.defaultLeftAxisOptions.labels.x),c=this.maxLabelLength+c,f=e.lineWidth,this.rightWall&&this.rightWall.destroy(),b.apply(this),b=this.axisGroup.getBBox(),this.horiz&&(this.rightWall=q.path(["M",b.x+
this.width+1,b.y,"L",b.x+this.width+1,b.y+b.height]).attr({stroke:e.tickColor||"#ccd6eb","stroke-width":e.tickWidth||1,zIndex:7,class:"grid-wall"}).add(this.axisGroup)),this.isOuterAxis()&&this.axisLine&&(this.horiz&&(c=b.height-1),f)){b=this.getLinePath(f);a=b.indexOf("M")+1;k=b.indexOf("L")+1;g=b.indexOf("M")+2;d=b.indexOf("L")+2;if(0===this.side||3===this.side)c=-c;this.horiz?(b[g]+=c,b[d]+=c):(b[a]+=c,b[k]+=c);this.axisLineExtra?this.axisLineExtra.animate({d:b}):this.axisLineExtra=q.path(b).attr({stroke:e.lineColor,
"stroke-width":f,zIndex:7}).add(this.axisGroup);this.axisLine[this.showAxis?"show":"hide"](!0)}}else b.apply(this)});n(v.prototype,"render",function(b){var e=25/11,c,f;m(this.axes,function(b){var d=b.options;d.grid&&(f=d.labels.style.fontSize,c=b.chart.renderer.fontMetrics(f),"datetime"===d.type&&(d.units=[["millisecond",[1]],["second",[1]],["minute",[1]],["hour",[1]],["day",[1]],["week",[1]],["month",[1]],["year",null]]),b.horiz?d.tickLength=d.cellHeight||c.h*e:(d.tickWidth=1,d.lineWidth||(d.lineWidth=
1)))});b.apply(this)})})(m);(function(h){var m=h.addEvent,r=h.defined,u=h.Color,n=h.seriesTypes.column,l=h.each,v=h.isNumber,p=h.isObject,b=h.merge,e=h.pick,c=h.seriesType,f=h.Axis,g=h.Point,d=h.Series;c("xrange","column",{colorByPoint:!0,dataLabels:{verticalAlign:"middle",inside:!0,formatter:function(){var a=this.point.partialFill;p(a)&&(a=a.amount);r(a)||(a=0);return 100*a+"%"}},tooltip:{headerFormat:'\x3cspan style\x3d"font-size: 0.85em"\x3e{point.x} - {point.x2}\x3c/span\x3e\x3cbr/\x3e',pointFormat:'\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e {series.name}: \x3cb\x3e{point.yCategory}\x3c/b\x3e\x3cbr/\x3e'},
borderRadius:3,pointRange:0},{type:"xrange",parallelArrays:["x","x2","y"],requireSorting:!1,animate:h.seriesTypes.line.prototype.animate,cropShoulder:1,getExtremesFromAll:!0,getColumnMetrics:function(){function a(){l(e.series,function(a){var b=a.xAxis;a.xAxis=a.yAxis;a.yAxis=b})}var b,e=this.chart;a();b=n.prototype.getColumnMetrics.call(this);a();return b},cropData:function(a,b,e,c){b=d.prototype.cropData.call(this,this.x2Data,b,e,c);b.xData=a.slice(b.start,b.end);return b},translatePoint:function(a){var k=
this.xAxis,c=this.columnMetrics,d=this.options.minPointLength||0,f=a.plotX,g=e(a.x2,a.x+(a.len||0)),h=k.translate(g,0,0,0,1),g=h-f,l=this.chart.inverted,m=e(this.options.borderWidth,1)%2/2;d&&(d-=g,0>d&&(d=0),f-=d/2,h+=d/2);f=Math.max(f,-10);h=Math.min(Math.max(h,-10),k.len+10);a.shapeArgs={x:Math.floor(Math.min(f,h))+m,y:Math.floor(a.plotY+c.offset)+m,width:Math.round(Math.abs(h-f)),height:Math.round(c.width),r:this.options.borderRadius};d=a.shapeArgs.x;h=d+a.shapeArgs.width;0>d||h>k.len?(d=Math.min(k.len,
Math.max(0,d)),h=Math.max(0,Math.min(h,k.len)),k=h-d,a.dlBox=b(a.shapeArgs,{x:d,width:h-d,centerX:k?k/2:null})):a.dlBox=null;a.tooltipPos[0]+=l?0:g/2;a.tooltipPos[1]-=l?g/2:c.width/2;if(k=a.partialFill)p(k)&&(k=k.amount),v(k)||(k=0),c=a.shapeArgs,a.partShapeArgs={x:c.x,y:c.y,width:c.width,height:c.height,r:this.options.borderRadius},a.clipRectArgs={x:c.x,y:c.y,width:Math.max(Math.round(g*k+(a.plotX-f)),0),height:c.height}},translate:function(){n.prototype.translate.apply(this,arguments);l(this.points,
function(a){this.translatePoint(a)},this)},drawPoint:function(a,k){var c=this.options,d=this.chart.renderer,e=a.graphic,f=a.shapeType,h=a.shapeArgs,g=a.partShapeArgs,l=a.clipRectArgs,m=a.partialFill,n=a.selected&&"select",r=c.stacking&&!c.borderRadius;if(a.isNull)e&&(a.graphic=e.destroy());else{if(e)a.graphicOriginal[k](b(h));else a.graphic=e=d.g("point").addClass(a.getClassName()).add(a.group||this.group),a.graphicOriginal=d[f](h).addClass(a.getClassName()).addClass("highcharts-partfill-original").add(e);
g&&(a.graphicOverlay?(a.graphicOverlay[k](b(g)),a.clipRect.animate(b(l))):(a.clipRect=d.clipRect(l.x,l.y,l.width,l.height),a.graphicOverlay=d[f](g).addClass("highcharts-partfill-overlay").add(e).clip(a.clipRect)));a.graphicOriginal.attr(this.pointAttribs(a,n)).shadow(c.shadow,null,r);g&&(p(m)||(m={}),p(c.partialFill)&&(m=b(m,c.partialFill)),k=m.fill||u(a.color||this.color).brighten(-.3).get(),a.graphicOverlay.attr(this.pointAttribs(a,n)).attr({fill:k}).shadow(c.shadow,null,r))}},drawPoints:function(){var a=
this,b=a.getAnimationVerb();l(a.points,function(c){a.drawPoint(c,b)})},getAnimationVerb:function(){return this.chart.pointCount<(this.options.animationLimit||250)?"animate":"attr"}},{init:function(){g.prototype.init.apply(this,arguments);var a;a=this.series;var b=a.chart.options.chart.colorCount;this.y||(this.y=0);a.options.colorByPoint&&(a=a.options.colors||a.chart.options.colors,b=a.length,!this.options.color&&a[this.y%b]&&(this.color=a[this.y%b]));this.colorIndex=e(this.options.colorIndex,this.y%
b);return this},setState:function(){g.prototype.setState.apply(this,arguments);this.series.drawPoint(this,this.series.getAnimationVerb())},getLabelConfig:function(){var a=g.prototype.getLabelConfig.call(this),b=this.series.yAxis.categories;a.x2=this.x2;a.yCategory=this.yCategory=b&&b[this.y];return a},tooltipDateKeys:["x","x2"],isValid:function(){return"number"===typeof this.x&&"number"===typeof this.x2}});m(f,"afterGetSeriesExtremes",function(){var a=this.series,b,c;this.isXAxis&&(b=e(this.dataMax,
-Number.MAX_VALUE),l(a,function(a){a.x2Data&&l(a.x2Data,function(a){a>b&&(b=a,c=!0)})}),c&&(this.dataMax=b))})})(m)});
|
window.require(["ace/snippets/pgsql"],function(e){"object"==typeof module&&"object"==typeof exports&&module&&(module.exports=e)});
|
/**
* vee-validate v2.1.0-beta.6
* (c) 2018 Abdelrahman Awad
* @license MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.VeeValidate = factory());
}(this, (function () { 'use strict';
//
var supportsPassive = true;
var detectPassiveSupport = function () {
try {
var opts = Object.defineProperty({}, 'passive', {
get: function get () {
supportsPassive = true;
}
});
window.addEventListener('testPassive', null, opts);
window.removeEventListener('testPassive', null, opts);
} catch (e) {
supportsPassive = false;
}
return supportsPassive;
};
var addEventListener = function (el, eventName, cb) {
el.addEventListener(eventName, cb, supportsPassive ? { passive: true } : false);
};
var isTextInput = function (el) {
return includes(['text', 'password', 'search', 'email', 'tel', 'url', 'textarea'], el.type);
};
var isCheckboxOrRadioInput = function (el) {
return includes(['radio', 'checkbox'], el.type);
};
var isDateInput = function (el) {
return includes(['date', 'week', 'month', 'datetime-local', 'time'], el.type);
};
/**
* Gets the data attribute. the name must be kebab-case.
*/
var getDataAttribute = function (el, name) { return el.getAttribute(("data-vv-" + name)); };
/**
* Checks if the values are either null or undefined.
*/
var isNullOrUndefined = function () {
var values = [], len = arguments.length;
while ( len-- ) values[ len ] = arguments[ len ];
return values.every(function (value) {
return value === null || value === undefined;
});
};
/**
* Creates the default flags object.
*/
var createFlags = function () { return ({
untouched: true,
touched: false,
dirty: false,
pristine: true,
valid: null,
invalid: null,
validated: false,
pending: false,
required: false,
changed: false
}); };
/**
* Shallow object comparison.
*/
var isEqual = function (lhs, rhs) {
if (lhs instanceof RegExp && rhs instanceof RegExp) {
return isEqual(lhs.source, rhs.source) && isEqual(lhs.flags, rhs.flags);
}
if (Array.isArray(lhs) && Array.isArray(rhs)) {
if (lhs.length !== rhs.length) { return false; }
for (var i = 0; i < lhs.length; i++) {
if (!isEqual(lhs[i], rhs[i])) {
return false;
}
}
return true;
}
// if both are objects, compare each key recursively.
if (isObject(lhs) && isObject(rhs)) {
return Object.keys(lhs).every(function (key) {
return isEqual(lhs[key], rhs[key]);
}) && Object.keys(rhs).every(function (key) {
return isEqual(lhs[key], rhs[key]);
});
}
return lhs === rhs;
};
/**
* Determines the input field scope.
*/
var getScope = function (el) {
var scope = getDataAttribute(el, 'scope');
if (isNullOrUndefined(scope)) {
var form = getForm(el);
if (form) {
scope = getDataAttribute(form, 'scope');
}
}
return !isNullOrUndefined(scope) ? scope : null;
};
/**
* Get the closest form element.
*/
var getForm = function (el) {
if (isNullOrUndefined(el)) { return null; }
if (el.tagName === 'FORM') { return el; }
if (!isNullOrUndefined(el.form)) { return el.form; }
return !isNullOrUndefined(el.parentNode) ? getForm(el.parentNode) : null;
};
/**
* Gets the value in an object safely.
*/
var getPath = function (path, target, def) {
if ( def === void 0 ) def = undefined;
if (!path || !target) { return def; }
var value = target;
path.split('.').every(function (prop) {
if (prop in value) {
value = value[prop];
return true;
}
value = def;
return false;
});
return value;
};
/**
* Checks if path exists within an object.
*/
var hasPath = function (path, target) {
var obj = target;
return path.split('.').every(function (prop) {
if (prop in obj) {
obj = obj[prop];
return true;
}
return false;
});
};
/**
* Parses a rule string expression.
*/
var parseRule = function (rule) {
var params = [];
var name = rule.split(':')[0];
if (includes(rule, ':')) {
params = rule.split(':').slice(1).join(':').split(',');
}
return { name: name, params: params };
};
/**
* Debounces a function.
*/
var debounce = function (fn, wait, immediate, token) {
if ( wait === void 0 ) wait = 0;
if ( immediate === void 0 ) immediate = false;
if ( token === void 0 ) token = { cancelled: false };
if (wait === 0) {
return fn;
}
var timeout;
return function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
var later = function () {
timeout = null;
if (!immediate && !token.cancelled) { fn.apply(void 0, args); }
};
/* istanbul ignore next */
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
/* istanbul ignore next */
if (callNow) { fn.apply(void 0, args); }
};
};
/**
* Appends a rule definition to a list of rules.
*/
var appendRule = function (rule, rules) {
if (!rules) {
return rule;
}
if (!rule) {
return rules;
}
if (typeof rules === 'string') {
return (rules + "|" + rule);
}
return assign({}, rules, normalizeRules(rule));
};
/**
* Normalizes the given rules expression.
*/
var normalizeRules = function (rules) {
// if falsy value return an empty object.
if (!rules) {
return {};
}
if (isObject(rules)) {
// $FlowFixMe
return Object.keys(rules).reduce(function (prev, curr) {
var params = [];
// $FlowFixMe
if (rules[curr] === true) {
params = [];
} else if (Array.isArray(rules[curr])) {
params = rules[curr];
} else {
params = [rules[curr]];
}
// $FlowFixMe
if (rules[curr] !== false) {
prev[curr] = params;
}
return prev;
}, {});
}
if (typeof rules !== 'string') {
warn('rules must be either a string or an object.');
return {};
}
return rules.split('|').reduce(function (prev, rule) {
var parsedRule = parseRule(rule);
if (!parsedRule.name) {
return prev;
}
prev[parsedRule.name] = parsedRule.params;
return prev;
}, {});
};
/**
* Emits a warning to the console.
*/
var warn = function (message) {
console.warn(("[vee-validate] " + message)); // eslint-disable-line
};
/**
* Creates a branded error object.
*/
var createError = function (message) { return new Error(("[vee-validate] " + message)); };
/**
* Checks if the value is an object.
*/
var isObject = function (obj) { return obj !== null && obj && typeof obj === 'object' && ! Array.isArray(obj); };
/**
* Checks if a function is callable.
*/
var isCallable = function (func) { return typeof func === 'function'; };
/**
* Check if element has the css class on it.
*/
var hasClass = function (el, className) {
if (el.classList) {
return el.classList.contains(className);
}
return !!el.className.match(new RegExp(("(\\s|^)" + className + "(\\s|$)")));
};
/**
* Adds the provided css className to the element.
*/
var addClass = function (el, className) {
if (el.classList) {
el.classList.add(className);
return;
}
if (!hasClass(el, className)) {
el.className += " " + className;
}
};
/**
* Remove the provided css className from the element.
*/
var removeClass = function (el, className) {
if (el.classList) {
el.classList.remove(className);
return;
}
if (hasClass(el, className)) {
var reg = new RegExp(("(\\s|^)" + className + "(\\s|$)"));
el.className = el.className.replace(reg, ' ');
}
};
/**
* Adds or removes a class name on the input depending on the status flag.
*/
var toggleClass = function (el, className, status) {
if (!el || !className) { return; }
if (Array.isArray(className)) {
className.forEach(function (item) { return toggleClass(el, item, status); });
return;
}
if (status) {
return addClass(el, className);
}
removeClass(el, className);
};
/**
* Converts an array-like object to array, provides a simple polyfill for Array.from
*/
var toArray = function (arrayLike) {
if (isCallable(Array.from)) {
return Array.from(arrayLike);
}
var array = [];
var length = arrayLike.length;
/* istanbul ignore next */
for (var i = 0; i < length; i++) {
array.push(arrayLike[i]);
}
/* istanbul ignore next */
return array;
};
/**
* Assign polyfill from the mdn.
*/
var assign = function (target) {
var others = [], len = arguments.length - 1;
while ( len-- > 0 ) others[ len ] = arguments[ len + 1 ];
/* istanbul ignore else */
if (isCallable(Object.assign)) {
return Object.assign.apply(Object, [ target ].concat( others ));
}
/* istanbul ignore next */
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
/* istanbul ignore next */
var to = Object(target);
/* istanbul ignore next */
others.forEach(function (arg) {
// Skip over if undefined or null
if (arg != null) {
Object.keys(arg).forEach(function (key) {
to[key] = arg[key];
});
}
});
/* istanbul ignore next */
return to;
};
var id = 0;
var idTemplate = '{id}';
/**
* Generates a unique id.
*/
var uniqId = function () {
// handle too many uses of uniqId, although unlikely.
if (id >= 9999) {
id = 0;
// shift the template.
idTemplate = idTemplate.replace('{id}', '_{id}');
}
id++;
var newId = idTemplate.replace('{id}', String(id));
return newId;
};
/**
* finds the first element that satisfies the predicate callback, polyfills array.find
*/
var find = function (arrayLike, predicate) {
var array = Array.isArray(arrayLike) ? arrayLike : toArray(arrayLike);
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return array[i];
}
}
return undefined;
};
var isBuiltInComponent = function (vnode) {
if (!vnode) {
return false;
}
var tag = vnode.componentOptions.tag;
return /^(keep-alive|transition|transition-group)$/.test(tag);
};
var makeEventsArray = function (events) {
return (typeof events === 'string' && events.length) ? events.split('|') : [];
};
var makeDelayObject = function (events, delay, delayConfig) {
if (typeof delay === 'number') {
return events.reduce(function (prev, e) {
prev[e] = delay;
return prev;
}, {});
}
return events.reduce(function (prev, e) {
if (typeof delay === 'object' && e in delay) {
prev[e] = delay[e];
return prev;
}
if (typeof delayConfig === 'number') {
prev[e] = delayConfig;
return prev;
}
prev[e] = (delayConfig && delayConfig[e]) || 0;
return prev;
}, {});
};
var deepParseInt = function (input) {
if (typeof input === 'number') { return input; }
if (typeof input === 'string') { return parseInt(input); }
var map = {};
for (var element in input) {
map[element] = parseInt(input[element]);
}
return map;
};
var merge = function (target, source) {
if (! (isObject(target) && isObject(source))) {
return target;
}
Object.keys(source).forEach(function (key) {
var obj, obj$1;
if (isObject(source[key])) {
if (! target[key]) {
assign(target, ( obj = {}, obj[key] = {}, obj ));
}
merge(target[key], source[key]);
return;
}
assign(target, ( obj$1 = {}, obj$1[key] = source[key], obj$1 ));
});
return target;
};
var fillRulesFromElement = function (el, rules) {
if (el.required) {
rules = appendRule('required', rules);
}
if (isTextInput(el)) {
if (el.type === 'email') {
rules = appendRule(("email" + (el.multiple ? ':multiple' : '')), rules);
}
if (el.pattern) {
rules = appendRule(("regex:" + (el.pattern)), rules);
}
// 524288 is the max on some browsers and test environments.
if (el.maxLength >= 0 && el.maxLength < 524288) {
rules = appendRule(("max:" + (el.maxLength)), rules);
}
if (el.minLength > 0) {
rules = appendRule(("min:" + (el.minLength)), rules);
}
return rules;
}
if (el.type === 'number') {
rules = appendRule('decimal', rules);
if (el.min !== '') {
rules = appendRule(("min_value:" + (el.min)), rules);
}
if (el.max !== '') {
rules = appendRule(("max_value:" + (el.max)), rules);
}
return rules;
}
if (isDateInput(el)) {
var timeFormat = el.step && Number(el.step) < 60 ? 'HH:mm:ss' : 'HH:mm';
if (el.type === 'date') {
return appendRule('date_format:YYYY-MM-DD', rules);
}
if (el.type === 'datetime-local') {
return appendRule(("date_format:YYYY-MM-DDT" + timeFormat), rules);
}
if (el.type === 'month') {
return appendRule('date_format:YYYY-MM', rules);
}
if (el.type === 'week') {
return appendRule('date_format:YYYY-[W]WW', rules);
}
if (el.type === 'time') {
return appendRule(("date_format:" + timeFormat), rules);
}
}
return rules;
};
var values = function (obj) {
if (isCallable(Object.values)) {
return Object.values(obj);
}
// fallback to keys()
/* istanbul ignore next */
return obj[Object.keys(obj)[0]];
};
var parseSelector = function (selector) {
var rule = null;
if (includes(selector, ':')) {
rule = selector.split(':').pop();
selector = selector.replace((":" + rule), '');
}
if (selector[0] === '#') {
return {
id: selector.slice(1),
rule: rule,
name: null,
scope: null
};
}
var scope = null;
var name = selector;
if (includes(selector, '.')) {
var parts = selector.split('.');
scope = parts[0];
name = parts.slice(1).join('.');
}
return {
id: null,
scope: scope,
name: name,
rule: rule
};
};
var includes = function (collection, item) {
return collection.indexOf(item) !== -1;
};
//
var LOCALE = 'en';
var Dictionary = function Dictionary (dictionary) {
if ( dictionary === void 0 ) dictionary = {};
this.container = {};
this.merge(dictionary);
};
var prototypeAccessors = { locale: { configurable: true } };
prototypeAccessors.locale.get = function () {
return LOCALE;
};
prototypeAccessors.locale.set = function (value) {
LOCALE = value || 'en';
};
Dictionary.prototype.hasLocale = function hasLocale (locale) {
return !!this.container[locale];
};
Dictionary.prototype.setDateFormat = function setDateFormat (locale, format) {
if (!this.container[locale]) {
this.container[locale] = {};
}
this.container[locale].dateFormat = format;
};
Dictionary.prototype.getDateFormat = function getDateFormat (locale) {
if (!this.container[locale] || !this.container[locale].dateFormat) {
return null;
}
return this.container[locale].dateFormat;
};
Dictionary.prototype.getMessage = function getMessage (locale, key, data) {
var message = null;
if (!this.hasMessage(locale, key)) {
message = this._getDefaultMessage(locale);
} else {
message = this.container[locale].messages[key];
}
return isCallable(message) ? message.apply(void 0, data) : message;
};
/**
* Gets a specific message for field. falls back to the rule message.
*/
Dictionary.prototype.getFieldMessage = function getFieldMessage (locale, field, key, data) {
if (!this.hasLocale(locale)) {
return this.getMessage(locale, key, data);
}
var dict = this.container[locale].custom && this.container[locale].custom[field];
if (!dict || !dict[key]) {
return this.getMessage(locale, key, data);
}
var message = dict[key];
return isCallable(message) ? message.apply(void 0, data) : message;
};
Dictionary.prototype._getDefaultMessage = function _getDefaultMessage (locale) {
if (this.hasMessage(locale, '_default')) {
return this.container[locale].messages._default;
}
return this.container.en.messages._default;
};
Dictionary.prototype.getAttribute = function getAttribute (locale, key, fallback) {
if ( fallback === void 0 ) fallback = '';
if (!this.hasAttribute(locale, key)) {
return fallback;
}
return this.container[locale].attributes[key];
};
Dictionary.prototype.hasMessage = function hasMessage (locale, key) {
return !! (
this.hasLocale(locale) &&
this.container[locale].messages &&
this.container[locale].messages[key]
);
};
Dictionary.prototype.hasAttribute = function hasAttribute (locale, key) {
return !! (
this.hasLocale(locale) &&
this.container[locale].attributes &&
this.container[locale].attributes[key]
);
};
Dictionary.prototype.merge = function merge$1 (dictionary) {
merge(this.container, dictionary);
};
Dictionary.prototype.setMessage = function setMessage (locale, key, message) {
if (! this.hasLocale(locale)) {
this.container[locale] = {
messages: {},
attributes: {}
};
}
this.container[locale].messages[key] = message;
};
Dictionary.prototype.setAttribute = function setAttribute (locale, key, attribute) {
if (! this.hasLocale(locale)) {
this.container[locale] = {
messages: {},
attributes: {}
};
}
this.container[locale].attributes[key] = attribute;
};
Object.defineProperties( Dictionary.prototype, prototypeAccessors );
//
var normalizeValue = function (value) {
if (isObject(value)) {
return Object.keys(value).reduce(function (prev, key) {
prev[key] = normalizeValue(value[key]);
return prev;
}, {});
}
if (isCallable(value)) {
return value('{0}', ['{1}', '{2}', '{3}']);
}
return value;
};
var normalizeFormat = function (locale) {
// normalize messages
var dictionary = {};
if (locale.messages) {
dictionary.messages = normalizeValue(locale.messages);
}
if (locale.custom) {
dictionary.custom = normalizeValue(locale.custom);
}
if (locale.attributes) {
dictionary.attributes = locale.attributes;
}
if (!isNullOrUndefined(locale.dateFormat)) {
dictionary.dateFormat = locale.dateFormat;
}
return dictionary;
};
var I18nDictionary = function I18nDictionary (i18n, rootKey) {
this.i18n = i18n;
this.rootKey = rootKey;
};
var prototypeAccessors$1 = { locale: { configurable: true } };
prototypeAccessors$1.locale.get = function () {
return this.i18n.locale;
};
prototypeAccessors$1.locale.set = function (value) {
warn('Cannot set locale from the validator when using vue-i18n, use i18n.locale setter instead');
};
I18nDictionary.prototype.getDateFormat = function getDateFormat (locale) {
return this.i18n.getDateTimeFormat(locale || this.locale);
};
I18nDictionary.prototype.setDateFormat = function setDateFormat (locale, value) {
this.i18n.setDateTimeFormat(locale || this.locale, value);
};
I18nDictionary.prototype.getMessage = function getMessage (locale, key, data) {
var path = (this.rootKey) + ".messages." + key;
if (!this.i18n.te(path)) {
return this.i18n.t(((this.rootKey) + ".messages._default"), locale, data);
}
return this.i18n.t(path, locale, data);
};
I18nDictionary.prototype.getAttribute = function getAttribute (locale, key, fallback) {
if ( fallback === void 0 ) fallback = '';
var path = (this.rootKey) + ".attributes." + key;
if (!this.i18n.te(path)) {
return fallback;
}
return this.i18n.t(path, locale);
};
I18nDictionary.prototype.getFieldMessage = function getFieldMessage (locale, field, key, data) {
var path = (this.rootKey) + ".custom." + field + "." + key;
if (this.i18n.te(path)) {
return this.i18n.t(path);
}
return this.getMessage(locale, key, data);
};
I18nDictionary.prototype.merge = function merge$1 (dictionary) {
var this$1 = this;
Object.keys(dictionary).forEach(function (localeKey) {
var obj;
// i18n doesn't deep merge
// first clone the existing locale (avoid mutations to locale)
var clone = merge({}, getPath((localeKey + "." + (this$1.rootKey)), this$1.i18n.messages, {}));
// Merge cloned locale with new one
var locale = merge(clone, normalizeFormat(dictionary[localeKey]));
this$1.i18n.mergeLocaleMessage(localeKey, ( obj = {}, obj[this$1.rootKey] = locale, obj ));
if (locale.dateFormat) {
this$1.i18n.setDateTimeFormat(localeKey, locale.dateFormat);
}
});
};
I18nDictionary.prototype.setMessage = function setMessage (locale, key, value) {
var obj, obj$1;
this.merge(( obj$1 = {}, obj$1[locale] = {
messages: ( obj = {}, obj[key] = value, obj )
}, obj$1 ));
};
I18nDictionary.prototype.setAttribute = function setAttribute (locale, key, value) {
var obj, obj$1;
this.merge(( obj$1 = {}, obj$1[locale] = {
attributes: ( obj = {}, obj[key] = value, obj )
}, obj$1 ));
};
Object.defineProperties( I18nDictionary.prototype, prototypeAccessors$1 );
//
var defaultConfig = {
locale: 'en',
delay: 0,
errorBagName: 'errors',
dictionary: null,
strict: true,
fieldsBagName: 'fields',
classes: false,
classNames: null,
events: 'input',
inject: true,
fastExit: true,
aria: true,
validity: false,
i18n: null,
i18nRootKey: 'validation'
};
var currentConfig = assign({}, defaultConfig);
var dependencies = {
dictionary: new Dictionary({
en: {
messages: {},
attributes: {},
custom: {}
}
})
};
var Config = function Config () {};
var staticAccessors = { default: { configurable: true },current: { configurable: true } };
staticAccessors.default.get = function () {
return defaultConfig;
};
staticAccessors.current.get = function () {
return currentConfig;
};
Config.dependency = function dependency (key) {
return dependencies[key];
};
/**
* Merges the config with a new one.
*/
Config.merge = function merge$$1 (config) {
currentConfig = assign({}, currentConfig, config);
if (currentConfig.i18n) {
Config.register('dictionary', new I18nDictionary(currentConfig.i18n, currentConfig.i18nRootKey));
}
};
/**
* Registers a dependency.
*/
Config.register = function register (key, value) {
dependencies[key] = value;
};
/**
* Resolves the working config from a Vue instance.
*/
Config.resolve = function resolve (context) {
var selfConfig = getPath('$options.$_veeValidate', context, {});
return assign({}, Config.current, selfConfig);
};
Object.defineProperties( Config, staticAccessors );
//
var ErrorBag = function ErrorBag (errorBag, id) {
if ( errorBag === void 0 ) errorBag = null;
if ( id === void 0 ) id = null;
this.vmId = id || null;
// make this bag a mirror of the provided one, sharing the same items reference.
if (errorBag && errorBag instanceof ErrorBag) {
this.items = errorBag.items;
} else {
this.items = [];
}
};
ErrorBag.prototype[typeof Symbol === 'function' ? Symbol.iterator : '@@iterator'] = function () {
var this$1 = this;
var index = 0;
return {
next: function () {
return { value: this$1.items[index++], done: index > this$1.items.length };
}
};
};
/**
* Adds an error to the internal array.
*/
ErrorBag.prototype.add = function add (error) {
var ref;
(ref = this.items).push.apply(
ref, this._normalizeError(error)
);
};
/**
* Normalizes passed errors to an error array.
*/
ErrorBag.prototype._normalizeError = function _normalizeError (error) {
var this$1 = this;
if (Array.isArray(error)) {
return error.map(function (e) {
e.scope = !isNullOrUndefined(e.scope) ? e.scope : null;
e.vmId = !isNullOrUndefined(e.vmId) ? e.vmId : (this$1.vmId || null);
return e;
});
}
error.scope = !isNullOrUndefined(error.scope) ? error.scope : null;
error.vmId = !isNullOrUndefined(error.vmId) ? error.vmId : (this.vmId || null);
return [error];
};
/**
* Regenrates error messages if they have a generator function.
*/
ErrorBag.prototype.regenerate = function regenerate () {
this.items.forEach(function (i) {
i.msg = isCallable(i.regenerate) ? i.regenerate() : i.msg;
});
};
/**
* Updates a field error with the new field scope.
*/
ErrorBag.prototype.update = function update (id, error) {
var item = find(this.items, function (i) { return i.id === id; });
if (!item) {
return;
}
var idx = this.items.indexOf(item);
this.items.splice(idx, 1);
item.scope = error.scope;
this.items.push(item);
};
/**
* Gets all error messages from the internal array.
*/
ErrorBag.prototype.all = function all (scope) {
var this$1 = this;
var filterFn = function (item) {
var matchesScope = true;
var matchesVM = true;
if (!isNullOrUndefined(scope)) {
matchesScope = item.scope === scope;
}
if (!isNullOrUndefined(this$1.vmId)) {
matchesVM = item.vmId === this$1.vmId;
}
return matchesVM && matchesScope;
};
return this.items.filter(filterFn).map(function (e) { return e.msg; });
};
/**
* Checks if there are any errors in the internal array.
*/
ErrorBag.prototype.any = function any (scope) {
var this$1 = this;
var filterFn = function (item) {
var matchesScope = true;
if (!isNullOrUndefined(scope)) {
matchesScope = item.scope === scope;
}
if (!isNullOrUndefined(this$1.vmId)) {
matchesScope = item.vmId === this$1.vmId;
}
return matchesScope;
};
return !!this.items.filter(filterFn).length;
};
/**
* Removes all items from the internal array.
*/
ErrorBag.prototype.clear = function clear (scope) {
var this$1 = this;
var matchesVM = isNullOrUndefined(this.id) ? function () { return true; } : function (i) { return i.vmId === this$1.vmId; };
if (isNullOrUndefined(scope)) {
scope = null;
}
for (var i = 0; i < this.items.length; ++i) {
if (matchesVM(this$1.items[i]) && this$1.items[i].scope === scope) {
this$1.items.splice(i, 1);
--i;
}
}
};
/**
* Collects errors into groups or for a specific field.
*/
ErrorBag.prototype.collect = function collect (field, scope, map) {
if ( map === void 0 ) map = true;
var groupErrors = function (items) {
var fieldsCount = 0;
var errors = items.reduce(function (collection, error) {
if (!collection[error.field]) {
collection[error.field] = [];
fieldsCount++;
}
collection[error.field].push(map ? error.msg : error);
return collection;
}, {});
// reduce the collection to be a single array.
if (fieldsCount <= 1) {
return values(errors)[0] || [];
}
return errors;
};
if (isNullOrUndefined(field)) {
return groupErrors(this.items);
}
var selector = isNullOrUndefined(scope) ? String(field) : (scope + "." + field);
var ref = this._makeCandidateFilters(selector);
var isPrimary = ref.isPrimary;
var isAlt = ref.isAlt;
var collected = this.items.reduce(function (prev, curr) {
if (isPrimary(curr)) {
prev.primary.push(curr);
}
if (isAlt(curr)) {
prev.alt.push(curr);
}
return prev;
}, { primary: [], alt: [] });
collected = collected.primary.length ? collected.primary : collected.alt;
return groupErrors(collected);
};
/**
* Gets the internal array length.
*/
ErrorBag.prototype.count = function count () {
var this$1 = this;
if (this.vmId) {
return this.items.filter(function (e) { return e.vmId === this$1.vmId; }).length;
}
return this.items.length;
};
/**
* Finds and fetches the first error message for the specified field id.
*/
ErrorBag.prototype.firstById = function firstById (id) {
var error = find(this.items, function (i) { return i.id === id; });
return error ? error.msg : undefined;
};
/**
* Gets the first error message for a specific field.
*/
ErrorBag.prototype.first = function first (field, scope) {
if ( scope === void 0 ) scope = null;
var selector = isNullOrUndefined(scope) ? field : (scope + "." + field);
var match = this._match(selector);
return match && match.msg;
};
/**
* Returns the first error rule for the specified field
*/
ErrorBag.prototype.firstRule = function firstRule (field, scope) {
var errors = this.collect(field, scope, false);
return (errors.length && errors[0].rule) || undefined;
};
/**
* Checks if the internal array has at least one error for the specified field.
*/
ErrorBag.prototype.has = function has (field, scope) {
if ( scope === void 0 ) scope = null;
return !!this.first(field, scope);
};
/**
* Gets the first error message for a specific field and a rule.
*/
ErrorBag.prototype.firstByRule = function firstByRule (name, rule, scope) {
if ( scope === void 0 ) scope = null;
var error = this.collect(name, scope, false).filter(function (e) { return e.rule === rule; })[0];
return (error && error.msg) || undefined;
};
/**
* Gets the first error message for a specific field that not match the rule.
*/
ErrorBag.prototype.firstNot = function firstNot (name, rule, scope) {
if ( rule === void 0 ) rule = 'required';
if ( scope === void 0 ) scope = null;
var error = this.collect(name, scope, false).filter(function (e) { return e.rule !== rule; })[0];
return (error && error.msg) || undefined;
};
/**
* Removes errors by matching against the id or ids.
*/
ErrorBag.prototype.removeById = function removeById (id) {
var this$1 = this;
var condition = function (item) { return item.id === id; };
if (Array.isArray(id)) {
condition = function (item) { return id.indexOf(item.id) !== -1; };
}
for (var i = 0; i < this.items.length; ++i) {
if (condition(this$1.items[i])) {
this$1.items.splice(i, 1);
--i;
}
}
};
/**
* Removes all error messages associated with a specific field.
*/
ErrorBag.prototype.remove = function remove (field, scope) {
var this$1 = this;
if (isNullOrUndefined(field)) {
return;
}
var selector = isNullOrUndefined(scope) ? String(field) : (scope + "." + field);
var ref = this._makeCandidateFilters(selector);
var isPrimary = ref.isPrimary;
for (var i = 0; i < this.items.length; ++i) {
if (isPrimary(this$1.items[i])) {
this$1.items.splice(i, 1);
--i;
}
}
};
ErrorBag.prototype._makeCandidateFilters = function _makeCandidateFilters (selector) {
var this$1 = this;
var matchesRule = function () { return true; };
var matchesScope = function () { return true; };
var matchesName = function () { return true; };
var matchesVM = function () { return true; };
var ref = parseSelector(selector);
var id = ref.id;
var rule = ref.rule;
var scope = ref.scope;
var name = ref.name;
if (rule) {
matchesRule = function (item) { return item.rule === rule; };
}
// match by id, can be combined with rule selection.
if (id) {
return {
isPrimary: function (item) { return matchesRule(item) && (function (item) { return id === item.id; }); },
isAlt: function () { return false; }
};
}
if (isNullOrUndefined(scope)) {
// if no scope specified, make sure the found error has no scope.
matchesScope = function (item) { return isNullOrUndefined(item.scope); };
} else {
matchesScope = function (item) { return item.scope === scope; };
}
if (!isNullOrUndefined(name) && name !== '*') {
matchesName = function (item) { return item.field === name; };
}
if (!isNullOrUndefined(this.vmId)) {
matchesVM = function (item) { return item.vmId === this$1.vmId; };
}
// matches the first candidate.
var isPrimary = function (item) {
return matchesVM(item) && matchesName(item) && matchesRule(item) && matchesScope(item);
};
// matches a second candidate, which is a field with a name containing the '.' character.
var isAlt = function (item) {
return matchesVM(item) && matchesRule(item) && item.field === (scope + "." + name);
};
return {
isPrimary: isPrimary,
isAlt: isAlt
};
};
ErrorBag.prototype._match = function _match (selector) {
if (isNullOrUndefined(selector)) {
return undefined;
}
var ref = this._makeCandidateFilters(selector);
var isPrimary = ref.isPrimary;
var isAlt = ref.isAlt;
return this.items.reduce(function (prev, item, idx, arr) {
var isLast = idx === arr.length - 1;
if (prev.primary) {
return isLast ? prev.primary : prev;
}
if (isPrimary(item)) {
prev.primary = item;
}
if (isAlt(item)) {
prev.alt = item;
}
// keep going.
if (!isLast) {
return prev;
}
return prev.primary || prev.alt;
}, {});
};
/**
* Generates the options required to construct a field.
*/
var Resolver = function Resolver () {};
Resolver.generate = function generate (el, binding, vnode) {
var model = Resolver.resolveModel(binding, vnode);
var options = Config.resolve(vnode.context);
return {
name: Resolver.resolveName(el, vnode),
el: el,
listen: !binding.modifiers.disable,
bails: binding.modifiers.bails ? true : (binding.modifiers.continues === true ? false : undefined),
scope: Resolver.resolveScope(el, binding, vnode),
vm: Resolver.makeVM(vnode.context),
expression: binding.value,
component: vnode.componentInstance,
classes: options.classes,
classNames: options.classNames,
getter: Resolver.resolveGetter(el, vnode, model),
events: Resolver.resolveEvents(el, vnode) || options.events,
model: model,
delay: Resolver.resolveDelay(el, vnode, options),
rules: Resolver.resolveRules(el, binding, vnode),
immediate: !!binding.modifiers.initial || !!binding.modifiers.immediate,
validity: options.validity,
aria: options.aria,
initialValue: Resolver.resolveInitialValue(vnode)
};
};
Resolver.getCtorConfig = function getCtorConfig (vnode) {
if (!vnode.componentInstance) { return null; }
var config = getPath('componentInstance.$options.$_veeValidate', vnode);
return config;
};
/**
* Resolves the rules defined on an element.
*/
Resolver.resolveRules = function resolveRules (el, binding, vnode) {
var rules = '';
if (!binding.value && (!binding || !binding.expression)) {
rules = getDataAttribute(el, 'rules');
}
if (binding.value && includes(['string', 'object'], typeof binding.value.rules)) {
rules = binding.value.rules;
} else if (binding.value) {
rules = binding.value;
}
if (vnode.componentInstance) {
return rules;
}
return fillRulesFromElement(el, rules);
};
/**
* @param {*} vnode
*/
Resolver.resolveInitialValue = function resolveInitialValue (vnode) {
var model = vnode.data.model || find(vnode.data.directives, function (d) { return d.name === 'model'; });
return model && model.value;
};
/**
* Creates a non-circular partial VM instance from a Vue instance.
* @param {*} vm
*/
Resolver.makeVM = function makeVM (vm) {
return {
get $el () {
return vm.$el;
},
get $refs () {
return vm.$refs;
},
$watch: vm.$watch ? vm.$watch.bind(vm) : function () {},
$validator: vm.$validator ? {
errors: vm.$validator.errors,
validate: vm.$validator.validate.bind(vm.$validator),
update: vm.$validator.update.bind(vm.$validator)
} : null
};
};
/**
* Resolves the delay value.
* @param {*} el
* @param {*} vnode
* @param {Object} options
*/
Resolver.resolveDelay = function resolveDelay (el, vnode, options) {
var delay = getDataAttribute(el, 'delay');
var globalDelay = (options && 'delay' in options) ? options.delay : 0;
if (!delay && vnode.componentInstance && vnode.componentInstance.$attrs) {
delay = vnode.componentInstance.$attrs['data-vv-delay'];
}
if (!isObject(globalDelay)) {
return deepParseInt(delay || globalDelay);
}
if (!isNullOrUndefined(delay)) {
globalDelay.input = delay;
}
return deepParseInt(globalDelay);
};
/**
* Resolves the events to validate in response to.
* @param {*} el
* @param {*} vnode
*/
Resolver.resolveEvents = function resolveEvents (el, vnode) {
// resolve it from the root element.
var events = getDataAttribute(el, 'validate-on');
// resolve from data-vv-validate-on if its a vue component.
if (!events && vnode.componentInstance && vnode.componentInstance.$attrs) {
events = vnode.componentInstance.$attrs['data-vv-validate-on'];
}
// resolve it from $_veeValidate options.
if (!events && vnode.componentInstance) {
var config = Resolver.getCtorConfig(vnode);
events = config && config.events;
}
if (!events && Config.current.events) {
events = Config.current.events;
}
// resolve the model event if its configured for custom components.
if (events && vnode.componentInstance && includes(events, 'input')) {
var ref = vnode.componentInstance.$options.model || { event: 'input' };
var event = ref.event;
events = events.replace('input', event);
}
return events;
};
/**
* Resolves the scope for the field.
* @param {*} el
* @param {*} binding
*/
Resolver.resolveScope = function resolveScope (el, binding, vnode) {
if ( vnode === void 0 ) vnode = {};
var scope = null;
if (vnode.componentInstance && isNullOrUndefined(scope)) {
scope = vnode.componentInstance.$attrs && vnode.componentInstance.$attrs['data-vv-scope'];
}
return !isNullOrUndefined(scope) ? scope : getScope(el);
};
/**
* Checks if the node directives contains a v-model or a specified arg.
* Args take priority over models.
*
* @return {Object}
*/
Resolver.resolveModel = function resolveModel (binding, vnode) {
if (binding.arg) {
return { expression: binding.arg };
}
var model = vnode.data.model || find(vnode.data.directives, function (d) { return d.name === 'model'; });
if (!model) {
return null;
}
// https://github.com/vuejs/vue/blob/dev/src/core/util/lang.js#L26
var watchable = !/[^\w.$]/.test(model.expression) && hasPath(model.expression, vnode.context);
var lazy = !!(model.modifiers && model.modifiers.lazy);
if (!watchable) {
return { expression: null, lazy: lazy };
}
return { expression: model.expression, lazy: lazy };
};
/**
* Resolves the field name to trigger validations.
* @return {String} The field name.
*/
Resolver.resolveName = function resolveName (el, vnode) {
var name = getDataAttribute(el, 'name');
if (!name && !vnode.componentInstance) {
return el.name;
}
if (!name && vnode.componentInstance && vnode.componentInstance.$attrs) {
name = vnode.componentInstance.$attrs['data-vv-name'] || vnode.componentInstance.$attrs['name'];
}
if (!name && vnode.componentInstance) {
var config = Resolver.getCtorConfig(vnode);
if (config && isCallable(config.name)) {
var boundGetter = config.name.bind(vnode.componentInstance);
return boundGetter();
}
return vnode.componentInstance.name;
}
return name;
};
/**
* Returns a value getter input type.
*/
Resolver.resolveGetter = function resolveGetter (el, vnode, model) {
if (model && model.expression) {
return function () {
return getPath(model.expression, vnode.context);
};
}
if (vnode.componentInstance) {
var path = getDataAttribute(el, 'value-path') || (vnode.componentInstance.$attrs && vnode.componentInstance.$attrs['data-vv-value-path']);
if (path) {
return function () {
return getPath(path, vnode.componentInstance);
};
}
var config = Resolver.getCtorConfig(vnode);
if (config && isCallable(config.value)) {
var boundGetter = config.value.bind(vnode.componentInstance);
return function () {
return boundGetter();
};
}
var ref = vnode.componentInstance.$options.model || { prop: 'value' };
var prop = ref.prop;
return function () {
return vnode.componentInstance[prop];
};
}
switch (el.type) {
case 'checkbox': return function () {
var els = document.querySelectorAll(("input[name=\"" + (el.name) + "\"]"));
els = toArray(els).filter(function (el) { return el.checked; });
if (!els.length) { return undefined; }
return els.map(function (checkbox) { return checkbox.value; });
};
case 'radio': return function () {
var els = document.querySelectorAll(("input[name=\"" + (el.name) + "\"]"));
var elm = find(els, function (el) { return el.checked; });
return elm && elm.value;
};
case 'file': return function (context) {
return toArray(el.files);
};
case 'select-multiple': return function () {
return toArray(el.options).filter(function (opt) { return opt.selected; }).map(function (opt) { return opt.value; });
};
default: return function () {
return el && el.value;
};
}
};
//
var RULES = {};
var STRICT_MODE = true;
var Validator = function Validator (validations, options) {
if ( options === void 0 ) options = { fastExit: true };
this.strict = STRICT_MODE;
this.errors = new ErrorBag();
this.fields = new FieldBag();
this._createFields(validations);
this.paused = false;
this.fastExit = !isNullOrUndefined(options && options.fastExit) ? options.fastExit : true;
};
var prototypeAccessors$2 = { rules: { configurable: true },flags: { configurable: true },dictionary: { configurable: true },_vm: { configurable: true },locale: { configurable: true } };
var staticAccessors$1 = { rules: { configurable: true },dictionary: { configurable: true },locale: { configurable: true } };
staticAccessors$1.rules.get = function () {
return RULES;
};
prototypeAccessors$2.rules.get = function () {
return RULES;
};
prototypeAccessors$2.flags.get = function () {
return this.fields.items.reduce(function (acc, field) {
var obj;
if (field.scope) {
acc[("$" + (field.scope))] = ( obj = {}, obj[field.name] = field.flags, obj );
return acc;
}
acc[field.name] = field.flags;
return acc;
}, {});
};
/**
* Getter for the dictionary.
*/
prototypeAccessors$2.dictionary.get = function () {
return Config.dependency('dictionary');
};
staticAccessors$1.dictionary.get = function () {
return Config.dependency('dictionary');
};
prototypeAccessors$2._vm.get = function () {
return Config.dependency('vm');
};
/**
* Getter for the current locale.
*/
prototypeAccessors$2.locale.get = function () {
return Validator.locale;
};
/**
* Setter for the validator locale.
*/
prototypeAccessors$2.locale.set = function (value) {
Validator.locale = value;
};
staticAccessors$1.locale.get = function () {
return this.dictionary.locale;
};
/**
* Setter for the validator locale.
*/
staticAccessors$1.locale.set = function (value) {
var hasChanged = value !== Validator.dictionary.locale;
Validator.dictionary.locale = value;
if (hasChanged && Config.dependency('vm')) {
Config.dependency('vm').$emit('localeChanged');
}
};
/**
* Static constructor.
*/
Validator.create = function create (validations, options) {
return new Validator(validations, options);
};
/**
* Adds a custom validator to the list of validation rules.
*/
Validator.extend = function extend (name, validator, options) {
if ( options === void 0 ) options = {};
Validator._guardExtend(name, validator);
Validator._merge(name, {
validator: validator,
options: assign({}, { hasTarget: false, immediate: true }, options || {})
});
};
/**
* Removes a rule from the list of validators.
*/
Validator.remove = function remove (name) {
delete RULES[name];
};
/**
* Checks if the given rule name is a rule that targets other fields.
*/
Validator.isTargetRule = function isTargetRule (name) {
return !!RULES[name] && RULES[name].options.hasTarget;
};
/**
* Sets the operating mode for all newly created validators.
* strictMode = true: Values without a rule are invalid and cause failure.
* strictMode = false: Values without a rule are valid and are skipped.
*/
Validator.setStrictMode = function setStrictMode (strictMode) {
if ( strictMode === void 0 ) strictMode = true;
STRICT_MODE = strictMode;
};
/**
* Adds and sets the current locale for the validator.
*/
Validator.prototype.localize = function localize (lang, dictionary) {
Validator.localize(lang, dictionary);
};
/**
* Adds and sets the current locale for the validator.
*/
Validator.localize = function localize (lang, dictionary) {
var obj;
if (isObject(lang)) {
Validator.dictionary.merge(lang);
return;
}
// merge the dictionary.
if (dictionary) {
var locale = lang || dictionary.name;
dictionary = assign({}, dictionary);
Validator.dictionary.merge(( obj = {}, obj[locale] = dictionary, obj ));
}
if (lang) {
// set the locale.
Validator.locale = lang;
}
};
/**
* Registers a field to be validated.
*/
Validator.prototype.attach = function attach (fieldOpts) {
// fixes initial value detection with v-model and select elements.
var value = fieldOpts.initialValue;
var field = new Field(fieldOpts);
this.fields.push(field);
// validate the field initially
if (field.immediate) {
this.validate(("#" + (field.id)), value || field.value);
} else {
this._validate(field, value || field.value, { initial: true }).then(function (result) {
field.flags.valid = result.valid;
field.flags.invalid = !result.valid;
});
}
return field;
};
/**
* Sets the flags on a field.
*/
Validator.prototype.flag = function flag (name, flags, uid) {
if ( uid === void 0 ) uid = null;
var field = this._resolveField(name, undefined, uid);
if (!field || !flags) {
return;
}
field.setFlags(flags);
};
/**
* Removes a field from the validator.
*/
Validator.prototype.detach = function detach (name, scope, uid) {
var field = isCallable(name.destroy) ? name : this._resolveField(name, scope, uid);
if (!field) { return; }
field.destroy();
this.errors.remove(field.name, field.scope, field.id);
this.fields.remove(field);
};
/**
* Adds a custom validator to the list of validation rules.
*/
Validator.prototype.extend = function extend (name, validator, options) {
if ( options === void 0 ) options = {};
Validator.extend(name, validator, options);
};
Validator.prototype.reset = function reset (matcher) {
var this$1 = this;
// two ticks
return this._vm.$nextTick().then(function () {
return this$1._vm.$nextTick();
}).then(function () {
this$1.fields.filter(matcher).forEach(function (field) {
field.reset(); // reset field flags.
this$1.errors.remove(field.name, field.scope, field.id);
});
});
};
/**
* Updates a field, updating both errors and flags.
*/
Validator.prototype.update = function update (id, ref) {
var scope = ref.scope;
var field = this._resolveField(("#" + id));
if (!field) { return; }
// remove old scope.
this.errors.update(id, { scope: scope });
};
/**
* Removes a rule from the list of validators.
*/
Validator.prototype.remove = function remove (name) {
Validator.remove(name);
};
/**
* Validates a value against a registered field validations.
*/
Validator.prototype.validate = function validate (fieldDescriptor, value, ref) {
var this$1 = this;
if ( ref === void 0 ) ref = {};
var silent = ref.silent;
var vmId = ref.vmId;
if (this.paused) { return Promise.resolve(true); }
// overload to validate all.
if (isNullOrUndefined(fieldDescriptor)) {
return this.validateScopes({ silent: silent, vmId: vmId });
}
// overload to validate scope-less fields.
if (fieldDescriptor === '*') {
return this.validateAll(undefined, { silent: silent, vmId: vmId });
}
// if scope validation was requested.
if (/^(.+)\.\*$/.test(fieldDescriptor)) {
var matched = fieldDescriptor.match(/^(.+)\.\*$/)[1];
return this.validateAll(matched);
}
var field = this._resolveField(fieldDescriptor);
if (!field) {
return this._handleFieldNotFound(name);
}
if (!silent) { field.flags.pending = true; }
if (value === undefined) {
value = field.value;
}
return this._validate(field, value).then(function (result) {
if (!silent) {
this$1._handleValidationResults([result]);
}
return result.valid;
});
};
/**
* Pauses the validator.
*/
Validator.prototype.pause = function pause () {
this.paused = true;
return this;
};
/**
* Resumes the validator.
*/
Validator.prototype.resume = function resume () {
this.paused = false;
return this;
};
/**
* Validates each value against the corresponding field validations.
*/
Validator.prototype.validateAll = function validateAll (values$$1, ref) {
var this$1 = this;
if ( ref === void 0 ) ref = {};
var silent = ref.silent;
var vmId = ref.vmId;
if (this.paused) { return Promise.resolve(true); }
var matcher = null;
var providedValues = false;
if (typeof values$$1 === 'string') {
matcher = { scope: values$$1, vmId: vmId };
} else if (isObject(values$$1)) {
matcher = Object.keys(values$$1).map(function (key) {
return { name: key, vmId: vmId, scope: null };
});
providedValues = true;
} else if (Array.isArray(values$$1)) {
matcher = values$$1.map(function (key) {
return { name: key, vmId: vmId };
});
} else {
matcher = { scope: null, vmId: vmId };
}
return Promise.all(
this.fields.filter(matcher).map(function (field) { return this$1._validate(field, providedValues ? values$$1[field.name] : field.value); })
).then(function (results) {
if (!silent) {
this$1._handleValidationResults(results);
}
return results.every(function (t) { return t.valid; });
});
};
/**
* Validates all scopes.
*/
Validator.prototype.validateScopes = function validateScopes (ref) {
var this$1 = this;
if ( ref === void 0 ) ref = {};
var silent = ref.silent;
var vmId = ref.vmId;
if (this.paused) { return Promise.resolve(true); }
return Promise.all(
this.fields.filter({ vmId: vmId }).map(function (field) { return this$1._validate(field, field.value); })
).then(function (results) {
if (!silent) {
this$1._handleValidationResults(results);
}
return results.every(function (t) { return t.valid; });
});
};
/**
* Perform cleanup.
*/
Validator.prototype.destroy = function destroy () {
this._vm.$off('localeChanged');
};
/**
* Creates the fields to be validated.
*/
Validator.prototype._createFields = function _createFields (validations) {
var this$1 = this;
if (!validations) { return; }
Object.keys(validations).forEach(function (field) {
var options = assign({}, { name: field, rules: validations[field] });
this$1.attach(options);
});
};
/**
* Date rules need the existence of a format, so date_format must be supplied.
*/
Validator.prototype._getDateFormat = function _getDateFormat (validations) {
var format = null;
if (validations.date_format && Array.isArray(validations.date_format)) {
format = validations.date_format[0];
}
return format || this.dictionary.getDateFormat(this.locale);
};
/**
* Formats an error message for field and a rule.
*/
Validator.prototype._formatErrorMessage = function _formatErrorMessage (field, rule, data, targetName) {
if ( data === void 0 ) data = {};
if ( targetName === void 0 ) targetName = null;
var name = this._getFieldDisplayName(field);
var params = this._getLocalizedParams(rule, targetName);
return this.dictionary.getFieldMessage(this.locale, field.name, rule.name, [name, params, data]);
};
/**
* Translates the parameters passed to the rule (mainly for target fields).
*/
Validator.prototype._getLocalizedParams = function _getLocalizedParams (rule, targetName) {
if ( targetName === void 0 ) targetName = null;
if (rule.options.hasTarget && rule.params && rule.params[0]) {
var localizedName = targetName || this.dictionary.getAttribute(this.locale, rule.params[0], rule.params[0]);
return [localizedName].concat(rule.params.slice(1));
}
return rule.params;
};
/**
* Resolves an appropriate display name, first checking 'data-as' or the registered 'prettyName'
*/
Validator.prototype._getFieldDisplayName = function _getFieldDisplayName (field) {
return field.alias || this.dictionary.getAttribute(this.locale, field.name, field.name);
};
/**
* Tests a single input value against a rule.
*/
Validator.prototype._test = function _test (field, value, rule) {
var this$1 = this;
var validator = RULES[rule.name] ? RULES[rule.name].validate : null;
var params = Array.isArray(rule.params) ? toArray(rule.params) : [];
var targetName = null;
if (!validator || typeof validator !== 'function') {
return Promise.reject(createError(("No such validator '" + (rule.name) + "' exists.")));
}
// has field dependencies.
if (rule.options.hasTarget) {
var target = find(field.dependencies, function (d) { return d.name === rule.name; });
if (target) {
targetName = target.field.alias;
params = [target.field.value].concat(params.slice(1));
}
} else if (rule.name === 'required' && field.rejectsFalse) {
// invalidate false if no args were specified and the field rejects false by default.
params = params.length ? params : [true];
}
if (rule.options.isDate) {
var dateFormat = this._getDateFormat(field.rules);
if (rule.name !== 'date_format') {
params.push(dateFormat);
}
}
var result = validator(value, params);
// If it is a promise.
if (isCallable(result.then)) {
return result.then(function (values$$1) {
var allValid = true;
var data = {};
if (Array.isArray(values$$1)) {
allValid = values$$1.every(function (t) { return (isObject(t) ? t.valid : t); });
} else { // Is a single object/boolean.
allValid = isObject(values$$1) ? values$$1.valid : values$$1;
data = values$$1.data;
}
return {
valid: allValid,
errors: allValid ? [] : [this$1._createFieldError(field, rule, data, targetName)]
};
});
}
if (!isObject(result)) {
result = { valid: result, data: {} };
}
return {
valid: result.valid,
errors: result.valid ? [] : [this._createFieldError(field, rule, result.data, targetName)]
};
};
/**
* Merges a validator object into the RULES and Messages.
*/
Validator._merge = function _merge (name, ref) {
var validator = ref.validator;
var options = ref.options;
var validate = isCallable(validator) ? validator : validator.validate;
if (validator.getMessage) {
Validator.dictionary.setMessage(Validator.locale, name, validator.getMessage);
}
RULES[name] = {
validate: validate,
options: options
};
};
/**
* Guards from extension violations.
*/
Validator._guardExtend = function _guardExtend (name, validator) {
if (isCallable(validator)) {
return;
}
if (!isCallable(validator.validate)) {
throw createError(
("Extension Error: The validator '" + name + "' must be a function or have a 'validate' method.")
);
}
};
/**
* Creates a Field Error Object.
*/
Validator.prototype._createFieldError = function _createFieldError (field, rule, data, targetName) {
var this$1 = this;
return {
id: field.id,
vmId: field.vmId,
field: field.name,
msg: this._formatErrorMessage(field, rule, data, targetName),
rule: rule.name,
scope: field.scope,
regenerate: function () {
return this$1._formatErrorMessage(field, rule, data, targetName);
}
};
};
/**
* Tries different strategies to find a field.
*/
Validator.prototype._resolveField = function _resolveField (name, scope, uid) {
if (name[0] === '#') {
return this.fields.find({ id: name.slice(1) });
}
if (!isNullOrUndefined(scope)) {
return this.fields.find({ name: name, scope: scope, vmId: uid });
}
if (includes(name, '.')) {
var ref = name.split('.');
var fieldScope = ref[0];
var fieldName = ref.slice(1);
var field = this.fields.find({ name: fieldName.join('.'), scope: fieldScope, vmId: uid });
if (field) {
return field;
}
}
return this.fields.find({ name: name, scope: null, vmId: uid });
};
/**
* Handles when a field is not found depending on the strict flag.
*/
Validator.prototype._handleFieldNotFound = function _handleFieldNotFound (name, scope) {
if (!this.strict) { return Promise.resolve(true); }
var fullName = isNullOrUndefined(scope) ? name : ("" + (!isNullOrUndefined(scope) ? scope + '.' : '') + name);
return Promise.reject(createError(
("Validating a non-existent field: \"" + fullName + "\". Use \"attach()\" first.")
));
};
/**
* Handles validation results.
*/
Validator.prototype._handleValidationResults = function _handleValidationResults (results) {
var this$1 = this;
var matchers = results.map(function (result) { return ({ id: result.id }); });
this.errors.removeById(matchers.map(function (m) { return m.id; }));
// remove by name and scope to remove any custom errors added.
results.forEach(function (result) {
this$1.errors.remove(result.field, result.scope);
});
var allErrors = results.reduce(function (prev, curr) {
prev.push.apply(prev, curr.errors);
return prev;
}, []);
this.errors.add(allErrors);
// handle flags.
this.fields.filter(matchers).forEach(function (field) {
var result = find(results, function (r) { return r.id === field.id; });
field.setFlags({
pending: false,
valid: result.valid,
validated: true
});
});
};
Validator.prototype._shouldSkip = function _shouldSkip (field, value) {
// field is configured to run through the pipeline regardless
if (field.bails === false) {
return false;
}
// disabled fields are skipped
if (field.isDisabled) {
return true;
}
// skip if the field is not required and has an empty value.
return !field.isRequired && (isNullOrUndefined(value) || value === '');
};
Validator.prototype._shouldBail = function _shouldBail (field, value) {
// if the field was configured explicitly.
if (field.bails !== undefined) {
return field.bails;
}
return this.fastExit;
};
/**
* Starts the validation process.
*/
Validator.prototype._validate = function _validate (field, value, ref) {
var this$1 = this;
if ( ref === void 0 ) ref = {};
var initial = ref.initial;
if (this._shouldSkip(field, value)) {
return Promise.resolve({ valid: true, id: field.id, field: field.name, scope: field.scope, errors: [] });
}
var promises = [];
var errors = [];
var isExitEarly = false;
// use of '.some()' is to break iteration in middle by returning true
Object.keys(field.rules).filter(function (rule) {
if (!initial || !RULES[rule]) { return true; }
return RULES[rule].options.immediate;
}).some(function (rule) {
var ruleOptions = RULES[rule] ? RULES[rule].options : {};
var result = this$1._test(field, value, { name: rule, params: field.rules[rule], options: ruleOptions });
if (isCallable(result.then)) {
promises.push(result);
} else if (!result.valid && this$1._shouldBail(field, value)) {
errors.push.apply(errors, result.errors);
isExitEarly = true;
} else {
// promisify the result.
promises.push(new Promise(function (resolve) { return resolve(result); }));
}
return isExitEarly;
});
if (isExitEarly) {
return Promise.resolve({ valid: false, errors: errors, id: field.id, field: field.name, scope: field.scope });
}
return Promise.all(promises).then(function (results) {
return results.reduce(function (prev, v) {
var ref;
if (!v.valid) {
(ref = prev.errors).push.apply(ref, v.errors);
}
prev.valid = prev.valid && v.valid;
return prev;
}, { valid: true, errors: errors, id: field.id, field: field.name, scope: field.scope });
});
};
Object.defineProperties( Validator.prototype, prototypeAccessors$2 );
Object.defineProperties( Validator, staticAccessors$1 );
//
var DEFAULT_OPTIONS = {
targetOf: null,
immediate: false,
scope: null,
listen: true,
name: null,
rules: {},
vm: null,
classes: false,
validity: true,
aria: true,
events: 'input|blur',
delay: 0,
classNames: {
touched: 'touched', // the control has been blurred
untouched: 'untouched', // the control hasn't been blurred
valid: 'valid', // model is valid
invalid: 'invalid', // model is invalid
pristine: 'pristine', // control has not been interacted with
dirty: 'dirty' // control has been interacted with
}
};
var Field = function Field (options) {
if ( options === void 0 ) options = {};
this.id = uniqId();
this.el = options.el;
this.updated = false;
this.dependencies = [];
this.vmId = options.vmId;
this.watchers = [];
this.events = [];
this.delay = 0;
this.rules = {};
this._cacheId(options);
this.classNames = assign({}, DEFAULT_OPTIONS.classNames);
options = assign({}, DEFAULT_OPTIONS, options);
this._delay = !isNullOrUndefined(options.delay) ? options.delay : 0; // cache initial delay
this.validity = options.validity;
this.aria = options.aria;
this.flags = createFlags();
this.vm = options.vm;
this.componentInstance = options.component;
this.ctorConfig = this.componentInstance ? getPath('$options.$_veeValidate', this.componentInstance) : undefined;
this.update(options);
// set initial value.
this.initialValue = this.value;
this.updated = false;
};
var prototypeAccessors$3 = { validator: { configurable: true },isRequired: { configurable: true },isDisabled: { configurable: true },alias: { configurable: true },value: { configurable: true },bails: { configurable: true },rejectsFalse: { configurable: true } };
prototypeAccessors$3.validator.get = function () {
if (!this.vm || !this.vm.$validator) {
return { validate: function () {} };
}
return this.vm.$validator;
};
prototypeAccessors$3.isRequired.get = function () {
return !!this.rules.required;
};
prototypeAccessors$3.isDisabled.get = function () {
return !!(this.componentInstance && this.componentInstance.disabled) || !!(this.el && this.el.disabled);
};
/**
* Gets the display name (user-friendly name).
*/
prototypeAccessors$3.alias.get = function () {
if (this._alias) {
return this._alias;
}
var alias = null;
if (this.el) {
alias = getDataAttribute(this.el, 'as');
}
if (!alias && this.componentInstance) {
return this.componentInstance.$attrs && this.componentInstance.$attrs['data-vv-as'];
}
return alias;
};
/**
* Gets the input value.
*/
prototypeAccessors$3.value.get = function () {
if (!isCallable(this.getter)) {
return undefined;
}
return this.getter();
};
prototypeAccessors$3.bails.get = function () {
return this._bails;
};
/**
* If the field rejects false as a valid value for the required rule.
*/
prototypeAccessors$3.rejectsFalse.get = function () {
if (this.componentInstance && this.ctorConfig) {
return !!this.ctorConfig.rejectsFalse;
}
if (!this.el) {
return false;
}
return this.el.type === 'checkbox';
};
/**
* Determines if the instance matches the options provided.
*/
Field.prototype.matches = function matches (options) {
var this$1 = this;
if (!options) {
return true;
}
if (options.id) {
return this.id === options.id;
}
var matchesComponentId = isNullOrUndefined(options.vmId) ? function () { return true; } : function (id) { return id === this$1.vmId; };
if (!matchesComponentId(options.vmId)) {
return false;
}
if (options.name === undefined && options.scope === undefined) {
return true;
}
if (options.scope === undefined) {
return this.name === options.name;
}
if (options.name === undefined) {
return this.scope === options.scope;
}
return options.name === this.name && options.scope === this.scope;
};
/**
* Caches the field id.
*/
Field.prototype._cacheId = function _cacheId (options) {
if (this.el && !options.targetOf) {
this.el._veeValidateId = this.id;
}
};
/**
* Updates the field with changed data.
*/
Field.prototype.update = function update (options) {
this.targetOf = options.targetOf || null;
this.immediate = options.immediate || this.immediate || false;
// update errors scope if the field scope was changed.
if (!isNullOrUndefined(options.scope) && options.scope !== this.scope && isCallable(this.validator.update)) {
this.validator.update(this.id, { scope: options.scope });
}
this.scope = !isNullOrUndefined(options.scope) ? options.scope
: !isNullOrUndefined(this.scope) ? this.scope : null;
this.name = (!isNullOrUndefined(options.name) ? String(options.name) : options.name) || this.name || null;
this.rules = options.rules !== undefined ? normalizeRules(options.rules) : this.rules;
this._bails = options.bails !== undefined ? options.bails : this._bails;
this.model = options.model || this.model;
this.listen = options.listen !== undefined ? options.listen : this.listen;
this.classes = (options.classes || this.classes || false) && !this.componentInstance;
this.classNames = isObject(options.classNames) ? merge(this.classNames, options.classNames) : this.classNames;
this.getter = isCallable(options.getter) ? options.getter : this.getter;
this._alias = options.alias || this._alias;
this.events = (options.events) ? makeEventsArray(options.events) : this.events;
this.delay = makeDelayObject(this.events, options.delay || this.delay, this._delay);
this.updateDependencies();
this.addActionListeners();
if (!this.name && !this.targetOf) {
warn('A field is missing a "name" or "data-vv-name" attribute');
}
// update required flag flags
if (options.rules !== undefined) {
this.flags.required = this.isRequired;
}
// validate if it was validated before and field was updated and there was a rules mutation.
if (this.flags.validated && options.rules !== undefined && this.updated) {
this.validator.validate(("#" + (this.id)));
}
this.updated = true;
this.addValueListeners();
// no need to continue.
if (!this.el) {
return;
}
this.updateClasses();
this.updateAriaAttrs();
};
/**
* Resets field flags and errors.
*/
Field.prototype.reset = function reset () {
var this$1 = this;
if (this._cancellationToken) {
this._cancellationToken.cancelled = true;
delete this._cancellationToken;
}
var defaults = createFlags();
Object.keys(this.flags).filter(function (flag) { return flag !== 'required'; }).forEach(function (flag) {
this$1.flags[flag] = defaults[flag];
});
this.addActionListeners();
this.updateClasses();
this.updateAriaAttrs();
this.updateCustomValidity();
};
/**
* Sets the flags and their negated counterparts, and updates the classes and re-adds action listeners.
*/
Field.prototype.setFlags = function setFlags (flags) {
var this$1 = this;
var negated = {
pristine: 'dirty',
dirty: 'pristine',
valid: 'invalid',
invalid: 'valid',
touched: 'untouched',
untouched: 'touched'
};
Object.keys(flags).forEach(function (flag) {
this$1.flags[flag] = flags[flag];
// if it has a negation and was not specified, set it as well.
if (negated[flag] && flags[negated[flag]] === undefined) {
this$1.flags[negated[flag]] = !flags[flag];
}
});
if (
flags.untouched !== undefined ||
flags.touched !== undefined ||
flags.dirty !== undefined ||
flags.pristine !== undefined
) {
this.addActionListeners();
}
this.updateClasses();
this.updateAriaAttrs();
this.updateCustomValidity();
};
/**
* Determines if the field requires references to target fields.
*/
Field.prototype.updateDependencies = function updateDependencies () {
var this$1 = this;
// reset dependencies.
this.dependencies.forEach(function (d) { return d.field.destroy(); });
this.dependencies = [];
// we get the selectors for each field.
var fields = Object.keys(this.rules).reduce(function (prev, r) {
if (Validator.isTargetRule(r)) {
prev.push({ selector: this$1.rules[r][0], name: r });
}
return prev;
}, []);
if (!fields.length || !this.vm || !this.vm.$el) { return; }
// must be contained within the same component, so we use the vm root element constrain our dom search.
fields.forEach(function (ref$1) {
var selector = ref$1.selector;
var name = ref$1.name;
var ref = this$1.vm.$refs[selector];
var el = Array.isArray(ref) ? ref[0] : ref;
if (!el) {
return;
}
var options = {
vm: this$1.vm,
classes: this$1.classes,
classNames: this$1.classNames,
delay: this$1.delay,
scope: this$1.scope,
events: this$1.events.join('|'),
immediate: this$1.immediate,
targetOf: this$1.id
};
// probably a component.
if (isCallable(el.$watch)) {
options.component = el;
options.el = el.$el;
options.getter = Resolver.resolveGetter(el.$el, el.$vnode);
} else {
options.el = el;
options.getter = Resolver.resolveGetter(el, {});
}
this$1.dependencies.push({ name: name, field: new Field(options) });
});
};
/**
* Removes listeners.
*/
Field.prototype.unwatch = function unwatch (tag) {
if ( tag === void 0 ) tag = null;
if (!tag) {
this.watchers.forEach(function (w) { return w.unwatch(); });
this.watchers = [];
return;
}
this.watchers.filter(function (w) { return tag.test(w.tag); }).forEach(function (w) { return w.unwatch(); });
this.watchers = this.watchers.filter(function (w) { return !tag.test(w.tag); });
};
/**
* Updates the element classes depending on each field flag status.
*/
Field.prototype.updateClasses = function updateClasses () {
var this$1 = this;
if (!this.classes || this.isDisabled) { return; }
var applyClasses = function (el) {
toggleClass(el, this$1.classNames.dirty, this$1.flags.dirty);
toggleClass(el, this$1.classNames.pristine, this$1.flags.pristine);
toggleClass(el, this$1.classNames.touched, this$1.flags.touched);
toggleClass(el, this$1.classNames.untouched, this$1.flags.untouched);
// make sure we don't set any classes if the state is undetermined.
if (!isNullOrUndefined(this$1.flags.valid) && this$1.flags.validated) {
toggleClass(el, this$1.classNames.valid, this$1.flags.valid);
}
if (!isNullOrUndefined(this$1.flags.invalid) && this$1.flags.validated) {
toggleClass(el, this$1.classNames.invalid, this$1.flags.invalid);
}
};
if (!isCheckboxOrRadioInput(this.el)) {
applyClasses(this.el);
return;
}
var els = document.querySelectorAll(("input[name=\"" + (this.el.name) + "\"]"));
toArray(els).forEach(applyClasses);
};
/**
* Adds the listeners required for automatic classes and some flags.
*/
Field.prototype.addActionListeners = function addActionListeners () {
var this$1 = this;
// remove previous listeners.
this.unwatch(/class/);
if (!this.el) { return; }
var onBlur = function () {
this$1.flags.touched = true;
this$1.flags.untouched = false;
if (this$1.classes) {
toggleClass(this$1.el, this$1.classNames.touched, true);
toggleClass(this$1.el, this$1.classNames.untouched, false);
}
// only needed once.
this$1.unwatch(/^class_blur$/);
};
var inputEvent = isTextInput(this.el) ? 'input' : 'change';
var onInput = function () {
this$1.flags.dirty = true;
this$1.flags.pristine = false;
if (this$1.classes) {
toggleClass(this$1.el, this$1.classNames.pristine, false);
toggleClass(this$1.el, this$1.classNames.dirty, true);
}
// only needed once.
this$1.unwatch(/^class_input$/);
};
if (this.componentInstance && isCallable(this.componentInstance.$once)) {
this.componentInstance.$once('input', onInput);
this.componentInstance.$once('blur', onBlur);
this.watchers.push({
tag: 'class_input',
unwatch: function () {
this$1.componentInstance.$off('input', onInput);
}
});
this.watchers.push({
tag: 'class_blur',
unwatch: function () {
this$1.componentInstance.$off('blur', onBlur);
}
});
return;
}
if (!this.el) { return; }
addEventListener(this.el, inputEvent, onInput);
// Checkboxes and radio buttons on Mac don't emit blur naturally, so we listen on click instead.
var blurEvent = isCheckboxOrRadioInput(this.el) ? 'change' : 'blur';
addEventListener(this.el, blurEvent, onBlur);
this.watchers.push({
tag: 'class_input',
unwatch: function () {
this$1.el.removeEventListener(inputEvent, onInput);
}
});
this.watchers.push({
tag: 'class_blur',
unwatch: function () {
this$1.el.removeEventListener(blurEvent, onBlur);
}
});
};
Field.prototype.checkValueChanged = function checkValueChanged () {
// handle some people initialize the value to null, since text inputs have empty string value.
if (this.initialValue === null && this.value === '' && isTextInput(this.el)) {
return false;
}
return this.value !== this.initialValue;
};
/**
* Determines the suitable primary event to listen for.
*/
Field.prototype._determineInputEvent = function _determineInputEvent () {
// if its a custom component, use the customized model event or the input event.
if (this.componentInstance) {
return (this.componentInstance.$options.model && this.componentInstance.$options.model.event) || 'input';
}
if (this.model) {
return this.model.lazy ? 'change' : 'input';
}
if (isTextInput(this.el)) {
return 'input';
}
return 'change';
};
/**
* Determines the list of events to listen to.
*/
Field.prototype._determineEventList = function _determineEventList (defaultInputEvent) {
// if no event is configured, or it is a component or a text input then respect the user choice.
if (!this.events.length || this.componentInstance || isTextInput(this.el)) {
return [].concat( this.events );
}
// force suitable event for non-text type fields.
return this.events.map(function (e) {
if (e === 'input') {
return defaultInputEvent;
}
return e;
});
};
/**
* Adds the listeners required for validation.
*/
Field.prototype.addValueListeners = function addValueListeners () {
var this$1 = this;
this.unwatch(/^input_.+/);
if (!this.listen || !this.el) { return; }
var token = { cancelled: false };
var fn = this.targetOf ? function () {
this$1.flags.changed = this$1.checkValueChanged(); this$1.validator.validate(("#" + (this$1.targetOf)));
} : function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
// if its a DOM event, resolve the value, otherwise use the first parameter as the value.
if (args.length === 0 || (isCallable(Event) && args[0] instanceof Event) || (args[0] && args[0].srcElement)) {
args[0] = this$1.value;
}
this$1.flags.changed = this$1.checkValueChanged();
this$1.validator.validate(("#" + (this$1.id)), args[0]);
};
var inputEvent = this._determineInputEvent();
var events = this._determineEventList(inputEvent);
// if there is a model and an on input validation is requested.
if (this.model && includes(events, inputEvent)) {
var ctx = null;
var expression = this.model.expression;
// if its watchable from the context vm.
if (this.model.expression) {
ctx = this.vm;
expression = this.model.expression;
}
// watch it from the custom component vm instead.
if (!expression && this.componentInstance && this.componentInstance.$options.model) {
ctx = this.componentInstance;
expression = this.componentInstance.$options.model.prop || 'value';
}
if (ctx && expression) {
var debouncedFn = debounce(fn, this.delay[inputEvent], false, token);
var unwatch = ctx.$watch(expression, function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
this$1.flags.pending = true;
this$1._cancellationToken = token;
debouncedFn.apply(void 0, args);
});
this.watchers.push({
tag: 'input_model',
unwatch: unwatch
});
// filter out input event as it is already handled by the watcher API.
events = events.filter(function (e) { return e !== inputEvent; });
}
}
// Add events.
events.forEach(function (e) {
var debouncedFn = debounce(fn, this$1.delay[e], false, token);
var validate = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
this$1.flags.pending = true;
this$1._cancellationToken = token;
debouncedFn.apply(void 0, args);
};
this$1._addComponentEventListener(e, validate);
this$1._addHTMLEventListener(e, validate);
});
};
Field.prototype._addComponentEventListener = function _addComponentEventListener (evt, validate) {
var this$1 = this;
if (!this.componentInstance) { return; }
this.componentInstance.$on(evt, validate);
this.watchers.push({
tag: 'input_vue',
unwatch: function () {
this$1.componentInstance.$off(evt, validate);
}
});
};
Field.prototype._addHTMLEventListener = function _addHTMLEventListener (evt, validate) {
var this$1 = this;
if (!this.el || this.componentInstance) { return; }
// listen for the current element.
var addListener = function (el) {
addEventListener(el, evt, validate);
this$1.watchers.push({
tag: 'input_native',
unwatch: function () {
el.removeEventListener(evt, validate);
}
});
};
addListener(this.el);
if (!isCheckboxOrRadioInput(this.el)) {
return;
}
var els = document.querySelectorAll(("input[name=\"" + (this.el.name) + "\"]"));
toArray(els).forEach(function (el) {
// skip if it is added by v-validate and is not the current element.
if (el._veeValidateId && el !== this$1.el) {
return;
}
addListener(el);
});
};
/**
* Updates aria attributes on the element.
*/
Field.prototype.updateAriaAttrs = function updateAriaAttrs () {
var this$1 = this;
if (!this.aria || !this.el || !isCallable(this.el.setAttribute)) { return; }
var applyAriaAttrs = function (el) {
el.setAttribute('aria-required', this$1.isRequired ? 'true' : 'false');
el.setAttribute('aria-invalid', this$1.flags.invalid ? 'true' : 'false');
};
if (!isCheckboxOrRadioInput(this.el)) {
applyAriaAttrs(this.el);
return;
}
var els = document.querySelectorAll(("input[name=\"" + (this.el.name) + "\"]"));
toArray(els).forEach(applyAriaAttrs);
};
/**
* Updates the custom validity for the field.
*/
Field.prototype.updateCustomValidity = function updateCustomValidity () {
if (!this.validity || !this.el || !isCallable(this.el.setCustomValidity) || !this.validator.errors) { return; }
this.el.setCustomValidity(this.flags.valid ? '' : (this.validator.errors.firstById(this.id) || ''));
};
/**
* Removes all listeners.
*/
Field.prototype.destroy = function destroy () {
this.unwatch();
this.dependencies.forEach(function (d) { return d.field.destroy(); });
this.dependencies = [];
};
Object.defineProperties( Field.prototype, prototypeAccessors$3 );
//
var FieldBag = function FieldBag (items) {
if ( items === void 0 ) items = [];
this.items = items || [];
};
var prototypeAccessors$4 = { length: { configurable: true } };
FieldBag.prototype[typeof Symbol === 'function' ? Symbol.iterator : '@@iterator'] = function () {
var this$1 = this;
var index = 0;
return {
next: function () {
return { value: this$1.items[index++], done: index > this$1.items.length };
}
};
};
/**
* Gets the current items length.
*/
prototypeAccessors$4.length.get = function () {
return this.items.length;
};
/**
* Finds the first field that matches the provided matcher object.
*/
FieldBag.prototype.find = function find$1 (matcher) {
return find(this.items, function (item) { return item.matches(matcher); });
};
/**
* Filters the items down to the matched fields.
*/
FieldBag.prototype.filter = function filter (matcher) {
// multiple matchers to be tried.
if (Array.isArray(matcher)) {
return this.items.filter(function (item) { return matcher.some(function (m) { return item.matches(m); }); });
}
return this.items.filter(function (item) { return item.matches(matcher); });
};
/**
* Maps the field items using the mapping function.
*/
FieldBag.prototype.map = function map (mapper) {
return this.items.map(mapper);
};
/**
* Finds and removes the first field that matches the provided matcher object, returns the removed item.
*/
FieldBag.prototype.remove = function remove (matcher) {
var item = null;
if (matcher instanceof Field) {
item = matcher;
} else {
item = this.find(matcher);
}
if (!item) { return null; }
var index = this.items.indexOf(item);
this.items.splice(index, 1);
return item;
};
/**
* Adds a field item to the list.
*/
FieldBag.prototype.push = function push (item) {
if (! (item instanceof Field)) {
throw createError('FieldBag only accepts instances of Field that has an id defined.');
}
if (!item.id) {
throw createError('Field id must be defined.');
}
if (this.find({ id: item.id })) {
throw createError(("Field with id " + (item.id) + " is already added."));
}
this.items.push(item);
};
Object.defineProperties( FieldBag.prototype, prototypeAccessors$4 );
var ScopedValidator = function ScopedValidator (base, vm) {
this.id = vm._uid;
this._base = base;
// create a mirror bag with limited component scope.
this.errors = new ErrorBag(base.errors, this.id);
};
var prototypeAccessors$5 = { flags: { configurable: true },rules: { configurable: true },fields: { configurable: true },dictionary: { configurable: true },locale: { configurable: true } };
prototypeAccessors$5.flags.get = function () {
var this$1 = this;
return this._base.fields.items.filter(function (f) { return f.vmId === this$1.id; }).reduce(function (acc, field) {
if (field.scope) {
if (!acc[("$" + (field.scope))]) {
acc[("$" + (field.scope))] = {};
}
acc[("$" + (field.scope))][field.name] = field.flags;
}
acc[field.name] = field.flags;
return acc;
}, {});
};
prototypeAccessors$5.rules.get = function () {
return this._base.rules;
};
prototypeAccessors$5.fields.get = function () {
return new FieldBag(this._base.fields.filter({ vmId: this.id }));
};
prototypeAccessors$5.dictionary.get = function () {
return this._base.dictionary;
};
prototypeAccessors$5.locale.get = function () {
return this._base.locale;
};
prototypeAccessors$5.locale.set = function (val) {
this._base.locale = val;
};
ScopedValidator.prototype.localize = function localize () {
var ref;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (ref = this._base).localize.apply(ref, args);
};
ScopedValidator.prototype.update = function update () {
var ref;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (ref = this._base).update.apply(ref, args);
};
ScopedValidator.prototype.attach = function attach (opts) {
var attachOpts = assign({}, opts, { vmId: this.id });
return this._base.attach(attachOpts);
};
ScopedValidator.prototype.remove = function remove (ruleName) {
return this._base.remove(ruleName);
};
ScopedValidator.prototype.detach = function detach () {
var ref;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (ref = this._base).detach.apply(ref, args.concat( [this.id] ));
};
ScopedValidator.prototype.extend = function extend () {
var ref;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (ref = this._base).extend.apply(ref, args);
};
ScopedValidator.prototype.validate = function validate (descriptor, value, opts) {
if ( opts === void 0 ) opts = {};
return this._base.validate(descriptor, value, assign({}, { vmId: this.id }, opts || {}));
};
ScopedValidator.prototype.validateAll = function validateAll (values$$1, opts) {
if ( opts === void 0 ) opts = {};
return this._base.validateAll(values$$1, assign({}, { vmId: this.id }, opts || {}));
};
ScopedValidator.prototype.validateScopes = function validateScopes (opts) {
if ( opts === void 0 ) opts = {};
return this._base.validateScopes(assign({}, { vmId: this.id }, opts || {}));
};
ScopedValidator.prototype.destroy = function destroy () {
delete this.id;
delete this._base;
};
ScopedValidator.prototype.reset = function reset (matcher) {
return this._base.reset(Object.assign({}, matcher || {}, { vmId: this.id }));
};
ScopedValidator.prototype.flag = function flag () {
var ref;
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (ref = this._base).flag.apply(ref, args.concat( [this.id] ));
};
Object.defineProperties( ScopedValidator.prototype, prototypeAccessors$5 );
//
/**
* Checks if a parent validator instance was requested.
*/
var requestsValidator = function (injections) {
if (isObject(injections) && injections.$validator) {
return true;
}
return false;
};
var mixin = {
provide: function provide () {
if (this.$validator && !isBuiltInComponent(this.$vnode)) {
return {
$validator: this.$validator
};
}
return {};
},
beforeCreate: function beforeCreate () {
// if built in do nothing.
if (isBuiltInComponent(this.$vnode)) {
return;
}
// if its a root instance set the config if it exists.
if (!this.$parent) {
Config.merge(this.$options.$_veeValidate || {});
}
var options = Config.resolve(this);
// if its a root instance, inject anyways, or if it requested a new instance.
if (!this.$parent || (this.$options.$_veeValidate && /new/.test(this.$options.$_veeValidate.validator))) {
this.$validator = new ScopedValidator(Config.dependency('validator'), this);
}
var requested = requestsValidator(this.$options.inject);
// if automatic injection is enabled and no instance was requested.
if (! this.$validator && options.inject && !requested) {
this.$validator = new ScopedValidator(Config.dependency('validator'), this);
}
// don't inject errors or fieldBag as no validator was resolved.
if (! requested && ! this.$validator) {
return;
}
// There is a validator but it isn't injected, mark as reactive.
if (!requested && this.$validator) {
var Vue = this.$options._base; // the vue constructor.
Vue.util.defineReactive(this.$validator, 'errors', this.$validator.errors);
}
if (! this.$options.computed) {
this.$options.computed = {};
}
this.$options.computed[options.errorBagName || 'errors'] = function errorBagGetter () {
return this.$validator.errors;
};
this.$options.computed[options.fieldsBagName || 'fields'] = function fieldBagGetter () {
return this.$validator.fields.items.reduce(function (acc, field) {
if (field.scope) {
if (!acc[("$" + (field.scope))]) {
acc[("$" + (field.scope))] = {};
}
acc[("$" + (field.scope))][field.name] = field.flags;
return acc;
}
acc[field.name] = field.flags;
return acc;
}, {});
};
},
beforeDestroy: function beforeDestroy () {
if (this.$validator && this._uid === this.$validator.id) {
this.$validator.errors.clear(); // remove errors generated by this component.
}
}
};
//
/**
* Finds the requested field by id from the context object.
*/
function findField (el, context) {
if (!context || !context.$validator) {
return null;
}
return context.$validator.fields.find({ id: el._veeValidateId });
}
var directive = {
bind: function bind (el, binding, vnode) {
var validator = vnode.context.$validator;
if (!validator) {
{
warn("No validator instance is present on vm, did you forget to inject '$validator'?");
}
return;
}
var fieldOptions = Resolver.generate(el, binding, vnode);
validator.attach(fieldOptions);
},
inserted: function inserted (el, binding, vnode) {
var field = findField(el, vnode.context);
var scope = Resolver.resolveScope(el, binding, vnode);
// skip if scope hasn't changed.
if (!field || scope === field.scope) { return; }
// only update scope.
field.update({ scope: scope });
// allows the field to re-evaluated once more in the update hook.
field.updated = false;
},
update: function update (el, binding, vnode) {
var field = findField(el, vnode.context);
// make sure we don't do unneccasary work if no important change was done.
if (!field || (field.updated && isEqual(binding.value, binding.oldValue))) { return; }
var scope = Resolver.resolveScope(el, binding, vnode);
var rules = Resolver.resolveRules(el, binding, vnode);
field.update({
scope: scope,
rules: rules
});
},
unbind: function unbind (el, binding, ref) {
var context = ref.context;
var field = findField(el, context);
if (!field) { return; }
context.$validator.detach(field);
}
};
var Vue;
function install (_Vue, options) {
if ( options === void 0 ) options = {};
if (Vue && _Vue === Vue) {
{
warn('already installed, Vue.use(VeeValidate) should only be called once.');
}
return;
}
detectPassiveSupport();
Vue = _Vue;
var validator = new Validator(null, options);
var localVue = new Vue({
data: function () { return ({
errors: validator.errors,
fields: validator.fields
}); }
});
Config.register('vm', localVue);
Config.register('validator', validator);
Config.merge(options);
var ref = Config.current;
var dictionary = ref.dictionary;
var i18n = ref.i18n;
if (dictionary) {
validator.localize(dictionary); // merge the dictionary.
}
var onLocaleChanged = function () {
validator.errors.regenerate();
};
// watch locale changes using localVue instance or i18n.
if (!i18n) {
if (typeof window !== 'undefined') {
localVue.$on('localeChanged', onLocaleChanged);
}
} else {
i18n._vm.$watch('locale', onLocaleChanged);
}
if (!i18n && options.locale) {
validator.localize(options.locale); // set the locale
}
Validator.setStrictMode(Config.current.strict);
Vue.mixin(mixin);
Vue.directive('validate', directive);
}
//
function use (plugin, options) {
if ( options === void 0 ) options = {};
if (!isCallable(plugin)) {
return warn('The plugin must be a callable function');
}
plugin({ Validator: Validator, ErrorBag: ErrorBag, Rules: Validator.rules }, options);
}
//
var normalize = function (fields) {
if (Array.isArray(fields)) {
return fields.reduce(function (prev, curr) {
if (includes(curr, '.')) {
prev[curr.split('.')[1]] = curr;
} else {
prev[curr] = curr;
}
return prev;
}, {});
}
return fields;
};
// Combines two flags using either AND or OR depending on the flag type.
var combine = function (lhs, rhs) {
var mapper = {
pristine: function (lhs, rhs) { return lhs && rhs; },
dirty: function (lhs, rhs) { return lhs || rhs; },
touched: function (lhs, rhs) { return lhs || rhs; },
untouched: function (lhs, rhs) { return lhs && rhs; },
valid: function (lhs, rhs) { return lhs && rhs; },
invalid: function (lhs, rhs) { return lhs || rhs; },
pending: function (lhs, rhs) { return lhs || rhs; },
required: function (lhs, rhs) { return lhs || rhs; },
validated: function (lhs, rhs) { return lhs && rhs; }
};
return Object.keys(mapper).reduce(function (flags, flag) {
flags[flag] = mapper[flag](lhs[flag], rhs[flag]);
return flags;
}, {});
};
var mapScope = function (scope, deep) {
if ( deep === void 0 ) deep = true;
return Object.keys(scope).reduce(function (flags, field) {
if (!flags) {
flags = assign({}, scope[field]);
return flags;
}
// scope.
var isScope = field.indexOf('$') === 0;
if (deep && isScope) {
return combine(mapScope(scope[field]), flags);
} else if (!deep && isScope) {
return flags;
}
flags = combine(flags, scope[field]);
return flags;
}, null);
};
/**
* Maps fields to computed functions.
*/
var mapFields = function (fields) {
if (!fields) {
return function () {
return mapScope(this.$validator.flags);
};
}
var normalized = normalize(fields);
return Object.keys(normalized).reduce(function (prev, curr) {
var field = normalized[curr];
prev[curr] = function mappedField () {
// if field exists
if (this.$validator.flags[field]) {
return this.$validator.flags[field];
}
// scopeless fields were selected.
if (normalized[curr] === '*') {
return mapScope(this.$validator.flags, false);
}
// if it has a scope defined
var index = field.indexOf('.');
if (index <= 0) {
return {};
}
var ref = field.split('.');
var scope = ref[0];
var name = ref.slice(1);
scope = this.$validator.flags[("$" + scope)];
name = name.join('.');
// an entire scope was selected: scope.*
if (name === '*' && scope) {
return mapScope(scope);
}
if (scope && scope[name]) {
return scope[name];
}
return {};
};
return prev;
}, {});
};
var ErrorComponent = {
name: 'vv-error',
inject: ['$validator'],
functional: true,
props: {
for: {
type: String,
required: true
},
tag: {
type: String,
default: 'span'
}
},
render: function render (createElement, ref) {
var props = ref.props;
var injections = ref.injections;
return createElement(props.tag, injections.$validator.errors.first(props.for));
}
};
var index_minimal = {
install: install,
use: use,
directive: directive,
mixin: mixin,
mapFields: mapFields,
Validator: Validator,
ErrorBag: ErrorBag,
ErrorComponent: ErrorComponent,
version: '2.1.0-beta.6'
};
return index_minimal;
})));
|
let x = {
one: 1,
two: 2
};
let y = { three: 3, four: 4 };
|
'use strict';
// check if gulp dist was called
if (process.argv.indexOf('dist') !== -1) {
// add ship options to command call
process.argv.push('--ship');
}
const path = require('path');
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
const gulpSequence = require('gulp-sequence');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
// Create clean distrubution package
gulp.task('dist', gulpSequence('clean', 'bundle', 'package-solution'));
// Create clean development package
gulp.task('dev', gulpSequence('clean', 'bundle', 'package-solution'));
/**
* Webpack Bundle Anlayzer
* Reference and gulp task
*/
const bundleAnalyzer = require('webpack-bundle-analyzer');
build.configureWebpack.mergeConfig({
additionalConfiguration: (generatedConfiguration) => {
const lastDirName = path.basename(__dirname);
const dropPath = path.join(__dirname, 'temp', 'stats');
generatedConfiguration.plugins.push(new bundleAnalyzer.BundleAnalyzerPlugin({
openAnalyzer: false,
analyzerMode: 'static',
reportFilename: path.join(dropPath, `${lastDirName}.stats.html`),
generateStatsFile: true,
statsFilename: path.join(dropPath, `${lastDirName}.stats.json`),
logLevel: 'error'
}));
return generatedConfiguration;
}
});
/**
* Custom Framework Specific gulp tasks
*/
build.initialize(gulp);
|
// buffer each user's email text in a queue, then flush them in single email
Meteor.startup(() => {
Notifications.subscribe('email', (user, title, description, params) => {
// add quote to make titles easier to read in email text
const quoteParams = _.clone(params);
['card', 'list', 'oldList', 'board', 'comment'].forEach((key) => {
if (quoteParams[key]) quoteParams[key] = `"${params[key]}"`;
});
const text = `${params.user} ${TAPi18n.__(description, quoteParams, user.getLanguage())}\n${params.url}`;
user.addEmailBuffer(text);
// unlike setTimeout(func, delay, args),
// Meteor.setTimeout(func, delay) does not accept args :-(
// so we pass userId with closure
const userId = user._id;
Meteor.setTimeout(() => {
const user = Users.findOne(userId);
// for each user, in the timed period, only the first call will get the cached content,
// other calls will get nothing
const texts = user.getEmailBuffer();
if (texts.length === 0) return;
// merge the cached content into single email and flush
const text = texts.join('\n\n');
user.clearEmailBuffer();
try {
Email.send({
to: user.emails[0].address.toLowerCase(),
from: Accounts.emailTemplates.from,
subject: TAPi18n.__('act-activity-notify', {}, user.getLanguage()),
text,
});
} catch (e) {
return;
}
}, 30000);
});
});
|
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var strings={prefixAgo:null,prefixFromNow:null,suffixAgo:"之前",suffixFromNow:"之后",seconds:"不到1分钟",minute:"大约1分钟",minutes:"%d分钟",hour:"大约1小时",hours:"大约%d小时",day:"1天",days:"%d天",month:"大约1个月",months:"%d月",year:"大约1年",years:"%d年",wordSeparator:""},_default=strings;exports.default=_default;
|
/*!
DataTables styling wrapper for Responsive
©2018 SpryMedia Ltd - datatables.net/license
*/
(function(c){"function"===typeof define&&define.amd?define(["jquery","datatables.net-dt","datatables.net-responsive"],function(a){return c(a,window,document)}):"object"===typeof exports?module.exports=function(a,b){a||(a=window);if(!b||!b.fn.dataTable)b=require("datatables.net-dt")(a,b).$;b.fn.dataTable.Responsive||require("datatables.net-responsive")(a,b);return c(b,a,a.document)}:c(jQuery,window,document)})(function(c){return c.fn.dataTable});
|
import Vue from '../../dist/vue.runtime.common.js'
import { createRenderer } from '../../packages/vue-server-renderer'
const { renderToStream } = createRenderer()
describe('SSR: renderToStream', () => {
it('should render to a stream', done => {
const stream = renderToStream(new Vue({
template: `
<div>
<p class="hi">yoyo</p>
<div id="ho" :class="[testClass, { red: isRed }]"></div>
<span>{{ test }}</span>
<input :value="test">
<b-comp></b-comp>
<c-comp></c-comp>
</div>
`,
data: {
test: 'hi',
isRed: true,
testClass: 'a'
},
components: {
bComp (resolve) {
return resolve({
render (h) {
return h('test-async-2')
},
components: {
testAsync2 (resolve) {
return resolve({
created () { this.$parent.$parent.testClass = 'b' },
render (h) {
return h('div', { class: [this.$parent.$parent.testClass] }, 'test')
}
})
}
}
})
},
cComp: {
render (h) {
return h('div', { class: [this.$parent.testClass] }, 'test')
}
}
}
}))
let res = ''
stream.on('data', chunk => {
res += chunk
})
stream.on('end', () => {
expect(res).toContain(
'<div server-rendered="true">' +
'<p class="hi">yoyo</p> ' +
'<div id="ho" class="a red"></div> ' +
'<span>hi</span> ' +
'<input value="hi"> ' +
'<div class="b">test</div> ' +
'<div class="b">test</div>' +
'</div>'
)
done()
})
})
it('should catch error', done => {
Vue.config.silent = true
const stream = renderToStream(new Vue({
render () {
throw new Error('oops')
}
}))
stream.on('error', err => {
expect(err.toString()).toMatch(/oops/)
Vue.config.silent = false
done()
})
stream.on('data', _ => _)
})
it('should not mingle two components', done => {
const padding = (new Array(20000)).join('x')
const component1 = new Vue({
template: `<div>${padding}<div></div></div>`,
_scopeId: '_component1'
})
const component2 = new Vue({
template: `<div></div>`,
_scopeId: '_component2'
})
var stream1 = renderToStream(component1)
var stream2 = renderToStream(component2)
var res = ''
stream1.on('data', (text) => {
res += text.toString('utf-8').replace(/x/g, '')
})
stream1.on('end', () => {
expect(res).not.toContain('_component2')
done()
})
stream1.read(1)
stream2.read(1)
})
})
|
var parent = require('../../../stable/string/virtual/pad-end');
module.exports = parent;
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'preview', 'ms', {
preview: 'Prebiu'
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var immutable_1 = require("immutable");
function copyCLIIgnoreToWatchOptions(incoming) {
if (!incoming.get("ignore")) {
return incoming;
}
return incoming.updateIn(["watchOptions", "ignored"], function (ignored) {
var userIgnore = immutable_1.List([]).concat(incoming.get("ignore"));
return ignored.concat(userIgnore);
});
}
exports.copyCLIIgnoreToWatchOptions = copyCLIIgnoreToWatchOptions;
//# sourceMappingURL=copyCLIIgnoreToWatchOptions.js.map
|
/* *
*
* (c) 2010-2019 Torstein Honsi
*
* 3D pie series
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../parts/Globals.js';
import '../parts/Utilities.js';
var deg2rad = H.deg2rad, pick = H.pick, seriesTypes = H.seriesTypes, svg = H.svg, wrap = H.wrap;
/**
* The thickness of a 3D pie. Requires `highcharts-3d.js`
*
* @type {number}
* @default 0
* @since 4.0
* @product highcharts
* @apioption plotOptions.pie.depth
*/
/* eslint-disable no-invalid-this */
wrap(seriesTypes.pie.prototype, 'translate', function (proceed) {
proceed.apply(this, [].slice.call(arguments, 1));
// Do not do this if the chart is not 3D
if (!this.chart.is3d()) {
return;
}
var series = this, seriesOptions = series.options, depth = seriesOptions.depth || 0, options3d = series.chart.options.chart.options3d, alpha = options3d.alpha, beta = options3d.beta, z = seriesOptions.stacking ?
(seriesOptions.stack || 0) * depth :
series._i * depth;
z += depth / 2;
if (seriesOptions.grouping !== false) {
z = 0;
}
series.data.forEach(function (point) {
var shapeArgs = point.shapeArgs, angle;
point.shapeType = 'arc3d';
shapeArgs.z = z;
shapeArgs.depth = depth * 0.75;
shapeArgs.alpha = alpha;
shapeArgs.beta = beta;
shapeArgs.center = series.center;
angle = (shapeArgs.end + shapeArgs.start) / 2;
point.slicedTranslation = {
translateX: Math.round(Math.cos(angle) *
seriesOptions.slicedOffset *
Math.cos(alpha * deg2rad)),
translateY: Math.round(Math.sin(angle) *
seriesOptions.slicedOffset *
Math.cos(alpha * deg2rad))
};
});
});
wrap(seriesTypes.pie.prototype.pointClass.prototype, 'haloPath', function (proceed) {
var args = arguments;
return this.series.chart.is3d() ? [] : proceed.call(this, args[1]);
});
wrap(seriesTypes.pie.prototype, 'pointAttribs', function (proceed, point, state) {
var attr = proceed.call(this, point, state), options = this.options;
if (this.chart.is3d() && !this.chart.styledMode) {
attr.stroke = options.edgeColor || point.color || this.color;
attr['stroke-width'] = pick(options.edgeWidth, 1);
}
return attr;
});
wrap(seriesTypes.pie.prototype, 'drawDataLabels', function (proceed) {
if (this.chart.is3d()) {
var series = this, chart = series.chart, options3d = chart.options.chart.options3d;
series.data.forEach(function (point) {
var shapeArgs = point.shapeArgs, r = shapeArgs.r,
// #3240 issue with datalabels for 0 and null values
a1 = (shapeArgs.alpha || options3d.alpha) * deg2rad, b1 = (shapeArgs.beta || options3d.beta) * deg2rad, a2 = (shapeArgs.start + shapeArgs.end) / 2, labelPosition = point.labelPosition, connectorPosition = labelPosition.connectorPosition, yOffset = (-r * (1 - Math.cos(a1)) * Math.sin(a2)), xOffset = r * (Math.cos(b1) - 1) * Math.cos(a2);
// Apply perspective on label positions
[
labelPosition.natural,
connectorPosition.breakAt,
connectorPosition.touchingSliceAt
].forEach(function (coordinates) {
coordinates.x += xOffset;
coordinates.y += yOffset;
});
});
}
proceed.apply(this, [].slice.call(arguments, 1));
});
wrap(seriesTypes.pie.prototype, 'addPoint', function (proceed) {
proceed.apply(this, [].slice.call(arguments, 1));
if (this.chart.is3d()) {
// destroy (and rebuild) everything!!!
this.update(this.userOptions, true); // #3845 pass the old options
}
});
wrap(seriesTypes.pie.prototype, 'animate', function (proceed) {
if (!this.chart.is3d()) {
proceed.apply(this, [].slice.call(arguments, 1));
}
else {
var args = arguments, init = args[1], animation = this.options.animation, attribs, center = this.center, group = this.group, markerGroup = this.markerGroup;
if (svg) { // VML is too slow anyway
if (animation === true) {
animation = {};
}
// Initialize the animation
if (init) {
// Scale down the group and place it in the center
group.oldtranslateX = group.translateX;
group.oldtranslateY = group.translateY;
attribs = {
translateX: center[0],
translateY: center[1],
scaleX: 0.001,
scaleY: 0.001
};
group.attr(attribs);
if (markerGroup) {
markerGroup.attrSetters = group.attrSetters;
markerGroup.attr(attribs);
}
// Run the animation
}
else {
attribs = {
translateX: group.oldtranslateX,
translateY: group.oldtranslateY,
scaleX: 1,
scaleY: 1
};
group.animate(attribs, animation);
if (markerGroup) {
markerGroup.animate(attribs, animation);
}
// Delete this function to allow it only once
this.animate = null;
}
}
}
});
|
var _obj;
function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); }
function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
foo = _obj = {
bar() {
return _set(_getPrototypeOf(_obj), "baz", Math.pow(_get(_getPrototypeOf(_obj), "baz", this), 12), this, false);
}
};
|
$(function(){
//convert Hex to RGBA
function convertHex(hex,opacity){
hex = hex.replace('#','');
r = parseInt(hex.substring(0,2), 16);
g = parseInt(hex.substring(2,4), 16);
b = parseInt(hex.substring(4,6), 16);
result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
return result;
}
//Cards with Charts
var labels = ['January','February','March','April','May','June','July'];
var data = {
labels: labels,
datasets: [
{
label: 'My First dataset',
backgroundColor: $.brandPrimary,
borderColor: 'rgba(255,255,255,.55)',
data: [65, 59, 84, 84, 51, 55, 40]
},
]
};
var options = {
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent',
}
}],
yAxes: [{
display: false,
ticks: {
display: false,
min: Math.min.apply(Math, data.datasets[0].data) - 5,
max: Math.max.apply(Math, data.datasets[0].data) + 5,
}
}],
},
elements: {
line: {
borderWidth: 1
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4,
},
}
};
var ctx = $('#card-chart1');
var cardChart1 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var data = {
labels: labels,
datasets: [
{
label: 'My First dataset',
backgroundColor: $.brandInfo,
borderColor: 'rgba(255,255,255,.55)',
data: [1, 18, 9, 17, 34, 22, 11]
},
]
};
var options = {
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent',
}
}],
yAxes: [{
display: false,
ticks: {
display: false,
min: Math.min.apply(Math, data.datasets[0].data) - 5,
max: Math.max.apply(Math, data.datasets[0].data) + 5,
}
}],
},
elements: {
line: {
tension: 0.00001,
borderWidth: 1
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4,
},
}
};
var ctx = $('#card-chart2');
var cardChart2 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var options = {
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}],
},
elements: {
line: {
borderWidth: 2
},
point: {
radius: 0,
hitRadius: 10,
hoverRadius: 4,
},
}
};
var data = {
maintainAspectRatio: false,
labels: labels,
datasets: [
{
label: 'My First dataset',
backgroundColor: 'rgba(255,255,255,.2)',
borderColor: 'rgba(255,255,255,.55)',
data: [78, 81, 80, 45, 34, 12, 40]
},
]
};
var ctx = $('#card-chart3');
var cardChart3 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
//Random Numbers
function random(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
var elements = 16;
var labels = [];
var data = [];
for (var i = 0; i <= elements; i++) {
labels.push('1');
data.push(random(40,100));
}
var options = {
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display: false,
barPercentage: 0.7,
}],
yAxes: [{
display: false,
}]
},
};
var data = {
labels: labels,
datasets: [
{
backgroundColor: 'rgba(255,255,255,.3)',
borderColor: 'transparent',
data: data
},
]
};
var ctx = $('#card-chart4');
var cardChart4 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var elements = 15;
var labels = [];
var data = [];
for (var i = 0; i <= elements; i++) {
labels.push('1');
data.push(random(40,100));
}
var options = {
responsive: false,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}]
}
};
var data = {
labels: labels,
datasets: [
{
backgroundColor: $.brandPrimary,
borderColor: 'transparent',
borderWidth: 1,
data: data
},
]
};
var ctx = $('#chart-1');
var Chart1 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var elements = 15;
var labels = [];
var data = [];
for (var i = 0; i <= elements; i++) {
labels.push('1');
data.push(random(40,100));
}
var options = {
responsive: false,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}]
}
};
var data = {
labels: labels,
datasets: [
{
backgroundColor: $.brandWarning,
borderColor: 'transparent',
borderWidth: 1,
data: data
},
]
};
var ctx = $('#chart-2');
var Chart2 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var elements = 15;
var labels = [];
var data = [];
for (var i = 0; i <= elements; i++) {
labels.push('1');
data.push(random(40,100));
}
var options = {
responsive: false,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}]
}
};
var data = {
labels: labels,
datasets: [
{
backgroundColor: $.brandSuccess,
borderColor: 'transparent',
borderWidth: 1,
data: data
},
]
};
var ctx = $('#chart-3');
var Chart3 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var options = {
responsive: false,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}]
},
elements: { point: { radius: 0 } }
};
var data = {
labels: ['January','February','March','April','May','June','July'],
datasets: [
{
backgroundColor: 'transparent',
borderColor: $.brandInfo,
borderWidth: 2,
data: [65, 59, 84, 84, 51, 55, 40]
},
]
};
var ctx = $('#chart-4');
var Chart4 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var options = {
responsive: false,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}]
},
elements: { point: { radius: 0 } }
};
var data = {
labels: ['January','February','March','April','May','June','July'],
datasets: [
{
backgroundColor: 'transparent',
borderColor: $.brandSuccess,
borderWidth: 2,
data: [65, 59, 84, 84, 51, 55, 40]
},
]
};
var ctx = $('#chart-5');
var Chart5 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var options = {
responsive: false,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display: false
}],
yAxes: [{
display: false
}]
},
elements: { point: { radius: 0 } }
};
var data = {
labels: ['January','February','March','April','May','June','July'],
datasets: [
{
backgroundColor: 'transparent',
borderColor: $.brandDanger,
borderWidth: 2,
data: [65, 59, 84, 84, 51, 55, 40]
},
]
};
var ctx = $('#chart-6');
var Chart6 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var options = {
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display:false,
points:false,
}],
yAxes: [{
display:false,
}]
},
elements: { point: { radius: 0 } }
};
var data = {
labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May'],
datasets: [
{
backgroundColor: 'transparent',
borderColor: 'rgba(255,255,255,.55)',
borderWidth: 2,
data: [4, 18, 9, 17, 34, 22, 11, 3, 15, 12, 18, 9, 9, 17, 34, 22, 11]
},
]
};
var ctx = $('.chart-7');
var Chart7 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var ctx = $('.chart-7-2');
var Chart72 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var ctx = $('.chart-7-3');
var Chart73 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var ctx = $('.chart-7-4');
var Chart74 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var options = {
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display:false,
barPercentage: 0.6,
}],
yAxes: [{
display:false,
ticks: {
beginAtZero: true,
}
}]
},
};
var data = {
labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May'],
datasets: [
{
backgroundColor: 'rgba(0,0,0,.2)',
data: [4, 18, 9, 17, 34, 22, 11, 3, 15, 12, 18, 9, 9, 17, 34, 22, 11]
},
]
};
var ctx = $('.chart-8');
var Chart8 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var ctx = $('.chart-8-2');
var Chart82 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var ctx = $('.chart-8-3');
var Chart83 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var ctx = $('.chart-8-4');
var Chart84 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var options = {
responsive: false,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent',
},
ticks: {
fontSize: 10,
maxRotation: 0,
},
barPercentage: 0.6,
}],
yAxes: [{
display:false,
ticks: {
beginAtZero: true,
}
}]
}
};
var data = {
labels: ['M','T','W','T','F','S','S'],
datasets: [
{
backgroundColor: $.grayLight,
data: [17, 34, 22, 11, 3, 15, 12]
},
]
};
var ctx = $('.chart-9');
var Chart9 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var ctx = $('.chart-9-2');
var Chart92 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var ctx = $('.chart-9-3');
var Chart93 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var ctx = $('.chart-9-4');
var Chart94 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var options = {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
display:false,
}],
yAxes: [{
display:false,
}]
},
elements: {
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4,
hoverBorderWidth: 3,
}
},
};
var data = {
labels: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],
datasets: [
{
backgroundColor: 'transparent',
borderColor: $.grayLighter,
pointBackgroundColor: '#fff',
borderWidth: 3,
data: [75, 59, 94, 104, 151, 155, 240]
},
]
};
var ctx = $('#chart-10');
var Chart10 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var options = {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
drawOnChartArea: false,
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontColor: '#fff',
maxTicksLimit: 3,
maxRotation: 0,
}
}],
yAxes: [{
gridLines: {
color: 'rgba(255,255,255,.2)',
zeroLineColor: 'rgba(255,255,255,.2)'
},
ticks: {
maxTicksLimit: 10,
stepSize: Math.ceil(45000 / 10),
max: 45000,
fontColor: '#fff',
callback: function(value) {
return '$' + value;
}
}
}]
},
elements: {
point: {
radius: 4,
borderWidth: 2,
hitRadius: 10,
hoverRadius: 4,
hoverBorderWidth: 3,
}
},
};
var data = {
labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
datasets: [
{
backgroundColor: 'transparent',
borderColor: '#fff',
borderWidth: 2,
pointBackgroundColor: $.brandPrimary,
data: [31000, 34000, 27000, 24000, 28000, 42500, 42000, 30000, 35500, 35500, 41500, 41600]
},
]
};
var ctx = $('#chart-11').get(0).getContext('2d');
var Chart11 = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
var options = {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent',
},
ticks: {
maxRotation: 0,
},
barPercentage: 0.6,
}],
yAxes: [{
display:false,
ticks: {
beginAtZero: true,
}
}]
}
};
var data = {
labels: ['US','PL','GB','DE','NL','CA','FI', 'RU', 'AU', 'N/A'],
datasets: [
{
backgroundColor: $.brandSuccess,
data: [35, 14, 10, 8, 6, 6, 5, 4, 3, 9]
},
]
};
var ctx = $('#chart-12').get(0).getContext('2d');
var Chart12 = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
var opts1 = {
lines: 12,
angle: 0.15,
lineWidth: 0.44,
pointer: {
length: 0.8,
strokeWidth: 0.035,
color: $.grayDark
},
limitMax: 'false',
colorStart: $.brandInfo,
colorStop: $.brandInfo,
strokeColor: $.grayLighter,
generateGradient: true,
responsive: true,
};
var target = document.getElementById('gauge1'); // your canvas element
var gauge = new Gauge(target).setOptions(opts1); // create sexy gauge!
gauge.maxValue = 3000; // set max gauge value
gauge.animationSpeed = 32; // set animation speed (32 is default value)
gauge.set(random(0,3000)); // set actual value
var opts2 = {
lines: 12,
angle: 0.15,
lineWidth: 0.44,
pointer: {
length: 0.8,
strokeWidth: 0.035,
color: $.grayDark
},
limitMax: 'false',
colorStart: $.brandSuccess,
colorStop: $.brandSuccess,
strokeColor: $.grayLighter,
generateGradient: true,
responsive: true,
};
var target = document.getElementById('gauge2'); // your canvas element
var gauge = new Gauge(target).setOptions(opts2); // create sexy gauge!
gauge.maxValue = 3000; // set max gauge value
gauge.animationSpeed = 32; // set animation speed (32 is default value)
gauge.set(random(0,3000)); // set actual value
var opts3 = {
lines: 12,
angle: 0.15,
lineWidth: 0.44,
pointer: {
length: 0.8,
strokeWidth: 0.035,
color: $.grayDark
},
limitMax: 'false',
colorStart: $.brandWarning,
colorStop: $.brandWarning,
strokeColor: $.grayLighter,
generateGradient: true,
responsive: true,
};
var target = document.getElementById('gauge3'); // your canvas element
var gauge = new Gauge(target).setOptions(opts3); // create sexy gauge!
gauge.maxValue = 3000; // set max gauge value
gauge.animationSpeed = 32; // set animation speed (32 is default value)
gauge.set(random(0,3000)); // set actual value
var opts4 = {
lines: 12,
angle: 0.15,
lineWidth: 0.44,
pointer: {
length: 0.8,
strokeWidth: 0.035,
color: $.grayDark
},
limitMax: 'false',
colorStart: $.brandDanger,
colorStop: $.brandDanger,
strokeColor: $.grayLighter,
generateGradient: true,
responsive: true,
};
var target = document.getElementById('gauge4'); // your canvas element
var gauge = new Gauge(target).setOptions(opts4); // create sexy gauge!
gauge.maxValue = 3000; // set max gauge value
gauge.animationSpeed = 32; // set animation speed (32 is default value)
gauge.set(random(0,3000)); // set actual value
})
|
import React from 'react';
import RadioGroupContext from './RadioGroupContext';
export default function useRadioGroup() {
return React.useContext(RadioGroupContext);
}
|
var util = require('./util');
var wrapper = util.wrapper;
var postJSON = util.postJSON;
/**
* 获取用户基本信息
* 详情请见:<http://mp.weixin.qq.com/wiki/index.php?title=获取用户基本信息>
* Examples:
* ```
* api.getUser(openid, callback);
* ```
* Callback:
*
* - `err`, 调用失败时得到的异常
* - `result`, 调用正常时得到的对象
*
* Result:
* ```
* {
* "subscribe": 1,
* "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M",
* "nickname": "Band",
* "sex": 1,
* "language": "zh_CN",
* "city": "广州",
* "province": "广东",
* "country": "中国",
* "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
* "subscribe_time": 1382694957
* }
* ```
* @param {String} openid 用户的openid
* @param {Function} callback 回调函数
*/
exports.getUser = function (openid, callback) {
this.preRequest(this._getUser, arguments);
};
/*!
* 获取用户基本信息的未封装版本
*/
exports._getUser = function (openid, callback) {
// https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID
var url = this.prefix + 'user/info?openid=' + openid + '&access_token=' + this.token.accessToken;
this.request(url, {dataType: 'json'}, wrapper(callback));
};
/**
* 获取关注者列表
* 详细细节 http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表
* Examples:
* ```
* api.getFollowers(callback);
* // or
* api.getFollowers(nextOpenid, callback);
* ```
* Callback:
*
* - `err`, 调用失败时得到的异常
* - `result`, 调用正常时得到的对象
*
* Result:
* ```
* {
* "total":2,
* "count":2,
* "data":{
* "openid":["","OPENID1","OPENID2"]
* },
* "next_openid":"NEXT_OPENID"
* }
* ```
* @param {String} nextOpenid 调用一次之后,传递回来的nextOpenid。第一次获取时可不填
* @param {Function} callback 回调函数
*/
exports.getFollowers = function (nextOpenid, callback) {
this.preRequest(this._getFollowers, arguments);
};
/*!
* 获取关注者列表的未封装版本
*/
exports._getFollowers = function (nextOpenid, callback) {
// https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
if (typeof nextOpenid === 'function') {
callback = nextOpenid;
nextOpenid = '';
}
var url = this.prefix + 'user/get?next_openid=' + nextOpenid + '&access_token=' + this.token.accessToken;
this.request(url, {dataType: 'json'}, wrapper(callback));
};
/**
* 设置用户备注名
* 详细细节 http://mp.weixin.qq.com/wiki/index.php?title=设置用户备注名接口
* Examples:
* ```
* api.updateRemark(openid, remark, callback);
* ```
* Callback:
*
* - `err`, 调用失败时得到的异常
* - `result`, 调用正常时得到的对象
*
* Result:
* ```
* {
* "errcode":0,
* "errmsg":"ok"
* }
* ```
* @param {String} openid 用户的openid
* @param {String} remark 新的备注名,长度必须小于30字符
* @param {Function} callback 回调函数
*/
exports.updateRemark = function (openid, remark, callback) {
this.preRequest(this._updateRemark, arguments);
};
/*!
* 设置用户备注名的未封装版本
*/
exports._updateRemark = function (openid, remark, callback) {
// https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=ACCESS_TOKEN
var url = this.prefix + 'user/info/updateremark?access_token=' + this.token.accessToken;
var data = {
openid: openid,
remark: remark
};
this.request(url, postJSON(data), wrapper(callback));
};
|
exports.isJavaObject = function( o ) {
if (o === global){
return false;
}
if (o !== undefined && o !== null){
try {
// this throws error for java objects in jre7
if (typeof o.constructor === 'function'){
return false;
}
} catch (e){
return true;
}
try {
var result = o.getClass ? true : false; // throws error for Enums/Class in jre7
if (result == true){
return result;
}
}catch (e2){
// fail silently and move on to next test
}
// java classes don't have a getClass so just because .getClass isn't present
// doesn't mean it's not a Java Enum or Class (.getClass only works for object instances?)
if (o instanceof java.lang.Object){
return true;
}
}
return o instanceof java.lang.Object;
};
|
var types = require("utils/types");
var knownColors = require("color/known-colors");
var AMP = "#";
var Color = (function () {
function Color() {
if (arguments.length === 1) {
var arg = arguments[0];
if (types.isString(arg)) {
if (knownColors.isKnownName(arg)) {
this._hex = knownColors.getKnownColor(arg);
this._name = arg;
}
else {
this._hex = this._normalizeHex(arg);
}
this._argb = this._argbFromString(this._hex);
}
else if (types.isNumber(arg)) {
this._argb = arg;
}
else {
throw new Error("Expected 1 or 4 constructor parameters.");
}
this._parseComponents();
if (!this._hex) {
this._hex = this._buildHex();
}
}
else if (arguments.length === 4) {
this._a = arguments[0];
this._r = arguments[1];
this._g = arguments[2];
this._b = arguments[3];
this._buildArgb();
this._hex = this._buildHex();
}
else {
throw new Error("Expected 1 or 4 constructor parameters.");
}
}
Object.defineProperty(Color.prototype, "a", {
get: function () {
return this._a;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "r", {
get: function () {
return this._r;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "g", {
get: function () {
return this._g;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "b", {
get: function () {
return this._b;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "argb", {
get: function () {
return this._argb;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "hex", {
get: function () {
return this._hex;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "name", {
get: function () {
return this._name;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "ios", {
get: function () {
return undefined;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Color.prototype, "android", {
get: function () {
return undefined;
},
enumerable: true,
configurable: true
});
Color.prototype._argbFromString = function (hex) {
return undefined;
};
Color.prototype.equals = function (value) {
return this.argb === value.argb;
};
Color.equals = function (value1, value2) {
if (!value1 && !value2) {
return true;
}
if (!value1 || !value2) {
return false;
}
return value1.equals(value2);
};
Color.prototype._buildHex = function () {
return AMP + this._componentToHex(this._a) + this._componentToHex(this._r) + this._componentToHex(this._g) + this._componentToHex(this._b);
};
Color.prototype._componentToHex = function (component) {
var hex = component.toString(16);
if (hex.length === 1) {
hex = "0" + hex;
}
return hex;
};
Color.prototype._parseComponents = function () {
if (types.isUndefined(this._argb)) {
throw new Error("Missing the ARGB numeric value");
}
this._a = (this._argb >> 24) & 255;
this._r = (this._argb >> 16) & 255;
this._g = (this._argb >> 8) & 255;
this._b = this._argb & 255;
};
Color.prototype._buildArgb = function () {
this._argb = (this._a << 24) | (this._r << 16) | (this._g << 8) | this._b;
};
Color.prototype._normalizeHex = function (hexStr) {
if (hexStr.charAt(0) === AMP && hexStr.length === 4) {
hexStr = hexStr.charAt(0)
+ hexStr.charAt(1) + hexStr.charAt(1)
+ hexStr.charAt(2) + hexStr.charAt(2)
+ hexStr.charAt(3) + hexStr.charAt(3);
}
return hexStr;
};
return Color;
})();
exports.Color = Color;
|
'use strict';
var React = require('react/addons');
var PureRenderMixin = React.addons.PureRenderMixin;
var SvgIcon = require('../../svg-icon');
var AvPauseCircleFilled = React.createClass({
displayName: 'AvPauseCircleFilled',
mixins: [PureRenderMixin],
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14H9V8h2v8zm4 0h-2V8h2v8z' })
);
}
});
module.exports = AvPauseCircleFilled;
|
var assert = require('assert'),
vows = require('vows'),
nock = require('nock');
var apiEndpoint = nock('http://dc.api.mailchimp.com:80').get('/export/1.0/campaignSubscriberActivity/?apikey=apiKey-dc')
.reply(200, '{\"error\":\"Invalid Campaign ID: \",\"code\":300}')
.get('/export/1.0/campaignSubscriberActivity/?apikey=apiKey-dc&id=12345')
.reply(200, "{\"user1@domain.tld\":[{\"action\":\"open\",\"timestamp\":\"2012-01-01 00:00:00\",\"url\":null,\"ip\":\"127.0.0.1\"}]}\n{\"user2@domain.tld\":[{\"action\":\"open\",\"timestamp\":\"2012-01-21 01:00:00\",\"url\":null,\"ip\":\"127.0.0.1\"}]}\n")
.get('/export/1.0/campaignSubscriberActivity/?apikey=apiKey-dc&id=12345&include_empty=true')
.reply(200, "{\"user1@domain.tld\":[{\"action\":\"open\",\"timestamp\":\"2012-01-01 00:00:00\",\"url\":null,\"ip\":\"127.0.0.1\"}]}\n{\"user2@domain.tld\":[{\"action\":\"open\",\"timestamp\":\"2012-01-21 01:00:00\",\"url\":null,\"ip\":\"127.0.0.1\"}]}\n")
.get('/export/1.0/campaignSubscriberActivity/?apikey=apiKey-dc&id=12345&include_empty=true')
.reply(200, "{\"user1@domain.tld\":[{\"action\":\"open\",\"timestamp\":\"2012-01-01 00:00:00\",\"url\":null,\"ip\":\"127.0.0.1\"}]}\n{\"user2@domain.tld\":[{\"action\":\"open\",\"timestamp\":\"2012-01-21 01:00:00\",\"url\":null,\"ip\":\"127.0.0.1\"}]}\n");
var MailChimpAPI = require('mailchimp').MailChimpExportAPI;
vows.describe('MailChimpExportAPI v1.1').addBatch({
'MailChimpExportAPI v1.1 wrapper': {
'when instantiated': {
topic: function () { return new MailChimpAPI('apiKey-dc', { version : '1.0' }) },
'successfully creates an instance': function (api) {
assert.isObject(api);
assert.strictEqual(api.version, '1.0');
},
/*** campaignSubscriberActivity ***/
'and calling method "campaignSubscriberActivity" with mandatory arguments': {
topic: function (api) { api.campaignSubscriberActivity({ id: "12345" }, this.callback) },
'exports subscriber activity for the requested campaign': function (error, data) {
assert.isNull(error);
assert.isArray(data);
}
},
'and calling method "campaignSubscriberActivity" without mandatory arguments': {
topic: function (api) { api.campaignSubscriberActivity(this.callback) },
'returns an error': function (error, data) {
assert.instanceOf(error, Error);
}
},
'and calling method "campaignSubscriberActivity" with all arguments': {
topic: function (api) { api.campaignSubscriberActivity({ id: "12345", include_empty: "true" }, this.callback) },
'exports subscriber activity for the requested campaign': function (error, data) {
assert.isNull(error);
assert.isArray(data);
}
},
'and calling method "campaignSubscriberActivity" with superflous arguments': {
topic: function (api) { api.campaignSubscriberActivity({ id: "12345", include_empty: "true", superflous: "superflous" }, this.callback) },
'exports subscriber activity for the requested campaign and superflous arguments are discarded': function (error, data) {
assert.isNull(error);
assert.isArray(data);
}
}
}
}
}).export(module);
|
/* flatpickr v4.3.2, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.sk = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined
? window.flatpickr
: {
l10ns: {},
};
var Slovak = {
weekdays: {
shorthand: ["Ned", "Pon", "Ut", "Str", "Štv", "Pia", "Sob"],
longhand: [
"Nedeľa",
"Pondelok",
"Utorok",
"Streda",
"Štvrtok",
"Piatok",
"Sobota",
],
},
months: {
shorthand: [
"Jan",
"Feb",
"Mar",
"Apr",
"Máj",
"Jún",
"Júl",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec",
],
longhand: [
"Január",
"Február",
"Marec",
"Apríl",
"Máj",
"Jún",
"Júl",
"August",
"September",
"Október",
"November",
"December",
],
},
firstDayOfWeek: 1,
rangeSeparator: " do ",
ordinal: function () {
return ".";
},
};
fp.l10ns.sk = Slovak;
var sk = fp.l10ns;
exports.Slovak = Slovak;
exports.default = sk;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
define("ace/theme/merbivore",["require","exports","module","ace/lib/dom"], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-merbivore";
exports.cssText = ".ace-merbivore .ace_gutter {\
background: #202020;\
color: #E6E1DC\
}\
.ace-merbivore .ace_print-margin {\
width: 1px;\
background: #555651\
}\
.ace-merbivore {\
background-color: #161616;\
color: #E6E1DC\
}\
.ace-merbivore .ace_cursor {\
color: #FFFFFF\
}\
.ace-merbivore .ace_marker-layer .ace_selection {\
background: #454545\
}\
.ace-merbivore.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px #161616;\
}\
.ace-merbivore .ace_marker-layer .ace_step {\
background: rgb(102, 82, 0)\
}\
.ace-merbivore .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #404040\
}\
.ace-merbivore .ace_marker-layer .ace_active-line {\
background: #333435\
}\
.ace-merbivore .ace_gutter-active-line {\
background-color: #333435\
}\
.ace-merbivore .ace_marker-layer .ace_selected-word {\
border: 1px solid #454545\
}\
.ace-merbivore .ace_invisible {\
color: #404040\
}\
.ace-merbivore .ace_entity.ace_name.ace_tag,\
.ace-merbivore .ace_keyword,\
.ace-merbivore .ace_meta,\
.ace-merbivore .ace_meta.ace_tag,\
.ace-merbivore .ace_storage,\
.ace-merbivore .ace_support.ace_function {\
color: #FC6F09\
}\
.ace-merbivore .ace_constant,\
.ace-merbivore .ace_constant.ace_character,\
.ace-merbivore .ace_constant.ace_character.ace_escape,\
.ace-merbivore .ace_constant.ace_other,\
.ace-merbivore .ace_support.ace_type {\
color: #1EDAFB\
}\
.ace-merbivore .ace_constant.ace_character.ace_escape {\
color: #519F50\
}\
.ace-merbivore .ace_constant.ace_language {\
color: #FDC251\
}\
.ace-merbivore .ace_constant.ace_library,\
.ace-merbivore .ace_string,\
.ace-merbivore .ace_support.ace_constant {\
color: #8DFF0A\
}\
.ace-merbivore .ace_constant.ace_numeric {\
color: #58C554\
}\
.ace-merbivore .ace_invalid {\
color: #FFFFFF;\
background-color: #990000\
}\
.ace-merbivore .ace_fold {\
background-color: #FC6F09;\
border-color: #E6E1DC\
}\
.ace-merbivore .ace_comment {\
font-style: italic;\
color: #AD2EA4\
}\
.ace-merbivore .ace_entity.ace_other.ace_attribute-name {\
color: #FFFF89\
}\
.ace-merbivore .ace_indent-guide {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWMQFxf3ZXB1df0PAAdsAmERTkEHAAAAAElFTkSuQmCC) right repeat-y\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
(function() {
window.require(["ace/theme/merbivore"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
/*!
* FileInput Estonian Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['et'] = {
fileSingle: 'fail',
filePlural: 'failid',
browseLabel: 'Sirvi …',
removeLabel: 'Eemalda',
removeTitle: 'Clear selected files',
cancelLabel: 'Tühista',
cancelTitle: 'Abort ongoing upload',
pauseLabel: 'Pause',
pauseTitle: 'Pause ongoing upload',
uploadLabel: 'Salvesta',
uploadTitle: 'Salvesta valitud failid',
msgNo: 'No',
msgNoFilesSelected: 'No files selected',
msgPaused: 'Paused',
msgCancelled: 'Cancelled',
msgPlaceholder: 'Select {files} ...',
msgZoomModalHeading: 'Detailed Preview',
msgFileRequired: 'You must select a file to upload.',
msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
msgSizeTooLarge: 'Fail "{name}" (<b>{size} KB</b>) ületab lubatu suuruse <b>{maxSize} KB</b>.',
msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
msgTotalFilesTooMany: 'You can upload a maximum of <b>{m}</b> files (<b>{n}</b> files detected).',
msgFileNotFound: 'File "{name}" not found!',
msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
msgFileNotReadable: 'File "{name}" is not readable.',
msgFilePreviewAborted: 'File preview aborted for "{name}".',
msgFilePreviewError: 'An error occurred while reading the file "{name}".',
msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
msgInvalidFileType: '"{name}" on vale tüüpi. Ainult "{types}" on lubatud.',
msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
msgFileTypes: {
'image': 'image',
'html': 'HTML',
'text': 'text',
'video': 'video',
'audio': 'audio',
'flash': 'flash',
'pdf': 'PDF',
'object': 'object'
},
msgUploadAborted: 'The file upload was aborted',
msgUploadThreshold: 'Processing …',
msgUploadBegin: 'Initializing …',
msgUploadEnd: 'Done',
msgUploadResume: 'Resuming upload …',
msgUploadEmpty: 'No valid data available for upload.',
msgUploadError: 'Upload Error',
msgDeleteError: 'Delete Error',
msgProgressError: 'Error',
msgValidationError: 'Validation Error',
msgLoading: 'Loading file {index} of {files} …',
msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
msgSelected: '{n} {files} selected',
msgFoldersNotAllowed: 'Drag & drop files only! Skipped {n} dropped folder(s).',
msgImageWidthSmall: 'Pildi laius peab olema vähemalt {size} px.',
msgImageHeightSmall: 'Pildi kõrgus peab olema vähemalt {size} px.',
msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
msgImageResizeError: 'Could not get the image dimensions to resize.',
msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
msgAjaxProgressError: '{operation} failed',
msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',
msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
msgPendingTime: '{time} remaining',
msgCalculatingTime: 'calculating time remaining',
ajaxOperations: {
deleteThumb: 'file delete',
uploadThumb: 'file upload',
uploadBatch: 'batch file upload',
uploadExtra: 'form data upload'
},
dropZoneTitle: 'Lohista failid siia …',
dropZoneClickTitle: '<br>(or click to select {files})',
fileActionSettings: {
removeTitle: 'Eemalda fail',
uploadTitle: 'Salvesta fail',
uploadRetryTitle: 'Retry upload',
zoomTitle: 'Vaata detaile',
dragTitle: 'Liiguta / Korralda',
indicatorNewTitle: 'Pole veel salvestatud',
indicatorSuccessTitle: 'Uploaded',
indicatorErrorTitle: 'Salvestamise viga',
indicatorPausedTitle: 'Upload Paused',
indicatorLoadingTitle: 'Salvestan …'
},
previewZoomButtonTitles: {
prev: 'View previous file',
next: 'View next file',
toggleheader: 'Toggle header',
fullscreen: 'Toggle full screen',
borderless: 'Toggle borderless mode',
close: 'Close detailed preview'
}
};
})(window.jQuery);
|
/*globals casper, __utils__, url */
casper.test.begin("Settings screen is correct", 15, function suite(test) {
test.filename = "settings_test.png";
casper.start(url + "ghost/settings/", function testTitleAndUrl() {
test.assertTitle("", "Ghost admin has no title");
test.assertUrlMatch(/ghost\/settings\/general\/$/, "Ghost doesn't require login this time");
}).viewport(1280, 1024);
casper.then(function testViews() {
test.assertExists(".wrapper", "Settings main view is present");
test.assertExists(".settings-sidebar", "Settings sidebar view is present");
test.assertExists(".settings-menu", "Settings menu is present");
test.assertExists(".wrapper", "Settings main view is present");
test.assertExists(".settings-content", "Settings content view is present");
test.assertEval(function testGeneralIsActive() {
return document.querySelector('.settings-menu .general').classList.contains('active');
}, "general tab is marked active");
test.assertEval(function testContentIsGeneral() {
return document.querySelector('.settings-content').id === 'general';
}, "loaded content is general screen");
});
// test the user tab
casper.thenClick('.settings-menu .users');
casper.waitForSelector('#user', function then() {
test.assertEval(function testGeneralIsNotActive() {
return !document.querySelector('.settings-menu .general').classList.contains('active');
}, "general tab is not marked active");
test.assertEval(function testUserIsActive() {
return document.querySelector('.settings-menu .users').classList.contains('active');
}, "user tab is marked active");
test.assertEval(function testContentIsUser() {
return document.querySelector('.settings-content').id === 'user';
}, "loaded content is user screen");
}, function onTimeOut() {
test.fail('User screen failed to load');
});
function handleUserRequest(requestData, request) {
// make sure we only get requests from the user pane
if (requestData.url.indexOf('settings/') !== -1) {
casper.test.fail("Saving the user pane triggered another settings pane to save");
}
}
function handleSettingsRequest(requestData, request) {
// make sure we only get requests from the user pane
if (requestData.url.indexOf('users/') !== -1) {
casper.test.fail("Saving a settings pane triggered the user pane to save");
}
}
casper.then(function listenForRequests() {
casper.on('resource.requested', handleUserRequest);
});
casper.thenClick('#user .button-save');
casper.waitFor(function successNotification() {
return this.evaluate(function () {
return document.querySelectorAll('.js-bb-notification section').length > 0;
});
}, function doneWaiting() {
}, function waitTimeout() {
casper.test.fail("Saving the user pane did not result in a notification");
});
casper.then(function checkUserWasSaved() {
casper.removeListener('resource.requested', handleUserRequest);
});
casper.waitForSelector('.notification-success', function onSuccess() {
test.assert(true, 'Got success notification');
}, function onTimeout() {
test.assert(false, 'No success notification :(');
});
casper.thenClick('#main-menu .settings a').then(function testOpeningSettingsTwice() {
casper.on('resource.requested', handleSettingsRequest);
test.assertEval(function testUserIsActive() {
return document.querySelector('.settings-menu .general').classList.contains('active');
}, "general tab is marked active");
});
casper.thenClick('#general .button-save').waitFor(function successNotification() {
return this.evaluate(function () {
return document.querySelectorAll('.js-bb-notification section').length > 0;
});
}, function doneWaiting() {
}, function waitTimeout() {
casper.test.fail("Saving the general pane did not result in a notification");
});
casper.then(function checkSettingsWereSaved() {
casper.removeListener('resource.requested', handleSettingsRequest);
});
casper.waitForSelector('.notification-success', function onSuccess() {
test.assert(true, 'Got success notification');
}, function onTimeout() {
test.assert(false, 'No success notification :(');
});
casper.run(function () {
casper.removeListener('resource.requested', handleUserRequest);
casper.removeListener('resource.requested', handleSettingsRequest);
test.done();
});
});
casper.test.begin("User settings screen validates email", 6, function suite(test) {
var email, brokenEmail;
test.filename = "user_settings_test.png";
casper.start(url + "ghost/settings/user/", function testTitleAndUrl() {
test.assertTitle("", "Ghost admin has no title");
test.assertUrlMatch(/ghost\/settings\/user\/$/, "Ghost doesn't require login this time");
}).viewport(1280, 1024);
casper.then(function setEmailToInvalid() {
email = casper.getElementInfo('#user-email').attributes.value;
brokenEmail = email.replace('.', '-');
casper.fillSelectors('.user-profile', {
'#user-email': brokenEmail
}, false);
});
casper.thenClick('#user .button-save');
casper.waitForResource('/users/');
casper.waitForSelector('.notification-error', function onSuccess() {
test.assert(true, 'Got error notification');
test.assertSelectorDoesntHaveText('.notification-error', '[object Object]');
}, function onTimeout() {
test.assert(false, 'No error notification :(');
});
casper.then(function resetEmailToValid() {
casper.fillSelectors('.user-profile', {
'#user-email': email
}, false);
});
casper.thenClick('#user .button-save');
casper.waitForResource(/users/);
casper.waitForSelector('.notification-success', function onSuccess() {
test.assert(true, 'Got success notification');
test.assertSelectorDoesntHaveText('.notification-success', '[object Object]');
}, function onTimeout() {
test.assert(false, 'No success notification :(');
});
casper.run(function () {
test.done();
});
});
|
import { foo } from './module';
import impA from "./helperA";
import impB from "./helperB";
import impC from "./helperC";
var notExportedAsync = function () {
var ref = impA(impB.mark(function _callee2() {
return impC.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
foo();
case 1:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function notExportedAsync() {
return ref.apply(this, arguments);
};
}();
export var exportedAsync = function () {
var ref = impA(impB.mark(function _callee() {
return impC.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return foo();
case 2:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function exportedAsync() {
return ref.apply(this, arguments);
};
}();
import { count } from "./module";
it("should run async functions", function() {
var org = count;
notExportedAsync();
count.should.be.eql(org + 1);
exportedAsync();
count.should.be.eql(org + 2);
});
|
App.deferReadiness();
|
/**
* Framework7 2.0.0-beta.18
* Full featured mobile HTML framework for building iOS & Android apps
* http://framework7.io/
*
* Copyright 2014-2017 Vladimir Kharlampidi
*
* Released under the MIT License
*
* Released on: November 30, 2017
*/
import Template7 from 'template7';
import $ from 'dom7';
/**
* https://github.com/gre/bezier-easing
* BezierEasing - use bezier curve for transition easing function
* by Gaëtan Renaudeau 2014 - 2015 – MIT License
*/
/* eslint-disable */
// These values are established by empiricism with tests (tradeoff: performance VS precision)
var NEWTON_ITERATIONS = 4;
var NEWTON_MIN_SLOPE = 0.001;
var SUBDIVISION_PRECISION = 0.0000001;
var SUBDIVISION_MAX_ITERATIONS = 10;
var kSplineTableSize = 11;
var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
var float32ArraySupported = typeof Float32Array === 'function';
function A (aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
function B (aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
function C (aA1) { return 3.0 * aA1; }
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
function calcBezier (aT, aA1, aA2) { return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; }
// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
function getSlope (aT, aA1, aA2) { return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); }
function binarySubdivide (aX, aA, aB, mX1, mX2) {
var currentX, currentT, i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
}
function newtonRaphsonIterate (aX, aGuessT, mX1, mX2) {
for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) {
return aGuessT;
}
var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
function bezier (mX1, mY1, mX2, mY2) {
if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) {
throw new Error('bezier x values must be in [0, 1] range');
}
// Precompute samples table
var sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
if (mX1 !== mY1 || mX2 !== mY2) {
for (var i = 0; i < kSplineTableSize; ++i) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
function getTForX (aX) {
var intervalStart = 0.0;
var currentSample = 1;
var lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample;
// Interpolate to provide an initial guess for t
var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
var guessForT = intervalStart + dist * kSampleStepSize;
var initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
}
return function BezierEasing (x) {
if (mX1 === mY1 && mX2 === mY2) {
return x; // linear
}
// Because JavaScript number are imprecise, we should guarantee the extremes are right.
if (x === 0) {
return 0;
}
if (x === 1) {
return 1;
}
return calcBezier(getTForX(x), mY1, mY2);
};
}
// Remove Diacritics
const defaultDiacriticsRemovalap = [
{ base: 'A', letters: '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F' },
{ base: 'AA', letters: '\uA732' },
{ base: 'AE', letters: '\u00C6\u01FC\u01E2' },
{ base: 'AO', letters: '\uA734' },
{ base: 'AU', letters: '\uA736' },
{ base: 'AV', letters: '\uA738\uA73A' },
{ base: 'AY', letters: '\uA73C' },
{ base: 'B', letters: '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181' },
{ base: 'C', letters: '\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E' },
{ base: 'D', letters: '\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779' },
{ base: 'DZ', letters: '\u01F1\u01C4' },
{ base: 'Dz', letters: '\u01F2\u01C5' },
{ base: 'E', letters: '\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E' },
{ base: 'F', letters: '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B' },
{ base: 'G', letters: '\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E' },
{ base: 'H', letters: '\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D' },
{ base: 'I', letters: '\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197' },
{ base: 'J', letters: '\u004A\u24BF\uFF2A\u0134\u0248' },
{ base: 'K', letters: '\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2' },
{ base: 'L', letters: '\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780' },
{ base: 'LJ', letters: '\u01C7' },
{ base: 'Lj', letters: '\u01C8' },
{ base: 'M', letters: '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C' },
{ base: 'N', letters: '\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4' },
{ base: 'NJ', letters: '\u01CA' },
{ base: 'Nj', letters: '\u01CB' },
{ base: 'O', letters: '\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C' },
{ base: 'OI', letters: '\u01A2' },
{ base: 'OO', letters: '\uA74E' },
{ base: 'OU', letters: '\u0222' },
{ base: 'OE', letters: '\u008C\u0152' },
{ base: 'oe', letters: '\u009C\u0153' },
{ base: 'P', letters: '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754' },
{ base: 'Q', letters: '\u0051\u24C6\uFF31\uA756\uA758\u024A' },
{ base: 'R', letters: '\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782' },
{ base: 'S', letters: '\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784' },
{ base: 'T', letters: '\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786' },
{ base: 'TZ', letters: '\uA728' },
{ base: 'U', letters: '\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244' },
{ base: 'V', letters: '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245' },
{ base: 'VY', letters: '\uA760' },
{ base: 'W', letters: '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72' },
{ base: 'X', letters: '\u0058\u24CD\uFF38\u1E8A\u1E8C' },
{ base: 'Y', letters: '\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE' },
{ base: 'Z', letters: '\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762' },
{ base: 'a', letters: '\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250' },
{ base: 'aa', letters: '\uA733' },
{ base: 'ae', letters: '\u00E6\u01FD\u01E3' },
{ base: 'ao', letters: '\uA735' },
{ base: 'au', letters: '\uA737' },
{ base: 'av', letters: '\uA739\uA73B' },
{ base: 'ay', letters: '\uA73D' },
{ base: 'b', letters: '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253' },
{ base: 'c', letters: '\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184' },
{ base: 'd', letters: '\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A' },
{ base: 'dz', letters: '\u01F3\u01C6' },
{ base: 'e', letters: '\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD' },
{ base: 'f', letters: '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C' },
{ base: 'g', letters: '\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F' },
{ base: 'h', letters: '\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265' },
{ base: 'hv', letters: '\u0195' },
{ base: 'i', letters: '\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131' },
{ base: 'j', letters: '\u006A\u24D9\uFF4A\u0135\u01F0\u0249' },
{ base: 'k', letters: '\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3' },
{ base: 'l', letters: '\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747' },
{ base: 'lj', letters: '\u01C9' },
{ base: 'm', letters: '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F' },
{ base: 'n', letters: '\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5' },
{ base: 'nj', letters: '\u01CC' },
{ base: 'o', letters: '\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275' },
{ base: 'oi', letters: '\u01A3' },
{ base: 'ou', letters: '\u0223' },
{ base: 'oo', letters: '\uA74F' },
{ base: 'p', letters: '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755' },
{ base: 'q', letters: '\u0071\u24E0\uFF51\u024B\uA757\uA759' },
{ base: 'r', letters: '\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783' },
{ base: 's', letters: '\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B' },
{ base: 't', letters: '\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787' },
{ base: 'tz', letters: '\uA729' },
{ base: 'u', letters: '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289' },
{ base: 'v', letters: '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C' },
{ base: 'vy', letters: '\uA761' },
{ base: 'w', letters: '\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73' },
{ base: 'x', letters: '\u0078\u24E7\uFF58\u1E8B\u1E8D' },
{ base: 'y', letters: '\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF' },
{ base: 'z', letters: '\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763' },
];
const diacriticsMap = {};
for (let i = 0; i < defaultDiacriticsRemovalap.length; i += 1) {
const letters = defaultDiacriticsRemovalap[i].letters;
for (let j = 0; j < letters.length; j += 1) {
diacriticsMap[letters[j]] = defaultDiacriticsRemovalap[i].base;
}
}
const createPromise = function createPromise(handler) {
let resolved = false;
let rejected = false;
let resolveArgs;
let rejectArgs;
const promiseHandlers = {
then: undefined,
catch: undefined,
};
const promise = {
then(thenHandler) {
if (resolved) {
thenHandler(...resolveArgs);
} else {
promiseHandlers.then = thenHandler;
}
return promise;
},
catch(catchHandler) {
if (rejected) {
catchHandler(...rejectArgs);
} else {
promiseHandlers.catch = catchHandler;
}
return promise;
},
};
function resolve(...args) {
resolved = true;
if (promiseHandlers.then) promiseHandlers.then(...args);
else resolveArgs = args;
}
function reject(...args) {
rejected = true;
if (promiseHandlers.catch) promiseHandlers.catch(...args);
else rejectArgs = args;
}
handler(resolve, reject);
return promise;
};
const Utils = {
mdPreloaderContent: `
<span class="preloader-inner">
<span class="preloader-inner-gap"></span>
<span class="preloader-inner-left">
<span class="preloader-inner-half-circle"></span>
</span>
<span class="preloader-inner-right">
<span class="preloader-inner-half-circle"></span>
</span>
</span>
`.trim(),
eventNameToColonCase(eventName) {
let hasColon;
return eventName.split('').map((char, index) => {
if (char.match(/[A-Z]/) && index !== 0 && !hasColon) {
hasColon = true;
return `:${char.toLowerCase()}`;
}
return char.toLowerCase();
}).join('');
},
deleteProps(obj) {
const object = obj;
Object.keys(object).forEach((key) => {
try {
object[key] = null;
} catch (e) {
// no getter for object
}
try {
delete object[key];
} catch (e) {
// something got wrong
}
});
},
bezier(...args) {
return bezier(...args);
},
nextTick(callback, delay = 0) {
return setTimeout(callback, delay);
},
nextFrame(callback) {
return Utils.requestAnimationFrame(callback);
},
now() {
return Date.now();
},
promise(handler) {
return window.Promise ? new Promise(handler) : createPromise(handler);
},
requestAnimationFrame(callback) {
if (window.requestAnimationFrame) return window.requestAnimationFrame(callback);
else if (window.webkitRequestAnimationFrame) return window.webkitRequestAnimationFrame(callback);
return window.setTimeout(callback, 1000 / 60);
},
cancelAnimationFrame(id) {
if (window.cancelAnimationFrame) return window.cancelAnimationFrame(id);
else if (window.webkitCancelAnimationFrame) return window.webkitCancelAnimationFrame(id);
return window.clearTimeout(id);
},
removeDiacritics(str) {
return str.replace(/[^\u0000-\u007E]/g, a => diacriticsMap[a] || a);
},
parseUrlQuery(url) {
const query = {};
let urlToParse = url || window.location.href;
let i;
let params;
let param;
let length;
if (typeof urlToParse === 'string' && urlToParse.length) {
urlToParse = urlToParse.indexOf('?') > -1 ? urlToParse.replace(/\S*\?/, '') : '';
params = urlToParse.split('&').filter(paramsPart => paramsPart !== '');
length = params.length;
for (i = 0; i < length; i += 1) {
param = params[i].replace(/#\S+/g, '').split('=');
query[decodeURIComponent(param[0])] = typeof param[1] === 'undefined' ? undefined : decodeURIComponent(param[1]) || '';
}
}
return query;
},
getTranslate(el, axis = 'x') {
let matrix;
let curTransform;
let transformMatrix;
const curStyle = window.getComputedStyle(el, null);
if (window.WebKitCSSMatrix) {
curTransform = curStyle.transform || curStyle.webkitTransform;
if (curTransform.split(',').length > 6) {
curTransform = curTransform.split(', ').map(a => a.replace(',', '.')).join(', ');
}
// Some old versions of Webkit choke when 'none' is passed; pass
// empty string instead in this case
transformMatrix = new window.WebKitCSSMatrix(curTransform === 'none' ? '' : curTransform);
} else {
transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue('transform').replace('translate(', 'matrix(1, 0, 0, 1,');
matrix = transformMatrix.toString().split(',');
}
if (axis === 'x') {
// Latest Chrome and webkits Fix
if (window.WebKitCSSMatrix) curTransform = transformMatrix.m41;
// Crazy IE10 Matrix
else if (matrix.length === 16) curTransform = parseFloat(matrix[12]);
// Normal Browsers
else curTransform = parseFloat(matrix[4]);
}
if (axis === 'y') {
// Latest Chrome and webkits Fix
if (window.WebKitCSSMatrix) curTransform = transformMatrix.m42;
// Crazy IE10 Matrix
else if (matrix.length === 16) curTransform = parseFloat(matrix[13]);
// Normal Browsers
else curTransform = parseFloat(matrix[5]);
}
return curTransform || 0;
},
serializeObject(obj, parents = []) {
if (typeof obj === 'string') return obj;
const resultArray = [];
const separator = '&';
let newParents;
function varName(name) {
if (parents.length > 0) {
let parentParts = '';
for (let j = 0; j < parents.length; j += 1) {
if (j === 0) parentParts += parents[j];
else parentParts += `[${encodeURIComponent(parents[j])}]`;
}
return `${parentParts}[${encodeURIComponent(name)}]`;
}
return encodeURIComponent(name);
}
function varValue(value) {
return encodeURIComponent(value);
}
Object.keys(obj).forEach((prop) => {
let toPush;
if (Array.isArray(obj[prop])) {
toPush = [];
for (let i = 0; i < obj[prop].length; i += 1) {
if (!Array.isArray(obj[prop][i]) && typeof obj[prop][i] === 'object') {
newParents = parents.slice();
newParents.push(prop);
newParents.push(String(i));
toPush.push(Utils.serializeObject(obj[prop][i], newParents));
} else {
toPush.push(`${varName(prop)}[]=${varValue(obj[prop][i])}`);
}
}
if (toPush.length > 0) resultArray.push(toPush.join(separator));
} else if (obj[prop] === null || obj[prop] === '') {
resultArray.push(`${varName(prop)}=`);
} else if (typeof obj[prop] === 'object') {
// Object, convert to named array
newParents = parents.slice();
newParents.push(prop);
toPush = Utils.serializeObject(obj[prop], newParents);
if (toPush !== '') resultArray.push(toPush);
} else if (typeof obj[prop] !== 'undefined' && obj[prop] !== '') {
// Should be string or plain value
resultArray.push(`${varName(prop)}=${varValue(obj[prop])}`);
} else if (obj[prop] === '') resultArray.push(varName(prop));
});
return resultArray.join(separator);
},
isObject(o) {
return typeof o === 'object' && o !== null && o.constructor && o.constructor === Object;
},
extend(...args) {
let deep = true;
let to;
let from;
if (typeof args[0] === 'boolean') {
deep = args[0];
to = args[1];
args.splice(0, 2);
from = args;
} else {
to = args[0];
args.splice(0, 1);
from = args;
}
for (let i = 0; i < from.length; i += 1) {
const nextSource = args[i];
if (nextSource !== undefined && nextSource !== null) {
const keysArray = Object.keys(Object(nextSource));
for (let nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex += 1) {
const nextKey = keysArray[nextIndex];
const desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
if (!deep) {
to[nextKey] = nextSource[nextKey];
} else if (Utils.isObject(to[nextKey]) && Utils.isObject(nextSource[nextKey])) {
Utils.extend(to[nextKey], nextSource[nextKey]);
} else if (!Utils.isObject(to[nextKey]) && Utils.isObject(nextSource[nextKey])) {
to[nextKey] = {};
Utils.extend(to[nextKey], nextSource[nextKey]);
} else {
to[nextKey] = nextSource[nextKey];
}
}
}
}
}
return to;
},
};
const Device = (function Device() {
const ua = window.navigator.userAgent;
const device = {
ios: false,
android: false,
androidChrome: false,
desktop: false,
windows: false,
iphone: false,
iphoneX: false,
ipod: false,
ipad: false,
cordova: window.cordova || window.phonegap,
phonegap: window.cordova || window.phonegap,
};
const windows = ua.match(/(Windows Phone);?[\s\/]+([\d.]+)?/); // eslint-disable-line
const android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); // eslint-disable-line
const ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
const ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
const iphone = !ipad && ua.match(/(iPhone\sOS|iOS)\s([\d_]+)/);
const iphoneX = iphone && window.screen.width === 375 && window.screen.height === 812;
// Windows
if (windows) {
device.os = 'windows';
device.osVersion = windows[2];
device.windows = true;
}
// Android
if (android && !windows) {
device.os = 'android';
device.osVersion = android[2];
device.android = true;
device.androidChrome = ua.toLowerCase().indexOf('chrome') >= 0;
}
if (ipad || iphone || ipod) {
device.os = 'ios';
device.ios = true;
}
// iOS
if (iphone && !ipod) {
device.osVersion = iphone[2].replace(/_/g, '.');
device.iphone = true;
device.iphoneX = iphoneX;
}
if (ipad) {
device.osVersion = ipad[2].replace(/_/g, '.');
device.ipad = true;
}
if (ipod) {
device.osVersion = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
device.iphone = true;
}
// iOS 8+ changed UA
if (device.ios && device.osVersion && ua.indexOf('Version/') >= 0) {
if (device.osVersion.split('.')[0] === '10') {
device.osVersion = ua.toLowerCase().split('version/')[1].split(' ')[0];
}
}
// Webview
device.webView = (iphone || ipad || ipod) && (ua.match(/.*AppleWebKit(?!.*Safari)/i) || window.navigator.standalone);
// Desktop
device.desktop = !(device.os || device.android || device.webView);
// Minimal UI
if (device.os && device.os === 'ios') {
const osVersionArr = device.osVersion.split('.');
const metaViewport = document.querySelector('meta[name="viewport"]');
device.minimalUi =
!device.webView &&
(ipod || iphone) &&
(osVersionArr[0] * 1 === 7 ? osVersionArr[1] * 1 >= 1 : osVersionArr[0] * 1 > 7) &&
metaViewport && metaViewport.getAttribute('content').indexOf('minimal-ui') >= 0;
}
// Check for status bar and fullscreen app mode
device.needsStatusbarOverlay = function needsStatusbarOverlay() {
if (device.webView && (window.innerWidth * window.innerHeight === window.screen.width * window.screen.height)) {
if (device.iphoneX && (window.orientation === 90 || window.orientation === -90)) {
return false;
}
return true;
}
return false;
};
device.statusbar = device.needsStatusbarOverlay();
// Pixel Ratio
device.pixelRatio = window.devicePixelRatio || 1;
// Export object
return device;
}());
class Framework7Class {
constructor(params = {}, parents = []) {
const self = this;
self.params = params;
// Events
self.eventsParents = parents;
self.eventsListeners = {};
if (self.params && self.params.on) {
Object.keys(self.params.on).forEach((eventName) => {
self.on(eventName, self.params.on[eventName]);
});
}
}
on(events, handler) {
const self = this;
if (typeof handler !== 'function') return self;
events.split(' ').forEach((event) => {
if (!self.eventsListeners[event]) self.eventsListeners[event] = [];
self.eventsListeners[event].push(handler);
});
return self;
}
once(events, handler) {
const self = this;
if (typeof handler !== 'function') return self;
function onceHandler(...args) {
handler.apply(self, args);
self.off(events, onceHandler);
}
return self.on(events, onceHandler);
}
off(events, handler) {
const self = this;
if (!self.eventsListeners) return self;
events.split(' ').forEach((event) => {
if (typeof handler === 'undefined') {
self.eventsListeners[event] = [];
} else {
self.eventsListeners[event].forEach((eventHandler, index) => {
if (eventHandler === handler) {
self.eventsListeners[event].splice(index, 1);
}
});
}
});
return self;
}
emit(...args) {
const self = this;
if (!self.eventsListeners) return self;
let events;
let data;
let context;
let eventsParents;
if (typeof args[0] === 'string' || Array.isArray(args[0])) {
events = args[0];
data = args.slice(1, args.length);
context = self;
eventsParents = self.eventsParents;
} else {
events = args[0].events;
data = args[0].data;
context = args[0].context || self;
eventsParents = args[0].local ? [] : args[0].parents || self.eventsParents;
}
const eventsArray = Array.isArray(events) ? events : events.split(' ');
const localEvents = eventsArray.map(eventName => eventName.replace('local::', ''));
const parentEvents = eventsArray.filter(eventName => eventName.indexOf('local::') < 0);
localEvents.forEach((event) => {
if (self.eventsListeners[event]) {
const handlers = [];
self.eventsListeners[event].forEach((eventHandler) => {
handlers.push(eventHandler);
});
handlers.forEach((eventHandler) => {
eventHandler.apply(context, data);
});
}
});
if (eventsParents && eventsParents.length > 0) {
eventsParents.forEach((eventsParent) => {
eventsParent.emit(parentEvents, ...data);
});
}
return self;
}
useModulesParams(instanceParams) {
const instance = this;
if (!instance.modules) return;
Object.keys(instance.modules).forEach((moduleName) => {
const module = instance.modules[moduleName];
// Extend params
if (module.params) {
Utils.extend(instanceParams, module.params);
}
});
}
useModules(modulesParams = {}) {
const instance = this;
if (!instance.modules) return;
Object.keys(instance.modules).forEach((moduleName) => {
const module = instance.modules[moduleName];
const moduleParams = modulesParams[moduleName] || {};
// Extend instance methods and props
if (module.instance) {
Object.keys(module.instance).forEach((modulePropName) => {
const moduleProp = module.instance[modulePropName];
if (typeof moduleProp === 'function') {
instance[modulePropName] = moduleProp.bind(instance);
} else {
instance[modulePropName] = moduleProp;
}
});
}
// Add event listeners
if (module.on && instance.on) {
Object.keys(module.on).forEach((moduleEventName) => {
instance.on(moduleEventName, module.on[moduleEventName]);
});
}
// Module create callback
if (module.create) {
module.create.bind(instance)(moduleParams);
}
});
}
static set components(components) {
const Class = this;
if (!Class.use) return;
Class.use(components);
}
static installModule(module, ...params) {
const Class = this;
if (!Class.prototype.modules) Class.prototype.modules = {};
const name = module.name || (`${Object.keys(Class.prototype.modules).length}_${Utils.now()}`);
Class.prototype.modules[name] = module;
// Prototype
if (module.proto) {
Object.keys(module.proto).forEach((key) => {
Class.prototype[key] = module.proto[key];
});
}
// Class
if (module.static) {
Object.keys(module.static).forEach((key) => {
Class[key] = module.static[key];
});
}
// Callback
if (module.install) {
module.install.apply(Class, params);
}
return Class;
}
static use(module, ...params) {
const Class = this;
if (Array.isArray(module)) {
module.forEach(m => Class.installModule(m));
return Class;
}
return Class.installModule(module, ...params);
}
}
class Framework7$1 extends Framework7Class {
constructor(params) {
super(params);
const passedParams = Utils.extend({}, params);
// App Instance
const app = this;
// Default
const defaults = {
version: '1.0.0',
id: 'io.framework7.test',
root: 'body',
theme: 'auto',
language: window.navigator.language,
routes: [],
name: 'Framework7',
initOnDeviceReady: true,
init: true,
};
// Extend defaults with modules params
app.useModulesParams(defaults);
// Extend defaults with passed params
app.params = Utils.extend(defaults, params);
const $rootEl = $(app.params.root);
Utils.extend(app, {
// App Id
id: app.params.id,
// App Name
name: app.params.name,
// App version
version: app.params.version,
// Routes
routes: app.params.routes,
// Lang
language: app.params.language,
// Root
root: $rootEl,
// Local Storage
ls: window.localStorage,
// RTL
rtl: $rootEl.css('direction') === 'rtl',
// Theme
theme: (function getTheme() {
if (app.params.theme === 'auto') {
return Device.ios ? 'ios' : 'md';
}
return app.params.theme;
}()),
// Initially passed parameters
passedParams,
});
// Save Root
app.root[0].f7 = app;
// Install Modules
app.useModules();
// Init
if (app.params.init) {
if (Device.cordova && app.params.initOnDeviceReady) {
$(document).on('deviceready', () => {
app.init();
});
} else {
app.init();
}
}
// Return app instance
return app;
}
init() {
const app = this;
if (app.initialized) return;
app.root.addClass('framework7-initializing');
// RTL attr
if (app.rtl) {
$('html').attr('dir', 'rtl');
}
// Root class
app.root.addClass('framework7-root');
// Theme class
$('html').removeClass('ios md').addClass(app.theme);
// Data
app.data = {};
if (app.params.data && typeof app.params.data === 'function') {
Utils.extend(app.data, app.params.data.bind(app)());
} else if (app.params.data) {
Utils.extend(app.data, app.params.data);
}
// Methods
app.methods = {};
if (app.params.methods) {
Utils.extend(app.methods, app.params.methods);
}
// Init class
Utils.nextFrame(() => {
app.root.removeClass('framework7-initializing');
});
// Emit, init other modules
app.initialized = true;
app.emit('init');
}
// eslint-disable-next-line
get $() {
return $;
}
// eslint-disable-next-line
get t7() {
return Template7;
}
static get Dom7() {
return $;
}
static get $() {
return $;
}
static get Template7() {
return Template7;
}
static get Class() {
return Framework7Class;
}
}
var Device$2 = {
name: 'device',
proto: {
device: Device,
},
static: {
device: Device,
},
on: {
init() {
const classNames = [];
const html = document.querySelector('html');
// Pixel Ratio
classNames.push(`device-pixel-ratio-${Math.floor(Device.pixelRatio)}`);
if (Device.pixelRatio >= 2) {
classNames.push('device-retina');
}
// OS classes
if (Device.os) {
classNames.push(
`device-${Device.os}`,
`device-${Device.os}-${Device.osVersion.split('.')[0]}`,
`device-${Device.os}-${Device.osVersion.replace(/\./g, '-')}`
);
if (Device.os === 'ios') {
const major = parseInt(Device.osVersion.split('.')[0], 10);
for (let i = major - 1; i >= 6; i -= 1) {
classNames.push(`device-ios-gt-${i}`);
}
if (Device.iphoneX) {
classNames.push('device-iphone-x');
}
}
} else if (Device.desktop) {
classNames.push('device-desktop');
}
// Status bar classes
if (Device.statusbar) {
classNames.push('with-statusbar');
} else {
html.classList.remove('with-statusbar');
}
// Add html classes
classNames.forEach((className) => {
html.classList.add(className);
});
},
},
};
const Support$1 = (function Support() {
const positionSticky = (function supportPositionSticky() {
let support = false;
const div = document.createElement('div');
('sticky -webkit-sticky -moz-sticky').split(' ').forEach((prop) => {
if (support) return;
div.style.position = prop;
if (div.style.position === prop) {
support = true;
}
});
return support;
}());
return {
positionSticky,
touch: (function checkTouch() {
return !!(('ontouchstart' in window) || (window.DocumentTouch && document instanceof window.DocumentTouch));
}()),
transforms3d: (function checkTransforms3d() {
const div = document.createElement('div').style;
return ('webkitPerspective' in div || 'MozPerspective' in div || 'OPerspective' in div || 'MsPerspective' in div || 'perspective' in div);
}()),
flexbox: (function checkFlexbox() {
const div = document.createElement('div').style;
const styles = ('alignItems webkitAlignItems webkitBoxAlign msFlexAlign mozBoxAlign webkitFlexDirection msFlexDirection mozBoxDirection mozBoxOrient webkitBoxDirection webkitBoxOrient').split(' ');
for (let i = 0; i < styles.length; i += 1) {
if (styles[i] in div) return true;
}
return false;
}()),
observer: (function checkObserver() {
return ('MutationObserver' in window || 'WebkitMutationObserver' in window);
}()),
passiveListener: (function checkPassiveListener() {
let supportsPassive = false;
try {
const opts = Object.defineProperty({}, 'passive', {
// eslint-disable-next-line
get() {
supportsPassive = true;
},
});
window.addEventListener('testPassiveListener', null, opts);
} catch (e) {
// No support
}
return supportsPassive;
}()),
gestures: (function checkGestures() {
return 'ongesturestart' in window;
}()),
};
}());
var Support = {
name: 'support',
proto: {
support: Support$1,
},
static: {
support: Support$1,
},
on: {
init() {
const html = document.querySelector('html');
const classNames = [];
if (Support$1.positionSticky) {
classNames.push('support-position-sticky');
}
// Add html classes
classNames.forEach((className) => {
html.classList.add(className);
});
},
},
};
var Utils$2 = {
name: 'utils',
proto: {
utils: Utils,
},
static: {
utils: Utils,
},
};
var Resize = {
name: 'resize',
instance: {
getSize() {
const app = this;
const offset = app.root.offset();
const [width, height, left, top] = [app.root[0].offsetWidth, app.root[0].offsetHeight, offset.left, offset.top];
app.width = width;
app.height = height;
app.left = left;
app.top = top;
return { width, height, left, top };
},
},
on: {
init() {
const app = this;
// Get Size
app.getSize();
// Emit resize
window.addEventListener('resize', () => {
app.emit('resize');
}, false);
// Emit orientationchange
window.addEventListener('orientationchange', () => {
app.emit('orientationchange');
});
},
orientationchange() {
const app = this;
if (app.device && app.device.minimalUi) {
if (window.orientation === 90 || window.orientation === -90) {
document.body.scrollTop = 0;
}
}
// Fix iPad weird body scroll
if (app.device.ipad) {
document.body.scrollLeft = 0;
setTimeout(() => {
document.body.scrollLeft = 0;
}, 0);
}
},
resize() {
const app = this;
app.getSize();
},
},
};
const globals = {};
let jsonpRequests = 0;
function Request$1(requestOptions) {
const globalsNoCallbacks = Utils.extend({}, globals);
('beforeCreate beforeOpen beforeSend error complete success statusCode').split(' ').forEach((callbackName) => {
delete globalsNoCallbacks[callbackName];
});
const defaults = Utils.extend({
url: window.location.toString(),
method: 'GET',
data: false,
async: true,
cache: true,
user: '',
password: '',
headers: {},
xhrFields: {},
statusCode: {},
processData: true,
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
timeout: 0,
}, globalsNoCallbacks);
const options = Utils.extend({}, defaults, requestOptions);
// Function to run XHR callbacks and events
function fireCallback(callbackName, ...data) {
/*
Callbacks:
beforeCreate (xhr, options),
beforeOpen (xhr, options),
beforeSend (xhr, options),
error (xhr, status),
complete (xhr, stautus),
success (response, status, xhr),
statusCode ()
*/
if (globals[callbackName]) globals[callbackName](...data);
if (options[callbackName]) options[callbackName](...data);
}
// Before create callback
fireCallback('beforeCreate', options);
// For jQuery guys
if (options.type) options.method = options.type;
// Parameters Prefix
let paramsPrefix = options.url.indexOf('?') >= 0 ? '&' : '?';
// UC method
const method = options.method.toUpperCase();
// Data to modify GET URL
if ((method === 'GET' || method === 'HEAD' || method === 'OPTIONS' || method === 'DELETE') && options.data) {
let stringData;
if (typeof options.data === 'string') {
// Should be key=value string
if (options.data.indexOf('?') >= 0) stringData = options.data.split('?')[1];
else stringData = options.data;
} else {
// Should be key=value object
stringData = Utils.serializeObject(options.data);
}
if (stringData.length) {
options.url += paramsPrefix + stringData;
if (paramsPrefix === '?') paramsPrefix = '&';
}
}
// JSONP
if (options.dataType === 'json' && options.url.indexOf('callback=') >= 0) {
const callbackName = `f7jsonp_${Date.now() + ((jsonpRequests += 1))}`;
let abortTimeout;
const callbackSplit = options.url.split('callback=');
let requestUrl = `${callbackSplit[0]}callback=${callbackName}`;
if (callbackSplit[1].indexOf('&') >= 0) {
const addVars = callbackSplit[1].split('&').filter(el => el.indexOf('=') > 0).join('&');
if (addVars.length > 0) requestUrl += `&${addVars}`;
}
// Create script
let script = document.createElement('script');
script.type = 'text/javascript';
script.onerror = function onerror() {
clearTimeout(abortTimeout);
fireCallback('error', null, 'scripterror');
fireCallback('complete', null, 'scripterror');
};
script.src = requestUrl;
// Handler
window[callbackName] = function jsonpCallback(data) {
clearTimeout(abortTimeout);
fireCallback('success', data);
script.parentNode.removeChild(script);
script = null;
delete window[callbackName];
};
document.querySelector('head').appendChild(script);
if (options.timeout > 0) {
abortTimeout = setTimeout(() => {
script.parentNode.removeChild(script);
script = null;
fireCallback('error', null, 'timeout');
}, options.timeout);
}
return undefined;
}
// Cache for GET/HEAD requests
if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS' || method === 'DELETE') {
if (options.cache === false) {
options.url += `${paramsPrefix}_nocache${Date.now()}`;
}
}
// Create XHR
const xhr = new XMLHttpRequest();
// Save Request URL
xhr.requestUrl = options.url;
xhr.requestParameters = options;
// Before open callback
fireCallback('beforeOpen', xhr, options);
// Open XHR
xhr.open(method, options.url, options.async, options.user, options.password);
// Create POST Data
let postData = null;
if ((method === 'POST' || method === 'PUT' || method === 'PATCH') && options.data) {
if (options.processData) {
const postDataInstances = [ArrayBuffer, Blob, Document, FormData];
// Post Data
if (postDataInstances.indexOf(options.data.constructor) >= 0) {
postData = options.data;
} else {
// POST Headers
const boundary = `---------------------------${Date.now().toString(16)}`;
if (options.contentType === 'multipart/form-data') {
xhr.setRequestHeader('Content-Type', `multipart/form-data; boundary=${boundary}`);
} else {
xhr.setRequestHeader('Content-Type', options.contentType);
}
postData = '';
let data = Utils.serializeObject(options.data);
if (options.contentType === 'multipart/form-data') {
data = data.split('&');
const newData = [];
for (let i = 0; i < data.length; i += 1) {
newData.push(`Content-Disposition: form-data; name="${data[i].split('=')[0]}"\r\n\r\n${data[i].split('=')[1]}\r\n`);
}
postData = `--${boundary}\r\n${newData.join(`--${boundary}\r\n`)}--${boundary}--\r\n`;
} else {
postData = data;
}
}
} else {
postData = options.data;
}
}
// Additional headers
if (options.headers) {
Object.keys(options.headers).forEach((headerName) => {
xhr.setRequestHeader(headerName, options[headerName]);
});
}
// Check for crossDomain
if (typeof options.crossDomain === 'undefined') {
// eslint-disable-next-line
options.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(options.url) && RegExp.$2 !== window.location.host;
}
if (!options.crossDomain) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
if (options.xhrFields) {
Utils.extend(xhr, options.xhrFields);
}
let xhrTimeout;
// Handle XHR
xhr.onload = function onload() {
if (xhrTimeout) clearTimeout(xhrTimeout);
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) {
let responseData;
if (options.dataType === 'json') {
try {
responseData = JSON.parse(xhr.responseText);
fireCallback('success', responseData, xhr.status, xhr);
} catch (err) {
fireCallback('error', xhr, 'parseerror');
}
} else {
responseData = xhr.responseType === 'text' || xhr.responseType === '' ? xhr.responseText : xhr.response;
fireCallback('success', responseData, xhr.status, xhr);
}
} else {
fireCallback('error', xhr, xhr.status);
}
if (options.statusCode) {
if (globals.statusCode && globals.statusCode[xhr.status]) globals.statusCode[xhr.status](xhr);
if (options.statusCode[xhr.status]) options.statusCode[xhr.status](xhr);
}
fireCallback('complete', xhr, xhr.status);
};
xhr.onerror = function onerror() {
if (xhrTimeout) clearTimeout(xhrTimeout);
fireCallback('error', xhr, xhr.status);
fireCallback('complete', xhr, 'error');
};
// Timeout
if (options.timeout > 0) {
xhr.onabort = function onabort() {
if (xhrTimeout) clearTimeout(xhrTimeout);
};
xhrTimeout = setTimeout(() => {
xhr.abort();
fireCallback('error', xhr, 'timeout');
fireCallback('complete', xhr, 'timeout');
}, options.timeout);
}
// Ajax start callback
fireCallback('beforeSend', xhr, options);
// Send XHR
xhr.send(postData);
// Return XHR object
return xhr;
}
function RequestShortcut(method, ...args) {
let [url, data, success, error, dataType] = [];
if (typeof args[1] === 'function') {
[url, success, error, dataType] = args;
} else {
[url, data, success, error, dataType] = args;
}
[success, error].forEach((callback) => {
if (typeof callback === 'string') {
dataType = callback;
if (callback === success) success = undefined;
else error = undefined;
}
});
dataType = dataType || (method === 'json' ? 'json' : undefined);
return Request$1({
url,
method: method === 'post' ? 'POST' : 'GET',
data,
success,
error,
dataType,
});
}
Request$1.get = function get(...args) {
return RequestShortcut('get', ...args);
};
Request$1.post = function post(...args) {
return RequestShortcut('post', ...args);
};
Request$1.json = function json(...args) {
return RequestShortcut('json', ...args);
};
Request$1.setup = function setup(options) {
if (options.type && !options.method) {
Utils.extend(options, { method: options.type });
}
Utils.extend(globals, options);
};
/* eslint no-param-reassign: "off" */
var Request = {
name: 'request',
create() {
const app = this;
app.request = Request$1;
},
static: {
request: Request$1,
},
};
function initTouch() {
const app = this;
const params = app.params.touch;
const useRipple = app.theme === 'md' && params.materialRipple;
if (Device.ios && Device.webView) {
// Strange hack required for iOS 8 webview to work on inputs
window.addEventListener('touchstart', () => {});
}
let touchStartX;
let touchStartY;
let touchStartTime;
let targetElement;
let trackClick;
let activeSelection;
let scrollParent;
let lastClickTime;
let isMoved;
let tapHoldFired;
let tapHoldTimeout;
let activableElement;
let activeTimeout;
let needsFastClick;
let needsFastClickTimeOut;
let rippleWave;
let rippleTarget;
let rippleTimeout;
function findActivableElement(el) {
const target = $(el);
const parents = target.parents(params.activeStateElements);
let activable;
if (target.is(params.activeStateElements)) {
activable = target;
}
if (parents.length > 0) {
activable = activable ? activable.add(parents) : parents;
}
return activable || target;
}
function isInsideScrollableView(el) {
const pageContent = el.parents('.page-content, .panel');
if (pageContent.length === 0) {
return false;
}
// This event handler covers the "tap to stop scrolling".
if (pageContent.prop('scrollHandlerSet') !== 'yes') {
pageContent.on('scroll', () => {
clearTimeout(activeTimeout);
clearTimeout(rippleTimeout);
});
pageContent.prop('scrollHandlerSet', 'yes');
}
return true;
}
function addActive() {
if (!activableElement) return;
activableElement.addClass('active-state');
}
function removeActive() {
if (!activableElement) return;
activableElement.removeClass('active-state');
activableElement = null;
}
function isFormElement(el) {
const nodes = ('input select textarea label').split(' ');
if (el.nodeName && nodes.indexOf(el.nodeName.toLowerCase()) >= 0) return true;
return false;
}
function androidNeedsBlur(el) {
const noBlur = ('button input textarea select').split(' ');
if (document.activeElement && el !== document.activeElement && document.activeElement !== document.body) {
if (noBlur.indexOf(el.nodeName.toLowerCase()) >= 0) {
return false;
}
return true;
}
return false;
}
function targetNeedsFastClick(el) {
/*
if (
Device.ios
&&
(
Device.osVersion.split('.')[0] > 9
||
(Device.osVersion.split('.')[0] * 1 === 9 && Device.osVersion.split('.')[1] >= 1)
)
) {
return false;
}
*/
const $el = $(el);
if (el.nodeName.toLowerCase() === 'input' && (el.type === 'file' || el.type === 'range')) return false;
if (el.nodeName.toLowerCase() === 'select' && Device.android) return false;
if ($el.hasClass('no-fastclick') || $el.parents('.no-fastclick').length > 0) return false;
if (params.fastClicksExclude && $el.is(params.fastClicksExclude)) return false;
return true;
}
function targetNeedsFocus(el) {
if (document.activeElement === el) {
return false;
}
const tag = el.nodeName.toLowerCase();
const skipInputs = ('button checkbox file image radio submit').split(' ');
if (el.disabled || el.readOnly) return false;
if (tag === 'textarea') return true;
if (tag === 'select') {
if (Device.android) return false;
return true;
}
if (tag === 'input' && skipInputs.indexOf(el.type) < 0) return true;
return false;
}
function targetNeedsPrevent(el) {
const $el = $(el);
let prevent = true;
if ($el.is('label') || $el.parents('label').length > 0) {
if (Device.android) {
prevent = false;
} else if (Device.ios && $el.is('input')) {
prevent = true;
} else prevent = false;
}
return prevent;
}
// Ripple handlers
function findRippleElement(el) {
const rippleElements = params.materialRippleElements;
const $el = $(el);
if ($el.is(rippleElements)) {
if ($el.hasClass('no-ripple')) {
return false;
}
return $el;
} else if ($el.parents(rippleElements).length > 0) {
const rippleParent = $el.parents(rippleElements).eq(0);
if (rippleParent.hasClass('no-ripple')) {
return false;
}
return rippleParent;
}
return false;
}
function createRipple($el, x, y) {
if (!$el) return;
rippleWave = app.touchRipple.create($el, x, y);
}
function removeRipple() {
if (!rippleWave) return;
rippleWave.remove();
rippleWave = undefined;
rippleTarget = undefined;
}
function rippleTouchStart(el) {
rippleTarget = findRippleElement(el);
if (!rippleTarget || rippleTarget.length === 0) {
rippleTarget = undefined;
return;
}
if (!isInsideScrollableView(rippleTarget)) {
createRipple(rippleTarget, touchStartX, touchStartY);
} else {
rippleTimeout = setTimeout(() => {
createRipple(rippleTarget, touchStartX, touchStartY);
}, 80);
}
}
function rippleTouchMove() {
clearTimeout(rippleTimeout);
removeRipple();
}
function rippleTouchEnd() {
if (rippleWave) {
removeRipple();
} else if (rippleTarget && !isMoved) {
clearTimeout(rippleTimeout);
createRipple(rippleTarget, touchStartX, touchStartY);
setTimeout(removeRipple, 0);
} else {
removeRipple();
}
}
// Mouse Handlers
function handleMouseDown(e) {
findActivableElement(e.target).addClass('active-state');
if ('which' in e && e.which === 3) {
setTimeout(() => {
$('.active-state').removeClass('active-state');
}, 0);
}
if (useRipple) {
touchStartX = e.pageX;
touchStartY = e.pageY;
rippleTouchStart(e.target, e.pageX, e.pageY);
}
}
function handleMouseMove() {
$('.active-state').removeClass('active-state');
if (useRipple) {
rippleTouchMove();
}
}
function handleMouseUp() {
$('.active-state').removeClass('active-state');
if (useRipple) {
rippleTouchEnd();
}
}
// Send Click
function sendClick(e) {
const touch = e.changedTouches[0];
const evt = document.createEvent('MouseEvents');
let eventType = 'click';
if (Device.android && targetElement.nodeName.toLowerCase() === 'select') {
eventType = 'mousedown';
}
evt.initMouseEvent(eventType, true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
evt.forwardedTouchEvent = true;
if (app.device.ios && window.navigator.standalone) {
// Fix the issue happens in iOS home screen apps where the wrong element is selected during a momentum scroll.
// Upon tapping, we give the scrolling time to stop, then we grab the element based where the user tapped.
setTimeout(() => {
targetElement = document.elementFromPoint(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
targetElement.dispatchEvent(evt);
}, 10);
} else {
targetElement.dispatchEvent(evt);
}
}
// Touch Handlers
function handleTouchStart(e) {
isMoved = false;
tapHoldFired = false;
if (e.targetTouches.length > 1) {
if (activableElement) removeActive();
return true;
}
if (e.touches.length > 1 && activableElement) {
removeActive();
}
if (params.tapHold) {
if (tapHoldTimeout) clearTimeout(tapHoldTimeout);
tapHoldTimeout = setTimeout(() => {
if (e && e.touches && e.touches.length > 1) return;
tapHoldFired = true;
e.preventDefault();
$(e.target).trigger('taphold');
}, params.tapHoldDelay);
}
if (needsFastClickTimeOut) clearTimeout(needsFastClickTimeOut);
needsFastClick = targetNeedsFastClick(e.target);
if (!needsFastClick) {
trackClick = false;
return true;
}
if (Device.ios || (Device.android && 'getSelection' in window)) {
const selection = window.getSelection();
if (
selection.rangeCount &&
selection.focusNode !== document.body &&
(!selection.isCollapsed || document.activeElement === selection.focusNode)
) {
activeSelection = true;
return true;
}
activeSelection = false;
}
if (Device.android) {
if (androidNeedsBlur(e.target)) {
document.activeElement.blur();
}
}
trackClick = true;
targetElement = e.target;
touchStartTime = (new Date()).getTime();
touchStartX = e.targetTouches[0].pageX;
touchStartY = e.targetTouches[0].pageY;
// Detect scroll parent
if (Device.ios) {
scrollParent = undefined;
$(targetElement).parents().each(() => {
const parent = this;
if (parent.scrollHeight > parent.offsetHeight && !scrollParent) {
scrollParent = parent;
scrollParent.f7ScrollTop = scrollParent.scrollTop;
}
});
}
if ((e.timeStamp - lastClickTime) < params.fastClicksDelayBetweenClicks) {
e.preventDefault();
}
if (params.activeState) {
activableElement = findActivableElement(targetElement);
// If it's inside a scrollable view, we don't trigger active-state yet,
// because it can be a scroll instead. Based on the link:
// http://labnote.beedesk.com/click-scroll-and-pseudo-active-on-mobile-webk
if (!isInsideScrollableView(activableElement)) {
addActive();
} else {
activeTimeout = setTimeout(addActive, 80);
}
}
if (useRipple) {
rippleTouchStart(targetElement, touchStartX, touchStartY);
}
return true;
}
function handleTouchMove(e) {
if (!trackClick) return;
const distance = params.fastClicksDistanceThreshold;
if (distance) {
const pageX = e.targetTouches[0].pageX;
const pageY = e.targetTouches[0].pageY;
if (Math.abs(pageX - touchStartX) > distance || Math.abs(pageY - touchStartY) > distance) {
isMoved = true;
}
} else {
isMoved = true;
}
if (isMoved) {
trackClick = false;
targetElement = null;
isMoved = true;
if (params.tapHold) {
clearTimeout(tapHoldTimeout);
}
if (params.activeState) {
clearTimeout(activeTimeout);
removeActive();
}
if (useRipple) {
rippleTouchMove();
}
}
}
function handleTouchEnd(e) {
clearTimeout(activeTimeout);
clearTimeout(tapHoldTimeout);
if (!trackClick) {
if (!activeSelection && needsFastClick) {
if (!(Device.android && !e.cancelable) && e.cancelable) {
e.preventDefault();
}
}
return true;
}
if (document.activeElement === e.target) {
if (params.activeState) removeActive();
if (useRipple) {
rippleTouchEnd();
}
return true;
}
if (!activeSelection) {
e.preventDefault();
}
if ((e.timeStamp - lastClickTime) < params.fastClicksDelayBetweenClicks) {
setTimeout(removeActive, 0);
return true;
}
lastClickTime = e.timeStamp;
trackClick = false;
if (Device.ios && scrollParent) {
if (scrollParent.scrollTop !== scrollParent.f7ScrollTop) {
return false;
}
}
// Add active-state here because, in a very fast tap, the timeout didn't
// have the chance to execute. Removing active-state in a timeout gives
// the chance to the animation execute.
if (params.activeState) {
addActive();
setTimeout(removeActive, 0);
}
// Remove Ripple
if (useRipple) {
rippleTouchEnd();
}
// Trigger focus when required
if (targetNeedsFocus(targetElement)) {
if (Device.ios && Device.webView) {
if ((e.timeStamp - touchStartTime) > 159) {
targetElement = null;
return false;
}
targetElement.focus();
return false;
}
targetElement.focus();
}
// Blur active elements
if (document.activeElement && targetElement !== document.activeElement && document.activeElement !== document.body && targetElement.nodeName.toLowerCase() !== 'label') {
document.activeElement.blur();
}
// Send click
e.preventDefault();
sendClick(e);
return false;
}
function handleTouchCancel() {
trackClick = false;
targetElement = null;
// Remove Active State
clearTimeout(activeTimeout);
clearTimeout(tapHoldTimeout);
if (params.activeState) {
removeActive();
}
// Remove Ripple
if (useRipple) {
rippleTouchEnd();
}
}
function handleClick(e) {
let allowClick = false;
if (trackClick) {
targetElement = null;
trackClick = false;
return true;
}
if ((e.target.type === 'submit' && e.detail === 0) || e.target.type === 'file') {
return true;
}
if (!targetElement) {
if (!isFormElement(e.target)) {
allowClick = true;
}
}
if (!needsFastClick) {
allowClick = true;
}
if (document.activeElement === targetElement) {
allowClick = true;
}
if (e.forwardedTouchEvent) {
allowClick = true;
}
if (!e.cancelable) {
allowClick = true;
}
if (params.tapHold && params.tapHoldPreventClicks && tapHoldFired) {
allowClick = false;
}
if (!allowClick) {
e.stopImmediatePropagation();
e.stopPropagation();
if (targetElement) {
if (targetNeedsPrevent(targetElement) || isMoved) {
e.preventDefault();
}
} else {
e.preventDefault();
}
targetElement = null;
}
needsFastClickTimeOut = setTimeout(() => {
needsFastClick = false;
}, (Device.ios || Device.androidChrome ? 100 : 400));
if (params.tapHold) {
tapHoldTimeout = setTimeout(() => {
tapHoldFired = false;
}, (Device.ios || Device.androidChrome ? 100 : 400));
}
return allowClick;
}
function emitAppTouchEvent(name, e) {
app.emit({
events: name,
data: [e],
});
}
function appClick(e) {
emitAppTouchEvent('click', e);
}
function appTouchStartActive(e) {
emitAppTouchEvent('touchstart touchstart:active', e);
}
function appTouchMoveActive(e) {
emitAppTouchEvent('touchmove touchmove:active', e);
}
function appTouchEndActive(e) {
emitAppTouchEvent('touchend touchend:active', e);
}
function appTouchStartPassive(e) {
emitAppTouchEvent('touchstart:passive', e);
}
function appTouchMovePassive(e) {
emitAppTouchEvent('touchmove:passive', e);
}
function appTouchEndPassive(e) {
emitAppTouchEvent('touchend:passive', e);
}
const passiveListener = Support$1.passiveListener ? { passive: true } : false;
const activeListener = Support$1.passiveListener ? { passive: false } : false;
document.addEventListener('click', appClick, true);
if (Support$1.passiveListener) {
document.addEventListener(app.touchEvents.start, appTouchStartActive, activeListener);
document.addEventListener(app.touchEvents.move, appTouchMoveActive, activeListener);
document.addEventListener(app.touchEvents.end, appTouchEndActive, activeListener);
document.addEventListener(app.touchEvents.start, appTouchStartPassive, passiveListener);
document.addEventListener(app.touchEvents.move, appTouchMovePassive, passiveListener);
document.addEventListener(app.touchEvents.end, appTouchEndPassive, passiveListener);
} else {
document.addEventListener(app.touchEvents.start, (e) => {
appTouchStartActive(e);
appTouchStartPassive(e);
}, false);
document.addEventListener(app.touchEvents.move, (e) => {
appTouchMoveActive(e);
appTouchMovePassive(e);
}, false);
document.addEventListener(app.touchEvents.end, (e) => {
appTouchEndActive(e);
appTouchEndPassive(e);
}, false);
}
if (Support$1.touch) {
app.on('click', handleClick);
app.on('touchstart', handleTouchStart);
app.on('touchmove', handleTouchMove);
app.on('touchend', handleTouchEnd);
document.addEventListener('touchcancel', handleTouchCancel, { passive: true });
} else if (params.activeState) {
app.on('touchstart', handleMouseDown);
app.on('touchmove', handleMouseMove);
app.on('touchend', handleMouseUp);
}
document.addEventListener('contextmenu', (e) => {
if (params.disableContextMenu && (Device.ios || Device.android || Device.cordova)) {
e.preventDefault();
}
if (useRipple) {
if (activableElement) removeActive();
rippleTouchEnd();
}
});
}
var Touch = {
name: 'touch',
params: {
touch: {
// Fast clicks
fastClicks: true,
fastClicksDistanceThreshold: 10,
fastClicksDelayBetweenClicks: 50,
fastClicksExclude: '', // CSS selector
// ContextMenu
disableContextMenu: true,
// Tap Hold
tapHold: false,
tapHoldDelay: 750,
tapHoldPreventClicks: true,
// Active State
activeState: true,
activeStateElements: 'a, button, label, span, .actions-button',
materialRipple: true,
materialRippleElements: '.ripple, .link, .item-link, .links-list a, .button, button, .input-clear-button, .dialog-button, .tab-link, .item-radio, .item-checkbox, .actions-button, .searchbar-disable-button, .fab a, .checkbox, .radio, .data-table .sortable-cell, .notification-close-button',
},
},
instance: {
touchEvents: {
start: Support$1.touch ? 'touchstart' : 'mousedown',
move: Support$1.touch ? 'touchmove' : 'mousemove',
end: Support$1.touch ? 'touchend' : 'mouseup',
},
},
on: {
init: initTouch,
},
};
/**
* Expose `pathToRegexp`.
*/
var pathToRegexp_1 = pathToRegexp;
var parse_1 = parse;
var compile_1 = compile;
var tokensToFunction_1 = tokensToFunction;
var tokensToRegExp_1 = tokensToRegExp;
/**
* Default configs.
*/
var DEFAULT_DELIMITER = '/';
var DEFAULT_DELIMITERS = './';
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined]
'(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?'
].join('|'), 'g');
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse (str, options) {
var tokens = [];
var key = 0;
var index = 0;
var path = '';
var defaultDelimiter = (options && options.delimiter) || DEFAULT_DELIMITER;
var delimiters = (options && options.delimiters) || DEFAULT_DELIMITERS;
var pathEscaped = false;
var res;
while ((res = PATH_REGEXP.exec(str)) !== null) {
var m = res[0];
var escaped = res[1];
var offset = res.index;
path += str.slice(index, offset);
index = offset + m.length;
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1];
pathEscaped = true;
continue
}
var prev = '';
var next = str[index];
var name = res[2];
var capture = res[3];
var group = res[4];
var modifier = res[5];
if (!pathEscaped && path.length) {
var k = path.length - 1;
if (delimiters.indexOf(path[k]) > -1) {
prev = path[k];
path = path.slice(0, k);
}
}
// Push the current path onto the tokens.
if (path) {
tokens.push(path);
path = '';
pathEscaped = false;
}
var partial = prev !== '' && next !== undefined && next !== prev;
var repeat = modifier === '+' || modifier === '*';
var optional = modifier === '?' || modifier === '*';
var delimiter = prev || defaultDelimiter;
var pattern = capture || group;
tokens.push({
name: name || key++,
prefix: prev,
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
pattern: pattern ? escapeGroup(pattern) : '[^' + escapeString(delimiter) + ']+?'
});
}
// Push any remaining characters.
if (path || index < str.length) {
tokens.push(path + str.substr(index));
}
return tokens
}
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
function compile (str, options) {
return tokensToFunction(parse(str, options))
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction (tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length);
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$');
}
}
return function (data, options) {
var path = '';
var encode = (options && options.encode) || encodeURIComponent;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
path += token;
continue
}
var value = data ? data[token.name] : undefined;
var segment;
if (Array.isArray(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but got array')
}
if (value.length === 0) {
if (token.optional) continue
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j]);
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '"')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment;
}
continue
}
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
segment = encode(String(value));
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but got "' + segment + '"')
}
path += token.prefix + segment;
continue
}
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) path += token.prefix;
continue
}
throw new TypeError('Expected "' + token.name + '" to be ' + (token.repeat ? 'an array' : 'a string'))
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString (str) {
return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup (group) {
return group.replace(/([=!:$/()])/g, '\\$1')
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
function flags (options) {
return options && options.sensitive ? '' : 'i'
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {Array=} keys
* @return {!RegExp}
*/
function regexpToRegexp (path, keys) {
if (!keys) return path
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g);
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
pattern: null
});
}
}
return path
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function arrayToRegexp (path, keys, options) {
var parts = [];
for (var i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source);
}
return new RegExp('(?:' + parts.join('|') + ')', flags(options))
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {Array=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function stringToRegexp (path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options)
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {Array=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function tokensToRegExp (tokens, keys, options) {
options = options || {};
var strict = options.strict;
var end = options.end !== false;
var delimiter = escapeString(options.delimiter || DEFAULT_DELIMITER);
var delimiters = options.delimiters || DEFAULT_DELIMITERS;
var endsWith = [].concat(options.endsWith || []).map(escapeString).concat('$').join('|');
var route = '';
var isEndDelimited = false;
// Iterate over the tokens and create our regexp string.
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (typeof token === 'string') {
route += escapeString(token);
isEndDelimited = i === tokens.length - 1 && delimiters.indexOf(token[token.length - 1]) > -1;
} else {
var prefix = escapeString(token.prefix);
var capture = token.repeat
? '(?:' + token.pattern + ')(?:' + prefix + '(?:' + token.pattern + '))*'
: token.pattern;
if (keys) keys.push(token);
if (token.optional) {
if (token.partial) {
route += prefix + '(' + capture + ')?';
} else {
route += '(?:' + prefix + '(' + capture + '))?';
}
} else {
route += prefix + '(' + capture + ')';
}
}
}
if (end) {
if (!strict) route += '(?:' + delimiter + ')?';
route += endsWith === '$' ? '$' : '(?=' + endsWith + ')';
} else {
if (!strict) route += '(?:' + delimiter + '(?=' + endsWith + '))?';
if (!isEndDelimited) route += '(?=' + delimiter + '|' + endsWith + ')';
}
return new RegExp('^' + route, flags(options))
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(string|RegExp|Array)} path
* @param {Array=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function pathToRegexp (path, keys, options) {
if (path instanceof RegExp) {
return regexpToRegexp(path, keys)
}
if (Array.isArray(path)) {
return arrayToRegexp(/** @type {!Array} */ (path), keys, options)
}
return stringToRegexp(/** @type {string} */ (path), keys, options)
}
pathToRegexp_1.parse = parse_1;
pathToRegexp_1.compile = compile_1;
pathToRegexp_1.tokensToFunction = tokensToFunction_1;
pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
const tempDom = document.createElement('div');
class Framework7Component {
constructor(c, extendContext = {}) {
const context = Utils.extend({}, extendContext);
const component = Utils.extend(this, c, { context });
// Apply context
('beforeCreate created beforeMount mounted beforeDestroy destroyed').split(' ').forEach((cycleKey) => {
if (component[cycleKey]) component[cycleKey] = component[cycleKey].bind(context);
});
if (component.data) {
component.data = component.data.bind(context);
// Data
Utils.extend(context, component.data());
}
if (component.render) component.render = component.render.bind(context);
if (component.methods) {
Object.keys(component.methods).forEach((methodName) => {
context[methodName] = component.methods[methodName].bind(context);
});
}
// Bind Events
if (component.on) {
Object.keys(component.on).forEach((eventName) => {
component.on[eventName] = component.on[eventName].bind(context);
});
}
if (component.once) {
Object.keys(component.once).forEach((eventName) => {
component.once[eventName] = component.once[eventName].bind(context);
});
}
if (component.beforeCreate) component.beforeCreate();
// Watchers
if (component.watch) {
Object.keys(component.watch).forEach((watchKey) => {
let dataKeyValue = component.context[watchKey];
Object.defineProperty(component.context, watchKey, {
enumerable: true,
configurable: true,
set(newValue) {
dataKeyValue = newValue;
component.watch[watchKey].call(context, dataKeyValue);
},
get() {
return dataKeyValue;
},
});
});
}
// Render template
let html = '';
if (component.render) {
html = component.render();
} else if (component.template) {
if (typeof component.template === 'string') {
try {
html = Template7.compile(component.template)(context);
} catch (err) {
throw err;
}
} else {
// Supposed to be function
html = component.template(context);
}
}
// Make Dom
if (html && typeof html === 'string') {
html = html.trim();
tempDom.innerHTML = html;
} else if (html) {
tempDom.innerHTML = '';
tempDom.appendChild(html);
}
// Extend context with $el
const el = tempDom.children[0];
const $el = $(el);
context.$el = $el;
context.el = el;
component.el = el;
// Find Events
const events = [];
$(tempDom).find('*').each((index, element) => {
for (let i = 0; i < element.attributes.length; i += 1) {
const attr = element.attributes[i];
if (attr.name.indexOf('@') === 0) {
const event = attr.name.replace('@', '');
let name = event;
let stop = false;
let prevent = false;
let once = false;
if (event.indexOf('.') >= 0) {
event.split('.').forEach((eventNamePart, eventNameIndex) => {
if (eventNameIndex === 0) name = eventNamePart;
else {
if (eventNamePart === 'stop') stop = true;
if (eventNamePart === 'prevent') prevent = true;
if (eventNamePart === 'once') once = true;
}
});
}
const value = attr.value;
element.removeAttribute(attr.name);
events.push({
el: element,
name,
once,
handler: (...args) => {
const e = args[0];
if (stop) e.stopPropagation();
if (prevent) e.preventDefault();
let methodName;
let method;
let customArgs = [];
if (value.indexOf('(') < 0) {
customArgs = args;
methodName = value;
} else {
methodName = value.split('(')[0];
value.split('(')[1].split(')')[0].split(',').forEach((argument) => {
let arg = argument.trim();
// eslint-disable-next-line
if (!isNaN(arg)) arg = parseFloat(arg);
else if (arg === 'true') arg = true;
else if (arg === 'false') arg = false;
else if (arg === 'null') arg = null;
else if (arg === 'undefined') arg = undefined;
else if (arg[0] === '"') arg = arg.replace(/"/g, '');
else if (arg[0] === '\'') arg = arg.replace(/'/g, '');
else if (arg.indexOf('.') > 0) {
let deepArg;
arg.split('.').forEach((path) => {
if (!deepArg) deepArg = context;
deepArg = deepArg[path];
});
arg = deepArg;
} else {
arg = context[arg];
}
customArgs.push(arg);
});
}
if (methodName.indexOf('.') >= 0) {
methodName.split('.').forEach((path, pathIndex) => {
if (!method) method = context;
if (method[path]) method = method[path];
else {
throw new Error(`Component doesn't have method "${methodName.split('.').slice(0, pathIndex + 1).join('.')}"`);
}
});
} else {
if (!context[methodName]) {
throw new Error(`Component doesn't have method "${methodName}"`);
}
method = context[methodName];
}
method(...customArgs);
},
});
}
}
});
// Set styles scope ID
let styleEl;
if (component.style) {
styleEl = document.createElement('style');
styleEl.innerHTML = component.style;
}
if (component.styleScopeId) {
el.setAttribute('data-scope', component.styleScopeId);
}
// Attach events
function attachEvents() {
if (component.on) {
Object.keys(component.on).forEach((eventName) => {
$el.on(Utils.eventNameToColonCase(eventName), component.on[eventName]);
});
}
if (component.once) {
Object.keys(component.once).forEach((eventName) => {
$el.once(Utils.eventNameToColonCase(eventName), component.once[eventName]);
});
}
events.forEach((event) => {
$(event.el)[event.once ? 'once' : 'on'](event.name, event.handler);
});
}
function detachEvents() {
if (component.on) {
Object.keys(component.on).forEach((eventName) => {
$el.off(Utils.eventNameToColonCase(eventName), component.on[eventName]);
});
}
if (component.once) {
Object.keys(component.once).forEach((eventName) => {
$el.off(Utils.eventNameToColonCase(eventName), component.once[eventName]);
});
}
events.forEach((event) => {
$(event.el).off(event.name, event.handler);
});
}
attachEvents();
// Created callback
if (component.created) component.created();
// Mount
component.mount = function mount(mountMethod) {
if (component.beforeMount) component.beforeMount();
if (styleEl) $('head').append(styleEl);
if (mountMethod) mountMethod(el);
if (component.mounted) component.mounted();
};
// Destroy
component.destroy = function destroy() {
if (component.beforeDestroy) component.beforeDestroy();
if (styleEl) $(styleEl).remove();
detachEvents();
if (component.destroyed) component.destroyed();
};
// Store component instance
for (let i = 0; i < tempDom.children.length; i += 1) {
tempDom.children[i].f7Component = component;
}
return component;
}
}
const Component = {
parse(componentString) {
const callbackName = `f7_component_callback_${new Date().getTime()}`;
// Template
let template;
if (componentString.indexOf('<template>') >= 0) {
template = componentString
.split('<template>')
.filter((item, index) => index > 0)
.join('<template>')
.split('</template>')
.filter((item, index, arr) => index < arr.length - 1)
.join('</template>')
.replace(/{{#raw}}([ \n]*)<template/g, '{{#raw}}<template')
.replace(/\/template>([ \n]*){{\/raw}}/g, '/template>{{/raw}}')
.replace(/([ \n])<template/g, '$1{{#raw}}<template')
.replace(/\/template>([ \n])/g, '/template>{{/raw}}$1');
}
// Styles
let style;
const styleScopeId = Utils.now();
if (componentString.indexOf('<style>') >= 0) {
style = componentString.split('<style>')[1].split('</style>')[0];
} else if (componentString.indexOf('<style scoped>') >= 0) {
style = componentString.split('<style scoped>')[1].split('</style>')[0];
style = style.split('\n').map((line) => {
if (line.indexOf('{') >= 0) {
if (line.indexOf('{{this}}') >= 0) {
return line.replace('{{this}}', `[data-scope="${styleScopeId}"]`);
}
return `[data-scope="${styleScopeId}"] ${line.trim()}`;
}
return line;
}).join('\n');
}
let scriptContent;
if (componentString.indexOf('<script>') >= 0) {
const scripts = componentString.split('<script>');
scriptContent = scripts[scripts.length - 1].split('</script>')[0].trim();
} else {
scriptContent = 'return {}';
}
scriptContent = `window.${callbackName} = function () {${scriptContent}}`;
// Insert Script El
const scriptEl = document.createElement('script');
scriptEl.innerHTML = scriptContent;
$('head').append(scriptEl);
const component = window[callbackName]();
// Remove Script El
$(scriptEl).remove();
if (!component.template && !component.render) {
component.template = template;
}
if (style) {
component.style = style;
component.styleScopeId = styleScopeId;
}
return component;
},
create(c, extendContext = {}) {
return new Framework7Component(c, extendContext);
},
};
const History = {
queue: [],
clearQueue() {
if (History.queue.length === 0) return;
const currentQueue = History.queue.shift();
currentQueue();
},
routerQueue: [],
clearRouterQueue() {
if (History.routerQueue.length === 0) return;
const currentQueue = History.routerQueue.pop();
const { router, stateUrl, action } = currentQueue;
let animate = router.params.animate;
if (router.params.pushStateAnimate === false) animate = false;
if (action === 'back') {
router.back({ animate, pushState: false });
}
if (action === 'load') {
router.navigate(stateUrl, { animate, pushState: false });
}
},
handle(e) {
if (History.blockPopstate) return;
const app = this;
// const mainView = app.views.main;
let state = e.state;
History.previousState = History.state;
History.state = state;
History.allowChange = true;
History.clearQueue();
state = History.state;
if (!state) state = {};
app.views.forEach((view) => {
const router = view.router;
let viewState = state[view.id];
if (!viewState && view.params.pushState) {
viewState = {
url: view.router.history[0],
};
}
if (!viewState) return;
const stateUrl = viewState.url || undefined;
let animate = router.params.animate;
if (router.params.pushStateAnimate === false) animate = false;
if (stateUrl !== router.url) {
if (router.history.indexOf(stateUrl) >= 0) {
// Go Back
if (router.allowPageChange) {
router.back({ animate, pushState: false });
} else {
History.routerQueue.push({
action: 'back',
router,
});
}
} else if (router.allowPageChange) {
// Load page
router.navigate(stateUrl, { animate, pushState: false });
} else {
History.routerQueue.unshift({
action: 'load',
stateUrl,
router,
});
}
}
});
},
push(viewId, viewState, url) {
if (!History.allowChange) {
History.queue.push(() => {
History.push(viewId, viewState, url);
});
return;
}
History.previousState = History.state;
const newState = Utils.extend({}, (History.previousState || {}), {
[viewId]: viewState,
});
History.state = newState;
window.history.pushState(newState, '', url);
},
replace(viewId, viewState, url) {
if (!History.allowChange) {
History.queue.push(() => {
History.replace(viewId, viewState, url);
});
return;
}
History.previousState = History.state;
const newState = Utils.extend({}, (History.previousState || {}), {
[viewId]: viewState,
});
History.state = newState;
window.history.replaceState(newState, '', url);
},
go(index) {
History.allowChange = false;
window.history.go(index);
},
back() {
History.allowChange = false;
window.history.back();
},
allowChange: true,
previousState: {},
state: window.history.state,
blockPopstate: true,
init(app) {
$(window).on('load', () => {
setTimeout(() => {
History.blockPopstate = false;
}, 0);
});
if (document.readyState && document.readyState === 'complete') {
History.blockPopstate = false;
}
$(window).on('popstate', History.handle.bind(app));
},
};
function SwipeBack(r) {
const router = r;
const { $el, $navbarEl, app } = router;
let isTouched = false;
let isMoved = false;
const touchesStart = {};
let isScrolling;
let currentPage = [];
let previousPage = [];
let viewContainerWidth;
let touchesDiff;
let allowViewTouchMove = true;
let touchStartTime;
let currentNavbar = [];
let previousNavbar = [];
let currentNavElements;
let previousNavElements;
let activeNavBackIcon;
let activeNavBackIconText;
let previousNavBackIcon;
// let previousNavBackIconText;
let dynamicNavbar;
let separateNavbar;
let pageShadow;
let pageOpacity;
let navbarWidth;
function handleTouchStart(e) {
if (!allowViewTouchMove || !router.params.iosSwipeBack || isTouched || (app.swipeout && app.swipeout.el) || !router.allowPageChange) return;
if ($(e.target).closest('.range-slider, .calendar-months').length > 0) return;
isMoved = false;
isTouched = true;
isScrolling = undefined;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
touchStartTime = Utils.now();
dynamicNavbar = router.dynamicNavbar;
separateNavbar = router.separateNavbar;
}
function handleTouchMove(e) {
if (!isTouched) return;
const pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x)) || pageX < touchesStart.x;
}
if (isScrolling || e.f7PreventSwipeBack || app.preventSwipeBack) {
isTouched = false;
return;
}
if (!isMoved) {
// Calc values during first move fired
let cancel = false;
const target = $(e.target);
const swipeout = target.closest('.swipeout');
if (swipeout.length > 0) {
if (!app.rtl && swipeout.find('.swipeout-actions-left').length > 0) cancel = true;
if (app.rtl && swipeout.find('.swipeout-actions-right').length > 0) cancel = true;
}
currentPage = target.closest('.page');
if (currentPage.hasClass('no-swipeback')) cancel = true;
previousPage = $el.find('.page-previous:not(.stacked)');
let notFromBorder = touchesStart.x - $el.offset().left > router.params.iosSwipeBackActiveArea;
viewContainerWidth = $el.width();
if (app.rtl) {
notFromBorder = touchesStart.x < ($el.offset().left - $el[0].scrollLeft) + (viewContainerWidth - router.params.iosSwipeBackActiveArea);
} else {
notFromBorder = touchesStart.x - $el.offset().left > router.params.iosSwipeBackActiveArea;
}
if (notFromBorder) cancel = true;
if (previousPage.length === 0 || currentPage.length === 0) cancel = true;
if (cancel) {
isTouched = false;
return;
}
if (router.params.iosSwipeBackAnimateShadow) {
pageShadow = currentPage.find('.page-shadow-effect');
if (pageShadow.length === 0) {
pageShadow = $('<div class="page-shadow-effect"></div>');
currentPage.append(pageShadow);
}
}
if (router.params.iosSwipeBackAnimateOpacity) {
pageOpacity = previousPage.find('.page-opacity-effect');
if (pageOpacity.length === 0) {
pageOpacity = $('<div class="page-opacity-effect"></div>');
previousPage.append(pageOpacity);
}
}
if (dynamicNavbar) {
if (separateNavbar) {
currentNavbar = $navbarEl.find('.navbar-current:not(.stacked)');
previousNavbar = $navbarEl.find('.navbar-previous:not(.stacked)');
} else {
currentNavbar = currentPage.children('.navbar').children('.navbar-inner');
previousNavbar = previousPage.children('.navbar').children('.navbar-inner');
}
navbarWidth = $navbarEl[0].offsetWidth;
currentNavElements = currentNavbar.children('.left, .title, .right, .subnavbar, .fading');
previousNavElements = previousNavbar.children('.left, .title, .right, .subnavbar, .fading');
if (router.params.iosAnimateNavbarBackIcon) {
if (currentNavbar.hasClass('sliding')) {
activeNavBackIcon = currentNavbar.children('.left').find('.back .icon');
activeNavBackIconText = currentNavbar.children('.left').find('.back span').eq(0);
} else {
activeNavBackIcon = currentNavbar.children('.left.sliding').find('.back .icon');
activeNavBackIconText = currentNavbar.children('.left.sliding').find('.back span').eq(0);
}
if (previousNavbar.hasClass('sliding')) {
previousNavBackIcon = previousNavbar.children('.left').find('.back .icon');
// previousNavBackIconText = previousNavbar.children('left').find('.back span').eq(0);
} else {
previousNavBackIcon = previousNavbar.children('.left.sliding').find('.back .icon');
// previousNavBackIconText = previousNavbar.children('.left.sliding').find('.back span').eq(0);
}
}
}
// Close/Hide Any Picker
if ($('.sheet.modal-in').length > 0 && app.sheet) {
app.sheet.close($('.sheet.modal-in'));
}
}
e.f7PreventPanelSwipe = true;
isMoved = true;
app.preventSwipePanelBySwipeBack = true;
e.preventDefault();
// RTL inverter
const inverter = app.rtl ? -1 : 1;
// Touches diff
touchesDiff = (pageX - touchesStart.x - router.params.iosSwipeBackThreshold) * inverter;
if (touchesDiff < 0) touchesDiff = 0;
const percentage = touchesDiff / viewContainerWidth;
// Swipe Back Callback
const callbackData = {
percentage,
currentPageEl: currentPage[0],
previousPageEl: previousPage[0],
currentNavbarEl: currentNavbar[0],
previousNavbarEl: previousNavbar[0],
};
$el.trigger('swipeback:move', callbackData);
router.emit('swipebackMove', callbackData);
// Transform pages
let currentPageTranslate = touchesDiff * inverter;
let previousPageTranslate = ((touchesDiff / 5) - (viewContainerWidth / 5)) * inverter;
if (Device.pixelRatio === 1) {
currentPageTranslate = Math.round(currentPageTranslate);
previousPageTranslate = Math.round(previousPageTranslate);
}
currentPage.transform(`translate3d(${currentPageTranslate}px,0,0)`);
if (router.params.iosSwipeBackAnimateShadow) pageShadow[0].style.opacity = 1 - (1 * percentage);
previousPage.transform(`translate3d(${previousPageTranslate}px,0,0)`);
if (router.params.iosSwipeBackAnimateOpacity) pageOpacity[0].style.opacity = 1 - (1 * percentage);
// Dynamic Navbars Animation
if (dynamicNavbar) {
currentNavElements.each((index, navEl) => {
const $navEl = $(navEl);
if (!$navEl.is('.subnavbar')) $navEl[0].style.opacity = (1 - (percentage ** 0.33));
if ($navEl[0].className.indexOf('sliding') >= 0 || currentNavbar.hasClass('sliding')) {
let activeNavTranslate = percentage * $navEl[0].f7NavbarRightOffset;
if (Device.pixelRatio === 1) activeNavTranslate = Math.round(activeNavTranslate);
$navEl.transform(`translate3d(${activeNavTranslate}px,0,0)`);
if (router.params.iosAnimateNavbarBackIcon) {
if ($navEl[0].className.indexOf('left') >= 0 && activeNavBackIcon.length > 0) {
let iconTranslate = -activeNavTranslate;
if (!separateNavbar) {
iconTranslate -= navbarWidth * percentage;
}
activeNavBackIcon.transform(`translate3d(${iconTranslate}px,0,0)`);
}
}
}
});
previousNavElements.each((index, navEl) => {
const $navEl = $(navEl);
if (!$navEl.is('.subnavbar')) $navEl[0].style.opacity = (percentage ** 3);
if ($navEl[0].className.indexOf('sliding') >= 0 || previousNavbar.hasClass('sliding')) {
let previousNavTranslate = $navEl[0].f7NavbarLeftOffset * (1 - percentage);
if ($navEl[0].className.indexOf('title') >= 0 && activeNavBackIcon && activeNavBackIcon.length && activeNavBackIconText.length) {
previousNavTranslate = ($navEl[0].f7NavbarLeftOffset + activeNavBackIconText[0].offsetLeft) * (1 - percentage);
} else {
previousNavTranslate = $navEl[0].f7NavbarLeftOffset * (1 - percentage);
}
if (Device.pixelRatio === 1) previousNavTranslate = Math.round(previousNavTranslate);
$navEl.transform(`translate3d(${previousNavTranslate}px,0,0)`);
if (router.params.iosAnimateNavbarBackIcon) {
if ($navEl[0].className.indexOf('left') >= 0 && previousNavBackIcon.length > 0) {
let iconTranslate = -previousNavTranslate;
if (!separateNavbar) {
iconTranslate += (navbarWidth / 5) * (1 - percentage);
}
previousNavBackIcon.transform(`translate3d(${iconTranslate}px,0,0)`);
}
}
}
});
}
}
function handleTouchEnd() {
app.preventSwipePanelBySwipeBack = false;
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
isTouched = false;
isMoved = false;
if (touchesDiff === 0) {
$([currentPage[0], previousPage[0]]).transform('');
if (dynamicNavbar) {
currentNavElements.transform('').css({ opacity: '' });
previousNavElements.transform('').css({ opacity: '' });
if (activeNavBackIcon && activeNavBackIcon.length > 0) activeNavBackIcon.transform('');
if (previousNavBackIcon && activeNavBackIcon.length > 0) previousNavBackIcon.transform('');
}
return;
}
const timeDiff = Utils.now() - touchStartTime;
let pageChanged = false;
// Swipe back to previous page
if (
(timeDiff < 300 && touchesDiff > 10) ||
(timeDiff >= 300 && touchesDiff > viewContainerWidth / 2)
) {
currentPage.removeClass('page-current').addClass('page-next');
previousPage.removeClass('page-previous').addClass('page-current');
if (pageShadow) pageShadow[0].style.opacity = '';
if (pageOpacity) pageOpacity[0].style.opacity = '';
if (dynamicNavbar) {
currentNavbar.removeClass('navbar-current').addClass('navbar-next');
previousNavbar.removeClass('navbar-previous').addClass('navbar-current');
}
pageChanged = true;
}
// Reset custom styles
// Add transitioning class for transition-duration
$([currentPage[0], previousPage[0]]).addClass('page-transitioning').transform('');
if (dynamicNavbar) {
currentNavElements.css({ opacity: '' })
.each((navElIndex, navEl) => {
const translate = pageChanged ? navEl.f7NavbarRightOffset : 0;
const sliding = $(navEl);
let iconTranslate = pageChanged ? -translate : 0;
if (!separateNavbar && pageChanged) iconTranslate -= navbarWidth;
sliding.transform(`translate3d(${translate}px,0,0)`);
if (router.params.iosAnimateNavbarBackIcon) {
if (sliding.hasClass('left') && activeNavBackIcon.length > 0) {
activeNavBackIcon.addClass('navbar-transitioning').transform(`translate3d(${iconTranslate}px,0,0)`);
}
}
}).addClass('navbar-transitioning');
previousNavElements.transform('').css({ opacity: '' }).each((navElIndex, navEl) => {
const translate = pageChanged ? 0 : navEl.f7NavbarLeftOffset;
const sliding = $(navEl);
let iconTranslate = pageChanged ? 0 : -translate;
if (!separateNavbar && !pageChanged) iconTranslate += navbarWidth / 5;
sliding.transform(`translate3d(${translate}px,0,0)`);
if (router.params.iosAnimateNavbarBackIcon) {
if (sliding.hasClass('left') && previousNavBackIcon.length > 0) {
previousNavBackIcon.addClass('navbar-transitioning').transform(`translate3d(${iconTranslate}px,0,0)`);
}
}
}).addClass('navbar-transitioning');
}
allowViewTouchMove = false;
router.allowPageChange = false;
// Swipe Back Callback
const callbackData = {
currentPage: currentPage[0],
previousPage: previousPage[0],
currentNavbar: currentNavbar[0],
previousNavbar: previousNavbar[0],
};
if (pageChanged) {
// Update Route
router.currentRoute = previousPage[0].f7Page.route;
router.currentPage = previousPage[0];
// Page before animation callback
router.pageCallback('beforeOut', currentPage, currentNavbar, 'current', 'next', { route: currentPage[0].f7Page.route });
router.pageCallback('beforeIn', previousPage, previousNavbar, 'previous', 'current', { route: previousPage[0].f7Page.route });
$el.trigger('swipeback:beforechange', callbackData);
router.emit('swipebackBeforeChange', callbackData);
} else {
$el.trigger('swipeback:beforereset', callbackData);
router.emit('swipebackBeforeReset', callbackData);
}
currentPage.transitionEnd(() => {
$([currentPage[0], previousPage[0]]).removeClass('page-transitioning');
if (dynamicNavbar) {
currentNavElements.removeClass('navbar-transitioning').css({ opacity: '' }).transform('');
previousNavElements.removeClass('navbar-transitioning').css({ opacity: '' }).transform('');
if (activeNavBackIcon && activeNavBackIcon.length > 0) activeNavBackIcon.removeClass('navbar-transitioning');
if (previousNavBackIcon && previousNavBackIcon.length > 0) previousNavBackIcon.removeClass('navbar-transitioning');
}
allowViewTouchMove = true;
router.allowPageChange = true;
if (pageChanged) {
// Update History
if (router.history.length === 1) {
router.history.unshift(router.url);
}
router.history.pop();
router.saveHistory();
// Update push state
if (router.params.pushState) {
History.back();
}
// Page after animation callback
router.pageCallback('afterOut', currentPage, currentNavbar, 'current', 'next', { route: currentPage[0].f7Page.route });
router.pageCallback('afterIn', previousPage, previousNavbar, 'previous', 'current', { route: previousPage[0].f7Page.route });
// Remove Old Page
if (router.params.stackPages && router.initialPages.indexOf(currentPage[0]) >= 0) {
currentPage.addClass('stacked');
if (separateNavbar) {
currentNavbar.addClass('stacked');
}
} else {
router.pageCallback('beforeRemove', currentPage, currentNavbar, 'next');
router.removePage(currentPage);
if (separateNavbar) {
router.removeNavbar(currentNavbar);
}
}
$el.trigger('swipeback:afterchange', callbackData);
router.emit('swipebackAfterChange', callbackData);
router.emit('routeChanged', router.currentRoute, router.previousRoute, router);
if (router.params.preloadPreviousPage) {
router.back(router.history[router.history.length - 2], { preload: true });
}
} else {
$el.trigger('swipeback:afterreset', callbackData);
router.emit('swipebackAfterReset', callbackData);
}
if (pageShadow && pageShadow.length > 0) pageShadow.remove();
if (pageOpacity && pageOpacity.length > 0) pageOpacity.remove();
});
}
function attachEvents() {
const passiveListener = (app.touchEvents.start === 'touchstart' && Support$1.passiveListener) ? { passive: true, capture: false } : false;
$el.on(app.touchEvents.start, handleTouchStart, passiveListener);
app.on('touchmove:active', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
}
function detachEvents() {
const passiveListener = (app.touchEvents.start === 'touchstart' && Support$1.passiveListener) ? { passive: true, capture: false } : false;
$el.off(app.touchEvents.start, handleTouchStart, passiveListener);
app.off('touchmove:active', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
}
attachEvents();
router.on('routerDestroy', detachEvents);
}
var redirect = function (direction, route, options) {
const router = this;
const redirect = route.route.redirect;
function redirectResolve(redirectUrl, redirectOptions = {}) {
router.allowPageChange = true;
router[direction](redirectUrl, Utils.extend({}, options, redirectOptions));
}
function redirectReject() {
router.allowPageChange = true;
}
if (typeof redirect === 'function') {
router.allowPageChange = false;
const redirectUrl = redirect.call(router, route, redirectResolve, redirectReject);
if (redirectUrl && typeof redirectUrl === 'string') {
router.allowPageChange = true;
return router[direction](redirectUrl, options);
}
return router;
}
return router[direction](redirect, options);
};
function forward(el, forwardOptions = {}) {
const router = this;
const app = router.app;
const view = router.view;
const options = Utils.extend({
animate: router.params.animate,
pushState: true,
history: true,
reloadCurrent: router.params.reloadPages,
reloadPrevious: false,
reloadAll: false,
on: {},
}, forwardOptions);
const dynamicNavbar = router.dynamicNavbar;
const separateNavbar = router.separateNavbar;
const $viewEl = router.$el;
const $newPage = $(el);
const reload = options.reloadPrevious || options.reloadCurrent || options.reloadAll;
let $oldPage;
let $navbarEl;
let $newNavbarInner;
let $oldNavbarInner;
if ($newPage.length) {
// Remove theme elements
router.removeThemeElements($newPage);
}
if (dynamicNavbar) {
$newNavbarInner = $newPage.children('.navbar').children('.navbar-inner');
if (separateNavbar) {
$navbarEl = router.$navbarEl;
if ($newNavbarInner.length > 0) {
$newPage.children('.navbar').remove();
}
if ($newNavbarInner.length === 0 && $newPage[0].f7Page) {
// Try from pageData
$newNavbarInner = $newPage[0].f7Page.$navbarEl;
}
}
}
router.allowPageChange = false;
if ($newPage.length === 0) {
router.allowPageChange = true;
return router;
}
// Pages In View
const $pagesInView = $viewEl
.children('.page:not(.stacked)')
.filter((index, pageInView) => pageInView !== $newPage[0]);
// Navbars In View
let $navbarsInView;
if (separateNavbar) {
$navbarsInView = $navbarEl
.children('.navbar-inner:not(.stacked)')
.filter((index, navbarInView) => navbarInView !== $newNavbarInner[0]);
}
// Exit when reload previous and only 1 page in view so nothing ro reload
if (options.reloadPrevious && $pagesInView.length < 2) {
router.allowPageChange = true;
return router;
}
// New Page
let newPagePosition = 'next';
if (options.reloadCurrent || options.reloadAll) {
newPagePosition = 'current';
} else if (options.reloadPrevious) {
newPagePosition = 'previous';
}
$newPage
.addClass(`page-${newPagePosition}`)
.removeClass('stacked');
if (dynamicNavbar && $newNavbarInner.length) {
$newNavbarInner
.addClass(`navbar-${newPagePosition}`)
.removeClass('stacked');
}
// Find Old Page
if (options.reloadCurrent) {
$oldPage = $pagesInView.eq($pagesInView.length - 1);
if (separateNavbar) {
// $oldNavbarInner = $navbarsInView.eq($pagesInView.length - 1);
$oldNavbarInner = $(app.navbar.getElByPage($oldPage));
}
} else if (options.reloadPrevious) {
$oldPage = $pagesInView.eq($pagesInView.length - 2);
if (separateNavbar) {
// $oldNavbarInner = $navbarsInView.eq($pagesInView.length - 2);
$oldNavbarInner = $(app.navbar.getElByPage($oldPage));
}
} else if (options.reloadAll) {
$oldPage = $pagesInView.filter((index, pageEl) => pageEl !== $newPage[0]);
if (separateNavbar) {
$oldNavbarInner = $navbarsInView.filter((index, navbarEl) => navbarEl !== $newNavbarInner[0]);
}
} else {
if ($pagesInView.length > 1) {
let i = 0;
for (i = 0; i < $pagesInView.length - 1; i += 1) {
const oldNavbarInnerEl = app.navbar.getElByPage($pagesInView.eq(i));
if (router.params.stackPages) {
$pagesInView.eq(i).addClass('stacked');
if (separateNavbar) {
// $navbarsInView.eq(i).addClass('stacked');
$(oldNavbarInnerEl).addClass('stacked');
}
} else {
// Page remove event
router.pageCallback('beforeRemove', $pagesInView[i], $navbarsInView && $navbarsInView[i], 'previous', undefined, options);
router.removePage($pagesInView[i]);
if (separateNavbar && oldNavbarInnerEl) {
router.removeNavbar(oldNavbarInnerEl);
}
}
}
}
$oldPage = $viewEl
.children('.page:not(.stacked)')
.filter((index, page) => page !== $newPage[0]);
if (separateNavbar) {
$oldNavbarInner = $navbarEl
.children('.navbar-inner:not(.stacked)')
.filter((index, navbarInner) => navbarInner !== $newNavbarInner[0]);
}
}
if (dynamicNavbar && !separateNavbar) {
$oldNavbarInner = $oldPage.children('.navbar').children('.navbar-inner');
}
// Push State
if (router.params.pushState && options.pushState && !options.reloadPrevious) {
const pushStateRoot = router.params.pushStateRoot || '';
History[options.reloadCurrent || options.reloadAll ? 'replace' : 'push'](
view.id,
{
url: options.route.url,
},
pushStateRoot + router.params.pushStateSeparator + options.route.url
);
}
// Current Page & Navbar
router.currentPageEl = $newPage[0];
if (dynamicNavbar && $newNavbarInner.length) {
router.currentNavbarEl = $newNavbarInner[0];
} else {
delete router.currentNavbarEl;
}
// Current Route
router.currentRoute = options.route;
// Update router history
const url = options.route.url;
if (options.history) {
if (options.reloadCurrent && router.history.length > 0) {
router.history[router.history.length - (options.reloadPrevious ? 2 : 1)] = url;
} else if (options.reloadAll) {
router.history = [url];
} else {
router.history.push(url);
}
}
router.saveHistory();
// Insert new page and navbar
const newPageInDom = $newPage.parents(document).length > 0;
const f7Component = $newPage[0].f7Component;
if (options.reloadPrevious) {
if (f7Component && !newPageInDom) {
f7Component.mount((componentEl) => {
$(componentEl).insertBefore($oldPage);
});
} else {
$newPage.insertBefore($oldPage);
}
if (separateNavbar && $newNavbarInner.length) {
if ($oldNavbarInner.length) {
$newNavbarInner.insertBefore($oldNavbarInner);
} else {
if (!router.$navbarEl.parents(document).length) {
router.$el.prepend(router.$navbarEl);
}
$navbarEl.append($newNavbarInner);
}
}
} else {
if ($oldPage.next('.page')[0] !== $newPage[0]) {
if (f7Component && !newPageInDom) {
f7Component.mount((componentEl) => {
$viewEl.append(componentEl);
});
} else {
$viewEl.append($newPage[0]);
}
}
if (separateNavbar && $newNavbarInner.length) {
if (!router.$navbarEl.parents(document).length) {
router.$el.prepend(router.$navbarEl);
}
$navbarEl.append($newNavbarInner[0]);
}
}
if (!newPageInDom) {
router.pageCallback('mounted', $newPage, $newNavbarInner, newPagePosition, reload ? newPagePosition : 'current', options, $oldPage);
}
// Remove old page
if (options.reloadCurrent && $oldPage.length > 0) {
if (router.params.stackPages && router.initialPages.indexOf($oldPage[0]) >= 0) {
$oldPage.addClass('stacked');
if (separateNavbar) {
$oldNavbarInner.addClass('stacked');
}
} else {
// Page remove event
router.pageCallback('beforeRemove', $oldPage, $oldNavbarInner, 'previous', undefined, options);
router.removePage($oldPage);
if (separateNavbar && $oldNavbarInner && $oldNavbarInner.length) {
router.removeNavbar($oldNavbarInner);
}
}
} else if (options.reloadAll) {
$oldPage.each((index, pageEl) => {
const $oldPageEl = $(pageEl);
const $oldNavbarInnerEl = $(app.navbar.getElByPage($oldPageEl));
if (router.params.stackPages && router.initialPages.indexOf($oldPageEl[0]) >= 0) {
$oldPageEl.addClass('stacked');
if (separateNavbar) {
$oldNavbarInnerEl.addClass('stacked');
}
} else {
// Page remove event
router.pageCallback('beforeRemove', $oldPageEl, $oldNavbarInner && $oldNavbarInner.eq(index), 'previous', undefined, options);
router.removePage($oldPageEl);
if (separateNavbar && $oldNavbarInnerEl.length) {
router.removeNavbar($oldNavbarInnerEl);
}
}
});
}
// Load Tab
if (options.route.route.tab) {
router.tabLoad(options.route.route.tab, Utils.extend({}, options, {
history: false,
pushState: false,
}));
}
// Page init and before init events
router.pageCallback('init', $newPage, $newNavbarInner, newPagePosition, reload ? newPagePosition : 'current', options, $oldPage);
if (options.reloadCurrent || options.reloadAll) {
router.allowPageChange = true;
router.pageCallback('beforeIn', $newPage, $newNavbarInner, newPagePosition, 'current', options);
router.pageCallback('afterIn', $newPage, $newNavbarInner, newPagePosition, 'current', options);
return router;
}
// Before animation event
router.pageCallback('beforeIn', $newPage, $newNavbarInner, 'next', 'current', options);
router.pageCallback('beforeOut', $oldPage, $oldNavbarInner, 'current', 'previous', options);
// Animation
function afterAnimation() {
const pageClasses = 'page-previous page-current page-next';
const navbarClasses = 'navbar-previous navbar-current navbar-next';
$newPage.removeClass(pageClasses).addClass('page-current').removeAttr('aria-hidden');
$oldPage.removeClass(pageClasses).addClass('page-previous').attr('aria-hidden', 'true');
if (dynamicNavbar) {
$newNavbarInner.removeClass(navbarClasses).addClass('navbar-current').removeAttr('aria-hidden');
$oldNavbarInner.removeClass(navbarClasses).addClass('navbar-previous').attr('aria-hidden', 'true');
}
// After animation event
router.allowPageChange = true;
router.pageCallback('afterIn', $newPage, $newNavbarInner, 'next', 'current', options);
router.pageCallback('afterOut', $oldPage, $oldNavbarInner, 'current', 'previous', options);
let keepOldPage = app.theme === 'ios' ? (router.params.preloadPreviousPage || router.params.iosSwipeBack) : router.params.preloadPreviousPage;
if (!keepOldPage) {
if ($newPage.hasClass('smart-select-page') || $newPage.hasClass('photo-browser-page') || $newPage.hasClass('autocomplete-page')) {
keepOldPage = true;
}
}
if (!keepOldPage) {
if (router.params.stackPages) {
$oldPage.addClass('stacked');
if (separateNavbar) {
$oldNavbarInner.addClass('stacked');
}
} else if (!($newPage.attr('data-name') && $newPage.attr('data-name') === 'smart-select-page')) {
// Remove event
router.pageCallback('beforeRemove', $oldPage, $oldNavbarInner, 'previous', undefined, options);
router.removePage($oldPage);
if (separateNavbar && $oldNavbarInner.length) {
router.removeNavbar($oldNavbarInner);
}
}
}
router.emit('routeChanged', router.currentRoute, router.previousRoute, router);
if (router.params.pushState) {
History.clearRouterQueue();
}
}
function setPositionClasses() {
const pageClasses = 'page-previous page-current page-next';
const navbarClasses = 'navbar-previous navbar-current navbar-next';
$oldPage.removeClass(pageClasses).addClass('page-current').removeAttr('aria-hidden');
$newPage.removeClass(pageClasses).addClass('page-next').removeAttr('aria-hidden');
if (dynamicNavbar) {
$oldNavbarInner.removeClass(navbarClasses).addClass('navbar-current').removeAttr('aria-hidden');
$newNavbarInner.removeClass(navbarClasses).addClass('navbar-next').removeAttr('aria-hidden');
}
}
if (options.animate) {
const delay = router.app.theme === 'md' ? router.params.materialPageLoadDelay : router.params.iosPageLoadDelay;
if (delay) {
setTimeout(() => {
setPositionClasses();
router.animate($oldPage, $newPage, $oldNavbarInner, $newNavbarInner, 'forward', () => {
afterAnimation();
});
}, delay);
} else {
setPositionClasses();
router.animate($oldPage, $newPage, $oldNavbarInner, $newNavbarInner, 'forward', () => {
afterAnimation();
});
}
} else {
afterAnimation();
}
return router;
}
function load(loadParams = {}, loadOptions = {}, ignorePageChange) {
const router = this;
if (!router.allowPageChange && !ignorePageChange) return router;
const params = loadParams;
const options = loadOptions;
const { url, content, el, pageName, template, templateUrl, component, componentUrl } = params;
const { ignoreCache } = options;
if (options.route &&
options.route.route &&
options.route.route.parentPath &&
router.currentRoute.route &&
router.currentRoute.route.parentPath === options.route.route.parentPath) {
// Do something nested
if (options.route.url === router.url) {
return false;
}
// Check for same params
let sameParams = Object.keys(options.route.params).length === Object.keys(router.currentRoute.params).length;
if (sameParams) {
// Check for equal params name
Object.keys(options.route.params).forEach((paramName) => {
if (
!(paramName in router.currentRoute.params) ||
(router.currentRoute.params[paramName] !== options.route.params[paramName])
) {
sameParams = false;
}
});
}
if (sameParams) {
if (options.route.route.tab) {
return router.tabLoad(options.route.route.tab, options);
}
return false;
}
}
if (
options.route &&
options.route.url &&
router.url === options.route.url &&
!(options.reloadCurrent || options.reloadPrevious) &&
!router.params.allowDuplicateUrls
) {
return false;
}
if (!options.route && url) {
options.route = router.parseRouteUrl(url);
Utils.extend(options.route, { route: { url, path: url } });
}
// Component Callbacks
function resolve(pageEl, newOptions) {
return router.forward(pageEl, Utils.extend(options, newOptions));
}
function reject() {
router.allowPageChange = true;
return router;
}
if (url || templateUrl || componentUrl) {
router.allowPageChange = false;
}
// Proceed
if (content) {
router.forward(router.getPageEl(content), options);
} else if (template || templateUrl) {
// Parse template and send page element
try {
router.pageTemplateLoader(template, templateUrl, options, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (el) {
// Load page from specified HTMLElement or by page name in pages container
router.forward(router.getPageEl(el), options);
} else if (pageName) {
// Load page by page name in pages container
router.forward(router.$el.children(`.page[data-name="${pageName}"]`).eq(0), options);
} else if (component || componentUrl) {
// Load from component (F7/Vue/React/...)
try {
router.pageComponentLoader(router.el, component, componentUrl, options, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (url) {
// Load using XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router.xhrRequest(url, ignoreCache)
.then((pageContent) => {
router.forward(router.getPageEl(pageContent), options);
})
.catch(() => {
router.allowPageChange = true;
});
}
return router;
}
function navigate(navigateParams, navigateOptions = {}) {
const router = this;
let url;
let createRoute;
if (typeof navigateParams === 'string') {
url = navigateParams;
} else {
url = navigateParams.url;
createRoute = navigateParams.route;
}
const app = router.app;
if (!router.view) {
if (app.views.main) {
app.views.main.router.navigate(url, navigateOptions);
}
return router;
}
if (url === '#' || url === '') {
return router;
}
let navigateUrl = url.replace('./', '');
if (navigateUrl[0] !== '/' && navigateUrl.indexOf('#') !== 0) {
const currentPath = router.currentRoute.parentPath || router.currentRoute.path;
navigateUrl = ((currentPath ? `${currentPath}/` : '/') + navigateUrl)
.replace('///', '/')
.replace('//', '/');
}
let route;
if (createRoute) {
route = Utils.extend(router.parseRouteUrl(navigateUrl), {
route: Utils.extend({}, createRoute),
});
} else {
route = router.findMatchingRoute(navigateUrl);
}
if (!route) {
return router;
}
if (route.route.redirect) {
return redirect.call(router, 'navigate', route, navigateOptions);
}
const options = {};
if (route.route.options) {
Utils.extend(options, route.route.options, navigateOptions, { route });
} else {
Utils.extend(options, navigateOptions, { route });
}
('popup popover sheet loginScreen actions customModal').split(' ').forEach((modalLoadProp) => {
if (route.route[modalLoadProp]) {
router.modalLoad(modalLoadProp, route, options);
}
});
('url content component pageName el componentUrl template templateUrl').split(' ').forEach((pageLoadProp) => {
if (route.route[pageLoadProp]) {
router.load({ [pageLoadProp]: route.route[pageLoadProp] }, options);
}
});
// Async
function asyncResolve(resolveParams, resolveOptions) {
router.allowPageChange = false;
let resolvedAsModal = false;
('popup popover sheet loginScreen actions customModal').split(' ').forEach((modalLoadProp) => {
if (resolveParams[modalLoadProp]) {
resolvedAsModal = true;
const modalRoute = Utils.extend({}, route, { route: resolveParams });
router.allowPageChange = true;
router.modalLoad(modalLoadProp, modalRoute, Utils.extend(options, resolveOptions));
}
});
if (resolvedAsModal) return;
router.load(resolveParams, Utils.extend(options, resolveOptions), true);
}
function asyncReject() {
router.allowPageChange = true;
}
if (route.route.async) {
router.allowPageChange = false;
route.route.async.call(router, route, router.currentRoute, asyncResolve, asyncReject);
}
// Retur Router
return router;
}
function tabLoad(tabRoute, loadOptions = {}) {
const router = this;
const options = Utils.extend({
animate: router.params.animate,
pushState: true,
history: true,
on: {},
}, loadOptions);
const { ignoreCache } = options;
if (options.route) {
// Set Route
if (options.route !== router.currentRoute) {
router.currentRoute = options.route;
}
// Update Browser History
if (router.params.pushState && options.pushState && !options.reloadPrevious) {
History.replace(
router.view.id,
{
url: options.route.url,
},
(router.params.pushStateRoot || '') + router.params.pushStateSeparator + options.route.url
);
}
// Update Router History
if (options.history) {
router.history[router.history.length - 1] = options.route.url;
router.saveHistory();
}
}
// Show Tab
const $currentPageEl = $(router.currentPageEl);
let tabEl;
if ($currentPageEl.length && $currentPageEl.find(`#${tabRoute.id}`).length) {
tabEl = $currentPageEl.find(`#${tabRoute.id}`).eq(0);
} else if (router.view.selector) {
tabEl = `${router.view.selector} #${tabRoute.id}`;
} else {
tabEl = `#${tabRoute.id}`;
}
const tabShowResult = router.app.tab.show({
tabEl,
animate: options.animate,
tabRoute: options.route,
});
const { $newTabEl, $oldTabEl, animated, onTabsChanged } = tabShowResult;
if ($newTabEl && $newTabEl.parents('.page').length > 0 && options.route) {
const tabParentPageData = $newTabEl.parents('.page')[0].f7Page;
if (tabParentPageData && options.route) {
tabParentPageData.route = options.route;
}
}
// Load Tab Content
const { url, content, el, template, templateUrl, component, componentUrl } = tabRoute;
function onTabLoaded() {
// Remove theme elements
router.removeThemeElements($newTabEl);
$newTabEl.trigger('tab:init tab:mounted', tabRoute);
router.emit('tabInit tabMounted', $newTabEl[0], tabRoute);
if ($oldTabEl && router.params.unloadTabContent) {
if (animated) {
onTabsChanged(() => {
router.tabRemove($oldTabEl, $newTabEl, tabRoute);
});
} else {
router.tabRemove($oldTabEl, $newTabEl, tabRoute);
}
}
}
if (!router.params.unloadTabContent) {
if ($newTabEl[0].f7RouterTabLoaded) return;
}
const { on = {}, once = {} } = tabRoute;
if (options.on) {
Utils.extend(on, options.on);
}
if (options.once) {
Utils.extend(once, options.once);
}
// Component/Template Callbacks
function resolve(contentEl) {
if (!contentEl) return;
if (typeof contentEl === 'string') {
$newTabEl.html(contentEl);
} else {
$newTabEl.html('');
if (contentEl.f7Component) {
contentEl.f7Component.mount((componentEl) => {
$newTabEl.append(componentEl);
});
} else {
$newTabEl.append(contentEl);
}
}
if (!router.params.unloadTabContent) {
$newTabEl[0].f7RouterTabLoaded = true;
}
onTabLoaded();
}
function reject() {
router.allowPageChange = true;
return router;
}
if (content) {
resolve(content);
} else if (template || templateUrl) {
try {
router.tabTemplateLoader(template, templateUrl, options, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (el) {
resolve(el);
} else if (component || componentUrl) {
// Load from component (F7/Vue/React/...)
try {
router.tabComponentLoader($newTabEl[0], component, componentUrl, options, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (url) {
// Load using XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router.xhrRequest(url, ignoreCache)
.then((tabContent) => {
resolve(tabContent);
})
.catch(() => {
router.allowPageChange = true;
});
}
}
function tabRemove($oldTabEl, $newTabEl, tabRoute) {
const router = this;
$oldTabEl.trigger('tab:beforeremove', tabRoute);
router.emit('tabBeforeRemove', $oldTabEl[0], $newTabEl[0], tabRoute);
$oldTabEl.children().each((index, tabChild) => {
if (tabChild.f7Component) {
tabChild.f7Component.destroy();
}
});
router.removeTabContent($oldTabEl[0], tabRoute);
}
function modalLoad(modalType, route, loadOptions = {}) {
const router = this;
const app = router.app;
const options = Utils.extend({
animate: router.params.animate,
pushState: true,
history: true,
on: {},
}, loadOptions);
const modalParams = route.route[modalType];
const modalRoute = route.route;
const { ignoreCache } = options;
// Load Modal Props
const { url, template, templateUrl, component, componentUrl } = modalParams;
function onModalLoaded() {
// Create Modal
const modal = app[modalType].create(modalParams);
modalRoute.modalInstance = modal;
function closeOnSwipeBack() {
modal.close();
}
modal.on('modalOpen', () => {
router.once('swipeBackMove', closeOnSwipeBack);
});
modal.on('modalClose', () => {
router.off('swipeBackMove', closeOnSwipeBack);
if (!modal.closeByRouter) {
router.back();
}
});
modal.on('modalClosed', () => {
modal.$el.trigger(`${modalType.toLowerCase()}:beforeremove`, route, modal);
modal.emit(`${modalType}BeforeRemove`, modal.el, route, modal);
const modalComponent = modal.el.f7Component;
if (modalComponent) {
modalComponent.destroy();
}
Utils.nextTick(() => {
if (modalComponent) {
router.removeModal(modal.el);
}
modal.destroy();
delete modalRoute.modalInstance;
});
});
if (options.route) {
// Update Browser History
if (router.params.pushState && options.pushState) {
History.push(
router.view.id,
{
url: options.route.url,
modal: modalType,
},
(router.params.pushStateRoot || '') + router.params.pushStateSeparator + options.route.url
);
}
// Set Route
if (options.route !== router.currentRoute) {
router.currentRoute = Utils.extend(options.route, { modal });
}
// Update Router History
if (options.history) {
router.history.push(options.route.url);
router.saveHistory();
}
}
// Remove theme elements
router.removeThemeElements(modal.el);
// Emit events
modal.$el.trigger(`${modalType.toLowerCase()}:init ${modalType.toLowerCase()}:mounted`, route, modal);
router.emit(`${modalType}Init ${modalType}Mounted`, modal.el, route, modal);
// Open
modal.open();
}
// Component/Template Callbacks
function resolve(contentEl) {
if (contentEl) {
if (typeof contentEl === 'string') {
modalParams.content = contentEl;
} else if (contentEl.f7Component) {
contentEl.f7Component.mount((componentEl) => {
modalParams.el = componentEl;
app.root.append(componentEl);
});
} else {
modalParams.el = contentEl;
}
onModalLoaded();
}
}
function reject() {
router.allowPageChange = true;
return router;
}
if (template || templateUrl) {
try {
router.modalTemplateLoader(template, templateUrl, options, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (component || componentUrl) {
// Load from component (F7/Vue/React/...)
try {
router.modalComponentLoader(app.root[0], component, componentUrl, options, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (url) {
// Load using XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router.xhrRequest(url, ignoreCache)
.then((modalContent) => {
modalParams.content = modalContent;
onModalLoaded();
})
.catch(() => {
router.allowPageChange = true;
});
} else {
onModalLoaded();
}
}
function modalRemove(modal) {
Utils.extend(modal, { closeByRouter: true });
modal.close();
}
function backward(el, backwardOptions) {
const router = this;
const app = router.app;
const view = router.view;
const options = Utils.extend({
animate: router.params.animate,
pushState: true,
}, backwardOptions);
const dynamicNavbar = router.dynamicNavbar;
const separateNavbar = router.separateNavbar;
const $newPage = $(el);
const $oldPage = router.$el.children('.page-current');
if ($newPage.length) {
// Remove theme elements
router.removeThemeElements($newPage);
}
let $navbarEl;
let $newNavbarInner;
let $oldNavbarInner;
if (dynamicNavbar) {
$newNavbarInner = $newPage.children('.navbar').children('.navbar-inner');
if (separateNavbar) {
$navbarEl = router.$navbarEl;
if ($newNavbarInner.length > 0) {
$newPage.children('.navbar').remove();
}
if ($newNavbarInner.length === 0 && $newPage[0].f7Page) {
// Try from pageData
$newNavbarInner = $newPage[0].f7Page.$navbarEl;
}
$oldNavbarInner = $navbarEl.find('.navbar-current');
} else {
$oldNavbarInner = $oldPage.children('.navbar').children('.navbar-inner');
}
}
router.allowPageChange = false;
if ($newPage.length === 0 || $oldPage.length === 0) {
router.allowPageChange = true;
return router;
}
// Remove theme elements
router.removeThemeElements($newPage);
// New Page
$newPage
.addClass('page-previous')
.removeClass('stacked')
.removeAttr('aria-hidden');
if (dynamicNavbar && $newNavbarInner.length > 0) {
$newNavbarInner
.addClass('navbar-previous')
.removeClass('stacked')
.removeAttr('aria-hidden');
}
// Remove previous page in case of "forced"
let backIndex;
if (options.force) {
if ($oldPage.prev('.page-previous:not(.stacked)').length > 0 || $oldPage.prev('.page-previous').length === 0) {
if (router.history.indexOf(options.route.url) >= 0) {
backIndex = router.history.length - router.history.indexOf(options.route.url) - 1;
router.history = router.history.slice(0, router.history.indexOf(options.route.url) + 2);
view.history = router.history;
} else if (router.history[[router.history.length - 2]]) {
router.history[router.history.length - 2] = options.route.url;
} else {
router.history.unshift(router.url);
}
if (backIndex && router.params.stackPages) {
$oldPage.prevAll('.page-previous').each((index, pageToRemove) => {
const $pageToRemove = $(pageToRemove);
let $navbarToRemove;
if (separateNavbar) {
// $navbarToRemove = $oldNavbarInner.prevAll('.navbar-previous').eq(index);
$navbarToRemove = $(app.navbar.getElByPage($pageToRemove));
}
if ($pageToRemove[0] !== $newPage[0] && $pageToRemove.index() > $newPage.index()) {
if (router.initialPages.indexOf($pageToRemove[0]) >= 0) {
$pageToRemove.addClass('stacked');
if (separateNavbar) {
$navbarToRemove.addClass('stacked');
}
} else {
router.pageCallback('beforeRemove', $pageToRemove, $navbarToRemove, 'previous', undefined, options);
router.removePage($pageToRemove);
if (separateNavbar && $navbarToRemove.length > 0) {
router.removeNavbar($navbarToRemove);
}
}
}
});
} else {
const $pageToRemove = $oldPage.prev('.page-previous:not(.stacked)');
let $navbarToRemove;
if (separateNavbar) {
// $navbarToRemove = $oldNavbarInner.prev('.navbar-inner:not(.stacked)');
$navbarToRemove = $(app.navbar.getElByPage($pageToRemove));
}
if (router.params.stackPages && router.initialPages.indexOf($pageToRemove[0]) >= 0) {
$pageToRemove.addClass('stacked');
$navbarToRemove.addClass('stacked');
} else if ($pageToRemove.length > 0) {
router.pageCallback('beforeRemove', $pageToRemove, $navbarToRemove, 'previous', undefined, options);
router.removePage($pageToRemove);
if (separateNavbar && $navbarToRemove.length) {
router.removeNavbar($navbarToRemove);
}
}
}
}
}
// Insert new page
const newPageInDom = $newPage.parents(document).length > 0;
const f7Component = $newPage[0].f7Component;
function insertPage() {
if ($newPage.next($oldPage).length === 0) {
if (!newPageInDom && f7Component) {
f7Component.mount((componentEl) => {
$(componentEl).insertBefore($oldPage);
});
} else {
$newPage.insertBefore($oldPage);
}
}
if (separateNavbar && $newNavbarInner.length) {
$newNavbarInner.insertBefore($oldNavbarInner);
if ($oldNavbarInner.length > 0) {
$newNavbarInner.insertBefore($oldNavbarInner);
} else {
if (!router.$navbarEl.parents(document).length) {
router.$el.prepend(router.$navbarEl);
}
$navbarEl.append($newNavbarInner);
}
}
if (!newPageInDom) {
router.pageCallback('mounted', $newPage, $newNavbarInner, 'previous', 'current', options, $oldPage);
}
}
if (options.preload) {
// Insert Page
insertPage();
// Page init and before init events
router.pageCallback('init', $newPage, $newNavbarInner, 'previous', 'current', options, $oldPage);
if ($newPage.prevAll('.page-previous:not(.stacked)').length > 0) {
$newPage.prevAll('.page-previous:not(.stacked)').each((index, pageToRemove) => {
const $pageToRemove = $(pageToRemove);
let $navbarToRemove;
if (separateNavbar) {
// $navbarToRemove = $newNavbarInner.prevAll('.navbar-previous:not(.stacked)').eq(index);
$navbarToRemove = $(app.navbar.getElByPage($pageToRemove));
}
if (router.params.stackPages && router.initialPages.indexOf(pageToRemove) >= 0) {
$pageToRemove.addClass('stacked');
if (separateNavbar) {
$navbarToRemove.addClass('stacked');
}
} else {
router.pageCallback('beforeRemove', $pageToRemove, $navbarToRemove, 'previous', undefined);
router.removePage($pageToRemove);
if (separateNavbar && $navbarToRemove.length) {
router.removeNavbar($navbarToRemove);
}
}
});
}
router.allowPageChange = true;
return router;
}
// History State
if (router.params.pushState && options.pushState) {
if (backIndex) History.go(-backIndex);
else History.back();
}
// Update History
if (router.history.length === 1) {
router.history.unshift(router.url);
}
router.history.pop();
router.saveHistory();
// Current Page & Navbar
router.currentPageEl = $newPage[0];
if (dynamicNavbar && $newNavbarInner.length) {
router.currentNavbarEl = $newNavbarInner[0];
} else {
delete router.currentNavbarEl;
}
// Current Route
router.currentRoute = options.route;
// Insert Page
insertPage();
// Load Tab
if (options.route.route.tab) {
router.tabLoad(options.route.route.tab, Utils.extend({}, options, {
history: false,
pushState: false,
}));
}
// Page init and before init events
router.pageCallback('init', $newPage, $newNavbarInner, 'previous', 'current', options, $oldPage);
// Before animation callback
router.pageCallback('beforeIn', $newPage, $newNavbarInner, 'previous', 'current', options);
router.pageCallback('beforeOut', $oldPage, $oldNavbarInner, 'current', 'next', options);
// Animation
function afterAnimation() {
// Set classes
const pageClasses = 'page-previous page-current page-next';
const navbarClasses = 'navbar-previous navbar-current navbar-next';
$newPage.removeClass(pageClasses).addClass('page-current').removeAttr('aria-hidden');
$oldPage.removeClass(pageClasses).addClass('page-next').attr('aria-hidden', 'true');
if (dynamicNavbar) {
$newNavbarInner.removeClass(navbarClasses).addClass('navbar-current').removeAttr('aria-hidden');
$oldNavbarInner.removeClass(navbarClasses).addClass('navbar-next').attr('aria-hidden', 'true');
}
// After animation event
router.pageCallback('afterIn', $newPage, $newNavbarInner, 'previous', 'current', options);
router.pageCallback('afterOut', $oldPage, $oldNavbarInner, 'current', 'next', options);
// Remove Old Page
if (router.params.stackPages && router.initialPages.indexOf($oldPage[0]) >= 0) {
$oldPage.addClass('stacked');
if (separateNavbar) {
$oldNavbarInner.addClass('stacked');
}
} else {
router.pageCallback('beforeRemove', $oldPage, $oldNavbarInner, 'next', undefined, options);
router.removePage($oldPage);
if (separateNavbar && $oldNavbarInner.length) {
router.removeNavbar($oldNavbarInner);
}
}
router.allowPageChange = true;
router.emit('routeChanged', router.currentRoute, router.previousRoute, router);
// Preload previous page
const preloadPreviousPage = app.theme === 'ios' ? (router.params.preloadPreviousPage || router.params.iosSwipeBack) : router.params.preloadPreviousPage;
if (preloadPreviousPage) {
router.back(router.history[router.history.length - 2], { preload: true });
}
if (router.params.pushState) {
History.clearRouterQueue();
}
}
function setPositionClasses() {
const pageClasses = 'page-previous page-current page-next';
const navbarClasses = 'navbar-previous navbar-current navbar-next';
$oldPage.removeClass(pageClasses).addClass('page-current');
$newPage.removeClass(pageClasses).addClass('page-previous').removeAttr('aria-hidden');
if (dynamicNavbar) {
$oldNavbarInner.removeClass(navbarClasses).addClass('navbar-current');
$newNavbarInner.removeClass(navbarClasses).addClass('navbar-previous').removeAttr('aria-hidden');
}
}
if (options.animate) {
setPositionClasses();
router.animate($oldPage, $newPage, $oldNavbarInner, $newNavbarInner, 'backward', () => {
afterAnimation();
});
} else {
afterAnimation();
}
return router;
}
function loadBack(backParams, backOptions, ignorePageChange) {
const router = this;
if (!router.allowPageChange && !ignorePageChange) return router;
const params = backParams;
const options = backOptions;
const { url, content, el, pageName, template, templateUrl, component, componentUrl } = params;
const { ignoreCache } = options;
if (
options.route.url &&
router.url === options.route.url &&
!(options.reloadCurrent || options.reloadPrevious) &&
!router.params.allowDuplicateUrls
) {
return false;
}
if (!options.route && url) {
options.route = router.parseRouteUrl(url);
}
// Component Callbacks
function resolve(pageEl, newOptions) {
return router.backward(pageEl, Utils.extend(options, newOptions));
}
function reject() {
router.allowPageChange = true;
return router;
}
if (url || templateUrl || componentUrl) {
router.allowPageChange = false;
}
// Proceed
if (content) {
router.backward(router.getPageEl(content), options);
} else if (template || templateUrl) {
// Parse template and send page element
try {
router.pageTemplateLoader(template, templateUrl, options, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (el) {
// Load page from specified HTMLElement or by page name in pages container
router.backward(router.getPageEl(el), options);
} else if (pageName) {
// Load page by page name in pages container
router.backward(router.$el.children(`.page[data-name="${pageName}"]`).eq(0), options);
} else if (component || componentUrl) {
// Load from component (F7/Vue/React/...)
try {
router.pageComponentLoader(router.el, component, componentUrl, options, resolve, reject);
} catch (err) {
router.allowPageChange = true;
throw err;
}
} else if (url) {
// Load using XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router.xhrRequest(url, ignoreCache)
.then((pageContent) => {
router.backward(router.getPageEl(pageContent), options);
})
.catch(() => {
router.allowPageChange = true;
});
}
return router;
}
function back(...args) {
let navigateUrl;
let navigateOptions;
if (typeof args[0] === 'object') {
navigateOptions = args[0] || {};
} else {
navigateUrl = args[0];
navigateOptions = args[1] || {};
}
const router = this;
const app = router.app;
if (!router.view) {
app.views.main.router.back(navigateUrl, navigateOptions);
return router;
}
let currentRouteIsModal = router.currentRoute.modal;
let modalType;
if (!currentRouteIsModal) {
('popup popover sheet loginScreen actions customModal').split(' ').forEach((modalLoadProp) => {
if (router.currentRoute.route[modalLoadProp]) {
currentRouteIsModal = true;
modalType = modalLoadProp;
}
});
}
if (currentRouteIsModal) {
const modalToClose = router.currentRoute.modal ||
router.currentRoute.route.modalInstance ||
app[modalType].get();
const previousUrl = router.history[router.history.length - 2];
let previousRoute = router.findMatchingRoute(previousUrl);
if (!previousRoute && previousUrl) {
previousRoute = {
url: previousUrl,
path: previousUrl.split('?')[0],
query: Utils.parseUrlQuery(previousUrl),
route: {
path: previousUrl.split('?')[0],
url: previousUrl,
},
};
}
if (!previousRoute || !modalToClose) {
return router;
}
if (router.params.pushState && navigateOptions.pushState !== false) {
History.back();
}
router.currentRoute = previousRoute;
router.history.pop();
router.saveHistory();
router.modalRemove(modalToClose);
return router;
}
const $previousPage = router.$el.children('.page-current').prevAll('.page-previous').eq(0);
if (!navigateOptions.force && $previousPage.length > 0) {
if (router.params.pushState && $previousPage[0].f7Page && router.history[router.history.length - 2] !== $previousPage[0].f7Page.route.url) {
router.back(router.history[router.history.length - 2], Utils.extend(navigateOptions, { force: true }));
return router;
}
router.loadBack({ el: $previousPage }, Utils.extend(navigateOptions, {
route: $previousPage[0].f7Page.route,
}));
return router;
}
// Navigate URL
if (navigateUrl === '#') {
navigateUrl = undefined;
}
if (navigateUrl && navigateUrl[0] !== '/' && navigateUrl.indexOf('#') !== 0) {
navigateUrl = ((router.path || '/') + navigateUrl).replace('//', '/');
}
if (!navigateUrl && router.history.length > 1) {
navigateUrl = router.history[router.history.length - 2];
}
// Find route to load
let route = router.findMatchingRoute(navigateUrl);
if (!route) {
if (navigateUrl) {
route = {
url: navigateUrl,
path: navigateUrl.split('?')[0],
query: Utils.parseUrlQuery(navigateUrl),
route: {
path: navigateUrl.split('?')[0],
url: navigateUrl,
},
};
}
}
if (!route) {
return router;
}
if (route.route.redirect) {
return redirect.call(router, 'back', route, navigateOptions);
}
const options = {};
if (route.route.options) {
Utils.extend(options, route.route.options, navigateOptions, { route });
} else {
Utils.extend(options, navigateOptions, { route });
}
if (options.force && router.params.stackPages) {
router.$el.children('.page-previous.stacked').each((index, pageEl) => {
if (pageEl.f7Page && pageEl.f7Page.route && pageEl.f7Page.route.url === route.url) {
router.loadBack({ el: pageEl }, options);
}
});
}
('url content component pageName el componentUrl template templateUrl').split(' ').forEach((pageLoadProp) => {
if (route.route[pageLoadProp]) {
router.loadBack({ [pageLoadProp]: route.route[pageLoadProp] }, options);
}
});
// Async
function asyncResolve(resolveParams, resolveOptions) {
router.allowPageChange = false;
router.loadBack(resolveParams, Utils.extend(options, resolveOptions), true);
}
function asyncReject() {
router.allowPageChange = true;
}
if (route.route.async) {
router.allowPageChange = false;
route.route.async.call(router, route, router.currentRoute, asyncResolve, asyncReject);
}
// Return Router
return router;
}
class Router$1 extends Framework7Class {
constructor(app, view) {
super({}, [typeof view === 'undefined' ? app : view]);
const router = this;
// Is App Router
router.isAppRouter = typeof view === 'undefined';
if (router.isAppRouter) {
// App Router
Utils.extend(false, router, {
app,
params: app.params.view,
routes: app.routes || [],
cache: app.cache,
});
} else {
// View Router
Utils.extend(false, router, {
app,
view,
viewId: view.id,
params: view.params,
routes: view.routes,
$el: view.$el,
el: view.el,
$navbarEl: view.$navbarEl,
navbarEl: view.navbarEl,
history: view.history,
scrollHistory: view.scrollHistory,
cache: app.cache,
dynamicNavbar: app.theme === 'ios' && view.params.iosDynamicNavbar,
separateNavbar: app.theme === 'ios' && view.params.iosDynamicNavbar && view.params.iosSeparateDynamicNavbar,
initialPages: [],
initialNavbars: [],
});
}
// Install Modules
router.useModules();
// Temporary Dom
router.tempDom = document.createElement('div');
// AllowPageChage
router.allowPageChange = true;
// Current Route
let currentRoute = {};
let previousRoute = {};
Object.defineProperty(router, 'currentRoute', {
enumerable: true,
configurable: true,
set(newRoute = {}) {
previousRoute = Utils.extend({}, currentRoute);
currentRoute = newRoute;
if (!currentRoute) return;
router.url = currentRoute.url;
router.emit('routeChange', newRoute, previousRoute, router);
},
get() {
return currentRoute;
},
});
Object.defineProperty(router, 'previousRoute', {
enumerable: true,
configurable: true,
get() {
return previousRoute;
},
set(newRoute) {
previousRoute = newRoute;
},
});
Utils.extend(router, {
// Load
forward,
load,
navigate,
// Tab
tabLoad,
tabRemove,
// Modal
modalLoad,
modalRemove,
// Back
backward,
loadBack,
back,
});
return router;
}
animatableNavElements(newNavbarInner, oldNavbarInner) {
const router = this;
const dynamicNavbar = router.dynamicNavbar;
const animateIcon = router.params.iosAnimateNavbarBackIcon;
let newNavEls;
let oldNavEls;
function animatableNavEl(el, navbarInner) {
const $el = $(el);
const isSliding = $el.hasClass('sliding') || navbarInner.hasClass('sliding');
const isSubnavbar = $el.hasClass('subnavbar');
const needsOpacityTransition = isSliding ? !isSubnavbar : true;
const hasIcon = isSliding && animateIcon && $el.hasClass('left') && $el.find('.back .icon').length > 0;
let $iconEl;
if (hasIcon) $iconEl = $el.find('.back .icon');
return {
$el,
$iconEl,
hasIcon,
leftOffset: $el[0].f7NavbarLeftOffset,
rightOffset: $el[0].f7NavbarRightOffset,
isSliding,
isSubnavbar,
needsOpacityTransition,
};
}
if (dynamicNavbar) {
newNavEls = [];
oldNavEls = [];
newNavbarInner.children('.left, .right, .title, .subnavbar').each((index, navEl) => {
newNavEls.push(animatableNavEl(navEl, newNavbarInner));
});
oldNavbarInner.children('.left, .right, .title, .subnavbar').each((index, navEl) => {
oldNavEls.push(animatableNavEl(navEl, oldNavbarInner));
});
[oldNavEls, newNavEls].forEach((navEls) => {
navEls.forEach((navEl) => {
const n = navEl;
const { isSliding, $el } = navEl;
const otherEls = navEls === oldNavEls ? newNavEls : oldNavEls;
if (!(isSliding && $el.hasClass('title') && otherEls)) return;
otherEls.forEach((otherNavEl) => {
if (otherNavEl.$el.hasClass('left') && otherNavEl.hasIcon) {
const iconTextEl = otherNavEl.$el.find('.back span')[0];
n.leftOffset += iconTextEl ? iconTextEl.offsetLeft : 0;
}
});
});
});
}
return { newNavEls, oldNavEls };
}
animateWithCSS(oldPage, newPage, oldNavbarInner, newNavbarInner, direction, callback) {
const router = this;
const dynamicNavbar = router.dynamicNavbar;
const separateNavbar = router.separateNavbar;
const ios = router.app.theme === 'ios';
// Router Animation class
const routerTransitionClass = `router-transition-${direction} router-transition-css-${direction}`;
let newNavEls;
let oldNavEls;
let navbarWidth = 0;
if (ios && dynamicNavbar) {
if (!separateNavbar) {
navbarWidth = newNavbarInner[0].offsetWidth;
}
const navEls = router.animatableNavElements(newNavbarInner, oldNavbarInner);
newNavEls = navEls.newNavEls;
oldNavEls = navEls.oldNavEls;
}
function animateNavbars(progress) {
if (ios && dynamicNavbar) {
newNavEls.forEach((navEl) => {
const $el = navEl.$el;
const offset = direction === 'forward' ? navEl.rightOffset : navEl.leftOffset;
if (navEl.isSliding) {
$el.transform(`translate3d(${offset * (1 - progress)}px,0,0)`);
}
if (navEl.hasIcon) {
if (direction === 'forward') {
navEl.$iconEl.transform(`translate3d(${(-offset - navbarWidth) * (1 - progress)}px,0,0)`);
} else {
navEl.$iconEl.transform(`translate3d(${(-offset + (navbarWidth / 5)) * (1 - progress)}px,0,0)`);
}
}
});
oldNavEls.forEach((navEl) => {
const $el = navEl.$el;
const offset = direction === 'forward' ? navEl.leftOffset : navEl.rightOffset;
if (navEl.isSliding) {
$el.transform(`translate3d(${offset * (progress)}px,0,0)`);
}
if (navEl.hasIcon) {
if (direction === 'forward') {
navEl.$iconEl.transform(`translate3d(${(-offset + (navbarWidth / 5)) * (progress)}px,0,0)`);
} else {
navEl.$iconEl.transform(`translate3d(${(-offset - navbarWidth) * (progress)}px,0,0)`);
}
}
});
}
}
// AnimationEnd Callback
function onDone() {
if (router.dynamicNavbar) {
if (newNavbarInner.hasClass('sliding')) {
newNavbarInner.find('.title, .left, .right, .left .icon, .subnavbar').transform('');
} else {
newNavbarInner.find('.sliding').transform('');
}
if (oldNavbarInner.hasClass('sliding')) {
oldNavbarInner.find('.title, .left, .right, .left .icon, .subnavbar').transform('');
} else {
oldNavbarInner.find('.sliding').transform('');
}
}
router.$el.removeClass(routerTransitionClass);
if (callback) callback();
}
(direction === 'forward' ? newPage : oldPage).animationEnd(() => {
onDone();
});
// Animate
if (dynamicNavbar) {
// Prepare Navbars
animateNavbars(0);
Utils.nextTick(() => {
// Add class, start animation
animateNavbars(1);
router.$el.addClass(routerTransitionClass);
});
} else {
// Add class, start animation
router.$el.addClass(routerTransitionClass);
}
}
animateWithJS(oldPage, newPage, oldNavbarInner, newNavbarInner, direction, callback) {
const router = this;
const dynamicNavbar = router.dynamicNavbar;
const separateNavbar = router.separateNavbar;
const ios = router.app.theme === 'ios';
const duration = ios ? 400 : 250;
const routerTransitionClass = `router-transition-${direction} router-transition-js-${direction}`;
let startTime = null;
let done = false;
let newNavEls;
let oldNavEls;
let navbarWidth = 0;
if (ios && dynamicNavbar) {
if (!separateNavbar) {
navbarWidth = newNavbarInner[0].offsetWidth;
}
const navEls = router.animatableNavElements(newNavbarInner, oldNavbarInner);
newNavEls = navEls.newNavEls;
oldNavEls = navEls.oldNavEls;
}
let $shadowEl;
let $opacityEl;
if (ios) {
$shadowEl = $('<div class="page-shadow-effect"></div>');
$opacityEl = $('<div class="page-opacity-effect"></div>');
if (direction === 'forward') {
newPage.append($shadowEl);
oldPage.append($opacityEl);
} else {
newPage.append($opacityEl);
oldPage.append($shadowEl);
}
}
const easing = Utils.bezier(0.25, 0.1, 0.25, 1);
function onDone() {
newPage.transform('').css('opacity', '');
oldPage.transform('').css('opacity', '');
if (ios) {
$shadowEl.remove();
$opacityEl.remove();
if (dynamicNavbar) {
newNavEls.forEach((navEl) => {
navEl.$el.transform('');
navEl.$el.css('opacity', '');
});
oldNavEls.forEach((navEl) => {
navEl.$el.transform('');
navEl.$el.css('opacity', '');
});
newNavEls = [];
oldNavEls = [];
}
}
router.$el.removeClass(routerTransitionClass);
if (callback) callback();
}
function render() {
const time = Utils.now();
if (!startTime) startTime = time;
const progress = Math.max(Math.min((time - startTime) / duration, 1), 0);
const easeProgress = easing(progress);
if (progress >= 1) {
done = true;
}
const inverter = router.app.rtl ? -1 : 1;
if (ios) {
if (direction === 'forward') {
newPage.transform(`translate3d(${(1 - easeProgress) * 100 * inverter}%,0,0)`);
oldPage.transform(`translate3d(${-easeProgress * 20 * inverter}%,0,0)`);
$shadowEl[0].style.opacity = easeProgress;
$opacityEl[0].style.opacity = easeProgress;
} else {
newPage.transform(`translate3d(${-(1 - easeProgress) * 20 * inverter}%,0,0)`);
oldPage.transform(`translate3d(${easeProgress * 100 * inverter}%,0,0)`);
$shadowEl[0].style.opacity = 1 - easeProgress;
$opacityEl[0].style.opacity = 1 - easeProgress;
}
if (dynamicNavbar) {
newNavEls.forEach((navEl) => {
const $el = navEl.$el;
const offset = direction === 'forward' ? navEl.rightOffset : navEl.leftOffset;
if (navEl.needsOpacityTransition) {
$el[0].style.opacity = easeProgress;
}
if (navEl.isSliding) {
$el.transform(`translate3d(${offset * (1 - easeProgress)}px,0,0)`);
}
if (navEl.hasIcon) {
if (direction === 'forward') {
navEl.$iconEl.transform(`translate3d(${(-offset - navbarWidth) * (1 - easeProgress)}px,0,0)`);
} else {
navEl.$iconEl.transform(`translate3d(${(-offset + (navbarWidth / 5)) * (1 - easeProgress)}px,0,0)`);
}
}
});
oldNavEls.forEach((navEl) => {
const $el = navEl.$el;
const offset = direction === 'forward' ? navEl.leftOffset : navEl.rightOffset;
if (navEl.needsOpacityTransition) {
$el[0].style.opacity = (1 - easeProgress);
}
if (navEl.isSliding) {
$el.transform(`translate3d(${offset * (easeProgress)}px,0,0)`);
}
if (navEl.hasIcon) {
if (direction === 'forward') {
navEl.$iconEl.transform(`translate3d(${(-offset + (navbarWidth / 5)) * (easeProgress)}px,0,0)`);
} else {
navEl.$iconEl.transform(`translate3d(${(-offset - navbarWidth) * (easeProgress)}px,0,0)`);
}
}
});
}
} else if (direction === 'forward') {
newPage.transform(`translate3d(0, ${(1 - easeProgress) * 56}px,0)`);
newPage.css('opacity', easeProgress);
} else {
oldPage.transform(`translate3d(0, ${easeProgress * 56}px,0)`);
oldPage.css('opacity', 1 - easeProgress);
}
if (done) {
onDone();
return;
}
Utils.nextFrame(render);
}
router.$el.addClass(routerTransitionClass);
Utils.nextFrame(render);
}
animate(...args) {
// Args: oldPage, newPage, oldNavbarInner, newNavbarInner, direction, callback
const router = this;
if (router.params.animateCustom) {
router.params.animateCustom.apply(router, args);
} else if (router.params.animateWithJS) {
router.animateWithJS(...args);
} else {
router.animateWithCSS(...args);
}
}
removeModal(modalEl) {
const router = this;
router.removeEl(modalEl);
}
// eslint-disable-next-line
removeTabContent(tabEl) {
const $tabEl = $(tabEl);
$tabEl.html('');
}
removeNavbar(el) {
const router = this;
router.removeEl(el);
}
removePage(el) {
const router = this;
router.removeEl(el);
}
removeEl(el) {
if (!el) return;
const router = this;
const $el = $(el);
if ($el.length === 0) return;
if ($el[0].f7Component && $el[0].f7Component.destroy) {
$el[0].f7Component.destroy();
}
if (!router.params.removeElements) {
return;
}
if (router.params.removeElementsWithTimeout) {
setTimeout(() => {
$el.remove();
}, router.params.removeElementsTimeout);
} else {
$el.remove();
}
}
getPageEl(content) {
const router = this;
if (typeof content === 'string') {
router.tempDom.innerHTML = content;
} else {
if ($(content).hasClass('page')) {
return content;
}
router.tempDom.innerHTML = '';
$(router.tempDom).append(content);
}
return router.findElement('.page', router.tempDom);
}
findElement(stringSelector, container, notStacked) {
const router = this;
const view = router.view;
const app = router.app;
// Modals Selector
const modalsSelector = '.popup, .dialog, .popover, .actions-modal, .sheet-modal, .login-screen, .page';
const $container = $(container);
let selector = stringSelector;
if (notStacked) selector += ':not(.stacked)';
let found = $container
.find(selector)
.filter((index, el) => $(el).parents(modalsSelector).length === 0);
if (found.length > 1) {
if (typeof view.selector === 'string') {
// Search in related view
found = $container.find(`${view.selector} ${selector}`);
}
if (found.length > 1) {
// Search in main view
found = $container.find(`.${app.params.viewMainClass} ${selector}`);
}
}
if (found.length === 1) return found;
// Try to find not stacked
if (!notStacked) found = router.findElement(selector, $container, true);
if (found && found.length === 1) return found;
if (found && found.length > 1) return $(found[0]);
return undefined;
}
flattenRoutes(routes = this.routes) {
let flattenedRoutes = [];
routes.forEach((route) => {
if ('routes' in route) {
const mergedPathsRoutes = route.routes.map((childRoute) => {
const cRoute = Utils.extend({}, childRoute);
cRoute.path = (`${route.path}/${cRoute.path}`).replace('///', '/').replace('//', '/');
return cRoute;
});
flattenedRoutes = flattenedRoutes.concat(route, this.flattenRoutes(mergedPathsRoutes));
} else if ('tabs' in route && route.tabs) {
const mergedPathsRoutes = route.tabs.map((tabRoute) => {
const tRoute = Utils.extend({}, route, {
path: (`${route.path}/${tabRoute.path}`).replace('///', '/').replace('//', '/'),
parentPath: route.path,
tab: tabRoute,
});
delete tRoute.tabs;
return tRoute;
});
flattenedRoutes = flattenedRoutes.concat(this.flattenRoutes(mergedPathsRoutes));
} else {
flattenedRoutes.push(route);
}
});
return flattenedRoutes;
}
// eslint-disable-next-line
parseRouteUrl(url) {
if (!url) return {};
const query = Utils.parseUrlQuery(url);
const hash = url.split('#')[1];
const params = {};
const path = url.split('#')[0].split('?')[0];
return {
query,
hash,
params,
url,
path,
};
}
findTabRoute(tabEl) {
const router = this;
const $tabEl = $(tabEl);
const parentPath = router.currentRoute.route.parentPath;
const tabId = $tabEl.attr('id');
const flattenedRoutes = router.flattenRoutes(router.routes);
let foundTabRoute;
flattenedRoutes.forEach((route) => {
if (
route.parentPath === parentPath &&
route.tab &&
route.tab.id === tabId
) {
foundTabRoute = route;
}
});
return foundTabRoute;
}
findRouteByKey(key, value) {
const router = this;
const routes = router.routes;
const flattenedRoutes = router.flattenRoutes(routes);
let matchingRoute;
flattenedRoutes.forEach((route) => {
if (matchingRoute) return;
if (route[key] === value) {
matchingRoute = route;
}
});
return matchingRoute;
}
findMatchingRoute(url) {
if (!url) return undefined;
const router = this;
const routes = router.routes;
const flattenedRoutes = router.flattenRoutes(routes);
const { path, query, hash, params } = router.parseRouteUrl(url);
let matchingRoute;
flattenedRoutes.forEach((route) => {
if (matchingRoute) return;
const keys = [];
const pathsToMatch = [route.path];
if (route.alias) {
if (typeof route.alias === 'string') pathsToMatch.push(route.alias);
else if (Array.isArray(route.alias)) {
route.alias.forEach((aliasPath) => {
pathsToMatch.push(aliasPath);
});
}
}
let matched;
pathsToMatch.forEach((pathToMatch) => {
if (matched) return;
matched = pathToRegexp_1(pathToMatch, keys).exec(path);
});
if (matched) {
keys.forEach((keyObj, index) => {
const paramValue = matched[index + 1];
params[keyObj.name] = paramValue;
});
let parentPath;
if (route.parentPath) {
parentPath = path.split('/').slice(0, route.parentPath.split('/').length - 1).join('/');
}
matchingRoute = {
query,
hash,
params,
url,
path,
parentPath,
route,
name: route.name,
};
}
});
return matchingRoute;
}
removeFromXhrCache(url) {
const router = this;
const xhrCache = router.cache.xhr;
let index = false;
for (let i = 0; i < xhrCache.length; i += 1) {
if (xhrCache[i].url === url) index = i;
}
if (index !== false) xhrCache.splice(index, 1);
}
xhrRequest(requestUrl, ignoreCache) {
const router = this;
const params = router.params;
let url = requestUrl;
// should we ignore get params or not
if (params.xhrCacheIgnoreGetParameters && url.indexOf('?') >= 0) {
url = url.split('?')[0];
}
return Utils.promise((resolve, reject) => {
if (params.xhrCache && !ignoreCache && url.indexOf('nocache') < 0 && params.xhrCacheIgnore.indexOf(url) < 0) {
for (let i = 0; i < router.cache.xhr.length; i += 1) {
const cachedUrl = router.cache.xhr[i];
if (cachedUrl.url === url) {
// Check expiration
if (Utils.now() - cachedUrl.time < params.xhrCacheDuration) {
// Load from cache
resolve(cachedUrl.content);
return;
}
}
}
}
router.xhr = router.app.request({
url,
method: 'GET',
beforeSend() {
router.emit('routerAjaxStart', router.xhr);
},
complete(xhr, status) {
router.emit('routerAjaxComplete', xhr);
if ((status !== 'error' && status !== 'timeout' && (xhr.status >= 200 && xhr.status < 300)) || xhr.status === 0) {
if (params.xhrCache && xhr.responseText !== '') {
router.removeFromXhrCache(url);
router.cache.xhr.push({
url,
time: Utils.now(),
content: xhr.responseText,
});
}
router.emit('routerAjaxSuccess', xhr);
resolve(xhr.responseText);
} else {
router.emit('routerAjaxError', xhr);
reject(xhr);
}
},
error(xhr) {
router.emit('routerAjaxError', xhr);
reject(xhr);
},
});
});
}
// Remove theme elements
removeThemeElements(el) {
const router = this;
const theme = router.app.theme;
$(el).find(`.${theme === 'md' ? 'ios' : 'md'}-only, .if-${theme === 'md' ? 'ios' : 'md'}`).remove();
}
templateLoader(template, templateUrl, options, resolve, reject) {
const router = this;
function compile(t) {
let compiledHtml;
let context;
try {
context = options.context || {};
if (typeof context === 'function') context = context.call(router);
else if (typeof context === 'string') {
try {
context = JSON.parse(context);
} catch (err) {
reject();
throw (err);
}
}
if (typeof t === 'function') {
compiledHtml = t(context);
} else {
compiledHtml = Template7.compile(t)(Utils.extend({}, context || {}, {
$app: router.app,
$root: Utils.extend({}, router.app.data, router.app.methods),
$route: options.route,
$router: router,
$theme: {
ios: router.app.theme === 'ios',
md: router.app.theme === 'md',
},
}));
}
} catch (err) {
reject();
throw (err);
}
resolve(compiledHtml, { context });
}
if (templateUrl) {
// Load via XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router
.xhrRequest(templateUrl)
.then((templateContent) => {
compile(templateContent);
})
.catch(() => {
reject();
});
} else {
compile(template);
}
}
modalTemplateLoader(template, templateUrl, options, resolve, reject) {
const router = this;
return router.templateLoader(template, templateUrl, options, (html) => {
resolve(html);
}, reject);
}
tabTemplateLoader(template, templateUrl, options, resolve, reject) {
const router = this;
return router.templateLoader(template, templateUrl, options, (html) => {
resolve(html);
}, reject);
}
pageTemplateLoader(template, templateUrl, options, resolve, reject) {
const router = this;
return router.templateLoader(template, templateUrl, options, (html, newOptions = {}) => {
resolve(router.getPageEl(html), newOptions);
}, reject);
}
componentLoader(component, componentUrl, options = {}, resolve, reject) {
const router = this;
const url = typeof component === 'string' ? component : componentUrl;
function compile(c) {
const extendContext = Utils.extend(
{},
options.context || {},
{
$,
$$: $,
$app: router.app,
$root: Utils.extend({}, router.app.data, router.app.methods),
$route: options.route,
$router: router,
$dom7: $,
$theme: {
ios: router.app.theme === 'ios',
md: router.app.theme === 'md',
},
}
);
const createdComponent = Component.create(c, extendContext);
resolve(createdComponent.el);
}
if (url) {
// Load via XHR
if (router.xhr) {
router.xhr.abort();
router.xhr = false;
}
router
.xhrRequest(url)
.then((loadedComponent) => {
compile(Component.parse(loadedComponent));
})
.catch((err) => {
reject();
throw (err);
});
} else {
compile(component);
}
}
modalComponentLoader(rootEl, component, componentUrl, options, resolve, reject) {
const router = this;
router.componentLoader(component, componentUrl, options, (el) => {
resolve(el);
}, reject);
}
tabComponentLoader(tabEl, component, componentUrl, options, resolve, reject) {
const router = this;
router.componentLoader(component, componentUrl, options, (el) => {
resolve(el);
}, reject);
}
pageComponentLoader(routerEl, component, componentUrl, options, resolve, reject) {
const router = this;
router.componentLoader(component, componentUrl, options, (el, newOptions = {}) => {
resolve(el, newOptions);
}, reject);
}
getPageData(pageEl, navbarEl, from, to, route = {}, pageFromEl) {
const router = this;
const $pageEl = $(pageEl);
const $navbarEl = $(navbarEl);
const currentPage = $pageEl[0].f7Page || {};
let direction;
let pageFrom;
if ((from === 'next' && to === 'current') || (from === 'current' && to === 'previous')) direction = 'forward';
if ((from === 'current' && to === 'next') || (from === 'previous' && to === 'current')) direction = 'backward';
if (currentPage && !currentPage.fromPage) {
const $pageFromEl = $(pageFromEl);
if ($pageFromEl.length) {
pageFrom = $pageFromEl[0].f7Page;
}
}
const page = {
app: router.app,
view: router.view,
router,
$el: $pageEl,
el: $pageEl[0],
$pageEl,
pageEl: $pageEl[0],
$navbarEl,
navbarEl: $navbarEl[0],
name: $pageEl.attr('data-name'),
position: from,
from,
to,
direction,
route: currentPage.route ? currentPage.route : route,
pageFrom: currentPage.pageFrom || pageFrom,
};
if ($navbarEl && $navbarEl[0]) {
$navbarEl[0].f7Page = page;
}
$pageEl[0].f7Page = page;
return page;
}
// Callbacks
pageCallback(callback, pageEl, navbarEl, from, to, options = {}, pageFromEl) {
if (!pageEl) return;
const router = this;
const $pageEl = $(pageEl);
if (!$pageEl.length) return;
const { route } = options;
const restoreScrollTopOnBack = router.params.restoreScrollTopOnBack;
const camelName = `page${callback[0].toUpperCase() + callback.slice(1, callback.length)}`;
const colonName = `page:${callback.toLowerCase()}`;
let page = {};
if (callback === 'beforeRemove' && $pageEl[0].f7Page) {
page = Utils.extend($pageEl[0].f7Page, { from, to, position: from });
} else {
page = router.getPageData(pageEl, navbarEl, from, to, route, pageFromEl);
}
const { on = {}, once = {} } = options.route ? options.route.route : {};
if (options.on) {
Utils.extend(on, options.on);
}
if (options.once) {
Utils.extend(once, options.once);
}
function attachEvents() {
if ($pageEl[0].f7RouteEventsAttached) return;
$pageEl[0].f7RouteEventsAttached = true;
if (on && Object.keys(on).length > 0) {
$pageEl[0].f7RouteEventsOn = on;
Object.keys(on).forEach((eventName) => {
on[eventName] = on[eventName].bind(router);
$pageEl.on(Utils.eventNameToColonCase(eventName), on[eventName]);
});
}
if (once && Object.keys(once).length > 0) {
$pageEl[0].f7RouteEventsOnce = once;
Object.keys(once).forEach((eventName) => {
once[eventName] = once[eventName].bind(router);
$pageEl.once(Utils.eventNameToColonCase(eventName), once[eventName]);
});
}
}
function detachEvents() {
if (!$pageEl[0].f7RouteEventsAttached) return;
if ($pageEl[0].f7RouteEventsOn) {
Object.keys($pageEl[0].f7RouteEventsOn).forEach((eventName) => {
$pageEl.off(Utils.eventNameToColonCase(eventName), $pageEl[0].f7RouteEventsOn[eventName]);
});
}
if ($pageEl[0].f7RouteEventsOnce) {
Object.keys($pageEl[0].f7RouteEventsOnce).forEach((eventName) => {
$pageEl.off(Utils.eventNameToColonCase(eventName), $pageEl[0].f7RouteEventsOnce[eventName]);
});
}
$pageEl[0].f7RouteEventsAttached = null;
$pageEl[0].f7RouteEventsOn = null;
$pageEl[0].f7RouteEventsOnce = null;
delete $pageEl[0].f7RouteEventsAttached;
delete $pageEl[0].f7RouteEventsOn;
delete $pageEl[0].f7RouteEventsOnce;
}
if (callback === 'mounted') {
attachEvents();
}
if (callback === 'init') {
if (restoreScrollTopOnBack && (from === 'previous' || !from) && to === 'current' && router.scrollHistory[page.route.url]) {
$pageEl.find('.page-content').scrollTop(router.scrollHistory[page.route.url]);
}
attachEvents();
if ($pageEl[0].f7PageInitialized) {
$pageEl.trigger('page:reinit', page);
router.emit('pageReinit', page);
return;
}
$pageEl[0].f7PageInitialized = true;
}
if (restoreScrollTopOnBack && callback === 'beforeOut' && from === 'current' && to === 'previous') {
// Save scroll position
router.scrollHistory[page.route.url] = $pageEl.find('.page-content').scrollTop();
}
if (restoreScrollTopOnBack && callback === 'beforeOut' && from === 'current' && to === 'next') {
// Delete scroll position
delete router.scrollHistory[page.route.url];
}
$pageEl.trigger(colonName, page);
router.emit(camelName, page);
if (callback === 'beforeRemove') {
detachEvents();
$pageEl[0].f7Page = null;
}
}
saveHistory() {
const router = this;
router.view.history = router.history;
if (router.params.pushState) {
window.localStorage[`f7router-${router.view.id}-history`] = JSON.stringify(router.history);
}
}
restoreHistory() {
const router = this;
if (router.params.pushState && window.localStorage[`f7router-${router.view.id}-history`]) {
router.history = JSON.parse(window.localStorage[`f7router-${router.view.id}-history`]);
router.view.history = router.history;
}
}
clearHistory() {
const router = this;
router.history = [];
router.saveHistory();
}
init() {
const router = this;
const { app, view } = router;
// Init Swipeback
{
if (view && router.params.iosSwipeBack && app.theme === 'ios') {
SwipeBack(router);
}
}
// Dynamic not separated navbbar
if (router.dynamicNavbar && !router.separateNavbar) {
router.$el.addClass('router-dynamic-navbar-inside');
}
let initUrl = router.params.url;
let documentUrl = document.location.href.split(document.location.origin)[1];
let historyRestored;
if (!router.params.pushState) {
if (!initUrl) {
initUrl = documentUrl;
}
if (document.location.search && initUrl.indexOf('?') < 0) {
initUrl += document.location.search;
}
if (document.location.hash && initUrl.indexOf('#') < 0) {
initUrl += document.location.hash;
}
} else {
if (router.params.pushStateRoot && documentUrl.indexOf(router.params.pushStateRoot) >= 0) {
documentUrl = documentUrl.split(router.params.pushStateRoot)[1];
if (documentUrl === '') documentUrl = '/';
}
if (router.params.pushStateSeparator.length > 0 && documentUrl.indexOf(router.params.pushStateSeparator) >= 0) {
initUrl = documentUrl.split(router.params.pushStateSeparator)[1];
} else {
initUrl = documentUrl;
}
router.restoreHistory();
if (router.history.indexOf(initUrl) >= 0) {
router.history = router.history.slice(0, router.history.indexOf(initUrl) + 1);
} else if (router.params.url === initUrl) {
router.history = [initUrl];
} else if (History.state && History.state[view.id] && History.state[view.id].url === router.history[router.history.length - 1]) {
initUrl = router.history[router.history.length - 1];
} else {
router.history = [documentUrl.split(router.params.pushStateSeparator)[0] || '/', initUrl];
}
if (router.history.length > 1) {
historyRestored = true;
} else {
router.history = [];
}
router.saveHistory();
}
let currentRoute;
if (router.history.length > 1) {
// Will load page
currentRoute = router.findMatchingRoute(router.history[0]);
if (!currentRoute) {
currentRoute = Utils.extend(router.parseRouteUrl(router.history[0]), {
route: {
url: router.history[0],
path: router.history[0].split('?')[0],
},
});
}
} else {
// Don't load page
currentRoute = router.findMatchingRoute(initUrl);
if (!currentRoute) {
currentRoute = Utils.extend(router.parseRouteUrl(initUrl), {
route: {
url: initUrl,
path: initUrl.split('?')[0],
},
});
}
}
if (router.params.stackPages) {
router.$el.children('.page').each((index, pageEl) => {
const $pageEl = $(pageEl);
router.initialPages.push($pageEl[0]);
if (router.separateNavbar && $pageEl.children('.navbar').length > 0) {
router.initialNavbars.push($pageEl.children('.navbar').find('.navbar-inner')[0]);
}
});
}
if (router.$el.children('.page:not(.stacked)').length === 0 && initUrl) {
// No pages presented in DOM, reload new page
router.navigate(initUrl, {
reloadCurrent: true,
pushState: false,
});
} else {
// Init current DOM page
router.currentRoute = currentRoute;
router.$el.children('.page:not(.stacked)').each((index, pageEl) => {
const $pageEl = $(pageEl);
let $navbarInnerEl;
$pageEl.addClass('page-current');
if (router.separateNavbar) {
$navbarInnerEl = $pageEl.children('.navbar').children('.navbar-inner');
if ($navbarInnerEl.length > 0) {
if (!router.$navbarEl.parents(document).length) {
router.$el.prepend(router.$navbarEl);
}
router.$navbarEl.append($navbarInnerEl);
$pageEl.children('.navbar').remove();
} else {
router.$navbarEl.addClass('navbar-hidden');
}
}
const initOptions = {
route: router.currentRoute,
};
if (router.currentRoute && router.currentRoute.route && router.currentRoute.route.options) {
Utils.extend(initOptions, router.currentRoute.route.options);
}
router.currentPageEl = $pageEl[0];
if (router.dynamicNavbar && $navbarInnerEl.length) {
router.currentNavbarEl = $navbarInnerEl[0];
}
router.removeThemeElements($pageEl);
if (router.dynamicNavbar && $navbarInnerEl.length) {
router.removeThemeElements($navbarInnerEl);
}
router.pageCallback('init', $pageEl, $navbarInnerEl, 'current', undefined, initOptions);
});
if (historyRestored) {
router.navigate(initUrl, {
pushState: false,
history: false,
animate: router.params.pushStateAnimateOnLoad,
once: {
pageAfterIn() {
if (router.history.length > 2) {
router.back({ preload: true });
}
},
},
});
} else {
router.history.push(initUrl);
router.saveHistory();
}
}
router.emit('local::init routerInit', router);
}
destroy() {
let router = this;
router.emit('local::destroy routerDestroy', router);
// Delete props & methods
Object.keys(router).forEach((routerProp) => {
router[routerProp] = null;
delete router[routerProp];
});
router = null;
}
}
var Router = {
name: 'router',
static: {
Router: Router$1,
},
instance: {
cache: {
xhr: [],
templates: [],
components: [],
},
},
create() {
const instance = this;
if (instance.app) {
// View Router
if (instance.params.router) {
instance.router = new Router$1(instance.app, instance);
}
} else {
// App Router
instance.router = new Router$1(instance);
}
},
};
class View extends Framework7Class {
constructor(appInstance, el, viewParams = {}) {
super(viewParams, [appInstance]);
const app = appInstance;
const $el = $(el);
const view = this;
const defaults = {
routes: [],
routesAdd: [],
};
// Default View params
view.params = Utils.extend(defaults, app.params.view, viewParams);
// Routes
if (view.params.routes.length > 0) {
view.routes = view.params.routes;
} else {
view.routes = [].concat(app.routes, view.params.routesAdd);
}
// Selector
let selector;
if (typeof el === 'string') selector = el;
else {
// Supposed to be HTMLElement or Dom7
selector = ($el.attr('id') ? `#${$el.attr('id')}` : '') + ($el.attr('class') ? `.${$el.attr('class').replace(/ /g, '.').replace('.active', '')}` : '');
}
// DynamicNavbar
let $navbarEl;
if (app.theme === 'ios' && view.params.iosDynamicNavbar && view.params.iosSeparateDynamicNavbar) {
$navbarEl = $el.children('.navbar').eq(0);
if ($navbarEl.length === 0) {
$navbarEl = $('<div class="navbar"></div>');
}
}
// View Props
Utils.extend(false, view, {
app,
$el,
el: $el[0],
name: view.params.name,
main: view.params.main || $el.hasClass('view-main'),
$navbarEl,
navbarEl: $navbarEl ? $navbarEl[0] : undefined,
selector,
history: [],
scrollHistory: {},
});
// Save in DOM
$el[0].f7View = view;
// Install Modules
view.useModules();
// Add to app
app.views.push(view);
if (view.main) {
app.views.main = view;
}
if (view.name) {
app.views[view.name] = view;
}
// Index
view.index = app.views.indexOf(view);
// View ID
let viewId;
if (view.name) {
viewId = `view_${view.name}`;
} else if (view.main) {
viewId = 'view_main';
} else {
viewId = `view_${view.index}`;
}
view.id = viewId;
// Init View
if (app.initialized) {
view.init();
} else {
app.on('init', view.init);
}
return view;
}
destroy() {
let view = this;
const app = view.app;
view.$el.trigger('view:beforedestroy', view);
view.emit('local::beforeDestroy viewBeforeDestroy', view);
if (view.main) {
app.views.main = null;
delete app.views.main;
} else if (view.name) {
app.views[view.name] = null;
delete app.views[view.name];
}
view.$el[0].f7View = null;
delete view.$el[0].f7View;
app.views.splice(app.views.indexOf(view), 1);
// Destroy Router
if (view.params.router && view.router) {
view.router.destroy();
}
view.emit('local::destroy viewDestroy', view);
// Delete props & methods
Object.keys(view).forEach((viewProp) => {
view[viewProp] = null;
delete view[viewProp];
});
view = null;
}
init() {
const view = this;
if (view.params.router) {
view.router.init();
}
}
}
// Use Router
View.use(Router);
function initClicks(app) {
function handleClicks(e) {
const clicked = $(e.target);
const clickedLink = clicked.closest('a');
const isLink = clickedLink.length > 0;
const url = isLink && clickedLink.attr('href');
const isTabLink = isLink && clickedLink.hasClass('tab-link') && (clickedLink.attr('data-tab') || (url && url.indexOf('#') === 0));
// Check if link is external
if (isLink) {
// eslint-disable-next-line
if (clickedLink.is(app.params.clicks.externalLinks) || (url && url.indexOf('javascript:') >= 0)) {
const target = clickedLink.attr('target');
if (url && (target === '_system' || target === '_blank')) {
e.preventDefault();
if (window.cordova && window.cordova.InAppBrowser) {
window.cordova.InAppBrowser.open(url, target);
} else {
window.open(url, target);
}
}
return;
}
}
// Modules Clicks
Object.keys(app.modules).forEach((moduleName) => {
const moduleClicks = app.modules[moduleName].clicks;
if (!moduleClicks) return;
Object.keys(moduleClicks).forEach((clickSelector) => {
const matchingClickedElement = clicked.closest(clickSelector).eq(0);
if (matchingClickedElement.length > 0) {
moduleClicks[clickSelector].call(app, matchingClickedElement, matchingClickedElement.dataset());
}
});
});
// Load Page
let clickedLinkData = {};
if (isLink) {
e.preventDefault();
clickedLinkData = clickedLink.dataset();
}
const validUrl = url && url.length > 0 && url !== '#' && !isTabLink;
const template = clickedLinkData.template;
if (validUrl || clickedLink.hasClass('back') || template) {
let view;
if (clickedLinkData.view) {
view = $(clickedLinkData.view)[0].f7View;
} else {
view = clicked.parents('.view')[0] && clicked.parents('.view')[0].f7View;
if (view && view.params.linksView) {
if (typeof view.params.linksView === 'string') view = $(view.params.linksView)[0].f7View;
else if (view.params.linksView instanceof View) view = view.params.linksView;
}
}
if (!view) {
if (app.views.main) view = app.views.main;
}
if (!view || !view.router) return;
if (clickedLink.hasClass('back')) view.router.back(url, clickedLinkData);
else view.router.navigate(url, clickedLinkData);
}
}
app.on('click', handleClicks);
// Prevent scrolling on overlays
function preventScrolling(e) {
e.preventDefault();
}
if (Support$1.touch && !Device.android) {
const activeListener = Support$1.passiveListener ? { passive: false, capture: false } : false;
$(document).on((app.params.fastClicks ? 'touchstart' : 'touchmove'), '.panel-backdrop, .dialog-backdrop, .preloader-backdrop, .popup-backdrop, .searchbar-backdrop', preventScrolling, activeListener);
}
}
var Clicks = {
name: 'clicks',
params: {
clicks: {
// External Links
externalLinks: '.external',
},
},
on: {
init() {
const app = this;
initClicks(app);
},
},
};
var History$2 = {
name: 'history',
static: {
history: History,
},
on: {
init() {
History.init(this);
},
},
};
const keyPrefix = 'f7storage-';
const Storage = {
get(key) {
return Utils.promise((resolve, reject) => {
try {
const value = JSON.parse(window.localStorage.getItem(`${keyPrefix}${key}`));
resolve(value);
} catch (e) {
reject(e);
}
});
},
set(key, value) {
return Utils.promise((resolve, reject) => {
try {
window.localStorage.setItem(`${keyPrefix}${key}`, JSON.stringify(value));
resolve();
} catch (e) {
reject(e);
}
});
},
remove(key) {
return Utils.promise((resolve, reject) => {
try {
window.localStorage.removeItem(`${keyPrefix}${key}`);
resolve();
} catch (e) {
reject(e);
}
});
},
clear() {
},
length() {
},
keys() {
return Utils.promise((resolve, reject) => {
try {
const keys = Object.keys(window.localStorage)
.filter(keyName => keyName.indexOf(keyPrefix) === 0)
.map(keyName => keyName.replace(keyPrefix, ''));
resolve(keys);
} catch (e) {
reject(e);
}
});
},
forEach(callback) {
return Utils.promise((resolve, reject) => {
try {
Object.keys(window.localStorage)
.filter(keyName => keyName.indexOf(keyPrefix) === 0)
.forEach((keyName, index) => {
const key = keyName.replace(keyPrefix, '');
Storage.get(key).then((value) => {
callback(key, value, index);
});
});
resolve();
} catch (e) {
reject(e);
}
});
},
};
var Storage$1 = {
name: 'storage',
static: {
Storage,
storage: Storage,
},
};
const Statusbar = {
hide() {
$('html').removeClass('with-statusbar');
if (Device.cordova && window.StatusBar) {
window.StatusBar.hide();
}
},
show() {
if (Device.cordova && window.StatusBar) {
window.StatusBar.show();
Utils.nextTick(() => {
if (Device.needsStatusbarOverlay()) {
$('html').addClass('with-statusbar');
}
});
return;
}
$('html').addClass('with-statusbar');
},
onClick() {
const app = this;
let pageContent;
if ($('.popup.modal-in').length > 0) {
// Check for opened popup
pageContent = $('.popup.modal-in').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
} else if ($('.panel.panel-active').length > 0) {
// Check for opened panel
pageContent = $('.panel.panel-active').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
} else if ($('.views > .view.tab-active').length > 0) {
// View in tab bar app layout
pageContent = $('.views > .view.tab-active').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
} else if ($('.views').length > 0) {
pageContent = $('.views').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
} else {
pageContent = app.root.children('.view').find('.page:not(.page-previous):not(.page-next):not(.cached)').find('.page-content');
}
if (pageContent && pageContent.length > 0) {
// Check for tab
if (pageContent.hasClass('tab')) {
pageContent = pageContent.parent('.tabs').children('.page-content.tab-active');
}
if (pageContent.length > 0) pageContent.scrollTop(0, 300);
}
},
setIosTextColor(color) {
if (Device.cordova && window.StatusBar) {
if (color === 'white') {
window.StatusBar.styleLightContent();
} else {
window.StatusBar.styleDefault();
}
}
},
setBackgroundColor(color) {
$('.statusbar').css('background-color', color);
if (Device.cordova && window.StatusBar) {
window.StatusBar.backgroundColorByHexString(color);
}
},
isVisible() {
if (Device.cordova && window.StatusBar) {
return window.StatusBar.isVisible;
}
return false;
},
iosOverlaysWebView(overlays = true) {
if (!Device.ios) return;
if (Device.cordova && window.StatusBar) {
window.StatusBar.overlaysWebView(overlays);
if (overlays) {
$('html').addClass('with-statusbar');
} else {
$('html').removeClass('with-statusbar');
}
}
},
checkOverlay() {
if (Device.needsStatusbarOverlay()) {
$('html').addClass('with-statusbar');
} else {
$('html').removeClass('with-statusbar');
}
},
init() {
const app = this;
const params = app.params.statusbar;
if (params.overlay === 'auto') {
if (Device.needsStatusbarOverlay()) {
$('html').addClass('with-statusbar');
}
if (Device.cordova) {
$(document).on('resume', () => {
Statusbar.checkOverlay();
}, false);
if (Device.iphoneX) {
app.on('orientationchange', () => {
Statusbar.checkOverlay();
});
}
}
} else if (params.overlay === true) {
$('html').addClass('with-statusbar');
} else if (params.overlay === false) {
$('html').removeClass('with-statusbar');
}
if (Device.cordova && window.StatusBar) {
if (params.scrollTopOnClick) {
$(window).on('statusTap', Statusbar.onClick.bind(app));
}
if (params.iosOverlaysWebView) {
window.StatusBar.overlaysWebView(true);
} else {
window.StatusBar.overlaysWebView(false);
}
if (params.iosTextColor === 'white') {
window.StatusBar.styleLightContent();
} else {
window.StatusBar.styleDefault();
}
}
if (params.iosBackgroundColor && app.theme === 'ios') {
Statusbar.setBackgroundColor(params.iosBackgroundColor);
}
if (params.materialBackgroundColor && app.theme === 'md') {
Statusbar.setBackgroundColor(params.materialBackgroundColor);
}
},
};
var Statusbar$1 = {
name: 'statusbar',
params: {
statusbar: {
overlay: 'auto',
scrollTopOnClick: true,
iosOverlaysWebView: true,
iosTextColor: 'black',
iosBackgroundColor: null,
materialBackgroundColor: null,
},
},
create() {
const app = this;
Utils.extend(app, {
statusbar: {
check: Statusbar.check,
hide: Statusbar.hide,
show: Statusbar.show,
iosOverlaysWebView: Statusbar.iosOverlaysWebView,
setIosTextColor: Statusbar.setIosTextColor,
setBackgroundColor: Statusbar.setBackgroundColor,
isVisible: Statusbar.isVisible,
init: Statusbar.init.bind(app),
},
});
},
on: {
init() {
const app = this;
Statusbar.init.call(app);
},
},
clicks: {
'.statusbar': function onStatusbarClick() {
const app = this;
if (!app.params.statusbar.scrollTopOnClick) return;
Statusbar.onClick.call(app);
},
},
};
function getCurrentView(app) {
const popoverView = $('.popover.modal-in .view');
const popupView = $('.popup.modal-in .view');
const panelView = $('.panel.panel-active .view');
let appViews = $('.views');
if (appViews.length === 0) appViews = app.root;
// Find active view as tab
let appView = appViews.children('.view');
// Propably in tabs or split view
if (appView.length > 1) {
if (appView.hasClass('tab')) {
// Tabs
appView = appViews.children('.view.tab-active');
} else {
// Split View, leave appView intact
}
}
if (popoverView.length > 0 && popoverView[0].f7View) return popoverView[0].f7View;
if (popupView.length > 0 && popupView[0].f7View) return popupView[0].f7View;
if (panelView.length > 0 && panelView[0].f7View) return panelView[0].f7View;
if (appView.length > 0) {
if (appView.length === 1 && appView[0].f7View) return appView[0].f7View;
if (appView.length > 1) {
return app.views.main;
}
}
return undefined;
}
var View$2 = {
name: 'view',
params: {
view: {
name: undefined,
main: false,
router: true,
linksView: null,
stackPages: false,
xhrCache: true,
xhrCacheIgnore: [],
xhrCacheIgnoreGetParameters: false,
xhrCacheDuration: 1000 * 60 * 10, // Ten minutes
preloadPreviousPage: true,
uniqueHistory: false,
uniqueHistoryIgnoreGetParameters: false,
allowDuplicateUrls: false,
reloadPages: false,
removeElements: true,
removeElementsWithTimeout: false,
removeElementsTimeout: 0,
restoreScrollTopOnBack: true,
unloadTabContent: true,
// Swipe Back
iosSwipeBack: true,
iosSwipeBackAnimateShadow: true,
iosSwipeBackAnimateOpacity: true,
iosSwipeBackActiveArea: 30,
iosSwipeBackThreshold: 0,
// Push State
pushState: false,
pushStateRoot: undefined,
pushStateAnimate: true,
pushStateAnimateOnLoad: false,
pushStateSeparator: '#!',
pushStateOnLoad: true,
// Animate Pages
animate: true,
animateWithJS: false,
// iOS Dynamic Navbar
iosDynamicNavbar: true,
iosSeparateDynamicNavbar: true,
// Animate iOS Navbar Back Icon
iosAnimateNavbarBackIcon: true,
// Delays
iosPageLoadDelay: 0,
materialPageLoadDelay: 0,
},
},
static: {
View,
},
create() {
const app = this;
Utils.extend(app, {
views: Utils.extend([], {
create(el, params) {
return new View(app, el, params);
},
get(viewEl) {
const $viewEl = $(viewEl);
if ($viewEl.length && $viewEl[0].f7View) return $viewEl[0].f7View;
return undefined;
},
}),
});
Object.defineProperty(app.views, 'current', {
enumerable: true,
configurable: true,
get() {
return getCurrentView(app);
},
});
// Alias
app.view = app.views;
},
on: {
init() {
const app = this;
$('.view-init').each((index, viewEl) => {
if (viewEl.f7View) return;
const viewParams = $(viewEl).dataset();
app.views.create(viewEl, viewParams);
});
},
modalOpen(modal) {
const app = this;
modal.$el.find('.view-init').each((index, viewEl) => {
if (viewEl.f7View) return;
const viewParams = $(viewEl).dataset();
app.views.create(viewEl, viewParams);
});
},
modalBeforeDestroy(modal) {
if (!modal || !modal.$el) return;
modal.$el.find('.view-init').each((index, viewEl) => {
const view = viewEl.f7View;
if (!view) return;
view.destroy();
});
},
},
};
const Navbar = {
size(el) {
const app = this;
if (app.theme !== 'ios') return;
let $el = $(el);
if ($el.hasClass('navbar')) {
$el = $el.children('.navbar-inner').each((index, navbarEl) => {
app.navbar.size(navbarEl);
});
return;
}
if (
$el.hasClass('stacked') ||
$el.parents('.stacked').length > 0 ||
$el.parents('.tab:not(.tab-active)').length > 0 ||
$el.parents('.popup:not(.modal-in)').length > 0
) {
return;
}
const $viewEl = $el.parents('.view').eq(0);
const left = app.rtl ? $el.children('.right') : $el.children('.left');
const right = app.rtl ? $el.children('.left') : $el.children('.right');
const title = $el.children('.title');
const subnavbar = $el.children('.subnavbar');
const noLeft = left.length === 0;
const noRight = right.length === 0;
const leftWidth = noLeft ? 0 : left.outerWidth(true);
const rightWidth = noRight ? 0 : right.outerWidth(true);
const titleWidth = title.outerWidth(true);
const navbarStyles = $el.styles();
const navbarWidth = $el[0].offsetWidth;
const navbarInnerWidth = navbarWidth - parseInt(navbarStyles.paddingLeft, 10) - parseInt(navbarStyles.paddingRight, 10);
const isPrevious = $el.hasClass('navbar-previous');
const sliding = $el.hasClass('sliding');
let router;
let dynamicNavbar;
let separateNavbar;
let separateNavbarRightOffset = 0;
let separateNavbarLeftOffset = 0;
if ($viewEl.length > 0 && $viewEl[0].f7View) {
router = $viewEl[0].f7View.router;
dynamicNavbar = router && router.dynamicNavbar;
separateNavbar = router && router.separateNavbar;
if (!separateNavbar) {
separateNavbarRightOffset = navbarWidth;
separateNavbarLeftOffset = navbarWidth / 5;
}
}
let currLeft;
let diff;
if (noRight) {
currLeft = navbarInnerWidth - titleWidth;
}
if (noLeft) {
currLeft = 0;
}
if (!noLeft && !noRight) {
currLeft = ((navbarInnerWidth - rightWidth - titleWidth) + leftWidth) / 2;
}
let requiredLeft = (navbarInnerWidth - titleWidth) / 2;
if (navbarInnerWidth - leftWidth - rightWidth > titleWidth) {
if (requiredLeft < leftWidth) {
requiredLeft = leftWidth;
}
if (requiredLeft + titleWidth > navbarInnerWidth - rightWidth) {
requiredLeft = navbarInnerWidth - rightWidth - titleWidth;
}
diff = requiredLeft - currLeft;
} else {
diff = 0;
}
// RTL inverter
const inverter = app.rtl ? -1 : 1;
if (dynamicNavbar) {
if (title.hasClass('sliding') || (title.length > 0 && sliding)) {
let titleLeftOffset = (-(currLeft + diff) * inverter) + separateNavbarLeftOffset;
const titleRightOffset = ((navbarInnerWidth - currLeft - diff - titleWidth) * inverter) - separateNavbarRightOffset;
if (isPrevious) {
if (router && router.params.iosAnimateNavbarBackIcon) {
const activeNavbarBackLink = $el.parent().find('.navbar-current').children('.left.sliding').find('.back .icon ~ span');
if (activeNavbarBackLink.length > 0) {
titleLeftOffset += activeNavbarBackLink[0].offsetLeft;
}
}
}
title[0].f7NavbarLeftOffset = titleLeftOffset;
title[0].f7NavbarRightOffset = titleRightOffset;
}
if (!noLeft && (left.hasClass('sliding') || sliding)) {
if (app.rtl) {
left[0].f7NavbarLeftOffset = (-(navbarInnerWidth - left[0].offsetWidth) / 2) * inverter;
left[0].f7NavbarRightOffset = leftWidth * inverter;
} else {
left[0].f7NavbarLeftOffset = -leftWidth + separateNavbarLeftOffset;
left[0].f7NavbarRightOffset = ((navbarInnerWidth - left[0].offsetWidth) / 2) - separateNavbarRightOffset;
if (router && router.params.iosAnimateNavbarBackIcon && left.find('.back .icon').length > 0) {
left[0].f7NavbarRightOffset -= left.find('.back .icon')[0].offsetWidth;
}
}
}
if (!noRight && (right.hasClass('sliding') || sliding)) {
if (app.rtl) {
right[0].f7NavbarLeftOffset = -rightWidth * inverter;
right[0].f7NavbarRightOffset = ((navbarInnerWidth - right[0].offsetWidth) / 2) * inverter;
} else {
right[0].f7NavbarLeftOffset = (-(navbarInnerWidth - right[0].offsetWidth) / 2) + separateNavbarLeftOffset;
right[0].f7NavbarRightOffset = rightWidth - separateNavbarRightOffset;
}
}
if (subnavbar.length && (subnavbar.hasClass('sliding') || sliding)) {
subnavbar[0].f7NavbarLeftOffset = app.rtl ? subnavbar[0].offsetWidth : (-subnavbar[0].offsetWidth + separateNavbarLeftOffset);
subnavbar[0].f7NavbarRightOffset = (-subnavbar[0].f7NavbarLeftOffset - separateNavbarRightOffset) + separateNavbarLeftOffset;
}
}
// Title left
if (app.params.navbar.iosCenterTitle) {
let titleLeft = diff;
if (app.rtl && noLeft && noRight && title.length > 0) titleLeft = -titleLeft;
title.css({ left: `${titleLeft}px` });
}
},
hide(el, animate = true) {
let $el = $(el);
if ($el.hasClass('navbar-inner')) $el = $el.parents('.navbar');
if (!$el.length) return;
if ($el.hasClass('navbar-hidden')) return;
const className = `navbar-hidden${animate ? ' navbar-transitioning' : ''}`;
$el.transitionEnd(() => {
$el.removeClass('navbar-transitioning');
});
$el.addClass(className);
},
show(el = '.navbar-hidden', animate = true) {
let $el = $(el);
if ($el.hasClass('navbar-inner')) $el = $el.parents('.navbar');
if (!$el.length) return;
if (!$el.hasClass('navbar-hidden')) return;
if (animate) {
$el.addClass('navbar-transitioning');
$el.transitionEnd(() => {
$el.removeClass('navbar-transitioning');
});
}
$el.removeClass('navbar-hidden');
},
getElByPage(page) {
let $pageEl;
let $navbarEl;
let pageData;
if (page.$navbarEl || page.$el) {
pageData = page;
$pageEl = page.$el;
} else {
$pageEl = $(page);
if ($pageEl.length > 0) pageData = $pageEl[0].f7Page;
}
if (pageData && pageData.$navbarEl && pageData.$navbarEl.length > 0) {
$navbarEl = pageData.$navbarEl;
} else if ($pageEl) {
$navbarEl = $pageEl.children('.navbar').children('.navbar-inner');
}
if (!$navbarEl || ($navbarEl && $navbarEl.length === 0)) return undefined;
return $navbarEl[0];
},
getPageByEl(navbarInnerEl) {
let $navbarInnerEl = $(navbarInnerEl);
if ($navbarInnerEl.hasClass('navbar')) {
$navbarInnerEl = $navbarInnerEl.find('.navbar-inner');
if ($navbarInnerEl.length > 1) return undefined;
}
return $navbarInnerEl[0].f7Page;
},
initHideNavbarOnScroll(pageEl, navbarInnerEl) {
const app = this;
const $pageEl = $(pageEl);
const $navbarEl = $(navbarInnerEl || app.navbar.getElByPage(pageEl)).closest('.navbar');
let previousScrollTop;
let currentScrollTop;
let scrollHeight;
let offsetHeight;
let reachEnd;
let action;
let navbarHidden;
function handleScroll() {
const scrollContent = this;
if ($pageEl.hasClass('page-previous')) return;
currentScrollTop = scrollContent.scrollTop;
scrollHeight = scrollContent.scrollHeight;
offsetHeight = scrollContent.offsetHeight;
reachEnd = currentScrollTop + offsetHeight >= scrollHeight;
navbarHidden = $navbarEl.hasClass('navbar-hidden');
if (reachEnd) {
if (app.params.navbar.showOnPageScrollEnd) {
action = 'show';
}
} else if (previousScrollTop > currentScrollTop) {
if (app.params.navbar.showOnPageScrollTop || currentScrollTop <= 44) {
action = 'show';
} else {
action = 'hide';
}
} else if (currentScrollTop > 44) {
action = 'hide';
} else {
action = 'show';
}
if (action === 'show' && navbarHidden) {
app.navbar.show($navbarEl);
navbarHidden = false;
} else if (action === 'hide' && !navbarHidden) {
app.navbar.hide($navbarEl);
navbarHidden = true;
}
previousScrollTop = currentScrollTop;
}
$pageEl.on('scroll', '.page-content', handleScroll, true);
$pageEl[0].f7ScrollNavbarHandler = handleScroll;
},
};
var Navbar$1 = {
name: 'navbar',
create() {
const app = this;
Utils.extend(app, {
navbar: {
size: Navbar.size.bind(app),
hide: Navbar.hide.bind(app),
show: Navbar.show.bind(app),
getElByPage: Navbar.getElByPage.bind(app),
initHideNavbarOnScroll: Navbar.initHideNavbarOnScroll.bind(app),
},
});
},
params: {
navbar: {
scrollTopOnTitleClick: true,
iosCenterTitle: true,
hideOnPageScroll: false,
showOnPageScrollEnd: true,
showOnPageScrollTop: true,
},
},
on: {
'panelBreakpoint resize': function onResize() {
const app = this;
if (app.theme !== 'ios') return;
$('.navbar').each((index, navbarEl) => {
app.navbar.size(navbarEl);
});
},
pageBeforeRemove(page) {
if (page.$el[0].f7ScrollNavbarHandler) {
page.$el.off('scroll', '.page-content', page.$el[0].f7ScrollNavbarHandler, true);
}
},
pageBeforeIn(page) {
const app = this;
if (app.theme !== 'ios') return;
let $navbarEl;
const view = page.$el.parents('.view')[0].f7View;
const navbarInnerEl = app.navbar.getElByPage(page);
if (!navbarInnerEl) {
$navbarEl = page.$el.parents('.view').children('.navbar');
} else {
$navbarEl = $(navbarInnerEl).parents('.navbar');
}
if (page.$el.hasClass('no-navbar') || (view.router.dynamicNavbar && !navbarInnerEl)) {
const animate = !!(page.pageFrom && page.router.history.length > 0);
app.navbar.hide($navbarEl, animate);
} else {
app.navbar.show($navbarEl);
}
},
pageReinit(page) {
const app = this;
if (app.theme !== 'ios') return;
const $navbarEl = $(app.navbar.getElByPage(page));
if (!$navbarEl || $navbarEl.length === 0) return;
app.navbar.size($navbarEl);
},
pageInit(page) {
const app = this;
const $navbarEl = $(app.navbar.getElByPage(page));
if (!$navbarEl || $navbarEl.length === 0) return;
if (app.theme === 'ios') {
app.navbar.size($navbarEl);
}
if (app.params.navbar.hideOnPageScroll || page.$el.find('.hide-navbar-on-scroll').length || page.$el.hasClass('hide-navbar-on-scroll') || page.$el.find('.hide-bars-on-scroll').length) {
if (page.$el.find('.keep-navbar-on-scroll').length || page.$el.find('.keep-bars-on-scroll').length) return;
app.navbar.initHideNavbarOnScroll(page.el, $navbarEl[0]);
}
},
modalOpen(modal) {
const app = this;
if (app.theme !== 'ios') return;
modal.$el.find('.navbar:not(.navbar-previous):not(.stacked)').each((index, navbarEl) => {
app.navbar.size(navbarEl);
});
},
panelOpen(panel) {
const app = this;
if (app.theme !== 'ios') return;
panel.$el.find('.navbar:not(.navbar-previous):not(.stacked)').each((index, navbarEl) => {
app.navbar.size(navbarEl);
});
},
panelSwipeOpen(panel) {
const app = this;
if (app.theme !== 'ios') return;
panel.$el.find('.navbar:not(.navbar-previous):not(.stacked)').each((index, navbarEl) => {
app.navbar.size(navbarEl);
});
},
tabShow(tabEl) {
const app = this;
$(tabEl).find('.navbar:not(.navbar-previous):not(.stacked)').each((index, navbarEl) => {
app.navbar.size(navbarEl);
});
},
},
clicks: {
'.navbar .title': function onTitleClick($clickedEl) {
const app = this;
if (!app.params.navbar.scrollTopOnTitleClick) return;
if ($clickedEl.closest('a').length > 0) {
return;
}
let pageContent;
// Find active page
const navbar = $clickedEl.parents('.navbar');
// Static Layout
pageContent = navbar.parents('.page-content');
if (pageContent.length === 0) {
// Fixed Layout
if (navbar.parents('.page').length > 0) {
pageContent = navbar.parents('.page').find('.page-content');
}
// Through Layout
if (pageContent.length === 0) {
if (navbar.nextAll('.page-current:not(.stacked)').length > 0) {
pageContent = navbar.nextAll('.page-current:not(.stacked)').find('.page-content');
}
}
}
if (pageContent && pageContent.length > 0) {
// Check for tab
if (pageContent.hasClass('tab')) {
pageContent = pageContent.parent('.tabs').children('.page-content.tab-active');
}
if (pageContent.length > 0) pageContent.scrollTop(0, 300);
}
},
},
};
const Toolbar = {
setHighlight(tabbarEl) {
const app = this;
if (app.theme !== 'md') return;
const $tabbarEl = $(tabbarEl);
if ($tabbarEl.length === 0 || !($tabbarEl.hasClass('tabbar') || $tabbarEl.hasClass('tabbar-labels'))) return;
if ($tabbarEl.find('.tab-link-highlight').length === 0) {
$tabbarEl.children('.toolbar-inner').append('<span class="tab-link-highlight"></span>');
}
const $highlightEl = $tabbarEl.find('.tab-link-highlight');
const $activeLink = $tabbarEl.find('.tab-link-active');
let highlightWidth;
let highlightTranslate;
if ($tabbarEl.hasClass('tabbar-scrollable')) {
highlightWidth = `${$activeLink[0].offsetWidth}px`;
highlightTranslate = `${$activeLink[0].offsetLeft}px`;
} else {
const activeIndex = $activeLink.index();
const tabLinksCount = $tabbarEl.find('.tab-link').length;
highlightWidth = `${100 / tabLinksCount}%`;
highlightTranslate = `${(app.rtl ? -activeIndex : activeIndex) * 100}%`;
}
$highlightEl
.css('width', highlightWidth)
.transform(`translate3d(${highlightTranslate},0,0)`);
},
init(tabbarEl) {
const app = this;
app.toolbar.setHighlight(tabbarEl);
},
hide(el, animate = true) {
const $el = $(el);
if ($el.hasClass('toolbar-hidden')) return;
const className = `toolbar-hidden${animate ? ' toolbar-transitioning' : ''}`;
$el.transitionEnd(() => {
$el.removeClass('toolbar-transitioning');
});
$el.addClass(className);
},
show(el, animate = true) {
const $el = $(el);
if (!$el.hasClass('toolbar-hidden')) return;
if (animate) {
$el.addClass('toolbar-transitioning');
$el.transitionEnd(() => {
$el.removeClass('toolbar-transitioning');
});
}
$el.removeClass('toolbar-hidden');
},
initHideToolbarOnScroll(pageEl) {
const app = this;
const $pageEl = $(pageEl);
let $toolbarEl = $pageEl.parents('.view').children('.toolbar');
if ($toolbarEl.length === 0) {
$toolbarEl = $pageEl.find('.toolbar');
}
if ($toolbarEl.length === 0) {
return;
}
let previousScrollTop;
let currentScrollTop;
let scrollHeight;
let offsetHeight;
let reachEnd;
let action;
let toolbarHidden;
function handleScroll() {
const scrollContent = this;
if ($pageEl.hasClass('page-previous')) return;
currentScrollTop = scrollContent.scrollTop;
scrollHeight = scrollContent.scrollHeight;
offsetHeight = scrollContent.offsetHeight;
reachEnd = currentScrollTop + offsetHeight >= scrollHeight;
toolbarHidden = $toolbarEl.hasClass('toolbar-hidden');
if (reachEnd) {
if (app.params.toolbar.showOnPageScrollEnd) {
action = 'show';
}
} else if (previousScrollTop > currentScrollTop) {
if (app.params.toolbar.showOnPageScrollTop || currentScrollTop <= 44) {
action = 'show';
} else {
action = 'hide';
}
} else if (currentScrollTop > 44) {
action = 'hide';
} else {
action = 'show';
}
if (action === 'show' && toolbarHidden) {
app.toolbar.show($toolbarEl);
toolbarHidden = false;
} else if (action === 'hide' && !toolbarHidden) {
app.toolbar.hide($toolbarEl);
toolbarHidden = true;
}
previousScrollTop = currentScrollTop;
}
$pageEl.on('scroll', '.page-content', handleScroll, true);
$pageEl[0].f7ScrollToolbarHandler = handleScroll;
},
};
var Toolbar$1 = {
name: 'toolbar',
create() {
const app = this;
Utils.extend(app, {
toolbar: {
hide: Toolbar.hide.bind(app),
show: Toolbar.show.bind(app),
setHighlight: Toolbar.setHighlight.bind(app),
initHideToolbarOnScroll: Toolbar.initHideToolbarOnScroll.bind(app),
init: Toolbar.init.bind(app),
},
});
},
params: {
toolbar: {
hideOnPageScroll: false,
showOnPageScrollEnd: true,
showOnPageScrollTop: true,
},
},
on: {
pageBeforeRemove(page) {
if (page.$el[0].f7ScrollToolbarHandler) {
page.$el.off('scroll', '.page-content', page.$el[0].f7ScrollToolbarHandler, true);
}
},
pageBeforeIn(page) {
const app = this;
if (app.theme !== 'ios') return;
let $toolbarEl = page.$el.parents('.view').children('.toolbar');
if ($toolbarEl.length === 0) {
$toolbarEl = page.$el.find('.toolbar');
}
if ($toolbarEl.length === 0) {
return;
}
if (page.$el.hasClass('no-toolbar')) {
app.toolbar.hide($toolbarEl);
} else {
app.toolbar.show($toolbarEl);
}
},
pageInit(page) {
const app = this;
page.$el.find('.tabbar, .tabbar-labels').each((index, tabbarEl) => {
app.toolbar.init(tabbarEl);
});
if (app.params.toolbar.hideOnPageScroll || page.$el.find('.hide-toolbar-on-scroll').length || page.$el.hasClass('hide-toolbar-on-scroll') || page.$el.find('.hide-bars-on-scroll').length) {
if (page.$el.find('.keep-toolbar-on-scroll').length || page.$el.find('.keep-bars-on-scroll').length) return;
app.toolbar.initHideToolbarOnScroll(page.el);
}
},
init() {
const app = this;
app.root.find('.tabbar, .tabbar-labels').each((index, tabbarEl) => {
app.toolbar.init(tabbarEl);
});
},
},
};
var Subnavbar = {
name: 'subnavbar',
on: {
pageInit(page) {
if (page.$navbarEl && page.$navbarEl.length && page.$navbarEl.find('.subnavbar').length) {
page.$el.addClass('page-with-subnavbar');
}
if (page.$el.find('.subnavbar').length) {
page.$el.addClass('page-with-subnavbar');
}
},
},
};
class TouchRipple$1 {
constructor($el, x, y) {
const ripple = this;
if (!$el) return undefined;
const box = $el[0].getBoundingClientRect();
const center = {
x: x - box.left,
y: y - box.top,
};
const width = box.width;
const height = box.height;
const diameter = Math.max((((height ** 2) + (width ** 2)) ** 0.5), 48);
ripple.$rippleWaveEl = $(`<div class="ripple-wave" style="width: ${diameter}px; height: ${diameter}px; margin-top:-${diameter / 2}px; margin-left:-${diameter / 2}px; left:${center.x}px; top:${center.y}px;"></div>`);
$el.prepend(ripple.$rippleWaveEl);
/* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
ripple._clientLeft = ripple.$rippleWaveEl[0].clientLeft;
ripple.rippleTransform = `translate3d(${-center.x + (width / 2)}px, ${-center.y + (height / 2)}px, 0) scale(1)`;
ripple.$rippleWaveEl.transform(ripple.rippleTransform);
return ripple;
}
onRemove() {
let ripple = this;
ripple.$rippleWaveEl.remove();
Object.keys(ripple).forEach((key) => {
ripple[key] = null;
delete ripple[key];
});
ripple = null;
}
remove() {
const ripple = this;
if (ripple.removing) return;
const $rippleWaveEl = this.$rippleWaveEl;
const rippleTransform = this.rippleTransform;
let removeTimeout = Utils.nextTick(() => {
ripple.onRemove();
}, 400);
ripple.removing = true;
$rippleWaveEl
.addClass('ripple-wave-fill')
.transform(rippleTransform.replace('scale(1)', 'scale(1.01)'))
.transitionEnd(() => {
clearTimeout(removeTimeout);
Utils.nextFrame(() => {
$rippleWaveEl
.addClass('ripple-wave-out')
.transform(rippleTransform.replace('scale(1)', 'scale(1.01)'));
removeTimeout = Utils.nextTick(() => {
ripple.onRemove();
}, 700);
$rippleWaveEl.transitionEnd(() => {
clearTimeout(removeTimeout);
ripple.onRemove();
});
});
});
}
}
var TouchRipple$$1 = {
name: 'touch-ripple',
static: {
TouchRipple: TouchRipple$1,
},
create() {
const app = this;
app.touchRipple = {
create(...args) {
return new TouchRipple$1(...args);
},
};
},
};
const openedModals = [];
const dialogsQueue = [];
function clearDialogsQueue() {
if (dialogsQueue.length === 0) return;
const dialog = dialogsQueue.shift();
dialog.open();
}
class Modal$1 extends Framework7Class {
constructor(app, params) {
super(params, [app]);
const modal = this;
const defaults = {};
// Extend defaults with modules params
modal.useModulesParams(defaults);
modal.params = Utils.extend(defaults, params);
// Install Modules
modal.useModules();
return this;
}
onOpen() {
const modal = this;
openedModals.push(modal);
$('html').addClass(`with-modal-${modal.type.toLowerCase()}`);
modal.$el.trigger(`modal:open ${modal.type.toLowerCase()}:open`, modal);
modal.emit(`local::open modalOpen ${modal.type}Open`, modal);
}
onOpened() {
const modal = this;
modal.$el.trigger(`modal:opened ${modal.type.toLowerCase()}:opened`, modal);
modal.emit(`local::opened modalOpened ${modal.type}Opened`, modal);
}
onClose() {
const modal = this;
if (!modal.type || !modal.$el) return;
openedModals.splice(openedModals.indexOf(modal), 1);
$('html').removeClass(`with-modal-${modal.type.toLowerCase()}`);
modal.$el.trigger(`modal:close ${modal.type.toLowerCase()}:close`, modal);
modal.emit(`local::close modalClose ${modal.type}Close`, modal);
}
onClosed() {
const modal = this;
if (!modal.type || !modal.$el) return;
modal.$el.removeClass('modal-out');
modal.$el.hide();
modal.$el.trigger(`modal:closed ${modal.type.toLowerCase()}:closed`, modal);
modal.emit(`local::closed modalClosed ${modal.type}Closed`, modal);
}
open(animateModal) {
const modal = this;
const app = modal.app;
const $el = modal.$el;
const $backdropEl = modal.$backdropEl;
const type = modal.type;
let animate = true;
if (typeof animateModal !== 'undefined') animate = animateModal;
else if (typeof modal.params.animate !== 'undefined') {
animate = modal.params.animate;
}
if (!$el || $el.hasClass('modal-in')) {
return modal;
}
if (type === 'dialog' && app.params.modal.queueDialogs) {
let pushToQueue;
if ($('.dialog.modal-in').length > 0) {
pushToQueue = true;
} else if (openedModals.length > 0) {
openedModals.forEach((openedModal) => {
if (openedModal.type === 'dialog') pushToQueue = true;
});
}
if (pushToQueue) {
dialogsQueue.push(modal);
return modal;
}
}
const $modalParentEl = $el.parent();
const wasInDom = $el.parents(document).length > 0;
if (app.params.modal.moveToRoot && !$modalParentEl.is(app.root)) {
app.root.append($el);
modal.once(`${type}Closed`, () => {
if (wasInDom) {
$modalParentEl.append($el);
} else {
$el.remove();
}
});
}
// Show Modal
$el.show();
// Set Dialog offset
if (type === 'dialog') {
$el.css({
marginTop: `${-Math.round($el.outerHeight() / 2)}px`,
});
}
// Emit open
/* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
modal._clientLeft = $el[0].clientLeft;
// Backdrop
if ($backdropEl) {
$backdropEl[animate ? 'removeClass' : 'addClass']('not-animated');
$backdropEl.addClass('backdrop-in');
}
// Modal
function transitionEnd() {
if ($el.hasClass('modal-out')) {
modal.onClosed();
} else {
modal.onOpened();
}
}
if (animate) {
$el
.animationEnd(() => {
transitionEnd();
});
$el
.transitionEnd(() => {
transitionEnd();
});
$el
.removeClass('modal-out not-animated')
.addClass('modal-in');
modal.onOpen();
} else {
$el.removeClass('modal-out').addClass('modal-in not-animated');
modal.onOpen();
modal.onOpened();
}
return modal;
}
close(animateModal) {
const modal = this;
const $el = modal.$el;
const $backdropEl = modal.$backdropEl;
let animate = true;
if (typeof animateModal !== 'undefined') animate = animateModal;
else if (typeof modal.params.animate !== 'undefined') {
animate = modal.params.animate;
}
if (!$el || !$el.hasClass('modal-in')) {
return modal;
}
// backdrop
if ($backdropEl) {
$backdropEl[animate ? 'removeClass' : 'addClass']('not-animated');
$backdropEl.removeClass('backdrop-in');
}
// Modal
$el[animate ? 'removeClass' : 'addClass']('not-animated');
function transitionEnd() {
if ($el.hasClass('modal-out')) {
modal.onClosed();
} else {
modal.onOpened();
}
}
if (animate) {
$el
.animationEnd(() => {
transitionEnd();
});
$el
.transitionEnd(() => {
transitionEnd();
});
$el
.removeClass('modal-in')
.addClass('modal-out');
// Emit close
modal.onClose();
} else {
$el
.addClass('not-animated')
.removeClass('modal-in')
.addClass('modal-out');
// Emit close
modal.onClose();
modal.onClosed();
}
if (modal.type === 'dialog') {
clearDialogsQueue();
}
return modal;
}
destroy() {
const modal = this;
if (modal.destroyed) return;
modal.emit(`local::beforeDestroy modalBeforeDestroy ${modal.type}BeforeDestroy`, modal);
if (modal.$el) {
modal.$el.trigger(`modal:beforedestroy ${modal.type.toLowerCase()}:beforedestroy`, modal);
if (modal.$el.length && modal.$el[0].f7Modal) {
delete modal.$el[0].f7Modal;
}
}
Utils.deleteProps(modal);
modal.destroyed = true;
}
}
class CustomModal extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend({
backdrop: true,
closeByBackdropClick: true,
on: {},
}, params);
// Extends with open/close Modal methods;
super(app, extendedParams);
const customModal = this;
customModal.params = extendedParams;
// Find Element
let $el;
if (!customModal.params.el) {
$el = $(customModal.params.content);
} else {
$el = $(customModal.params.el);
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
if ($el.length === 0) {
return customModal.destroy();
}
let $backdropEl;
if (customModal.params.backdrop) {
$backdropEl = app.root.children('.custom-modal-backdrop');
if ($backdropEl.length === 0) {
$backdropEl = $('<div class="custom-modal-backdrop"></div>');
app.root.append($backdropEl);
}
}
function handleClick(e) {
if (!customModal || customModal.destroyed) return;
if ($backdropEl && e.target === $backdropEl[0]) {
customModal.close();
}
}
customModal.on('customModalOpened', () => {
if (customModal.params.closeByBackdropClick && customModal.params.backdrop) {
app.on('click', handleClick);
}
});
customModal.on('customModalClose', () => {
if (customModal.params.closeByBackdropClick && customModal.params.backdrop) {
app.off('click', handleClick);
}
});
Utils.extend(customModal, {
app,
$el,
el: $el[0],
$backdropEl,
backdropEl: $backdropEl && $backdropEl[0],
type: 'customModal',
});
$el[0].f7Modal = customModal;
return customModal;
}
}
var Modal = {
name: 'modal',
static: {
Modal: Modal$1,
CustomModal,
},
create() {
const app = this;
app.customModal = {
create(params) {
return new CustomModal(app, params);
},
};
},
params: {
modal: {
moveToRoot: true,
queueDialogs: true,
},
},
};
class Dialog$1 extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend({
title: app.params.dialog.title,
text: undefined,
content: '',
buttons: [],
verticalButtons: false,
onClick: undefined,
cssClass: undefined,
on: {},
}, params);
// Extends with open/close Modal methods;
super(app, extendedParams);
const dialog = this;
const { title, text, content, buttons, verticalButtons, cssClass } = extendedParams;
dialog.params = extendedParams;
// Find Element
let $el;
if (!dialog.params.el) {
const dialogClasses = ['dialog'];
if (buttons.length === 0) dialogClasses.push('dialog-no-buttons');
if (buttons.length > 0) dialogClasses.push(`dialog-buttons-${buttons.length}`);
if (verticalButtons) dialogClasses.push('dialog-buttons-vertical');
if (cssClass) dialogClasses.push(cssClass);
let buttonsHTML = '';
if (buttons.length > 0) {
buttonsHTML = `
<div class="dialog-buttons">
${buttons.map(button => `
<span class="dialog-button${button.bold ? ' dialog-button-bold' : ''}${button.color ? ` color-${button.color}` : ''}${button.cssClass ? ` ${button.cssClass}` : ''}">${button.text}</span>
`).join('')}
</div>
`;
}
const dialogHtml = `
<div class="${dialogClasses.join(' ')}">
<div class="dialog-inner">
${title ? `<div class="dialog-title">${title}</div>` : ''}
${text ? `<div class="dialog-text">${text}</div>` : ''}
${content}
</div>
${buttonsHTML}
</div>
`;
$el = $(dialogHtml);
} else {
$el = $(dialog.params.el);
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
if ($el.length === 0) {
return dialog.destroy();
}
let $backdropEl = app.root.children('.dialog-backdrop');
if ($backdropEl.length === 0) {
$backdropEl = $('<div class="dialog-backdrop"></div>');
app.root.append($backdropEl);
}
// Assign events
function buttonOnClick(e) {
const buttonEl = this;
const index = $(buttonEl).index();
const button = buttons[index];
if (button.onClick) button.onClick(dialog, e);
if (dialog.params.onClick) dialog.params.onClick(dialog, index);
if (button.close !== false) dialog.close();
}
if (buttons && buttons.length > 0) {
$el.find('.dialog-button').each((index, buttonEl) => {
$(buttonEl).on('click', buttonOnClick);
});
dialog.on('close', () => {
$el.find('.dialog-button').each((index, buttonEl) => {
$(buttonEl).off('click', buttonOnClick);
});
});
}
Utils.extend(dialog, {
app,
$el,
el: $el[0],
$backdropEl,
backdropEl: $backdropEl[0],
type: 'dialog',
setProgress(progress, duration) {
app.progressbar.set($el.find('.progressbar'), progress, duration);
return dialog;
},
setText(newText) {
let $textEl = $el.find('.dialog-text');
if ($textEl.length === 0) {
$textEl = $('<div class="dialog-text"></div>');
if (typeof title !== 'undefined') {
$textEl.insertAfter($el.find('.dialog-title'));
} else {
$el.find('.dialog-inner').prepend($textEl);
}
}
$textEl.html(newText);
dialog.params.text = newText;
return dialog;
},
setTitle(newTitle) {
let $titleEl = $el.find('.dialog-title');
if ($titleEl.length === 0) {
$titleEl = $('<div class="dialog-title"></div>');
$el.find('.dialog-inner').prepend($titleEl);
}
$titleEl.html(newTitle);
dialog.params.title = newTitle;
return dialog;
},
});
$el[0].f7Modal = dialog;
return dialog;
}
}
var ConstructorMethods = function (parameters = {}) {
const {
defaultSelector,
constructor,
domProp,
app,
addMethods,
} = parameters;
const methods = {
create(...args) {
if (app) return new constructor(app, ...args);
return new constructor(...args);
},
get(el = defaultSelector) {
if (el instanceof constructor) return el;
const $el = $(el);
if ($el.length === 0) return undefined;
return $el[0][domProp];
},
destroy(el) {
const instance = methods.get(el);
if (instance && instance.destroy) return instance.destroy();
return undefined;
},
};
if (addMethods && Array.isArray(addMethods)) {
addMethods.forEach((methodName) => {
methods[methodName] = (el = defaultSelector, ...args) => {
const instance = methods.get(el);
if (instance && instance[methodName]) return instance[methodName](...args);
return undefined;
};
});
}
return methods;
};
var ModalMethods = function (parameters = {}) {
const { defaultSelector, constructor, app } = parameters;
const methods = Utils.extend(
ConstructorMethods({
defaultSelector,
constructor,
app,
domProp: 'f7Modal',
}),
{
open(el, animate) {
const $el = $(el);
let instance = $el[0].f7Modal;
if (!instance) instance = new constructor(app, { el: $el });
return instance.open(animate);
},
close(el = defaultSelector, animate) {
const $el = $(el);
if ($el.length === 0) return undefined;
let instance = $el[0].f7Modal;
if (!instance) instance = new constructor(app, { el: $el });
return instance.close(animate);
},
}
);
return methods;
};
var Dialog = {
name: 'dialog',
params: {
dialog: {
title: undefined,
buttonOk: 'OK',
buttonCancel: 'Cancel',
usernamePlaceholder: 'Username',
passwordPlaceholder: 'Password',
preloaderTitle: 'Loading... ',
progressTitle: 'Loading... ',
closeByBackdropClick: false,
},
},
static: {
Dialog: Dialog$1,
},
create() {
const app = this;
const defaultDialogTitle = app.params.dialog.title || app.name;
app.dialog = Utils.extend(
ModalMethods({
app,
constructor: Dialog$1,
defaultSelector: '.dialog.modal-in',
}),
{
// Shortcuts
alert(...args) {
let [text, title, callbackOk] = args;
if (args.length === 2 && typeof args[1] === 'function') {
[text, callbackOk, title] = args;
}
return new Dialog$1(app, {
title: typeof title === 'undefined' ? defaultDialogTitle : title,
text,
buttons: [{
text: app.params.dialog.buttonOk,
bold: true,
onClick: callbackOk,
}],
}).open();
},
prompt(...args) {
let [text, title, callbackOk, callbackCancel] = args;
if (typeof args[1] === 'function') {
[text, callbackOk, callbackCancel, title] = args;
}
return new Dialog$1(app, {
title: typeof title === 'undefined' ? defaultDialogTitle : title,
text,
content: '<div class="dialog-input-field item-input"><div class="item-input-wrap"><input type="text" class="dialog-input"></div></div>',
buttons: [
{
text: app.params.dialog.buttonCancel,
},
{
text: app.params.dialog.buttonOk,
bold: true,
},
],
onClick(dialog, index) {
const inputValue = dialog.$el.find('.dialog-input').val();
if (index === 0 && callbackCancel) callbackCancel(inputValue);
if (index === 1 && callbackOk) callbackOk(inputValue);
},
}).open();
},
confirm(...args) {
let [text, title, callbackOk, callbackCancel] = args;
if (typeof args[1] === 'function') {
[text, callbackOk, callbackCancel, title] = args;
}
return new Dialog$1(app, {
title: typeof title === 'undefined' ? defaultDialogTitle : title,
text,
buttons: [
{
text: app.params.dialog.buttonCancel,
onClick: callbackCancel,
},
{
text: app.params.dialog.buttonOk,
bold: true,
onClick: callbackOk,
},
],
}).open();
},
login(...args) {
let [text, title, callbackOk, callbackCancel] = args;
if (typeof args[1] === 'function') {
[text, callbackOk, callbackCancel, title] = args;
}
return new Dialog$1(app, {
title: typeof title === 'undefined' ? defaultDialogTitle : title,
text,
content: `
<div class="dialog-input-field dialog-input-double item-input">
<div class="item-input-wrap">
<input type="text" name="dialog-username" placeholder="${app.params.dialog.usernamePlaceholder}" class="dialog-input">
</div>
</div>
<div class="dialog-input-field dialog-input-double item-input">
<div class="item-input-wrap">
<input type="password" name="dialog-password" placeholder="${app.params.dialog.passwordPlaceholder}" class="dialog-input">
</div>
</div>`,
buttons: [
{
text: app.params.dialog.buttonCancel,
},
{
text: app.params.dialog.buttonOk,
bold: true,
},
],
onClick(dialog, index) {
const username = dialog.$el.find('[name="dialog-username"]').val();
const password = dialog.$el.find('[name="dialog-password"]').val();
if (index === 0 && callbackCancel) callbackCancel(username, password);
if (index === 1 && callbackOk) callbackOk(username, password);
},
}).open();
},
password(...args) {
let [text, title, callbackOk, callbackCancel] = args;
if (typeof args[1] === 'function') {
[text, callbackOk, callbackCancel, title] = args;
}
return new Dialog$1(app, {
title: typeof title === 'undefined' ? defaultDialogTitle : title,
text,
content: `
<div class="dialog-input-field item-input">
<div class="item-input-wrap">
<input type="password" name="dialog-password" placeholder="${app.params.dialog.passwordPlaceholder}" class="dialog-input">
</div>
</div>`,
buttons: [
{
text: app.params.dialog.buttonCancel,
},
{
text: app.params.dialog.buttonOk,
bold: true,
},
],
onClick(dialog, index) {
const password = dialog.$el.find('[name="dialog-password"]').val();
if (index === 0 && callbackCancel) callbackCancel(password);
if (index === 1 && callbackOk) callbackOk(password);
},
}).open();
},
preloader(title) {
const preloaderInner = app.theme !== 'md' ? '' : Utils.mdPreloaderContent;
return new Dialog$1(app, {
title: typeof title === 'undefined' ? app.params.dialog.preloaderTitle : title,
content: `<div class="preloader">${preloaderInner}</div>`,
cssClass: 'dialog-preloader',
}).open();
},
progress(...args) {
let [title, progress, color] = args;
if (args.length === 2) {
if (typeof args[0] === 'number') {
[progress, color, title] = args;
} else if (typeof args[0] === 'string' && typeof args[1] === 'string') {
[title, color, progress] = args;
}
} else if (args.length === 1) {
if (typeof args[0] === 'number') {
[progress, title, color] = args;
}
}
const infinite = typeof progress === 'undefined';
const dialog = new Dialog$1(app, {
title: typeof title === 'undefined' ? app.params.dialog.progressTitle : title,
cssClass: 'dialog-progress',
content: `
<div class="progressbar${infinite ? '-infinite' : ''}${color ? ` color-${color}` : ''}">
${!infinite ? '<span></span>' : ''}
</div>
`,
});
if (!infinite) dialog.setProgress(progress);
return dialog.open();
},
}
);
},
clicks: {
'.dialog-backdrop': function closeDialog() {
const app = this;
if (!app.params.dialog.closeByBackdropClick) return;
app.dialog.close();
},
},
};
class Popup$1 extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend(
{ on: {} },
app.params.popup,
params
);
// Extends with open/close Modal methods;
super(app, extendedParams);
const popup = this;
popup.params = extendedParams;
// Find Element
let $el;
if (!popup.params.el) {
$el = $(popup.params.content);
} else {
$el = $(popup.params.el);
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
if ($el.length === 0) {
return popup.destroy();
}
let $backdropEl;
if (popup.params.backdrop) {
$backdropEl = app.root.children('.popup-backdrop');
if ($backdropEl.length === 0) {
$backdropEl = $('<div class="popup-backdrop"></div>');
app.root.append($backdropEl);
}
}
Utils.extend(popup, {
app,
$el,
el: $el[0],
$backdropEl,
backdropEl: $backdropEl && $backdropEl[0],
type: 'popup',
});
$el[0].f7Modal = popup;
return popup;
}
}
var Popup = {
name: 'popup',
params: {
popup: {
backdrop: true,
closeByBackdropClick: true,
},
},
static: {
Popup: Popup$1,
},
create() {
const app = this;
app.popup = ModalMethods({
app,
constructor: Popup$1,
defaultSelector: '.popup.modal-in',
});
},
clicks: {
'.popup-open': function openPopup($clickedEl, data = {}) {
const app = this;
app.popup.open(data.popup, data.animate);
},
'.popup-close': function closePopup($clickedEl, data = {}) {
const app = this;
app.popup.close(data.popup, data.animate);
},
'.popup-backdrop': function closePopup() {
const app = this;
if (!app.params.popup.closeByBackdropClick) return;
app.popup.close();
},
},
};
class LoginScreen$1 extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend({
on: {},
}, params);
// Extends with open/close Modal methods;
super(app, extendedParams);
const loginScreen = this;
loginScreen.params = extendedParams;
// Find Element
let $el;
if (!loginScreen.params.el) {
$el = $(loginScreen.params.content);
} else {
$el = $(loginScreen.params.el);
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
if ($el.length === 0) {
return loginScreen.destroy();
}
Utils.extend(loginScreen, {
app,
$el,
el: $el[0],
type: 'loginScreen',
});
$el[0].f7Modal = loginScreen;
return loginScreen;
}
}
var LoginScreen = {
name: 'loginScreen',
static: {
LoginScreen: LoginScreen$1,
},
create() {
const app = this;
app.loginScreen = ModalMethods({
app,
constructor: LoginScreen$1,
defaultSelector: '.login-screen.modal-in',
});
},
clicks: {
'.login-screen-open': function openLoginScreen($clickedEl, data = {}) {
const app = this;
app.loginScreen.open(data.loginScreen, data.animate);
},
'.login-screen-close': function closeLoginScreen($clickedEl, data = {}) {
const app = this;
app.loginScreen.close(data.loginScreen, data.animate);
},
},
};
class Popover$1 extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend(
{ on: {} },
app.params.popover,
params
);
// Extends with open/close Modal methods;
super(app, extendedParams);
const popover = this;
popover.params = extendedParams;
// Find Element
let $el;
if (!popover.params.el) {
$el = $(popover.params.content);
} else {
$el = $(popover.params.el);
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
// Find Target
const $targetEl = $(popover.params.targetEl).eq(0);
if ($el.length === 0) {
return popover.destroy();
}
// Backdrop
let $backdropEl;
if (popover.params.backdrop) {
$backdropEl = app.root.children('.popover-backdrop');
if ($backdropEl.length === 0) {
$backdropEl = $('<div class="popover-backdrop"></div>');
app.root.append($backdropEl);
}
}
// Find Angle
let $angleEl;
if ($el.find('.popover-angle').length === 0) {
$angleEl = $('<div class="popover-angle"></div>');
$el.prepend($angleEl);
} else {
$angleEl = $el.find('.popover-angle');
}
// Open
const originalOpen = popover.open;
Utils.extend(popover, {
app,
$el,
el: $el[0],
$targetEl,
targetEl: $targetEl[0],
$angleEl,
angleEl: $angleEl[0],
$backdropEl,
backdropEl: $backdropEl && $backdropEl[0],
type: 'popover',
open(...args) {
let [targetEl, animate] = args;
if (typeof args[0] === 'boolean') [animate, targetEl] = args;
if (targetEl) {
popover.$targetEl = $(targetEl);
popover.targetEl = popover.$targetEl[0];
}
originalOpen.call(popover, animate);
},
});
function handleResize() {
popover.resize();
}
popover.on('popoverOpen', () => {
popover.resize();
app.on('resize', handleResize);
popover.on('popoverClose popoverBeforeDestroy', () => {
app.off('resize', handleResize);
});
});
function handleClick(e) {
const target = e.target;
if ($(target).closest(popover.el).length === 0) {
popover.close();
}
}
popover.on('popoverOpened', () => {
if (popover.params.closeByOutsideClick && !popover.params.backdrop) {
app.on('click', handleClick);
}
});
popover.on('popoverClose', () => {
if (popover.params.closeByOutsideClick && !popover.params.backdrop) {
app.off('click', handleClick);
}
});
$el[0].f7Modal = popover;
return popover;
}
resize() {
const popover = this;
const { app, $el, $targetEl, $angleEl } = popover;
const { targetX, targetY } = popover.params;
$el.css({ left: '', top: '' });
const [width, height] = [$el.width(), $el.height()];
let angleSize = 0;
let angleLeft;
let angleTop;
if (app.theme === 'ios') {
$angleEl.removeClass('on-left on-right on-top on-bottom').css({ left: '', top: '' });
angleSize = $angleEl.width() / 2;
} else {
$el.removeClass('popover-on-left popover-on-right popover-on-top popover-on-bottom').css({ left: '', top: '' });
}
let targetWidth;
let targetHeight;
let targetOffsetLeft;
let targetOffsetTop;
if ($targetEl && $targetEl.length > 0) {
targetWidth = $targetEl.outerWidth();
targetHeight = $targetEl.outerHeight();
const targetOffset = $targetEl.offset();
targetOffsetLeft = targetOffset.left - app.left;
targetOffsetTop = targetOffset.top - app.top;
const targetParentPage = $targetEl.parents('.page');
if (targetParentPage.length > 0) {
targetOffsetTop -= targetParentPage[0].scrollTop;
}
} else if (typeof targetX !== 'undefined' && targetY !== 'undefined') {
targetOffsetLeft = targetX;
targetOffsetTop = targetY;
targetWidth = popover.params.targetWidth || 0;
targetHeight = popover.params.targetHeight || 0;
}
let [left, top, diff] = [0, 0, 0];
// Top Position
let position = app.theme === 'md' ? 'bottom' : 'top';
if (app.theme === 'md') {
if (height < app.height - targetOffsetTop - targetHeight) {
// On bottom
position = 'bottom';
top = targetOffsetTop;
} else if (height < targetOffsetTop) {
// On top
top = (targetOffsetTop - height) + targetHeight;
position = 'top';
} else {
// On middle
position = 'bottom';
top = targetOffsetTop;
}
if (top <= 0) {
top = 8;
} else if (top + height >= app.height) {
top = app.height - height - 8;
}
// Horizontal Position
left = (targetOffsetLeft + targetWidth) - width - 8;
if (left + width >= app.width - 8) {
left = (targetOffsetLeft + targetWidth) - width - 8;
}
if (left < 8) {
left = 8;
}
if (position === 'top') {
$el.addClass('popover-on-top');
}
if (position === 'bottom') {
$el.addClass('popover-on-bottom');
}
} else {
if ((height + angleSize) < targetOffsetTop) {
// On top
top = targetOffsetTop - height - angleSize;
} else if ((height + angleSize) < app.height - targetOffsetTop - targetHeight) {
// On bottom
position = 'bottom';
top = targetOffsetTop + targetHeight + angleSize;
} else {
// On middle
position = 'middle';
top = ((targetHeight / 2) + targetOffsetTop) - (height / 2);
diff = top;
if (top <= 0) {
top = 5;
} else if (top + height >= app.height) {
top = app.height - height - 5;
}
diff -= top;
}
// Horizontal Position
if (position === 'top' || position === 'bottom') {
left = ((targetWidth / 2) + targetOffsetLeft) - (width / 2);
diff = left;
if (left < 5) left = 5;
if (left + width > app.width) left = app.width - width - 5;
if (left < 0) left = 0;
if (position === 'top') {
$angleEl.addClass('on-bottom');
}
if (position === 'bottom') {
$angleEl.addClass('on-top');
}
diff -= left;
angleLeft = ((width / 2) - angleSize) + diff;
angleLeft = Math.max(Math.min(angleLeft, width - (angleSize * 2) - 13), 13);
$angleEl.css({ left: `${angleLeft}px` });
} else if (position === 'middle') {
left = targetOffsetLeft - width - angleSize;
$angleEl.addClass('on-right');
if (left < 5 || (left + width > app.width)) {
if (left < 5) left = targetOffsetLeft + targetWidth + angleSize;
if (left + width > app.width) left = app.width - width - 5;
$angleEl.removeClass('on-right').addClass('on-left');
}
angleTop = ((height / 2) - angleSize) + diff;
angleTop = Math.max(Math.min(angleTop, height - (angleSize * 2) - 13), 13);
$angleEl.css({ top: `${angleTop}px` });
}
}
// Apply Styles
$el.css({ top: `${top}px`, left: `${left}px` });
}
}
var Popover = {
name: 'popover',
params: {
popover: {
closeByBackdropClick: true,
closeByOutsideClick: true,
backdrop: true,
},
},
static: {
Popover: Popover$1,
},
create() {
const app = this;
app.popover = Utils.extend(
ModalMethods({
app,
constructor: Popover$1,
defaultSelector: '.popover.modal-in',
}),
{
open(popoverEl, targetEl, animate) {
const $popoverEl = $(popoverEl);
let popover = $popoverEl[0].f7Modal;
if (!popover) popover = new Popover$1(app, { el: $popoverEl, targetEl });
return popover.open(targetEl, animate);
},
}
);
},
clicks: {
'.popover-open': function openPopover($clickedEl, data = {}) {
const app = this;
app.popover.open(data.popover, $clickedEl, data.animate);
},
'.popover-close': function closePopover($clickedEl, data = {}) {
const app = this;
app.popover.close(data.popover, data.animate);
},
'.popover-backdrop': function closePopover() {
const app = this;
if (!app.params.popover.closeByBackdropClick) return;
app.popover.close();
},
},
};
/* eslint indent: ["off"] */
class Actions$1 extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend(
{ on: {} },
app.params.actions,
params
);
// Extends with open/close Modal methods;
super(app, extendedParams);
const actions = this;
actions.params = extendedParams;
// Buttons
let groups;
if (actions.params.buttons) {
groups = actions.params.buttons;
if (!Array.isArray(groups[0])) groups = [groups];
}
actions.groups = groups;
// Find Element
let $el;
if (actions.params.el) {
$el = $(actions.params.el);
} else if (actions.params.content) {
$el = $(actions.params.content);
} else if (actions.params.buttons) {
if (actions.params.convertToPopover) {
actions.popoverHtml = actions.renderPopover();
}
actions.actionsHtml = actions.render();
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
if ($el && $el.length === 0 && !(actions.actionsHtml || actions.popoverHtml)) {
return actions.destroy();
}
// Backdrop
let $backdropEl;
if (actions.params.backdrop) {
$backdropEl = app.root.children('.actions-backdrop');
if ($backdropEl.length === 0) {
$backdropEl = $('<div class="actions-backdrop"></div>');
app.root.append($backdropEl);
}
}
const originalOpen = actions.open;
const originalClose = actions.close;
let popover;
function buttonOnClick(e) {
const buttonEl = this;
let buttonIndex;
let groupIndex;
if ($(buttonEl).hasClass('item-link')) {
buttonIndex = $(buttonEl).parents('li').index();
groupIndex = $(buttonEl).parents('.list').index();
} else {
buttonIndex = $(buttonEl).index();
groupIndex = $(buttonEl).parents('.actions-group').index();
}
const button = groups[groupIndex][buttonIndex];
if (button.onClick) button.onClick(actions, e);
if (actions.params.onClick) actions.params.onClick(actions, e);
if (button.close !== false) actions.close();
}
actions.open = function open(animate) {
let convertToPopover = false;
const { targetEl, targetX, targetY, targetWidth, targetHeight } = actions.params;
if (actions.params.convertToPopover && (targetEl || (targetX !== undefined && targetY !== undefined))) {
// Popover
if (
actions.params.forceToPopover ||
(app.device.ios && app.device.ipad) ||
app.width >= 768
) {
convertToPopover = true;
}
}
if (convertToPopover) {
popover = app.popover.create({
content: actions.popoverHtml,
backdrop: actions.params.backdrop,
targetEl,
targetX,
targetY,
targetWidth,
targetHeight,
});
popover.open(animate);
popover.once('popoverOpened', () => {
popover.$el.find('.item-link').each((groupIndex, buttonEl) => {
$(buttonEl).on('click', buttonOnClick);
});
});
popover.once('popoverClosed', () => {
popover.$el.find('.item-link').each((groupIndex, buttonEl) => {
$(buttonEl).off('click', buttonOnClick);
});
Utils.nextTick(() => {
popover.destroy();
popover = undefined;
});
});
} else {
actions.$el = $(actions.actionsHtml);
actions.$el[0].f7Modal = actions;
actions.$el.find('.actions-button').each((groupIndex, buttonEl) => {
$(buttonEl).on('click', buttonOnClick);
});
actions.once('actionsClosed', () => {
actions.$el.find('.list-button').each((groupIndex, buttonEl) => {
$(buttonEl).off('click', buttonOnClick);
});
});
originalOpen.call(actions, animate);
}
return actions;
};
actions.close = function close(animate) {
if (popover) {
popover.close(animate);
} else {
originalClose.call(actions, animate);
}
return actions;
};
Utils.extend(actions, {
app,
$el,
el: $el ? $el[0] : undefined,
$backdropEl,
backdropEl: $backdropEl && $backdropEl[0],
type: 'actions',
});
if ($el) {
$el[0].f7Modal = actions;
}
return actions;
}
render() {
const actions = this;
if (actions.params.render) return actions.params.render.call(actions, actions);
const { groups } = actions;
return `
<div class="actions-modal${actions.params.grid ? ' actions-grid' : ''}">
${groups.map(group =>
`<div class="actions-group">
${group.map((button) => {
const buttonClasses = [`actions-${button.label ? 'label' : 'button'}`];
const { color, bg, bold, disabled, label, text, icon } = button;
if (color) buttonClasses.push(`color-${color}`);
if (bg) buttonClasses.push(`bg-${color}`);
if (bold) buttonClasses.push('actions-button-bold');
if (disabled) buttonClasses.push('disabled');
if (label) {
return `<div class="${buttonClasses.join(' ')}">${text}</div>`;
}
return `
<div class="${buttonClasses.join(' ')}">
${icon ? `<div class="actions-button-media">${icon}</div>` : ''}
<div class="actions-button-text">${text}</div>
</div>`.trim();
}).join('')}
</div>`).join('')}
</div>
`.trim();
}
renderPopover() {
const actions = this;
if (actions.params.renderPopover) return actions.params.renderPopover.call(actions, actions);
const { groups } = actions;
return `
<div class="popover popover-from-actions">
<div class="popover-inner">
${groups.map(group => `
<div class="list">
<ul>
${group.map((button) => {
const itemClasses = [];
const { color, bg, bold, disabled, label, text, icon } = button;
if (color) itemClasses.push(`color-${color}`);
if (bg) itemClasses.push(`bg-${bg}`);
if (bold) itemClasses.push('popover-from-actions-bold');
if (disabled) itemClasses.push('disabled');
if (label) {
itemClasses.push('popover-from-actions-label');
return `<li class="${itemClasses.join(' ')}">${text}</li>`;
}
itemClasses.push('item-link');
if (icon) {
itemClasses.push('item-content');
return `
<li>
<a class="${itemClasses.join(' ')}">
<div class="item-media">
${icon}
</div>
<div class="item-inner">
<div class="item-title">
${text}
</div>
</div>
</a>
</li>
`;
}
itemClasses.push('list-button');
return `
<li>
<a href="#" class="list-button ${itemClasses.join(' ')}">${text}</a>
</li>
`;
}).join('')}
</ul>
</div>
`).join('')}
</div>
</div>
`.trim();
}
}
var Actions = {
name: 'actions',
params: {
actions: {
convertToPopover: true,
forceToPopover: false,
closeByBackdropClick: true,
render: null,
renderPopover: null,
backdrop: true,
},
},
static: {
Actions: Actions$1,
},
create() {
const app = this;
app.actions = ModalMethods({
app,
constructor: Actions$1,
defaultSelector: '.actions-modal.modal-in',
});
},
clicks: {
'.actions-open': function openActions($clickedEl, data = {}) {
const app = this;
app.actions.open(data.actions, data.animate);
},
'.actions-close': function closeActions($clickedEl, data = {}) {
const app = this;
app.actions.close(data.actions, data.animate);
},
'.actions-backdrop': function closeActions() {
const app = this;
if (!app.params.actions.closeByBackdropClick) return;
app.actions.close();
},
},
};
class Sheet$1 extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend({
backdrop: app.theme === 'md',
closeByOutsideClick: app.params.sheet.closeByOutsideClick,
on: {},
}, params);
// Extends with open/close Modal methods;
super(app, extendedParams);
const sheet = this;
sheet.params = extendedParams;
// Find Element
let $el;
if (!sheet.params.el) {
$el = $(sheet.params.content);
} else {
$el = $(sheet.params.el);
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
if ($el.length === 0) {
return sheet.destroy();
}
let $backdropEl;
if (sheet.params.backdrop) {
$backdropEl = app.root.children('.sheet-backdrop');
if ($backdropEl.length === 0) {
$backdropEl = $('<div class="sheet-backdrop"></div>');
app.root.append($backdropEl);
}
}
let $pageContentEl;
function scrollToOpen() {
const $scrollEl = $(sheet.params.scrollToEl).eq(0);
if ($scrollEl.length === 0) return;
$pageContentEl = $scrollEl.parents('.page-content');
if ($pageContentEl.length === 0) return;
const paddingTop = parseInt($pageContentEl.css('padding-top'), 10);
const paddingBottom = parseInt($pageContentEl.css('padding-bottom'), 10);
const pageHeight = $pageContentEl[0].offsetHeight - paddingTop - $el.height();
const pageScrollHeight = $pageContentEl[0].scrollHeight - paddingTop - $el.height();
const pageScroll = $pageContentEl.scrollTop();
let newPaddingBottom;
const scrollElTop = ($scrollEl.offset().top - paddingTop) + $scrollEl[0].offsetHeight;
if (scrollElTop > pageHeight) {
const scrollTop = (pageScroll + scrollElTop) - pageHeight;
if (scrollTop + pageHeight > pageScrollHeight) {
newPaddingBottom = ((scrollTop + pageHeight) - pageScrollHeight) + paddingBottom;
if (pageHeight === pageScrollHeight) {
newPaddingBottom = $el.height();
}
$pageContentEl.css({
'padding-bottom': `${newPaddingBottom}px`,
});
}
$pageContentEl.scrollTop(scrollTop, 300);
}
}
function scrollToClose() {
if ($pageContentEl && $pageContentEl.length > 0) {
$pageContentEl.css({
'padding-bottom': '',
});
}
}
function handleClick(e) {
const target = e.target;
if ($(target).closest(sheet.el).length === 0) {
sheet.close();
}
}
sheet.on('sheetOpen', () => {
if (sheet.params.scrollToEl) {
scrollToOpen();
}
});
sheet.on('sheetOpened', () => {
if (sheet.params.closeByOutsideClick && !sheet.params.backdrop) {
app.on('click', handleClick);
}
});
sheet.on('sheetClose', () => {
if (sheet.params.scrollToEl) {
scrollToClose();
}
if (sheet.params.closeByOutsideClick && !sheet.params.backdrop) {
app.off('click', handleClick);
}
});
Utils.extend(sheet, {
app,
$el,
el: $el[0],
$backdropEl,
backdropEl: $backdropEl && $backdropEl[0],
type: 'sheet',
});
$el[0].f7Modal = sheet;
return sheet;
}
}
var Sheet = {
name: 'sheet',
params: {
sheet: {
closeByBackdropClick: true,
closeByOutsideClick: false,
},
},
static: {
Sheet: Sheet$1,
},
create() {
const app = this;
app.sheet = Utils.extend(
{},
ModalMethods({
app,
constructor: Sheet$1,
defaultSelector: '.sheet-modal.modal-in',
})
);
},
clicks: {
'.sheet-open': function openSheet($clickedEl, data = {}) {
const app = this;
if ($('.sheet-modal.modal-in').length > 0 && data.sheet && $(data.sheet)[0] !== $('.sheet-modal.modal-in')[0]) {
app.sheet.close('.sheet-modal.modal-in');
}
app.sheet.open(data.sheet, data.animate);
},
'.sheet-close': function closeSheet($clickedEl, data = {}) {
const app = this;
app.sheet.close(data.sheet, data.animate);
},
'.sheet-backdrop': function closeSheet() {
const app = this;
if (!app.params.sheet.closeByBackdropClick) return;
app.sheet.close();
},
},
};
class Toast$1 extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend({
on: {},
}, app.params.toast, params);
// Extends with open/close Modal methods;
super(app, extendedParams);
const toast = this;
toast.app = app;
toast.params = extendedParams;
const { closeButton, closeTimeout } = toast.params;
let $el;
if (!toast.params.el) {
// Find Element
const toastHtml = toast.render();
$el = $(toastHtml);
} else {
$el = $(toast.params.el);
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
if ($el.length === 0) {
return toast.destroy();
}
Utils.extend(toast, {
$el,
el: $el[0],
type: 'toast',
});
$el[0].f7Modal = toast;
if (closeButton) {
$el.find('.toast-button').on('click', () => {
toast.emit('local::closeButtonClick toastCloseButtonClick', toast);
toast.close();
});
toast.on('beforeDestroy', () => {
$el.find('.toast-button').off('click');
});
}
let timeoutId;
toast.on('open', () => {
$('.toast.modal-in').each((index, openedEl) => {
const toastInstance = app.toast.get(openedEl);
if (openedEl !== toast.el && toastInstance) {
toastInstance.close();
}
});
if (closeTimeout) {
timeoutId = Utils.nextTick(() => {
toast.close();
}, closeTimeout);
}
});
toast.on('close', () => {
window.clearTimeout(timeoutId);
});
return toast;
}
render() {
const toast = this;
const app = toast.app;
if (toast.params.render) return toast.params.render.call(toast, toast);
const { position, cssClass, icon, text, closeButton, closeButtonColor, closeButtonText } = toast.params;
return `
<div class="toast toast-${position} ${cssClass || ''} ${icon ? 'toast-with-icon' : ''}">
<div class="toast-content">
${icon ? `<div class="toast-icon">${icon}</div>` : ''}
<div class="toast-text">${text}</div>
${closeButton && !icon ? `
<a class="toast-button ${app.theme === 'md' ? 'button' : 'link'} ${closeButtonColor ? `color-${closeButtonColor}` : ''}">${closeButtonText}</a>
`.trim() : ''}
</div>
</div>
`.trim();
}
}
var Toast = {
name: 'toast',
static: {
Toast: Toast$1,
},
create() {
const app = this;
app.toast = Utils.extend(
{},
ModalMethods({
app,
constructor: Toast$1,
defaultSelector: '.toast.modal-in',
})
);
},
params: {
toast: {
icon: null,
text: null,
position: 'bottom',
closeButton: false,
closeButtonColor: null,
closeButtonText: 'Ok',
closeTimeout: null,
cssClass: null,
render: null,
},
},
};
const Preloader = {
init(el) {
const app = this;
if (app.theme !== 'md') return;
const $el = $(el);
if ($el.length === 0 || $el.children('.preloader-inner').length > 0) return;
$el.append(Utils.mdPreloaderContent);
},
// Modal
visible: false,
show(color = 'white') {
const app = this;
if (Preloader.visible) return;
const preloaderInner = app.theme !== 'md' ? '' : Utils.mdPreloaderContent;
$('html').addClass('with-modal-preloader');
app.root.append(`
<div class="preloader-backdrop"></div>
<div class="preloader-modal">
<div class="preloader color-${color}">${preloaderInner}</div>
</div>
`);
Preloader.visible = true;
},
hide() {
const app = this;
if (!Preloader.visible) return;
$('html').removeClass('with-modal-preloader');
app.root.find('.preloader-backdrop, .preloader-modal').remove();
Preloader.visible = false;
},
};
var Preloader$1 = {
name: 'preloader',
create() {
const app = this;
Utils.extend(app, {
preloader: {
init: Preloader.init.bind(app),
show: Preloader.show.bind(app),
hide: Preloader.hide.bind(app),
},
});
},
on: {
photoBrowserOpen(pb) {
const app = this;
if (app.theme !== 'md') return;
pb.$containerEl.find('.preloader').each((index, preloaderEl) => {
app.preloader.init(preloaderEl);
});
},
pageInit(page) {
const app = this;
if (app.theme !== 'md') return;
page.$el.find('.preloader').each((index, preloaderEl) => {
app.preloader.init(preloaderEl);
});
},
},
};
const Progressbar = {
set(...args) {
const app = this;
let [el, progress, duration] = args;
if (typeof args[0] === 'number') {
[progress, duration] = args;
el = app.root;
}
if (typeof progress === 'undefined' || progress === null) return el;
if (!progress) progress = 0;
const $el = $(el || app.root);
if ($el.length === 0) {
return el;
}
const progressNormalized = Math.min(Math.max(progress, 0), 100);
let $progressbarEl;
if ($el.hasClass('progressbar')) $progressbarEl = $el.eq(0);
else {
$progressbarEl = $el.children('.progressbar');
}
if ($progressbarEl.length === 0 || $progressbarEl.hasClass('progressbar-infinite')) {
return $progressbarEl;
}
let $progressbarLine = $progressbarEl.children('span');
if ($progressbarLine.length === 0) {
$progressbarLine = $('<span></span>');
$progressbarEl.append($progressbarLine);
}
$progressbarLine
.transition(typeof duration !== 'undefined' ? duration : '')
.transform(`translate3d(${(-100 + progressNormalized)}%,0,0)`);
return $progressbarEl[0];
},
show(...args) {
const app = this;
// '.page', 50, 'multi'
let [el, progress, color] = args;
let type = 'determined';
if (args.length === 2) {
if ((typeof args[0] === 'string' || typeof args[0] === 'object') && typeof args[1] === 'string') {
// '.page', 'multi'
[el, color, progress] = args;
type = 'infinite';
} else if (typeof args[0] === 'number' && typeof args[1] === 'string') {
// 50, 'multi'
[progress, color] = args;
el = app.root;
}
} else if (args.length === 1) {
if (typeof args[0] === 'number') {
el = app.root;
progress = args[0];
} else if (typeof args[0] === 'string') {
type = 'infinite';
el = app.root;
color = args[0];
}
} else if (args.length === 0) {
type = 'infinite';
el = app.root;
}
const $el = $(el);
if ($el.length === 0) return undefined;
let $progressbarEl;
if ($el.hasClass('progressbar') || $el.hasClass('progressbar-infinite')) {
$progressbarEl = $el;
} else {
$progressbarEl = $el.children('.progressbar:not(.progressbar-out), .progressbar-infinite:not(.progressbar-out)');
if ($progressbarEl.length === 0) {
$progressbarEl = $(`
<span class="progressbar${type === 'infinite' ? '-infinite' : ''}${color ? ` color-${color}` : ''} progressbar-in">
${type === 'infinite' ? '' : '<span></span>'}
</span>`);
$el.append($progressbarEl);
}
}
if (typeof progress !== 'undefined') {
app.progressbar.set($progressbarEl, progress);
}
return $progressbarEl[0];
},
hide(el, removeAfterHide = true) {
const app = this;
const $el = $(el || app.root);
if ($el.length === 0) return undefined;
let $progressbarEl;
if ($el.hasClass('progressbar') || $el.hasClass('progressbar-infinite')) {
$progressbarEl = $el;
} else {
$progressbarEl = $el.children('.progressbar, .progressbar-infinite');
}
if ($progressbarEl.length === 0 || !$progressbarEl.hasClass('progressbar-in') || $progressbarEl.hasClass('progressbar-out')) {
return $progressbarEl;
}
$progressbarEl
.removeClass('progressbar-in')
.addClass('progressbar-out')
.animationEnd(() => {
if (removeAfterHide) {
$progressbarEl.remove();
}
});
return $progressbarEl;
},
};
var Progressbar$1 = {
name: 'progressbar',
create() {
const app = this;
Utils.extend(app, {
progressbar: {
set: Progressbar.set.bind(app),
show: Progressbar.show.bind(app),
hide: Progressbar.hide.bind(app),
},
});
},
on: {
pageInit(page) {
const app = this;
page.$el.find('.progressbar').each((index, progressbarEl) => {
const $progressbarEl = $(progressbarEl);
app.progressbar.set($progressbarEl, $progressbarEl.attr('data-progress'));
});
},
},
};
const Sortable = {
init() {
const app = this;
let isTouched;
let isMoved;
let touchStartY;
let touchesDiff;
let $sortingEl;
let $sortingItems;
let $sortableContainer;
let sortingElHeight;
let minTop;
let maxTop;
let $insertAfterEl;
let $insertBeforeEl;
let indexFrom;
let $pageEl;
let $pageContentEl;
let pageHeight;
let pageOffset;
let sortingElOffsetLocal;
let sortingElOffsetTop;
let initialScrollTop;
function handleTouchStart(e) {
isMoved = false;
isTouched = true;
touchStartY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
$sortingEl = $(this).parent('li');
indexFrom = $sortingEl.index();
$sortableContainer = $sortingEl.parents('.sortable');
$sortingItems = $sortableContainer.children('ul').children('li');
if (app.panel) app.panel.allowOpen = false;
if (app.swipeout) app.swipeout.allow = false;
}
function handleTouchMove(e) {
if (!isTouched || !$sortingEl) return;
const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (!isMoved) {
$pageEl = $sortingEl.parents('.page');
$pageContentEl = $sortingEl.parents('.page-content');
const paddingTop = parseInt($pageContentEl.css('padding-top'), 10);
const paddingBottom = parseInt($pageContentEl.css('padding-bottom'), 10);
initialScrollTop = $pageContentEl[0].scrollTop;
pageOffset = $pageEl.offset().top + paddingTop;
pageHeight = $pageEl.height() - paddingTop - paddingBottom;
$sortingEl.addClass('sorting');
$sortableContainer.addClass('sortable-sorting');
sortingElOffsetLocal = $sortingEl[0].offsetTop;
minTop = $sortingEl[0].offsetTop;
maxTop = $sortingEl.parent().height() - sortingElOffsetLocal - $sortingEl.height();
sortingElHeight = $sortingEl[0].offsetHeight;
sortingElOffsetTop = $sortingEl.offset().top;
}
isMoved = true;
e.preventDefault();
e.f7PreventSwipePanel = true;
touchesDiff = pageY - touchStartY;
const translateScrollOffset = $pageContentEl[0].scrollTop - initialScrollTop;
const translate = Math.min(Math.max(touchesDiff + translateScrollOffset, -minTop), maxTop);
$sortingEl.transform(`translate3d(0,${translate}px,0)`);
const scrollAddition = 44;
let allowScroll = true;
if ((touchesDiff + translateScrollOffset) + scrollAddition < -minTop) {
allowScroll = false;
}
if ((touchesDiff + translateScrollOffset) - scrollAddition > maxTop) {
allowScroll = false;
}
$insertBeforeEl = undefined;
$insertAfterEl = undefined;
let scrollDiff;
if (allowScroll) {
if (sortingElOffsetTop + touchesDiff + sortingElHeight + scrollAddition > pageOffset + pageHeight) {
// To Bottom
scrollDiff = (sortingElOffsetTop + touchesDiff + sortingElHeight + scrollAddition) - (pageOffset + pageHeight);
}
if (sortingElOffsetTop + touchesDiff < pageOffset + scrollAddition) {
// To Top
scrollDiff = (sortingElOffsetTop + touchesDiff) - pageOffset - scrollAddition;
}
if (scrollDiff) {
$pageContentEl[0].scrollTop += scrollDiff;
}
}
$sortingItems.each((index, el) => {
const $currentEl = $(el);
if ($currentEl[0] === $sortingEl[0]) return;
const currentElOffset = $currentEl[0].offsetTop;
const currentElHeight = $currentEl.height();
const sortingElOffset = sortingElOffsetLocal + translate;
if ((sortingElOffset >= currentElOffset - (currentElHeight / 2)) && $sortingEl.index() < $currentEl.index()) {
$currentEl.transform(`translate3d(0, ${-sortingElHeight}px,0)`);
$insertAfterEl = $currentEl;
$insertBeforeEl = undefined;
} else if ((sortingElOffset <= currentElOffset + (currentElHeight / 2)) && $sortingEl.index() > $currentEl.index()) {
$currentEl.transform(`translate3d(0, ${sortingElHeight}px,0)`);
$insertAfterEl = undefined;
if (!$insertBeforeEl) $insertBeforeEl = $currentEl;
} else {
$currentEl.transform('translate3d(0, 0%,0)');
}
});
}
function handleTouchEnd() {
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
if (isTouched && !isMoved) {
if (app.panel) app.panel.allowOpen = true;
if (app.swipeout) app.swipeout.allow = true;
}
return;
}
if (app.panel) app.panel.allowOpen = true;
if (app.swipeout) app.swipeout.allow = true;
$sortingItems.transform('');
$sortingEl.removeClass('sorting');
$sortableContainer.removeClass('sortable-sorting');
let virtualList;
let oldIndex;
let newIndex;
if ($insertAfterEl) {
$sortingEl.insertAfter($insertAfterEl);
}
if ($insertBeforeEl) {
$sortingEl.insertBefore($insertBeforeEl);
}
$sortingEl.trigger('sortable:sort', { from: indexFrom, to: $sortingEl.index() });
app.emit('sortableSort', $sortingEl[0], { from: indexFrom, to: $sortingEl.index() });
if (($insertAfterEl || $insertBeforeEl) && $sortableContainer.hasClass('virtual-list')) {
virtualList = $sortableContainer[0].f7VirtualList;
oldIndex = $sortingEl[0].f7VirtualListIndex;
newIndex = $insertBeforeEl ? $insertBeforeEl[0].f7VirtualListIndex : $insertAfterEl[0].f7VirtualListIndex;
if (virtualList) virtualList.moveItem(oldIndex, newIndex);
}
$insertBeforeEl = undefined;
$insertAfterEl = undefined;
isTouched = false;
isMoved = false;
}
const activeListener = app.support.passiveListener ? { passive: false, capture: false } : false;
$(document).on(app.touchEvents.start, '.list.sortable .sortable-handler', handleTouchStart, activeListener);
app.on('touchmove:active', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
},
enable(el = '.list.sortable') {
const app = this;
const $el = $(el);
if ($el.length === 0) return;
$el.addClass('sortable-enabled');
$el.trigger('sortable:enable');
app.emit('sortableEnable', $el[0]);
},
disable(el = '.list.sortable') {
const app = this;
const $el = $(el);
if ($el.length === 0) return;
$el.removeClass('sortable-enabled');
$el.trigger('sortable:disable');
app.emit('sortableDisable', $el[0]);
},
toggle(el = '.list.sortable') {
const app = this;
const $el = $(el);
if ($el.length === 0) return;
if ($el.hasClass('sortable-enabled')) {
app.sortable.disable($el);
} else {
app.sortable.enable($el);
}
},
};
var Sortable$1 = {
name: 'sortable',
params: {
sortable: true,
},
create() {
const app = this;
Utils.extend(app, {
sortable: {
init: Sortable.init.bind(app),
enable: Sortable.enable.bind(app),
disable: Sortable.disable.bind(app),
toggle: Sortable.toggle.bind(app),
},
});
},
on: {
init() {
const app = this;
if (app.params.sortable) app.sortable.init();
},
},
clicks: {
'.sortable-enable': function enable($clickedEl, data = {}) {
const app = this;
app.sortable.enable(data.sortable);
},
'.sortable-disable': function disable($clickedEl, data = {}) {
const app = this;
app.sortable.disable(data.sortable);
},
'.sortable-toggle': function toggle($clickedEl, data = {}) {
const app = this;
app.sortable.toggle(data.sortable);
},
},
};
const Swipeout = {
init() {
const app = this;
const touchesStart = {};
let isTouched;
let isMoved;
let isScrolling;
let touchStartTime;
let touchesDiff;
let $swipeoutEl;
let $swipeoutContent;
let $actionsRight;
let $actionsLeft;
let actionsLeftWidth;
let actionsRightWidth;
let translate;
let opened;
let openedActionsSide;
let $leftButtons;
let $rightButtons;
let direction;
let $overswipeLeftButton;
let $overswipeRightButton;
let overswipeLeft;
let overswipeRight;
function handleTouchStart(e) {
if (!Swipeout.allow) return;
isMoved = false;
isTouched = true;
isScrolling = undefined;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
touchStartTime = (new Date()).getTime();
$swipeoutEl = $(this);
}
function handleTouchMove(e) {
if (!isTouched) return;
const pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
}
if (isScrolling) {
isTouched = false;
return;
}
if (!isMoved) {
if ($('.list.sortable-opened').length > 0) return;
$swipeoutContent = $swipeoutEl.find('.swipeout-content');
$actionsRight = $swipeoutEl.find('.swipeout-actions-right');
$actionsLeft = $swipeoutEl.find('.swipeout-actions-left');
actionsLeftWidth = null;
actionsRightWidth = null;
$leftButtons = null;
$rightButtons = null;
$overswipeRightButton = null;
$overswipeLeftButton = null;
if ($actionsLeft.length > 0) {
actionsLeftWidth = $actionsLeft.outerWidth();
$leftButtons = $actionsLeft.children('a');
$overswipeLeftButton = $actionsLeft.find('.swipeout-overswipe');
}
if ($actionsRight.length > 0) {
actionsRightWidth = $actionsRight.outerWidth();
$rightButtons = $actionsRight.children('a');
$overswipeRightButton = $actionsRight.find('.swipeout-overswipe');
}
opened = $swipeoutEl.hasClass('swipeout-opened');
if (opened) {
openedActionsSide = $swipeoutEl.find('.swipeout-actions-left.swipeout-actions-opened').length > 0 ? 'left' : 'right';
}
$swipeoutEl.removeClass('swipeout-transitioning');
if (!app.params.swipeout.noFollow) {
$swipeoutEl.find('.swipeout-actions-opened').removeClass('swipeout-actions-opened');
$swipeoutEl.removeClass('swipeout-opened');
}
}
isMoved = true;
e.preventDefault();
touchesDiff = pageX - touchesStart.x;
translate = touchesDiff;
if (opened) {
if (openedActionsSide === 'right') translate -= actionsRightWidth;
else translate += actionsLeftWidth;
}
if (
(translate > 0 && $actionsLeft.length === 0)
||
(translate < 0 && $actionsRight.length === 0)
) {
if (!opened) {
isTouched = false;
isMoved = false;
$swipeoutContent.transform('');
if ($rightButtons && $rightButtons.length > 0) {
$rightButtons.transform('');
}
if ($leftButtons && $leftButtons.length > 0) {
$leftButtons.transform('');
}
return;
}
translate = 0;
}
if (translate < 0) direction = 'to-left';
else if (translate > 0) direction = 'to-right';
else if (!direction) direction = 'to-left';
let buttonOffset;
let progress;
e.f7PreventSwipePanel = true;
if (app.params.swipeout.noFollow) {
if (opened) {
if (openedActionsSide === 'right' && touchesDiff > 0) {
app.swipeout.close($swipeoutEl);
}
if (openedActionsSide === 'left' && touchesDiff < 0) {
app.swipeout.close($swipeoutEl);
}
} else {
if (touchesDiff < 0 && $actionsRight.length > 0) {
app.swipeout.open($swipeoutEl, 'right');
}
if (touchesDiff > 0 && $actionsLeft.length > 0) {
app.swipeout.open($swipeoutEl, 'left');
}
}
isTouched = false;
isMoved = false;
return;
}
overswipeLeft = false;
overswipeRight = false;
if ($actionsRight.length > 0) {
// Show right actions
let buttonTranslate = translate;
progress = buttonTranslate / actionsRightWidth;
if (buttonTranslate < -actionsRightWidth) {
buttonTranslate = -actionsRightWidth - ((-buttonTranslate - actionsRightWidth) ** 0.8);
translate = buttonTranslate;
if ($overswipeRightButton.length > 0) {
overswipeRight = true;
}
}
if (direction !== 'to-left') {
progress = 0;
buttonTranslate = 0;
}
$rightButtons.each((index, buttonEl) => {
const $buttonEl = $(buttonEl);
if (typeof buttonEl.f7SwipeoutButtonOffset === 'undefined') {
$buttonEl[0].f7SwipeoutButtonOffset = buttonEl.offsetLeft;
}
buttonOffset = buttonEl.f7SwipeoutButtonOffset;
if ($overswipeRightButton.length > 0 && $buttonEl.hasClass('swipeout-overswipe') && direction === 'to-left') {
$buttonEl.css({ left: `${overswipeRight ? -buttonOffset : 0}px` });
if (overswipeRight) {
$buttonEl.addClass('swipeout-overswipe-active');
} else {
$buttonEl.removeClass('swipeout-overswipe-active');
}
}
$buttonEl.transform(`translate3d(${buttonTranslate - (buttonOffset * (1 + Math.max(progress, -1)))}px,0,0)`);
});
}
if ($actionsLeft.length > 0) {
// Show left actions
let buttonTranslate = translate;
progress = buttonTranslate / actionsLeftWidth;
if (buttonTranslate > actionsLeftWidth) {
buttonTranslate = actionsLeftWidth + ((buttonTranslate - actionsLeftWidth) ** 0.8);
translate = buttonTranslate;
if ($overswipeLeftButton.length > 0) {
overswipeLeft = true;
}
}
if (direction !== 'to-right') {
buttonTranslate = 0;
progress = 0;
}
$leftButtons.each((index, buttonEl) => {
const $buttonEl = $(buttonEl);
if (typeof buttonEl.f7SwipeoutButtonOffset === 'undefined') {
$buttonEl[0].f7SwipeoutButtonOffset = actionsLeftWidth - buttonEl.offsetLeft - buttonEl.offsetWidth;
}
buttonOffset = buttonEl.f7SwipeoutButtonOffset;
if ($overswipeLeftButton.length > 0 && $buttonEl.hasClass('swipeout-overswipe') && direction === 'to-right') {
$buttonEl.css({ left: `${overswipeLeft ? buttonOffset : 0}px` });
if (overswipeLeft) {
$buttonEl.addClass('swipeout-overswipe-active');
} else {
$buttonEl.removeClass('swipeout-overswipe-active');
}
}
if ($leftButtons.length > 1) {
$buttonEl.css('z-index', $leftButtons.length - index);
}
$buttonEl.transform(`translate3d(${buttonTranslate + (buttonOffset * (1 - Math.min(progress, 1)))}px,0,0)`);
});
}
$swipeoutEl.trigger('swipeout', progress);
app.emit('swipeout', $swipeoutEl[0], progress);
$swipeoutContent.transform(`translate3d(${translate}px,0,0)`);
}
function handleTouchEnd() {
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
isTouched = false;
isMoved = false;
const timeDiff = (new Date()).getTime() - touchStartTime;
const $actions = direction === 'to-left' ? $actionsRight : $actionsLeft;
const actionsWidth = direction === 'to-left' ? actionsRightWidth : actionsLeftWidth;
let action;
let $buttons;
let i;
if (
(
timeDiff < 300
&&
(
(touchesDiff < -10 && direction === 'to-left')
||
(touchesDiff > 10 && direction === 'to-right')
)
)
||
(
timeDiff >= 300
&&
(Math.abs(translate) > actionsWidth / 2)
)
) {
action = 'open';
} else {
action = 'close';
}
if (timeDiff < 300) {
if (Math.abs(translate) === 0) action = 'close';
if (Math.abs(translate) === actionsWidth) action = 'open';
}
if (action === 'open') {
Swipeout.el = $swipeoutEl[0];
$swipeoutEl.trigger('swipeout:open');
app.emit('swipeoutOpen', $swipeoutEl[0]);
$swipeoutEl.addClass('swipeout-opened swipeout-transitioning');
const newTranslate = direction === 'to-left' ? -actionsWidth : actionsWidth;
$swipeoutContent.transform(`translate3d(${newTranslate}px,0,0)`);
$actions.addClass('swipeout-actions-opened');
$buttons = direction === 'to-left' ? $rightButtons : $leftButtons;
if ($buttons) {
for (i = 0; i < $buttons.length; i += 1) {
$($buttons[i]).transform(`translate3d(${newTranslate}px,0,0)`);
}
}
if (overswipeRight) {
$actionsRight.find('.swipeout-overswipe')[0].click();
}
if (overswipeLeft) {
$actionsLeft.find('.swipeout-overswipe')[0].click();
}
} else {
$swipeoutEl.trigger('swipeout:close');
app.emit('swipeoutClose', $swipeoutEl[0]);
Swipeout.el = undefined;
$swipeoutEl.addClass('swipeout-transitioning').removeClass('swipeout-opened');
$swipeoutContent.transform('');
$actions.removeClass('swipeout-actions-opened');
}
let buttonOffset;
if ($leftButtons && $leftButtons.length > 0 && $leftButtons !== $buttons) {
$leftButtons.each((index, buttonEl) => {
const $buttonEl = $(buttonEl);
buttonOffset = buttonEl.f7SwipeoutButtonOffset;
if (typeof buttonOffset === 'undefined') {
$buttonEl[0].f7SwipeoutButtonOffset = actionsLeftWidth - buttonEl.offsetLeft - buttonEl.offsetWidth;
}
$buttonEl.transform(`translate3d(${buttonOffset}px,0,0)`);
});
}
if ($rightButtons && $rightButtons.length > 0 && $rightButtons !== $buttons) {
$rightButtons.each((index, buttonEl) => {
const $buttonEl = $(buttonEl);
buttonOffset = buttonEl.f7SwipeoutButtonOffset;
if (typeof buttonOffset === 'undefined') {
$buttonEl[0].f7SwipeoutButtonOffset = buttonEl.offsetLeft;
}
$buttonEl.transform(`translate3d(${-buttonOffset}px,0,0)`);
});
}
$swipeoutContent.transitionEnd(() => {
if ((opened && action === 'open') || (!opened && action === 'close')) return;
$swipeoutEl.trigger(action === 'open' ? 'swipeout:opened' : 'swipeout:closed');
app.emit(action === 'open' ? 'swipeoutOpened' : 'swipeoutClosed', $swipeoutEl[0]);
$swipeoutEl.removeClass('swipeout-transitioning');
if (opened && action === 'close') {
if ($actionsRight.length > 0) {
$rightButtons.transform('');
}
if ($actionsLeft.length > 0) {
$leftButtons.transform('');
}
}
});
}
const passiveListener = app.support.passiveListener ? { passive: true } : false;
app.on('touchstart', (e) => {
if (Swipeout.el) {
const $targetEl = $(e.target);
if (!(
$(Swipeout.el).is($targetEl[0]) ||
$targetEl.parents('.swipeout').is(Swipeout.el) ||
$targetEl.hasClass('modal-in') ||
$targetEl[0].className.indexOf('-backdrop') > 0 ||
$targetEl.hasClass('actions-modal') ||
$targetEl.parents('.actions-modal.modal-in, .dialog.modal-in').length > 0
)) {
app.swipeout.close(Swipeout.el);
}
}
});
$(document).on(app.touchEvents.start, 'li.swipeout', handleTouchStart, passiveListener);
app.on('touchmove:active', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
},
allow: true,
el: undefined,
open(...args) {
const app = this;
let [el, side, callback] = args;
if (typeof args[1] === 'function') {
[el, callback, side] = args;
}
const $el = $(el).eq(0);
if ($el.length === 0) return;
if (!$el.hasClass('swipeout') || $el.hasClass('swipeout-opened')) return;
if (!side) {
if ($el.find('.swipeout-actions-right').length > 0) side = 'right';
else side = 'left';
}
const $swipeoutActions = $el.find(`.swipeout-actions-${side}`);
const $swipeoutContent = $el.find('.swipeout-content');
if ($swipeoutActions.length === 0) return;
$el.trigger('swipeout:open').addClass('swipeout-opened').removeClass('swipeout-transitioning');
app.emit('swipeoutOpen', $el[0]);
$swipeoutActions.addClass('swipeout-actions-opened');
const $buttons = $swipeoutActions.children('a');
const swipeoutActionsWidth = $swipeoutActions.outerWidth();
const translate = side === 'right' ? -swipeoutActionsWidth : swipeoutActionsWidth;
if ($buttons.length > 1) {
$buttons.each((buttonIndex, buttonEl) => {
const $buttonEl = $(buttonEl);
if (side === 'right') {
$buttonEl.transform(`translate3d(${-buttonEl.offsetLeft}px,0,0)`);
} else {
$buttonEl.css('z-index', $buttons.length - buttonIndex).transform(`translate3d(${swipeoutActionsWidth - buttonEl.offsetWidth - buttonEl.offsetLeft}px,0,0)`);
}
});
}
$el.addClass('swipeout-transitioning');
$swipeoutContent.transitionEnd(() => {
$el.trigger('swipeout:opened');
app.emit('swipeoutOpened', $el[0]);
if (callback) callback.call($el[0]);
});
Utils.nextFrame(() => {
$buttons.transform(`translate3d(${translate}px,0,0)`);
$swipeoutContent.transform(`translate3d(${translate}px,0,0)`);
});
Swipeout.el = $el[0];
},
close(el, callback) {
const app = this;
const $el = $(el).eq(0);
if ($el.length === 0) return;
if (!$el.hasClass('swipeout-opened')) return;
const side = $el.find('.swipeout-actions-opened').hasClass('swipeout-actions-right') ? 'right' : 'left';
const $swipeoutActions = $el.find('.swipeout-actions-opened').removeClass('swipeout-actions-opened');
const $buttons = $swipeoutActions.children('a');
const swipeoutActionsWidth = $swipeoutActions.outerWidth();
Swipeout.allow = false;
$el.trigger('swipeout:close');
app.emit('swipeoutClose', $el[0]);
$el.removeClass('swipeout-opened').addClass('swipeout-transitioning');
let closeTimeout;
function onSwipeoutClose() {
Swipeout.allow = true;
if ($el.hasClass('swipeout-opened')) return;
$el.removeClass('swipeout-transitioning');
$buttons.transform('');
$el.trigger('swipeout:closed');
app.emit('swipeoutClosed', $el[0]);
if (callback) callback.call($el[0]);
if (closeTimeout) clearTimeout(closeTimeout);
}
$el.find('.swipeout-content').transform('').transitionEnd(onSwipeoutClose);
closeTimeout = setTimeout(onSwipeoutClose, 500);
$buttons.each((index, buttonEl) => {
const $buttonEl = $(buttonEl);
if (side === 'right') {
$buttonEl.transform(`translate3d(${-buttonEl.offsetLeft}px,0,0)`);
} else {
$buttonEl.transform(`translate3d(${swipeoutActionsWidth - buttonEl.offsetWidth - buttonEl.offsetLeft}px,0,0)`);
}
$buttonEl.css({ left: '0px' }).removeClass('swipeout-overswipe-active');
});
if (Swipeout.el && Swipeout.el === $el[0]) Swipeout.el = undefined;
},
delete(el, callback) {
const app = this;
const $el = $(el).eq(0);
if ($el.length === 0) return;
Swipeout.el = undefined;
$el.trigger('swipeout:delete');
app.emit('swipeoutDelete', $el[0]);
$el.css({ height: `${$el.outerHeight()}px` });
$el.transitionEnd(() => {
$el.trigger('swipeout:deleted');
app.emit('swipeoutDeleted', $el[0]);
if (callback) callback.call($el[0]);
if ($el.parents('.virtual-list').length > 0) {
const virtualList = $el.parents('.virtual-list')[0].f7VirtualList;
const virtualIndex = $el[0].f7VirtualListIndex;
if (virtualList && typeof virtualIndex !== 'undefined') virtualList.deleteItem(virtualIndex);
} else if (app.params.swipeout.removeElements) {
if (app.params.swipeout.removeElementsWithTimeout) {
setTimeout(() => {
$el.remove();
}, app.params.swipeout.removeElementsTimeout);
} else {
$el.remove();
}
} else {
$el.removeClass('swipeout-deleting swipeout-transitioning');
}
});
Utils.nextFrame(() => {
$el
.addClass('swipeout-deleting swipeout-transitioning')
.css({ height: '0px' })
.find('.swipeout-content')
.transform('translate3d(-100%,0,0)');
});
},
};
var Swipeout$1 = {
name: 'swipeout',
params: {
swipeout: {
actionsNoFold: false,
noFollow: false,
removeElements: true,
removeElementsWithTimeout: false,
removeElementsTimeout: 0,
},
},
create() {
const app = this;
Utils.extend(app, {
swipeout: {
init: Swipeout.init.bind(app),
open: Swipeout.open.bind(app),
close: Swipeout.close.bind(app),
delete: Swipeout.delete.bind(app),
},
});
Object.defineProperty(app.swipeout, 'el', {
enumerable: true,
configurable: true,
get: () => Swipeout.el,
set(el) {
Swipeout.el = el;
},
});
Object.defineProperty(app.swipeout, 'allow', {
enumerable: true,
configurable: true,
get: () => Swipeout.allow,
set(allow) {
Swipeout.allow = allow;
},
});
},
clicks: {
'.swipeout-open': function openSwipeout($clickedEl, data = {}) {
const app = this;
app.swipeout.open(data.swipeout, data.side);
},
'.swipeout-close': function closeSwipeout($clickedEl) {
const app = this;
const $swipeoutEl = $clickedEl.closest('.swipeout');
if ($swipeoutEl.length === 0) return;
app.swipeout.close($swipeoutEl);
},
'.swipeout-delete': function deleteSwipeout($clickedEl, data = {}) {
const app = this;
const $swipeoutEl = $clickedEl.closest('.swipeout');
if ($swipeoutEl.length === 0) return;
const { confirm, confirmTitle } = data;
if (data.confirm) {
app.dialog.confirm(confirm, confirmTitle, () => {
app.swipeout.delete($swipeoutEl);
});
} else {
app.swipeout.delete($swipeoutEl);
}
},
},
on: {
init() {
const app = this;
if (!app.params.swipeout) return;
app.swipeout.init();
},
},
};
const Accordion = {
toggleClicked($clickedEl) {
const app = this;
let $accordionItemEl = $clickedEl.closest('.accordion-item').eq(0);
if (!$accordionItemEl.length) $accordionItemEl = $clickedEl.parents('li').eq(0);
app.accordion.toggle($accordionItemEl);
},
open(el) {
const app = this;
const $el = $(el);
const $list = $el.parents('.accordion-list').eq(0);
let $contentEl = $el.children('.accordion-item-content');
if ($contentEl.length === 0) $contentEl = $el.find('.accordion-item-content');
if ($contentEl.length === 0) return;
const $openedItem = $list.length > 0 && $el.parent().children('.accordion-item-opened');
if ($openedItem.length > 0) {
app.accordion.close($openedItem);
}
$contentEl.transitionEnd(() => {
if ($el.hasClass('accordion-item-opened')) {
$contentEl.css('height', '');
$contentEl.transition('');
$el.trigger('accordion:opened');
app.emit('accordionOpened', $el[0]);
} else {
$contentEl.css('height', '');
$el.trigger('accordion:closed');
app.emit('accordionClosed', $el[0]);
}
});
$contentEl.css('height', `${$contentEl[0].scrollHeight}px`);
$el.trigger('accordion:open');
$el.addClass('accordion-item-opened');
app.emit('accordionOpen', $el[0]);
},
close(el) {
const app = this;
const $el = $(el);
let $contentEl = $el.children('.accordion-item-content');
if ($contentEl.length === 0) $contentEl = $el.find('.accordion-item-content');
$el.removeClass('accordion-item-opened');
$contentEl.transition(0);
$contentEl.css('height', `${$contentEl[0].scrollHeight}px`);
// Close
$contentEl.transitionEnd(() => {
if ($el.hasClass('accordion-item-opened')) {
$contentEl.css('height', '');
$contentEl.transition('');
$el.trigger('accordion:opened');
app.emit('accordionOpened', $el[0]);
} else {
$contentEl.css('height', '');
$el.trigger('accordion:closed');
app.emit('accordionClosed', $el[0]);
}
});
Utils.nextFrame(() => {
$contentEl.transition('');
$contentEl.css('height', '');
$el.trigger('accordion:close');
app.emit('accordionClose');
});
},
toggle(el) {
const app = this;
const $el = $(el);
if ($el.length === 0) return;
if ($el.hasClass('accordion-item-opened')) app.accordion.close(el);
else app.accordion.open(el);
},
};
var Accordion$1 = {
name: 'accordion',
create() {
const app = this;
Utils.extend(app, {
accordion: {
open: Accordion.open.bind(app),
close: Accordion.close.bind(app),
toggle: Accordion.toggle.bind(app),
},
});
},
clicks: {
'.accordion-item .item-link, .accordion-item-toggle, .links-list.accordion-list > ul > li > a': function open($clickedEl) {
const app = this;
Accordion.toggleClicked.call(app, $clickedEl);
},
},
};
class VirtualList$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const vl = this;
const defaults = {
cols: 1,
height: app.theme === 'md' ? 48 : 44,
cache: true,
dynamicHeightBufferSize: 1,
showFilteredItemsOnly: false,
renderExternal: undefined,
setListHeight: true,
searchByItem: undefined,
searchAll: undefined,
itemTemplate: undefined,
renderItem(item) {
return `
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title">${item}</div>
</div>
</div>
</li>
`.trim();
},
on: {},
};
// Extend defaults with modules params
vl.useModulesParams(defaults);
vl.params = Utils.extend(defaults, params);
if (vl.params.height === undefined || !vl.params.height) {
vl.params.height = app.theme === 'md' ? 48 : 44;
}
vl.$el = $(params.el);
vl.el = vl.$el[0];
if (vl.$el.length === 0) return undefined;
vl.$el[0].f7VirtualList = vl;
vl.items = vl.params.items;
if (vl.params.showFilteredItemsOnly) {
vl.filteredItems = [];
}
if (vl.params.itemTemplate) {
if (typeof vl.params.itemTemplate === 'string') vl.renderItem = Template7.compile(vl.params.itemTemplate);
else if (typeof vl.params.itemTemplate === 'function') vl.renderItem = vl.params.itemTemplate;
} else if (vl.params.renderItem) {
vl.renderItem = vl.params.renderItem;
}
vl.$pageContentEl = vl.$el.parents('.page-content');
// Bad scroll
if (typeof vl.params.updatableScroll !== 'undefined') {
vl.updatableScroll = vl.params.updatableScroll;
} else {
vl.updatableScroll = true;
if (Device.ios && Device.osVersion.split('.')[0] < 8) {
vl.updatableScroll = false;
}
}
// Append <ul>
vl.$ul = vl.params.ul ? $(vl.params.ul) : vl.$el.children('ul');
if (vl.$ul.length === 0) {
vl.$el.append('<ul></ul>');
vl.$ul = vl.$el.children('ul');
}
vl.ul = vl.$ul[0];
Utils.extend(vl, {
// DOM cached items
domCache: {},
displayDomCache: {},
// Temporary DOM Element
tempDomElement: document.createElement('ul'),
// Last repain position
lastRepaintY: null,
// Fragment
fragment: document.createDocumentFragment(),
// Props
pageHeight: undefined,
rowsPerScreen: undefined,
rowsBefore: undefined,
rowsAfter: undefined,
rowsToRender: undefined,
maxBufferHeight: 0,
listHeight: undefined,
dynamicHeight: typeof vl.params.height === 'function',
});
// Install Modules
vl.useModules();
// Attach events
const handleScrollBound = vl.handleScroll.bind(vl);
const handleResizeBound = vl.handleResize.bind(vl);
let $pageEl;
let $tabEl;
let $panelEl;
let $popupEl;
vl.attachEvents = function attachEvents() {
$pageEl = vl.$el.parents('.page').eq(0);
$tabEl = vl.$el.parents('.tab').eq(0);
$panelEl = vl.$el.parents('.panel').eq(0);
$popupEl = vl.$el.parents('.popup').eq(0);
vl.$pageContentEl.on('scroll', handleScrollBound);
if ($pageEl) $pageEl.on('page:reinit', handleResizeBound);
if ($tabEl) $tabEl.on('tab:show', handleResizeBound);
if ($panelEl) $panelEl.on('panel:open', handleResizeBound);
if ($popupEl) $popupEl.on('popup:open', handleResizeBound);
app.on('resize', handleResizeBound);
};
vl.detachEvents = function attachEvents() {
vl.$pageContentEl.off('scroll', handleScrollBound);
if ($pageEl) $pageEl.off('page:reinit', handleResizeBound);
if ($tabEl) $tabEl.off('tab:show', handleResizeBound);
if ($panelEl) $panelEl.off('panel:open', handleResizeBound);
if ($popupEl) $popupEl.off('popup:open', handleResizeBound);
app.off('resize', handleResizeBound);
};
// Init
vl.init();
return vl;
}
setListSize() {
const vl = this;
const items = vl.filteredItems || vl.items;
vl.pageHeight = vl.$pageContentEl[0].offsetHeight;
if (vl.dynamicHeight) {
vl.listHeight = 0;
vl.heights = [];
for (let i = 0; i < items.length; i += 1) {
const itemHeight = vl.params.height(items[i]);
vl.listHeight += itemHeight;
vl.heights.push(itemHeight);
}
} else {
vl.listHeight = Math.ceil(items.length / vl.params.cols) * vl.params.height;
vl.rowsPerScreen = Math.ceil(vl.pageHeight / vl.params.height);
vl.rowsBefore = vl.params.rowsBefore || vl.rowsPerScreen * 2;
vl.rowsAfter = vl.params.rowsAfter || vl.rowsPerScreen;
vl.rowsToRender = (vl.rowsPerScreen + vl.rowsBefore + vl.rowsAfter);
vl.maxBufferHeight = (vl.rowsBefore / 2) * vl.params.height;
}
if (vl.updatableScroll || vl.params.setListHeight) {
vl.$ul.css({ height: `${vl.listHeight}px` });
}
}
render(force, forceScrollTop) {
const vl = this;
if (force) vl.lastRepaintY = null;
let scrollTop = -(vl.$el[0].getBoundingClientRect().top - vl.$pageContentEl[0].getBoundingClientRect().top);
if (typeof forceScrollTop !== 'undefined') scrollTop = forceScrollTop;
if (vl.lastRepaintY === null || Math.abs(scrollTop - vl.lastRepaintY) > vl.maxBufferHeight || (!vl.updatableScroll && (vl.$pageContentEl[0].scrollTop + vl.pageHeight >= vl.$pageContentEl[0].scrollHeight))) {
vl.lastRepaintY = scrollTop;
} else {
return;
}
const items = vl.filteredItems || vl.items;
let fromIndex;
let toIndex;
let heightBeforeFirstItem = 0;
let heightBeforeLastItem = 0;
if (vl.dynamicHeight) {
let itemTop = 0;
let itemHeight;
vl.maxBufferHeight = vl.pageHeight;
for (let j = 0; j < vl.heights.length; j += 1) {
itemHeight = vl.heights[j];
if (typeof fromIndex === 'undefined') {
if (itemTop + itemHeight >= scrollTop - (vl.pageHeight * 2 * vl.params.dynamicHeightBufferSize)) fromIndex = j;
else heightBeforeFirstItem += itemHeight;
}
if (typeof toIndex === 'undefined') {
if (itemTop + itemHeight >= scrollTop + (vl.pageHeight * 2 * vl.params.dynamicHeightBufferSize) || j === vl.heights.length - 1) toIndex = j + 1;
heightBeforeLastItem += itemHeight;
}
itemTop += itemHeight;
}
toIndex = Math.min(toIndex, items.length);
} else {
fromIndex = (parseInt(scrollTop / vl.params.height, 10) - vl.rowsBefore) * vl.params.cols;
if (fromIndex < 0) {
fromIndex = 0;
}
toIndex = Math.min(fromIndex + (vl.rowsToRender * vl.params.cols), items.length);
}
let topPosition;
const renderExternalItems = [];
vl.reachEnd = false;
let i;
for (i = fromIndex; i < toIndex; i += 1) {
let itemEl;
// Define real item index
const index = vl.items.indexOf(items[i]);
if (i === fromIndex) vl.currentFromIndex = index;
if (i === toIndex - 1) vl.currentToIndex = index;
if (vl.filteredItems) {
if (vl.items[index] === vl.filteredItems[vl.filteredItems.length - 1]) vl.reachEnd = true;
} else if (index === vl.items.length - 1) vl.reachEnd = true;
// Find items
if (vl.params.renderExternal) {
renderExternalItems.push(items[i]);
} else if (vl.domCache[index]) {
itemEl = vl.domCache[index];
itemEl.f7VirtualListIndex = index;
} else {
if (vl.renderItem) {
vl.tempDomElement.innerHTML = vl.renderItem(items[i], index).trim();
} else {
vl.tempDomElement.innerHTML = items[i].toString().trim();
}
itemEl = vl.tempDomElement.childNodes[0];
if (vl.params.cache) vl.domCache[index] = itemEl;
itemEl.f7VirtualListIndex = index;
}
// Set item top position
if (i === fromIndex) {
if (vl.dynamicHeight) {
topPosition = heightBeforeFirstItem;
} else {
topPosition = ((i * vl.params.height) / vl.params.cols);
}
}
if (!vl.params.renderExternal) {
itemEl.style.top = `${topPosition}px`;
// Before item insert
vl.emit({
events: 'itemBeforeInsert',
data: [itemEl, items[i]],
parents: [],
});
vl.emit('vlItemBeforeInsert', vl, itemEl, items[i]);
// Append item to fragment
vl.fragment.appendChild(itemEl);
}
}
// Update list height with not updatable scroll
if (!vl.updatableScroll) {
if (vl.dynamicHeight) {
vl.ul.style.height = `${heightBeforeLastItem}px`;
} else {
vl.ul.style.height = `${(i * vl.params.height) / vl.params.cols}px`;
}
}
// Update list html
if (vl.params.renderExternal) {
if (items && items.length === 0) {
vl.reachEnd = true;
}
} else {
vl.emit({
events: 'beforeClear',
data: [vl.fragment],
parents: [],
});
vl.emit('vlBeforeClear', vl, vl.fragment);
vl.ul.innerHTML = '';
vl.emit({
events: 'itemsBeforeInsert',
data: [vl.fragment],
parents: [],
});
vl.emit('vlItemsBeforeInsert', vl, vl.fragment);
if (items && items.length === 0) {
vl.reachEnd = true;
if (vl.params.emptyTemplate) vl.ul.innerHTML = vl.params.emptyTemplate;
} else {
vl.ul.appendChild(vl.fragment);
}
vl.emit({
events: 'itemsAfterInsert',
data: [vl.fragment],
parents: [],
});
vl.emit('vlItemsAfterInsert', vl, vl.fragment);
}
if (typeof forceScrollTop !== 'undefined' && force) {
vl.$pageContentEl.scrollTop(forceScrollTop, 0);
}
if (vl.params.renderExternal) {
vl.params.renderExternal(vl, {
fromIndex,
toIndex,
listHeight: vl.listHeight,
topPosition,
items: renderExternalItems,
});
}
}
// Filter
filterItems(indexes, resetScrollTop = true) {
const vl = this;
vl.filteredItems = [];
for (let i = 0; i < indexes.length; i += 1) {
vl.filteredItems.push(vl.items[indexes[i]]);
}
if (resetScrollTop) {
vl.$pageContentEl[0].scrollTop = 0;
}
vl.update();
}
resetFilter() {
const vl = this;
if (vl.params.showFilteredItemsOnly) {
vl.filteredItems = [];
} else {
vl.filteredItems = null;
delete vl.filteredItems;
}
vl.update();
}
scrollToItem(index) {
const vl = this;
if (index > vl.items.length) return false;
let itemTop = 0;
if (vl.dynamicHeight) {
for (let i = 0; i < index; i += 1) {
itemTop += vl.heights[i];
}
} else {
itemTop = index * vl.params.height;
}
const listTop = vl.$el[0].offsetTop;
vl.render(true, (listTop + itemTop) - parseInt(vl.$pageContentEl.css('padding-top'), 10));
return true;
}
handleScroll() {
const vl = this;
vl.render();
}
// Handle resize event
isVisible() {
const vl = this;
return !!(vl.el.offsetWidth || vl.el.offsetHeight || vl.el.getClientRects().length);
}
handleResize() {
const vl = this;
if (vl.isVisible()) {
vl.setListSize();
vl.render(true);
}
}
// Append
appendItems(items) {
const vl = this;
for (let i = 0; i < items.length; i += 1) {
vl.items.push(items[i]);
}
vl.update();
}
appendItem(item) {
const vl = this;
vl.appendItems([item]);
}
// Replace
replaceAllItems(items) {
const vl = this;
vl.items = items;
delete vl.filteredItems;
vl.domCache = {};
vl.update();
}
replaceItem(index, item) {
const vl = this;
vl.items[index] = item;
if (vl.params.cache) delete vl.domCache[index];
vl.update();
}
// Prepend
prependItems(items) {
const vl = this;
for (let i = items.length - 1; i >= 0; i -= 1) {
vl.items.unshift(items[i]);
}
if (vl.params.cache) {
const newCache = {};
Object.keys(vl.domCache).forEach((cached) => {
newCache[parseInt(cached, 10) + items.length] = vl.domCache[cached];
});
vl.domCache = newCache;
}
vl.update();
}
prependItem(item) {
const vl = this;
vl.prependItems([item]);
}
// Move
moveItem(from, to) {
const vl = this;
const fromIndex = from;
let toIndex = to;
if (fromIndex === toIndex) return;
// remove item from array
const item = vl.items.splice(fromIndex, 1)[0];
if (toIndex >= vl.items.length) {
// Add item to the end
vl.items.push(item);
toIndex = vl.items.length - 1;
} else {
// Add item to new index
vl.items.splice(toIndex, 0, item);
}
// Update cache
if (vl.params.cache) {
const newCache = {};
Object.keys(vl.domCache).forEach((cached) => {
const cachedIndex = parseInt(cached, 10);
const leftIndex = fromIndex < toIndex ? fromIndex : toIndex;
const rightIndex = fromIndex < toIndex ? toIndex : fromIndex;
const indexShift = fromIndex < toIndex ? -1 : 1;
if (cachedIndex < leftIndex || cachedIndex > rightIndex) newCache[cachedIndex] = vl.domCache[cachedIndex];
if (cachedIndex === leftIndex) newCache[rightIndex] = vl.domCache[cachedIndex];
if (cachedIndex > leftIndex && cachedIndex <= rightIndex) newCache[cachedIndex + indexShift] = vl.domCache[cachedIndex];
});
vl.domCache = newCache;
}
vl.update();
}
// Insert before
insertItemBefore(index, item) {
const vl = this;
if (index === 0) {
vl.prependItem(item);
return;
}
if (index >= vl.items.length) {
vl.appendItem(item);
return;
}
vl.items.splice(index, 0, item);
// Update cache
if (vl.params.cache) {
const newCache = {};
Object.keys(vl.domCache).forEach((cached) => {
const cachedIndex = parseInt(cached, 10);
if (cachedIndex >= index) {
newCache[cachedIndex + 1] = vl.domCache[cachedIndex];
}
});
vl.domCache = newCache;
}
vl.update();
}
// Delete
deleteItems(indexes) {
const vl = this;
let prevIndex;
let indexShift = 0;
for (let i = 0; i < indexes.length; i += 1) {
let index = indexes[i];
if (typeof prevIndex !== 'undefined') {
if (index > prevIndex) {
indexShift = -i;
}
}
index += indexShift;
prevIndex = indexes[i];
// Delete item
const deletedItem = vl.items.splice(index, 1)[0];
// Delete from filtered
if (vl.filteredItems && vl.filteredItems.indexOf(deletedItem) >= 0) {
vl.filteredItems.splice(vl.filteredItems.indexOf(deletedItem), 1);
}
// Update cache
if (vl.params.cache) {
const newCache = {};
Object.keys(vl.domCache).forEach((cached) => {
const cachedIndex = parseInt(cached, 10);
if (cachedIndex === index) {
delete vl.domCache[index];
} else if (parseInt(cached, 10) > index) {
newCache[cachedIndex - 1] = vl.domCache[cached];
} else {
newCache[cachedIndex] = vl.domCache[cached];
}
});
vl.domCache = newCache;
}
}
vl.update();
}
deleteAllItems() {
const vl = this;
vl.items = [];
delete vl.filteredItems;
if (vl.params.cache) vl.domCache = {};
vl.update();
}
deleteItem(index) {
const vl = this;
vl.deleteItems([index]);
}
// Clear cache
clearCachefunction() {
const vl = this;
vl.domCache = {};
}
// Update Virtual List
update() {
const vl = this;
vl.setListSize();
vl.render(true);
}
init() {
const vl = this;
vl.attachEvents();
vl.setListSize();
vl.render();
}
destroy() {
let vl = this;
vl.detachEvents();
vl.$el[0].f7VirtualList = null;
delete vl.$el[0].f7VirtualList;
Utils.deleteProps(vl);
vl = null;
}
}
var VirtualList = {
name: 'virtualList',
static: {
VirtualList: VirtualList$1,
},
create() {
const app = this;
app.virtualList = ConstructorMethods({
defaultSelector: '.virtual-list',
constructor: VirtualList$1,
app,
domProp: 'f7VirtualList',
});
},
};
var Timeline = {
name: 'timeline',
};
const Tab = {
show(...args) {
const app = this;
let tabEl;
let tabLinkEl;
let animate;
let tabRoute;
if (args.length === 1 && args[0].constructor === Object) {
tabEl = args[0].tabEl;
tabLinkEl = args[0].tabLinkEl;
animate = args[0].animate;
tabRoute = args[0].tabRoute;
} else {
[tabEl, tabLinkEl, animate, tabRoute] = args;
if (typeof args[1] === 'boolean') {
[tabEl, animate, tabLinkEl, tabRoute] = args;
if (args.length > 2 && tabLinkEl.constructor === Object) {
[tabEl, animate, tabRoute, tabLinkEl] = args;
}
}
}
if (typeof animate === 'undefined') animate = true;
const $newTabEl = $(tabEl);
if ($newTabEl.length === 0 || $newTabEl.hasClass('tab-active')) {
return {
$newTabEl,
newTabEl: $newTabEl[0],
};
}
let $tabLinkEl;
if (tabLinkEl) $tabLinkEl = $(tabLinkEl);
const $tabsEl = $newTabEl.parent('.tabs');
if ($tabsEl.length === 0) {
return {
$newTabEl,
newTabEl: $newTabEl[0],
};
}
// Release swipeouts in hidden tabs
if (app.swipeout) app.swipeout.allowOpen = true;
// Animated tabs
const tabsChangedCallbacks = [];
function onTabsChanged(callback) {
tabsChangedCallbacks.push(callback);
}
function tabsChanged() {
tabsChangedCallbacks.forEach((callback) => {
callback();
});
}
let animated = false;
if ($tabsEl.parent().hasClass('tabs-animated-wrap')) {
$tabsEl.parent()[animate ? 'removeClass' : 'addClass']('not-animated');
const transitionDuration = parseFloat($tabsEl.css('transition-duration').replace(',', '.'));
if (animate && transitionDuration) {
$tabsEl.transitionEnd(tabsChanged);
animated = true;
}
const tabsTranslate = (app.rtl ? $newTabEl.index() : -$newTabEl.index()) * 100;
$tabsEl.transform(`translate3d(${tabsTranslate}%,0,0)`);
}
// Swipeable tabs
if ($tabsEl.parent().hasClass('tabs-swipeable-wrap') && app.swiper) {
const swiper = $tabsEl.parent()[0].swiper;
if (swiper && swiper.activeIndex !== $newTabEl.index()) {
animated = true;
swiper
.once('slideChangeTransitionEnd', () => {
tabsChanged();
})
.slideTo($newTabEl.index(), animate ? undefined : 0);
}
}
// Remove active class from old tabs
const $oldTabEl = $tabsEl.children('.tab-active');
$oldTabEl
.removeClass('tab-active')
.trigger('tab:hide');
app.emit('tabHide', $oldTabEl[0]);
// Trigger 'show' event on new tab
$newTabEl
.addClass('tab-active')
.trigger('tab:show');
app.emit('tabShow', $newTabEl[0]);
// Find related link for new tab
if (!$tabLinkEl) {
// Search by id
if (typeof tabEl === 'string') $tabLinkEl = $(`.tab-link[href="${tabEl}"]`);
else $tabLinkEl = $(`.tab-link[href="#${$newTabEl.attr('id')}"]`);
// Search by data-tab
if (!$tabLinkEl || ($tabLinkEl && $tabLinkEl.length === 0)) {
$('[data-tab]').each((index, el) => {
if ($newTabEl.is($(el).attr('data-tab'))) $tabLinkEl = $(el);
});
}
if (tabRoute && (!$tabLinkEl || ($tabLinkEl && $tabLinkEl.length === 0))) {
$tabLinkEl = $(`[data-route-tab-id="${tabRoute.route.tab.id}"]`);
if ($tabLinkEl.length === 0) {
$tabLinkEl = $(`.tab-link[href="${tabRoute.url}"]`);
}
}
if ($tabLinkEl.length > 1 && $newTabEl.parents('.page').length) {
// eslint-disable-next-line
$tabLinkEl = $tabLinkEl.filter((index, tabLinkElement) => {
return $(tabLinkElement).parents('.page')[0] === $newTabEl.parents('.page')[0];
});
}
}
if ($tabLinkEl.length > 0) {
// Find related link for old tab
let $oldTabLinkEl;
if ($oldTabEl && $oldTabEl.length > 0) {
// Search by id
const oldTabId = $oldTabEl.attr('id');
if (oldTabId) $oldTabLinkEl = $(`.tab-link[href="#${oldTabId}"]`);
// Search by data-tab
if (!$oldTabLinkEl || ($oldTabLinkEl && $oldTabLinkEl.length === 0)) {
$('[data-tab]').each((index, tabLinkElement) => {
if ($oldTabEl.is($(tabLinkElement).attr('data-tab'))) $oldTabLinkEl = $(tabLinkElement);
});
}
if (!$oldTabLinkEl || ($oldTabLinkEl && $oldTabLinkEl.length === 0)) {
$oldTabLinkEl = $tabLinkEl.siblings('.tab-link-active');
}
} else if (tabRoute) {
$oldTabLinkEl = $tabLinkEl.siblings('.tab-link-active');
}
if ($oldTabLinkEl && $oldTabLinkEl.length > 1 && $oldTabEl && $oldTabEl.parents('.page').length) {
// eslint-disable-next-line
$oldTabLinkEl = $oldTabLinkEl.filter((index, tabLinkElement) => {
return $(tabLinkElement).parents('.page')[0] === $oldTabEl.parents('.page')[0];
});
}
if ($oldTabLinkEl && $oldTabLinkEl.length > 0) $oldTabLinkEl.removeClass('tab-link-active');
// Update links' classes
if ($tabLinkEl && $tabLinkEl.length > 0) {
$tabLinkEl.addClass('tab-link-active');
// Material Highlight
if (app.theme === 'md' && app.toolbar) {
const $tabbarEl = $tabLinkEl.parents('.tabbar, .tabbar-labels');
if ($tabbarEl.length > 0) {
app.toolbar.setHighlight($tabbarEl);
}
}
}
}
return {
$newTabEl,
newTabEl: $newTabEl[0],
$oldTabEl,
oldTabEl: $oldTabEl[0],
onTabsChanged,
animated,
};
},
};
var Tabs = {
name: 'tabs',
create() {
const app = this;
Utils.extend(app, {
tab: {
show: Tab.show.bind(app),
},
});
},
clicks: {
'.tab-link': function tabLinkClick($clickedEl, data = {}) {
const app = this;
if (($clickedEl.attr('href') && $clickedEl.attr('href').indexOf('#') === 0) || $clickedEl.attr('data-tab')) {
app.tab.show({
tabEl: data.tab || $clickedEl.attr('href'),
tabLinkEl: $clickedEl,
animate: data.animate,
});
}
},
},
};
function swipePanel$1(panel) {
const app = panel.app;
Utils.extend(panel, {
swipeable: true,
swipeInitialized: true,
});
const params = app.params.panel;
const { $el, $backdropEl, side, effect } = panel;
let otherPanel;
let isTouched;
let isMoved;
let isScrolling;
const touchesStart = {};
let touchStartTime;
let touchesDiff;
let translate;
let backdropOpacity;
let panelWidth;
let direction;
let $viewEl;
let touchMoves = 0;
function handleTouchStart(e) {
if (!panel.swipeable) return;
if (!app.panel.allowOpen || (!params.swipe && !params.swipeOnlyClose) || isTouched) return;
if ($('.modal-in, .photo-browser-in').length > 0) return;
otherPanel = app.panel[side === 'left' ? 'right' : 'left'] || {};
if (!panel.opened && otherPanel.opened) return;
if (!(params.swipeCloseOpposite || params.swipeOnlyClose)) {
if (otherPanel.opened) return;
}
if (e.target && e.target.nodeName.toLowerCase() === 'input' && e.target.type === 'range') return;
if ($(e.target).closest('.range-slider, .tabs-swipeable-wrap, .calendar-months').length > 0) return;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
if (params.swipeOnlyClose && !panel.opened) {
return;
}
if (params.swipe !== 'both' && params.swipeCloseOpposite && params.swipe !== side && !panel.opened) {
return;
}
if (params.swipeActiveArea && !panel.opened) {
if (side === 'left') {
if (touchesStart.x > params.swipeActiveArea) return;
}
if (side === 'right') {
if (touchesStart.x < app.width - params.swipeActiveArea) return;
}
}
touchMoves = 0;
$viewEl = $(panel.getViewEl());
isMoved = false;
isTouched = true;
isScrolling = undefined;
touchStartTime = Utils.now();
direction = undefined;
}
function handleTouchMove(e) {
if (!isTouched) return;
touchMoves += 1;
if (touchMoves < 2) return;
if (e.f7PreventSwipePanel || app.preventSwipePanelBySwipeBack || app.preventSwipePanel) {
isTouched = false;
return;
}
const pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
}
if (isScrolling) {
isTouched = false;
return;
}
if (!direction) {
if (pageX > touchesStart.x) {
direction = 'to-right';
} else {
direction = 'to-left';
}
if (params.swipe === 'both') {
if (params.swipeActiveArea > 0) {
if (side === 'left' && touchesStart.x > params.swipeActiveArea) {
isTouched = false;
return;
}
if (side === 'right' && touchesStart.x < app.width - params.swipeActiveArea) {
isTouched = false;
return;
}
}
}
if ($el.hasClass('panel-visible-by-breakpoint')) {
isTouched = false;
return;
}
if (
(side === 'left' &&
(
direction === 'to-left' && !$el.hasClass('panel-active')
)
)
||
(side === 'right' &&
(
direction === 'to-right' && !$el.hasClass('panel-active')
)
)
) {
isTouched = false;
return;
}
}
if (params.swipeNoFollow) {
const timeDiff = (new Date()).getTime() - touchStartTime;
if (timeDiff < 300) {
if (direction === 'to-left') {
if (side === 'right') app.openPanel(side);
if (side === 'left' && $el.hasClass('panel-active')) app.closePanel();
}
if (direction === 'to-right') {
if (side === 'left') app.openPanel(side);
if (side === 'right' && $el.hasClass('panel-active')) app.closePanel();
}
}
isTouched = false;
isMoved = false;
return;
}
if (!isMoved) {
if (!panel.opened) {
$el.show();
$backdropEl.show();
$el.trigger('panel:swipeopen', panel);
panel.emit('local::swipeOpen panelSwipeOpen', panel);
}
panelWidth = $el[0].offsetWidth;
$el.transition(0);
}
isMoved = true;
e.preventDefault();
let threshold = panel.opened ? 0 : -params.swipeThreshold;
if (side === 'right') threshold = -threshold;
touchesDiff = (pageX - touchesStart.x) + threshold;
if (side === 'right') {
if (effect === 'cover') {
translate = touchesDiff + (panel.opened ? 0 : panelWidth);
if (translate < 0) translate = 0;
if (translate > panelWidth) {
translate = panelWidth;
}
} else {
translate = touchesDiff - (panel.opened ? panelWidth : 0);
if (translate > 0) translate = 0;
if (translate < -panelWidth) {
translate = -panelWidth;
}
}
} else {
translate = touchesDiff + (panel.opened ? panelWidth : 0);
if (translate < 0) translate = 0;
if (translate > panelWidth) {
translate = panelWidth;
}
}
if (effect === 'reveal') {
$viewEl.transform(`translate3d(${translate}px,0,0)`).transition(0);
$backdropEl.transform(`translate3d(${translate}px,0,0)`).transition(0);
$el.trigger('panel:swipe', panel, Math.abs(translate / panelWidth));
panel.emit('local::swipe panelSwipe', panel, Math.abs(translate / panelWidth));
} else {
if (side === 'left') translate -= panelWidth;
$el.transform(`translate3d(${translate}px,0,0)`).transition(0);
$backdropEl.transition(0);
backdropOpacity = 1 - Math.abs(translate / panelWidth);
$backdropEl.css({ opacity: backdropOpacity });
$el.trigger('panel:swipe', panel, Math.abs(translate / panelWidth));
panel.emit('local::swipe panelSwipe', panel, Math.abs(translate / panelWidth));
}
}
function handleTouchEnd() {
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
isTouched = false;
isMoved = false;
const timeDiff = (new Date()).getTime() - touchStartTime;
let action;
const edge = (translate === 0 || Math.abs(translate) === panelWidth);
if (!panel.opened) {
if (effect === 'cover') {
if (translate === 0) {
action = 'swap'; // open
} else if (timeDiff < 300 && Math.abs(translate) > 0) {
action = 'swap'; // open
} else if (timeDiff >= 300 && Math.abs(translate) < panelWidth / 2) {
action = 'swap'; // open
} else {
action = 'reset'; // close
}
} else if (translate === 0) {
action = 'reset';
} else if (
(timeDiff < 300 && Math.abs(translate) > 0)
||
(timeDiff >= 300 && (Math.abs(translate) >= panelWidth / 2))
) {
action = 'swap';
} else {
action = 'reset';
}
} else if (effect === 'cover') {
if (translate === 0) {
action = 'reset'; // open
} else if (timeDiff < 300 && Math.abs(translate) > 0) {
action = 'swap'; // open
} else if (timeDiff >= 300 && Math.abs(translate) < panelWidth / 2) {
action = 'reset'; // open
} else {
action = 'swap'; // close
}
} else if (translate === -panelWidth) {
action = 'reset';
} else if (
(timeDiff < 300 && Math.abs(translate) >= 0)
||
(timeDiff >= 300 && (Math.abs(translate) <= panelWidth / 2))
) {
if (side === 'left' && translate === panelWidth) action = 'reset';
else action = 'swap';
} else {
action = 'reset';
}
if (action === 'swap') {
if (panel.opened) {
panel.close(!edge);
} else {
panel.open(!edge);
}
}
if (action === 'reset') {
if (!panel.opened) {
if (edge) {
$el.css({ display: '' });
} else {
const target = effect === 'reveal' ? $viewEl : $el;
$('html').addClass('with-panel-transitioning');
target.transitionEnd(() => {
if ($el.hasClass('panel-active')) return;
$el.css({ display: '' });
$('html').removeClass('with-panel-transitioning');
});
}
}
}
if (effect === 'reveal') {
Utils.nextFrame(() => {
$viewEl.transition('');
$viewEl.transform('');
});
}
$el.transition('').transform('');
$backdropEl.css({ display: '' }).transform('').transition('').css('opacity', '');
}
// Add Events
app.on('touchstart:passive', handleTouchStart);
app.on('touchmove:active', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
panel.on('panelDestroy', () => {
app.off('touchstart:passive', handleTouchStart);
app.off('touchmove:active', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
});
}
class Panel$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const panel = this;
const el = params.el;
const $el = $(el);
if ($el.length === 0) return panel;
if ($el[0].f7Panel) return $el[0].f7Panel;
$el[0].f7Panel = panel;
let { opened, side, effect } = params;
if (typeof opened === 'undefined') opened = $el.hasClass('panel-active');
if (typeof side === 'undefined') side = $el.hasClass('panel-left') ? 'left' : 'right';
if (typeof effect === 'undefined') effect = $el.hasClass('panel-cover') ? 'cover' : 'reveal';
if (!app.panel[side]) {
Utils.extend(app.panel, {
[side]: panel,
});
}
let $backdropEl = $('.panel-backdrop');
if ($backdropEl.length === 0) {
$backdropEl = $('<div class="panel-backdrop"></div>');
$backdropEl.insertBefore($el);
}
Utils.extend(panel, {
app,
side,
effect,
$el,
el: $el[0],
opened,
$backdropEl,
backdropEl: $backdropEl[0],
});
// Install Modules
panel.useModules();
// Init
panel.init();
return panel;
}
init() {
const panel = this;
const app = panel.app;
if (app.params.panel[`${panel.side}Breakpoint`]) {
panel.initBreakpoints();
}
{
if (
(app.params.panel.swipe === panel.side)
||
(app.params.panel.swipe === 'both')
||
(app.params.panel.swipe && app.params.panel.swipe !== panel.side && app.params.panel.swipeCloseOpposite)
) {
panel.initSwipePanel();
}
}
}
getViewEl() {
const panel = this;
const app = panel.app;
let viewEl;
if (app.root.children('.views').length > 0) {
viewEl = app.root.children('.views')[0];
} else {
viewEl = app.root.children('.view')[0];
}
return viewEl;
}
setBreakpoint() {
const panel = this;
const app = panel.app;
const { side, $el } = panel;
const $viewEl = $(panel.getViewEl());
const breakpoint = app.params.panel[`${side}Breakpoint`];
const wasVisible = $el.hasClass('panel-visible-by-breakpoint');
if (app.width >= breakpoint) {
if (!wasVisible) {
$('html').removeClass(`with-panel-${side}-reveal with-panel-${side}-cover with-panel`);
$el.css('display', '').addClass('panel-visible-by-breakpoint').removeClass('panel-active');
panel.onOpen();
panel.onOpened();
$viewEl.css({
[`margin-${side}`]: `${$el.width()}px`,
});
app.allowPanelOpen = true;
app.emit('local::breakpoint panelBreakpoint');
panel.$el.trigger('panel:breakpoint', panel);
}
} else if (wasVisible) {
$el.css('display', '').removeClass('panel-visible-by-breakpoint panel-active');
panel.onClose();
panel.onClosed();
$viewEl.css({
[`margin-${side}`]: '',
});
app.emit('local::breakpoint panelBreakpoint');
panel.$el.trigger('panel:breakpoint', panel);
}
}
initBreakpoints() {
const panel = this;
const app = panel.app;
panel.resizeHandler = function resizeHandler() {
panel.setBreakpoint();
};
if (app.params.panel[`${panel.side}Breakpoint`]) {
app.on('resize', panel.resizeHandler);
}
panel.setBreakpoint();
return panel;
}
initSwipePanel() {
{
swipePanel$1(this);
}
}
destroy() {
let panel = this;
const app = panel.app;
panel.emit('local::beforeDestroy panelBeforeDestroy', panel);
panel.$el.trigger('panel:beforedestroy', panel);
if (panel.resizeHandler) {
app.off('resize', panel.resizeHandler);
}
panel.$el.trigger('panel:destroy', panel);
panel.emit('local::destroy panelDestroy');
delete app.panel[panel.side];
delete panel.el.f7Panel;
Utils.deleteProps(panel);
panel = null;
}
open(animate = true) {
const panel = this;
const app = panel.app;
if (!app.panel.allowOpen) return false;
const { side, effect, $el, $backdropEl, opened } = panel;
// Ignore if opened
if (opened || $el.hasClass('panel-visible-by-breakpoint') || $el.hasClass('panel-active')) return false;
// Close if some panel is opened
app.panel.close(side === 'left' ? 'right' : 'left', animate);
app.panel.allowOpen = false;
$el[animate ? 'removeClass' : 'addClass']('not-animated');
$el
.css({ display: 'block' })
.addClass('panel-active');
$backdropEl[animate ? 'removeClass' : 'addClass']('not-animated');
$backdropEl.show();
/* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
panel._clientLeft = $el[0].clientLeft;
$('html').addClass(`with-panel with-panel-${side}-${effect}`);
panel.onOpen();
// Transition End;
const transitionEndTarget = effect === 'reveal' ? $el.nextAll('.view, .views').eq(0) : $el;
function panelTransitionEnd() {
transitionEndTarget.transitionEnd((e) => {
if ($(e.target).is(transitionEndTarget)) {
if ($el.hasClass('panel-active')) {
panel.onOpened();
$backdropEl.css({ display: '' });
} else {
panel.onClosed();
$backdropEl.css({ display: '' });
}
} else panelTransitionEnd();
});
}
if (animate) {
panelTransitionEnd();
} else {
panel.onOpened();
$backdropEl.css({ display: '' });
}
return true;
}
close(animate = true) {
const panel = this;
const app = panel.app;
const { side, effect, $el, $backdropEl, opened } = panel;
if (!opened || $el.hasClass('panel-visible-by-breakpoint') || !$el.hasClass('panel-active')) return false;
$el[animate ? 'removeClass' : 'addClass']('not-animated');
$el.removeClass('panel-active');
$backdropEl[animate ? 'removeClass' : 'addClass']('not-animated');
const transitionEndTarget = effect === 'reveal' ? $el.nextAll('.view, .views').eq(0) : $el;
panel.onClose();
app.panel.allowOpen = false;
if (animate) {
transitionEndTarget.transitionEnd(() => {
if ($el.hasClass('panel-active')) return;
$el.css({ display: '' });
$('html').removeClass('with-panel-transitioning');
panel.onClosed();
});
$('html')
.removeClass(`with-panel with-panel-${side}-${effect}`)
.addClass('with-panel-transitioning');
} else {
$el.css({ display: '' });
$el.removeClass('not-animated');
$('html').removeClass(`with-panel with-panel-transitioning with-panel-${side}-${effect}`);
panel.onClosed();
}
return true;
}
onOpen() {
const panel = this;
panel.opened = true;
panel.$el.trigger('panel:open', panel);
panel.emit('local::open panelOpen', panel);
}
onOpened() {
const panel = this;
const app = panel.app;
app.panel.allowOpen = true;
panel.$el.trigger('panel:opened', panel);
panel.emit('local::opened panelOpened', panel);
}
onClose() {
const panel = this;
panel.opened = false;
panel.$el.addClass('panel-closing');
panel.$el.trigger('panel:close', panel);
panel.emit('local::close panelClose', panel);
}
onClosed() {
const panel = this;
const app = panel.app;
app.panel.allowOpen = true;
panel.$el.removeClass('panel-closing');
panel.$el.trigger('panel:closed', panel);
panel.emit('local::closed panelClosed', panel);
}
}
var Panel = {
name: 'panel',
params: {
panel: {
leftBreakpoint: 0,
rightBreakpoint: 0,
swipe: undefined, // or 'left' or 'right' or 'both'
swipeActiveArea: 0,
swipeCloseOpposite: true,
swipeOnlyClose: false,
swipeNoFollow: false,
swipeThreshold: 0,
closeByBackdropClick: true,
},
},
static: {
Panel: Panel$1,
},
instance: {
panel: {
allowOpen: true,
},
},
create() {
const app = this;
Utils.extend(app.panel, {
disableSwipe(panel = 'both') {
let side;
let panels = [];
if (typeof panel === 'string') {
if (panel === 'both') {
side = 'both';
panels = [app.panel.left, app.panel.right];
} else {
side = panel;
panels = app.panel[side];
}
} else {
panels = [panel];
}
panels.forEach((panelInstance) => {
if (panelInstance) Utils.extend(panelInstance, { swipeable: false });
});
},
enableSwipe(panel = 'both') {
let panels = [];
let side;
if (typeof panel === 'string') {
side = panel;
if (
(app.params.panel.swipe === 'left' && side === 'right') ||
(app.params.panel.swipe === 'right' && side === 'left') ||
side === 'both'
) {
side = 'both';
app.params.panel.swipe = side;
panels = [app.panel.left, app.panel.right];
} else {
app.params.panel.swipe = side;
panels.push(app.panel[side]);
}
} else if (panel) {
panels.push(panel);
}
if (panels.length) {
panels.forEach((panelInstance) => {
if (!panelInstance) return;
if (!panelInstance.swipeInitialized) {
panelInstance.initSwipePanel();
} else {
Utils.extend(panelInstance, { swipeable: true });
}
});
}
},
create(params) {
return new Panel$1(app, params);
},
open(side, animate) {
let panelSide = side;
if (!panelSide) {
if ($('.panel').length > 1) {
return false;
}
panelSide = $('.panel').hasClass('panel-left') ? 'left' : 'right';
}
if (!panelSide) return false;
if (app.panel[panelSide]) {
return app.panel[panelSide].open(animate);
}
const $panelEl = $(`.panel-${panelSide}`);
if ($panelEl.length > 0) {
return app.panel.create({ el: $panelEl }).open(animate);
}
return false;
},
close(side, animate) {
let $panelEl;
let panelSide;
if (panelSide) {
panelSide = side;
$panelEl = $(`.panel-${panelSide}`);
} else {
$panelEl = $('.panel.panel-active');
panelSide = $panelEl.hasClass('panel-left') ? 'left' : 'right';
}
if (!panelSide) return false;
if (app.panel[panelSide]) {
return app.panel[panelSide].close(animate);
}
if ($panelEl.length > 0) {
return app.panel.create({ el: $panelEl }).close(animate);
}
return false;
},
get(side) {
let panelSide = side;
if (!panelSide) {
if ($('.panel').length > 1) {
return undefined;
}
panelSide = $('.panel').hasClass('panel-left') ? 'left' : 'right';
}
if (!panelSide) return undefined;
if (app.panel[panelSide]) {
return app.panel[panelSide];
}
const $panelEl = $(`.panel-${panelSide}`);
if ($panelEl.length > 0) {
return app.panel.create({ el: $panelEl });
}
return undefined;
},
});
},
on: {
init() {
const app = this;
// Create Panels
$('.panel').each((index, panelEl) => {
const side = $(panelEl).hasClass('panel-left') ? 'left' : 'right';
app.panel[side] = app.panel.create({ el: panelEl, side });
});
},
},
clicks: {
'.panel-open': function open(clickedEl, data = {}) {
const app = this;
let side = 'left';
if (data.panel === 'right' || ($('.panel').length === 1 && $('.panel').hasClass('panel-right'))) {
side = 'right';
}
app.panel.open(side, data.animate);
},
'.panel-close': function close(clickedEl, data = {}) {
const app = this;
const side = data.panel;
app.panel.close(side, data.animate);
},
'.panel-backdrop': function close() {
const app = this;
$('.panel-active').trigger('panel:backdrop-click');
app.emit('panelBackdropClick', $('.panel-active')[0]);
if (app.params.panel.closeByBackdropClick) app.panel.close();
},
},
};
var Card = {
name: 'card',
};
var Chip = {
name: 'chip',
};
// Form Data
const FormData$1 = {
store(form, data) {
const app = this;
let formId = form;
const $formEl = $(form);
if ($formEl.length && $formEl.is('form') && $formEl.attr('id')) {
formId = $formEl.attr('id');
}
// Store form data in app.formsData
app.form.data[`form-${formId}`] = data;
// Store form data in local storage also
try {
window.localStorage[`f7form-${formId}`] = JSON.stringify(data);
} catch (e) {
throw e;
}
},
get(form) {
const app = this;
let formId = form;
const $formEl = $(form);
if ($formEl.length && $formEl.is('form') && $formEl.attr('id')) {
formId = $formEl.attr('id');
}
try {
if (window.localStorage[`f7form-${formId}`]) {
return JSON.parse(window.localStorage[`f7form-${formId}`]);
}
} catch (e) {
throw e;
}
if (app.form.data[`form-${formId}`]) {
return app.form.data[`form-${formId}`];
}
return undefined;
},
remove(form) {
const app = this;
let formId = form;
const $formEl = $(form);
if ($formEl.length && $formEl.is('form') && $formEl.attr('id')) {
formId = $formEl.attr('id');
}
// Delete form data from app.formsData
if (app.form.data[`form-${formId}`]) {
app.form.data[`form-${formId}`] = '';
delete app.form.data[`form-${formId}`];
}
// Delete form data from local storage also
try {
if (window.localStorage[`f7form-${formId}`]) {
window.localStorage[`f7form-${formId}`] = '';
window.localStorage.removeItem(`f7form-${formId}`);
}
} catch (e) {
throw e;
}
},
};
// Form Storage
const FormStorage = {
init(formEl) {
const app = this;
const $formEl = $(formEl);
const formId = $formEl.attr('id');
if (!formId) return;
const initialData = app.form.getFormData(formId);
if (initialData) {
app.form.fillFromData($formEl, initialData);
}
function store() {
const data = app.form.convertToData($formEl);
if (!data) return;
app.form.storeFormData(formId, data);
$formEl.trigger('form:storedata', data);
app.emit('formStoreData', $formEl[0], data);
}
$formEl.on('change submit', store);
},
destroy(formEl) {
const $formEl = $(formEl);
$formEl.off('change submit');
},
};
// Form To/From Data
function formToData(formEl) {
const app = this;
const $formEl = $(formEl).eq(0);
if ($formEl.length === 0) return undefined;
// Form data
const data = {};
// Skip input types
const skipTypes = ['submit', 'image', 'button', 'file'];
const skipNames = [];
$formEl.find('input, select, textarea').each((inputIndex, inputEl) => {
const $inputEl = $(inputEl);
const name = $inputEl.attr('name');
const type = $inputEl.attr('type');
const tag = inputEl.nodeName.toLowerCase();
if (skipTypes.indexOf(type) >= 0) return;
if (skipNames.indexOf(name) >= 0 || !name) return;
if (tag === 'select' && $inputEl.prop('multiple')) {
skipNames.push(name);
data[name] = [];
$formEl.find(`select[name="${name}"] option`).each((index, el) => {
if (el.selected) data[name].push(el.value);
});
} else {
switch (type) {
case 'checkbox':
skipNames.push(name);
data[name] = [];
$formEl.find(`input[name="${name}"]`).each((index, el) => {
if (el.checked) data[name].push(el.value);
});
break;
case 'radio':
skipNames.push(name);
$formEl.find(`input[name="${name}"]`).each((index, el) => {
if (el.checked) data[name] = el.value;
});
break;
default:
data[name] = $inputEl.val();
break;
}
}
});
$formEl.trigger('form:todata', data);
app.emit('formToData', $formEl[0], data);
return data;
}
function formFromData(formEl, formData) {
const app = this;
const $formEl = $(formEl).eq(0);
if (!$formEl.length) return;
let data = formData;
const formId = $formEl.attr('id');
if (!data && formId) {
data = app.form.getFormData(formId);
}
if (!data) return;
// Skip input types
const skipTypes = ['submit', 'image', 'button', 'file'];
const skipNames = [];
$formEl.find('input, select, textarea').each((inputIndex, inputEl) => {
const $inputEl = $(inputEl);
const name = $inputEl.attr('name');
const type = $inputEl.attr('type');
const tag = inputEl.nodeName.toLowerCase();
if (typeof data[name] === 'undefined' || data[name] === null) return;
if (skipTypes.indexOf(type) >= 0) return;
if (skipNames.indexOf(name) >= 0 || !name) return;
if (tag === 'select' && $inputEl.prop('multiple')) {
skipNames.push(name);
$formEl.find(`select[name="${name}"] option`).each((index, el) => {
const selectEl = el;
if (data[name].indexOf(el.value) >= 0) selectEl.selected = true;
else selectEl.selected = false;
});
} else {
switch (type) {
case 'checkbox':
skipNames.push(name);
$formEl.find(`input[name="${name}"]`).each((index, el) => {
const checkboxEl = el;
if (data[name].indexOf(el.value) >= 0) checkboxEl.checked = true;
else checkboxEl.checked = false;
});
break;
case 'radio':
skipNames.push(name);
$formEl.find(`input[name="${name}"]`).each((index, el) => {
const radioEl = el;
if (data[name] === el.value) radioEl.checked = true;
else radioEl.checked = false;
});
break;
default:
$inputEl.val(data[name]);
break;
}
}
if (tag === 'select' || tag === 'input' || tag === 'textarea') {
$inputEl.trigger('change', 'fromdata');
}
});
$formEl.trigger('form:fromdata', data);
app.emit('formFromData', $formEl[0], data);
}
function initAjaxForm() {
const app = this;
function onSubmitChange(e, fromData) {
const $formEl = $(this);
if (e.type === 'change' && !$formEl.hasClass('form-ajax-submit-onchange')) return;
if (e.type === 'submit') e.preventDefault();
if (e.type === 'change' && fromData === 'fromdata') return;
const method = ($formEl.attr('method') || 'GET').toUpperCase();
const contentType = $formEl.prop('enctype') || $formEl.attr('enctype');
const url = $formEl.attr('action');
if (!url) return;
let data;
if (method === 'POST') data = new FormData$1($formEl[0]);
else data = Utils.serializeObject(app.form.convertToData($formEl[0]));
const xhr = app.request({
method,
url,
contentType,
data,
beforeSend() {
$formEl.trigger('formajax:beforesend', data, xhr);
app.emit('formAjaxBeforeSend', $formEl[0], data, xhr);
},
error() {
$formEl.trigger('formajax:error', data, xhr);
app.emit('formAjaxError', $formEl[0], data, xhr);
},
complete() {
$formEl.trigger('formajax:complete', data, xhr);
app.emit('formAjaxComplete', $formEl[0], data, xhr);
},
success() {
$formEl.trigger('formajax:success', data, xhr);
app.emit('formAjaxSuccess', $formEl[0], data, xhr);
},
});
}
$(document).on('submit change', 'form.form-ajax-submit, form.form-ajax-submit-onchange', onSubmitChange);
}
var Form = {
name: 'form',
create() {
const app = this;
Utils.extend(app, {
form: {
data: {},
storeFormData: FormData$1.store.bind(app),
getFormData: FormData$1.get.bind(app),
removeFormData: FormData$1.remove.bind(app),
convertToData: formToData.bind(app),
fillFromData: formFromData.bind(app),
storage: {
init: FormStorage.init.bind(app),
destroy: FormStorage.destroy.bind(app),
},
},
});
},
on: {
init() {
const app = this;
initAjaxForm.call(app);
},
tabBeforeRemove(tabEl) {
const app = this;
$(tabEl).find('.form-store-data').each((index, formEl) => {
app.form.storage.destroy(formEl);
});
},
tabMounted(tabEl) {
const app = this;
$(tabEl).find('.form-store-data').each((index, formEl) => {
app.form.storage.init(formEl);
});
},
pageBeforeRemove(page) {
const app = this;
page.$el.find('.form-store-data').each((index, formEl) => {
app.form.storage.destroy(formEl);
});
},
pageInit(page) {
const app = this;
page.$el.find('.form-store-data').each((index, formEl) => {
app.form.storage.init(formEl);
});
},
},
};
const Input = {
ignoreTypes: ['checkbox', 'button', 'submit', 'range', 'radio', 'image'],
createTextareaResizableShadow() {
const $shadowEl = $(document.createElement('textarea'));
$shadowEl.addClass('textarea-resizable-shadow');
$shadowEl.prop({
disabled: true,
readonly: true,
});
Input.textareaResizableShadow = $shadowEl;
},
textareaResizableShadow: undefined,
resizeTextarea(textareaEl) {
const app = this;
const $textareaEl = $(textareaEl);
if (!Input.textareaResizableShadow) {
Input.createTextareaResizableShadow();
}
const $shadowEl = Input.textareaResizableShadow;
if (!$textareaEl.length) return;
if (!$textareaEl.hasClass('resizable')) return;
if (Input.textareaResizableShadow.parents().length === 0) {
app.root.append($shadowEl);
}
const styles = window.getComputedStyle($textareaEl[0]);
('padding margin width font-size font-family font-style font-weight line-height font-variant text-transform letter-spacing border box-sizing display').split(' ').forEach((style) => {
let styleValue = styles[style];
if (('font-size line-height letter-spacing width').split(' ').indexOf(style) >= 0) {
styleValue = styleValue.replace(',', '.');
}
$shadowEl.css(style, styleValue);
});
const currentHeight = $textareaEl[0].clientHeight;
$shadowEl.val('');
const initialHeight = $shadowEl[0].scrollHeight;
$shadowEl.val($textareaEl.val());
$shadowEl.css('height', 0);
const scrollHeight = $shadowEl[0].scrollHeight;
if (currentHeight !== scrollHeight) {
if (scrollHeight > initialHeight) {
$textareaEl.css('height', `${scrollHeight}px`);
$textareaEl.trigger('textarea:resize', initialHeight, currentHeight, scrollHeight);
} else if (scrollHeight < currentHeight) {
$textareaEl.css('height', '');
$textareaEl.trigger('textarea:resize', initialHeight, currentHeight, initialHeight);
}
}
},
validate(inputEl) {
const $inputEl = $(inputEl);
if (!$inputEl.length) return;
const $itemInputEl = $inputEl.parents('.item-input');
const validity = $inputEl[0].validity;
const validationMessage = $inputEl.dataset().errorMessage || $inputEl[0].validationMessage || '';
if (!validity) return;
if (!validity.valid) {
let $errorEl = $inputEl.nextAll('.item-input-error-message');
if (validationMessage) {
if ($errorEl.length === 0) {
$errorEl = $('<div class="item-input-error-message"></div>');
$errorEl.insertAfter($inputEl);
}
$errorEl.text(validationMessage);
}
if ($errorEl.length > 0) {
$itemInputEl.addClass('item-input-with-error-message');
}
$itemInputEl.addClass('item-input-invalid');
$inputEl.addClass('input-invalid');
} else {
$itemInputEl.removeClass('item-input-invalid item-input-with-error-message');
$inputEl.removeClass('input-invalid');
}
},
validateInputs(el) {
const app = this;
$(el).find('input, textarea, select').each((index, inputEl) => {
app.input.validate(inputEl);
});
},
focus(inputEl) {
const $inputEl = $(inputEl);
const type = $inputEl.attr('type');
if (Input.ignoreTypes.indexOf(type) >= 0) return;
const $itemInputEl = $inputEl.parents('.item-input');
$itemInputEl.addClass('item-input-focused');
$inputEl.addClass('input-focused');
},
blur(inputEl) {
$(inputEl).parents('.item-input').removeClass('item-input-focused');
$(inputEl).removeClass('input-focused');
},
checkEmptyState(inputEl) {
const $inputEl = $(inputEl);
const value = $inputEl.val();
const $itemInputEl = $inputEl.parents('.item-input');
if ((value && (typeof value === 'string' && value.trim() !== '')) || (Array.isArray(value) && value.length > 0)) {
$itemInputEl.addClass('item-input-with-value');
$inputEl.addClass('input-with-value');
$inputEl.trigger('input:notempty');
} else {
$itemInputEl.removeClass('item-input-with-value');
$inputEl.removeClass('input-with-value');
$inputEl.trigger('input:empty');
}
},
scrollIntoView(inputEl, duration = 0, centered) {
const $inputEl = $(inputEl);
const $scrollableEl = $inputEl.parents('.page-content, .panel').eq(0);
if (!$scrollableEl.length) {
return false;
}
const contentHeight = $scrollableEl[0].offsetHeight;
const contentScrollTop = $scrollableEl[0].scrollTop;
const contentPaddingTop = parseInt($scrollableEl.css('padding-top'), 10);
const contentPaddingBottom = parseInt($scrollableEl.css('padding-bottom'), 10);
const contentOffsetTop = $scrollableEl.offset().top - contentScrollTop;
const inputOffsetTop = $inputEl.offset().top - contentOffsetTop;
const inputHeight = $inputEl[0].offsetHeight;
const min = (inputOffsetTop + contentScrollTop) - contentPaddingTop;
const max = ((inputOffsetTop + contentScrollTop) - contentHeight) + contentPaddingBottom + inputHeight;
const centeredPosition = min + ((max - min) / 2);
if (contentScrollTop > min) {
$scrollableEl.scrollTop(centered ? centeredPosition : min, duration);
return true;
} else if (contentScrollTop < max) {
$scrollableEl.scrollTop(centered ? centeredPosition : max, duration);
return true;
}
return false;
},
init() {
const app = this;
Input.createTextareaResizableShadow();
function onFocus() {
const inputEl = this;
if (app.params.input.scrollIntoViewOnFocus) {
if (Device.android) {
$(window).once('resize', () => {
if (document && document.activeElement === inputEl) {
app.input.scrollIntoView(inputEl, app.params.input.scrollIntoViewCentered);
}
});
} else {
app.input.scrollIntoView(inputEl, app.params.input.scrollIntoViewCentered);
}
}
app.input.focus(inputEl);
}
function onBlur() {
const $inputEl = $(this);
const tag = $inputEl[0].nodeName.toLowerCase();
app.input.blur($inputEl);
if ($inputEl.dataset().validate || $inputEl.attr('validate') !== null) {
app.input.validate($inputEl);
}
// Resize textarea
if (tag === 'textarea' && $inputEl.hasClass('resizable')) {
if (Input.textareaResizableShadow) Input.textareaResizableShadow.remove();
}
}
function onChange() {
const $inputEl = $(this);
const type = $inputEl.attr('type');
const tag = $inputEl[0].nodeName.toLowerCase();
if (Input.ignoreTypes.indexOf(type) >= 0) return;
// Check Empty State
app.input.checkEmptyState($inputEl);
// Check validation
if ($inputEl.dataset().validate || $inputEl.attr('validate') !== null) {
app.input.validate($inputEl);
}
// Resize textarea
if (tag === 'textarea' && $inputEl.hasClass('resizable')) {
app.input.resizeTextarea($inputEl);
}
}
function onInvalid(e) {
const $inputEl = $(this);
if ($inputEl.dataset().validate || $inputEl.attr('validate') !== null) {
e.preventDefault();
app.input.validate($inputEl);
}
}
function clearInput() {
const $clicked = $(this);
const $inputEl = $clicked.siblings('input, textarea').eq(0);
const previousValue = $inputEl.val();
$inputEl
.val('')
.trigger('change')
.focus()
.trigger('input:clear', previousValue);
}
$(document).on('click', '.input-clear-button', clearInput);
$(document).on('change input', 'input, textarea, select', onChange, true);
$(document).on('focus', 'input, textarea, select', onFocus, true);
$(document).on('blur', 'input, textarea, select', onBlur, true);
$(document).on('invalid', 'input, textarea, select', onInvalid, true);
},
};
var Input$1 = {
name: 'input',
params: {
input: {
scrollIntoViewOnFocus: Device.android,
scrollIntoViewCentered: false,
},
},
create() {
const app = this;
Utils.extend(app, {
input: {
scrollIntoView: Input.scrollIntoView.bind(app),
focus: Input.focus.bind(app),
blur: Input.blur.bind(app),
validate: Input.validate.bind(app),
validateInputs: Input.validate.bind(app),
checkEmptyState: Input.checkEmptyState.bind(app),
resizeTextarea: Input.resizeTextarea.bind(app),
init: Input.init.bind(app),
},
});
},
on: {
init() {
const app = this;
app.input.init();
},
tabMounted(tabEl) {
const app = this;
const $tabEl = $(tabEl);
$tabEl.find('.item-input').each((itemInputIndex, itemInputEl) => {
const $itemInputEl = $(itemInputEl);
$itemInputEl.find('input, select, textarea').each((inputIndex, inputEl) => {
const $inputEl = $(inputEl);
if (Input.ignoreTypes.indexOf($inputEl.attr('type')) >= 0) return;
app.input.checkEmptyState($inputEl);
});
});
$tabEl.find('textarea.resizable').each((textareaIndex, textareaEl) => {
app.input.resizeTextarea(textareaEl);
});
},
pageInit(page) {
const app = this;
const $pageEl = page.$el;
$pageEl.find('.item-input').each((itemInputIndex, itemInputEl) => {
const $itemInputEl = $(itemInputEl);
$itemInputEl.find('input, select, textarea').each((inputIndex, inputEl) => {
const $inputEl = $(inputEl);
if (Input.ignoreTypes.indexOf($inputEl.attr('type')) >= 0) return;
app.input.checkEmptyState($inputEl);
});
});
$pageEl.find('textarea.resizable').each((textareaIndex, textareaEl) => {
app.input.resizeTextarea(textareaEl);
});
},
},
};
var Checkbox = {
name: 'checkbox',
};
var Radio = {
name: 'radio',
};
class Toggle$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const toggle = this;
const defaults = {};
// Extend defaults with modules params
toggle.useModulesParams(defaults);
toggle.params = Utils.extend(defaults, params);
const el = toggle.params.el;
if (!el) return toggle;
const $el = $(el);
if ($el.length === 0) return toggle;
const $inputEl = $el.children('input[type="checkbox"]');
Utils.extend(toggle, {
app,
$el,
el: $el[0],
$inputEl,
inputEl: $inputEl[0],
disabled: $el.hasClass('disabled') || $inputEl.hasClass('disabled') || $inputEl.attr('disabled') || $inputEl[0].disabled,
});
Object.defineProperty(toggle, 'checked', {
enumerable: true,
configurable: true,
set(checked) {
if (!toggle || typeof toggle.$inputEl === 'undefined') return;
if (toggle.checked === checked) return;
$inputEl[0].checked = checked;
toggle.$inputEl.trigger('change');
},
get() {
return $inputEl[0].checked;
},
});
$el[0].f7Toggle = toggle;
let isTouched;
const touchesStart = {};
let isScrolling;
let touchesDiff;
let toggleWidth;
let touchStartTime;
let touchStartChecked;
function handleTouchStart(e) {
if (isTouched || toggle.disabled) return;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
touchesDiff = 0;
isTouched = true;
isScrolling = undefined;
touchStartTime = Utils.now();
touchStartChecked = toggle.checked;
toggleWidth = $el[0].offsetWidth;
Utils.nextTick(() => {
if (isTouched) {
$el.addClass('toggle-active-state');
}
});
}
function handleTouchMove(e) {
if (!isTouched || toggle.disabled) return;
const pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
const inverter = app.rtl ? -1 : 1;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
}
if (isScrolling) {
isTouched = false;
return;
}
e.preventDefault();
touchesDiff = pageX - touchesStart.x;
let changed;
if (touchesDiff * inverter < 0 && Math.abs(touchesDiff) > toggleWidth / 3 && touchStartChecked) {
changed = true;
}
if (touchesDiff * inverter > 0 && Math.abs(touchesDiff) > toggleWidth / 3 && !touchStartChecked) {
changed = true;
}
if (changed) {
touchesStart.x = pageX;
toggle.checked = !touchStartChecked;
touchStartChecked = !touchStartChecked;
}
}
function handleTouchEnd() {
if (!isTouched || toggle.disabled) {
if (isScrolling) $el.removeClass('toggle-active-state');
isTouched = false;
return;
}
const inverter = app.rtl ? -1 : 1;
isTouched = false;
$el.removeClass('toggle-active-state');
let changed;
if ((Utils.now() - touchStartTime) < 300) {
if (touchesDiff * inverter < 0 && touchStartChecked) {
changed = true;
}
if (touchesDiff * inverter > 0 && !touchStartChecked) {
changed = true;
}
if (changed) {
toggle.checked = !touchStartChecked;
}
}
}
function handleInputChange() {
toggle.$el.trigger('toggle:change', toggle);
toggle.emit('local::change toggleChange', toggle);
}
toggle.attachEvents = function attachEvents() {
{
if (!Support$1.touch) return;
const passive = Support$1.passiveListener ? { passive: true } : false;
$el.on(app.touchEvents.start, handleTouchStart, passive);
app.on('touchmove', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
}
toggle.$inputEl.on('change', handleInputChange);
};
toggle.detachEvents = function detachEvents() {
{
if (!Support$1.touch) return;
const passive = Support$1.passiveListener ? { passive: true } : false;
$el.off(app.touchEvents.start, handleTouchStart, passive);
app.off('touchmove', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
}
toggle.$inputEl.off('change', handleInputChange);
};
// Install Modules
toggle.useModules();
// Init
toggle.init();
}
toggle() {
const toggle = this;
toggle.checked = !toggle.checked;
}
init() {
const toggle = this;
toggle.attachEvents();
}
destroy() {
let toggle = this;
toggle.$el.trigger('toggle:beforedestroy', toggle);
toggle.emit('local::beforeDestroy toggleBeforeDestroy', toggle);
delete toggle.$el[0].f7Toggle;
toggle.detachEvents();
Utils.deleteProps(toggle);
toggle = null;
}
}
var Toggle = {
name: 'toggle',
create() {
const app = this;
app.toggle = ConstructorMethods({
defaultSelector: '.toggle',
constructor: Toggle$1,
app,
domProp: 'f7Toggle',
});
},
static: {
Toggle: Toggle$1,
},
on: {
tabMounted(tabEl) {
const app = this;
$(tabEl).find('.toggle-init').each((index, toggleEl) => app.toggle.create({ el: toggleEl }));
},
tabBeforeRemove(tabEl) {
$(tabEl).find('.toggle-init').each((index, toggleEl) => {
if (toggleEl.f7Toggle) toggleEl.f7Toggle.destroy();
});
},
pageInit(page) {
const app = this;
page.$el.find('.toggle-init').each((index, toggleEl) => app.toggle.create({ el: toggleEl }));
},
pageBeforeRemove(page) {
page.$el.find('.toggle-init').each((index, toggleEl) => {
if (toggleEl.f7Toggle) toggleEl.f7Toggle.destroy();
});
},
},
};
class Range$1 extends Framework7Class {
constructor(app, params) {
super(params, [app]);
const range = this;
const defaults = {
dual: false,
step: 1,
label: false,
};
// Extend defaults with modules params
range.useModulesParams(defaults);
range.params = Utils.extend(defaults, params);
const el = range.params.el;
if (!el) return range;
const $el = $(el);
if ($el.length === 0) return range;
const dataset = $el.dataset();
('step min max value').split(' ').forEach((paramName) => {
if (typeof params[paramName] === 'undefined' && typeof dataset[paramName] !== 'undefined') {
range.params[paramName] = parseFloat(dataset[paramName]);
}
});
('dual label').split(' ').forEach((paramName) => {
if (typeof params[paramName] === 'undefined' && typeof dataset[paramName] !== 'undefined') {
range.params[paramName] = dataset[paramName];
}
});
if (!range.params.value) {
if (typeof dataset.value !== 'undefined') range.params.value = dataset.value;
if (typeof dataset.valueLeft !== 'undefined' && typeof dataset.valueRight !== 'undefined') {
range.params.value = [parseFloat(dataset.valueLeft), parseFloat(dataset.valueRight)];
}
}
let $inputEl;
if (!range.params.dual) {
if (range.params.inputEl) {
$inputEl = $(range.params.inputEl);
} else if ($el.find('input[type="range"]').length) {
$inputEl = $el.find('input[type="range"]').eq(0);
}
}
Utils.extend(range, range.params, {
$el,
el: $el[0],
$inputEl,
inputEl: $inputEl ? $inputEl[0] : undefined,
});
if ($inputEl) {
('step min max').split(' ').forEach((paramName) => {
if (!params[paramName] && $inputEl.attr(paramName)) {
range.params[paramName] = parseFloat($inputEl.attr(paramName));
range[paramName] = parseFloat($inputEl.attr(paramName));
}
if (typeof $inputEl.val() !== 'undefined') {
range.params.value = parseFloat($inputEl.val());
range.value = parseFloat($inputEl.val());
}
});
}
// Dual
if (range.dual) {
$el.addClass('range-slider-dual');
}
if (range.label) {
$el.addClass('range-slider-label');
}
// Check for layout
const $barEl = $('<div class="range-bar"></div>');
const $barActiveEl = $('<div class="range-bar-active"></div>');
$barEl.append($barActiveEl);
// Create Knobs
const knobHTML = `
<div class="range-knob-wrap">
<div class="range-knob"></div>
${range.label ? '<div class="range-knob-label"></div>' : ''}
</div>
`;
const knobs = [$(knobHTML)];
const labels = [];
if (range.dual) {
knobs.push($(knobHTML));
}
$el.append($barEl);
knobs.forEach(($knobEl) => {
$el.append($knobEl);
});
// Labels
if (range.label) {
labels.push(knobs[0].find('.range-knob-label'));
if (range.dual) {
labels.push(knobs[1].find('.range-knob-label'));
}
}
Utils.extend(range, {
app,
knobs,
labels,
$barEl,
$barActiveEl,
});
$el[0].f7Range = range;
// Touch Events
let isTouched;
const touchesStart = {};
let isScrolling;
let rangeOffsetLeft;
let $touchedKnobEl;
let dualValueIndex;
function handleTouchStart(e) {
if (isTouched) return;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
isTouched = true;
isScrolling = undefined;
rangeOffsetLeft = $el.offset().left;
let progress;
if (range.app.rtl) {
progress = ((rangeOffsetLeft + range.rangeWidth) - touchesStart.x) / range.rangeWidth;
} else {
progress = (touchesStart.x - rangeOffsetLeft) / range.rangeWidth;
}
let newValue = (progress * (range.max - range.min)) + range.min;
if (range.dual) {
if (Math.abs(range.value[0] - newValue) < Math.abs(range.value[1] - newValue)) {
dualValueIndex = 0;
$touchedKnobEl = range.knobs[0];
newValue = [newValue, range.value[1]];
} else {
dualValueIndex = 1;
$touchedKnobEl = range.knobs[1];
newValue = [range.value[0], newValue];
}
} else {
$touchedKnobEl = range.knobs[0];
newValue = (progress * (range.max - range.min)) + range.min;
}
Utils.nextTick(() => {
if (isTouched) $touchedKnobEl.addClass('range-knob-active-state');
}, 70);
range.setValue(newValue);
}
function handleTouchMove(e) {
if (!isTouched) return;
const pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
}
if (isScrolling) {
isTouched = false;
return;
}
e.preventDefault();
let progress;
if (range.app.rtl) {
progress = ((rangeOffsetLeft + range.rangeWidth) - pageX) / range.rangeWidth;
} else {
progress = (pageX - rangeOffsetLeft) / range.rangeWidth;
}
let newValue = (progress * (range.max - range.min)) + range.min;
if (range.dual) {
let leftValue;
let rightValue;
if (dualValueIndex === 0) {
leftValue = newValue;
rightValue = range.value[1];
if (leftValue > rightValue) {
rightValue = leftValue;
}
} else {
leftValue = range.value[0];
rightValue = newValue;
if (rightValue < leftValue) {
leftValue = rightValue;
}
}
newValue = [leftValue, rightValue];
}
range.setValue(newValue);
}
function handleTouchEnd() {
if (!isTouched) {
if (isScrolling) $touchedKnobEl.removeClass('range-knob-active-state');
isTouched = false;
return;
}
isTouched = false;
$touchedKnobEl.removeClass('range-knob-active-state');
}
function handleResize() {
range.calcSize();
range.layout();
}
range.attachEvents = function attachEvents() {
const passive = Support$1.passiveListener ? { passive: true } : false;
range.$el.on(app.touchEvents.start, handleTouchStart, passive);
app.on('touchmove', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
app.on('resize', handleResize);
};
range.detachEvents = function detachEvents() {
const passive = Support$1.passiveListener ? { passive: true } : false;
range.$el.off(app.touchEvents.start, handleTouchStart, passive);
app.off('touchmove', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
app.off('resize', handleResize);
};
// Install Modules
range.useModules();
// Init
range.init();
return range;
}
calcSize() {
const range = this;
range.rangeWidth = range.$el.outerWidth();
range.knobWidth = range.knobs[0].outerWidth();
}
layout() {
const range = this;
const {
app,
knobWidth,
rangeWidth,
min,
max,
knobs,
$barActiveEl,
value,
label,
labels,
} = range;
const positionProperty = app.rtl ? 'right' : 'left';
if (range.dual) {
const progress = [((value[0] - min) / (max - min)), ((value[1] - min) / (max - min))];
$barActiveEl.css({
[positionProperty]: `${progress[0] * 100}%`,
width: `${(progress[1] - progress[0]) * 100}%`,
});
knobs.forEach(($knobEl, knobIndex) => {
let leftPos = rangeWidth * progress[knobIndex];
const realLeft = (rangeWidth * progress[knobIndex]) - (knobWidth / 2);
if (realLeft < 0) leftPos = knobWidth / 2;
if ((realLeft + knobWidth) > rangeWidth) leftPos = rangeWidth - (knobWidth / 2);
$knobEl.css(positionProperty, `${leftPos}px`);
if (label) labels[knobIndex].text(value[knobIndex]);
});
} else {
const progress = ((value - min) / (max - min));
$barActiveEl.css('width', `${progress * 100}%`);
let leftPos = rangeWidth * progress;
const realLeft = (rangeWidth * progress) - (knobWidth / 2);
if (realLeft < 0) leftPos = knobWidth / 2;
if ((realLeft + knobWidth) > rangeWidth) leftPos = rangeWidth - (knobWidth / 2);
knobs[0].css(positionProperty, `${leftPos}px`);
if (label) labels[0].text(value);
}
if ((range.dual && value.indexOf(min) >= 0) || (!range.dual && value === min)) {
range.$el.addClass('range-slider-min');
} else {
range.$el.removeClass('range-slider-min');
}
if ((range.dual && value.indexOf(max) >= 0) || (!range.dual && value === max)) {
range.$el.addClass('range-slider-max');
} else {
range.$el.removeClass('range-slider-max');
}
}
setValue(newValue) {
const range = this;
const { step, min, max } = range;
if (range.dual) {
let newValues = newValue;
if (!Array.isArray(newValues)) newValues = [newValue, newValue];
if (newValue[0] > newValue[1]) {
newValues = [newValues[0], newValues[0]];
}
newValues = newValues.map(value => Math.max(Math.min(Math.round(value / step) * step, max), min));
if (newValues[0] === range.value[0] && newValues[1] === range.value[1]) {
return range;
}
newValues.forEach((value, valueIndex) => {
range.value[valueIndex] = value;
});
range.layout();
} else {
const value = Math.max(Math.min(Math.round(newValue / step) * step, max), min);
range.value = value;
range.layout();
}
// Events
range.$el.trigger('range:change', range, range.value);
if (range.$inputEl && !range.dual) {
range.$inputEl.val(range.value).trigger('input change');
}
range.emit('local::change rangeChange', range, range.value);
return range;
}
getValue() {
return this.value;
}
init() {
const range = this;
range.calcSize();
range.layout();
range.attachEvents();
return range;
}
destroy() {
let range = this;
range.$el.trigger('range:beforedestroy', range);
range.emit('local::beforeDestroy rangeBeforeDestroy', range);
delete range.$el[0].f7Range;
range.detachEvents();
Utils.deleteProps(range);
range = null;
}
}
var Range = {
name: 'range',
create() {
const app = this;
app.range = Utils.extend(
ConstructorMethods({
defaultSelector: '.range-slider',
constructor: Range$1,
app,
domProp: 'f7Range',
}),
{
getValue(el = '.range-slider') {
const range = app.range.get(el);
if (range) return range.getValue();
return undefined;
},
setValue(el = '.range-slider', value) {
const range = app.range.get(el);
if (range) return range.setValue(value);
return undefined;
},
}
);
},
static: {
Range: Range$1,
},
on: {
tabMounted(tabEl) {
const app = this;
$(tabEl).find('.range-slider-init').each((index, rangeEl) => new Range$1(app, {
el: rangeEl,
}));
},
tabBeforeRemove(tabEl) {
$(tabEl).find('.range-slider-init').each((index, rangeEl) => {
if (rangeEl.f7Range) rangeEl.f7Range.destroy();
});
},
pageInit(page) {
const app = this;
page.$el.find('.range-slider-init').each((index, rangeEl) => new Range$1(app, {
el: rangeEl,
}));
},
pageBeforeRemove(page) {
page.$el.find('.range-slider-init').each((index, rangeEl) => {
if (rangeEl.f7Range) rangeEl.f7Range.destroy();
});
},
},
};
class SmartSelect$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const ss = this;
ss.app = app;
const defaults = Utils.extend({
on: {},
}, app.params.smartSelect);
const $el = $(params.el).eq(0);
if ($el.length === 0) return ss;
const $selectEl = $el.find('select').eq(0);
if ($selectEl.length === 0) return ss;
let $valueEl = $(params.valueEl);
if ($valueEl.length === 0) {
$valueEl = $('<div class="item-after"></div>');
$valueEl.insertAfter($el.find('.item-title'));
}
// Extend defaults with modules params
ss.useModulesParams(defaults);
// View
const view = $el.parents('.view').length && $el.parents('.view')[0].f7View;
if (!view) {
throw Error('Smart Select requires initialized View');
}
// Url
let url = params.url;
if (!url) {
if ($el.attr('href') && $el.attr('href') !== '#') url = $el.attr('href');
else url = `${$selectEl.attr('name').toLowerCase()}-select/`;
}
if (!url) url = ss.params.url;
const multiple = $selectEl[0].multiple;
const inputType = multiple ? 'checkbox' : 'radio';
const id = Utils.now();
Utils.extend(ss, {
params: Utils.extend(defaults, params),
$el,
el: $el[0],
$selectEl,
selectEl: $selectEl[0],
$valueEl,
valueEl: $valueEl[0],
url,
multiple,
inputType,
id,
view,
inputName: `${inputType}-${id}`,
selectName: $selectEl.attr('name'),
maxLength: $selectEl.attr('maxlength') || params.maxLength,
});
$el[0].f7SmartSelect = ss;
// Events
function onClick() {
ss.open();
}
function onChange() {
ss.setValue();
}
ss.attachEvents = function attachEvents() {
$el.on('click', onClick);
$el.on('change', 'input[type="checkbox"], input[type="radio"]', onChange);
};
ss.detachEvents = function detachEvents() {
$el.off('click', onClick);
$el.off('change', 'input[type="checkbox"], input[type="radio"]', onChange);
};
function handleInputChange() {
let optionEl;
let text;
const inputEl = this;
const value = inputEl.value;
let optionText = [];
let displayAs;
if (inputEl.type === 'checkbox') {
for (let i = 0; i < ss.selectEl.options.length; i += 1) {
optionEl = ss.selectEl.options[i];
if (optionEl.value === value) {
optionEl.selected = inputEl.checked;
}
if (optionEl.selected) {
displayAs = optionEl.dataset ? optionEl.dataset.displayAs : $(optionEl).data('display-value-as');
text = displayAs && typeof displayAs !== 'undefined' ? displayAs : optionEl.textContent;
optionText.push(text.trim());
}
}
if (ss.maxLength) {
ss.checkMaxLength();
}
} else {
optionEl = ss.$selectEl.find(`option[value="${value}"]`)[0];
displayAs = optionEl.dataset ? optionEl.dataset.displayAs : $(optionEl).data('display-as');
text = displayAs && typeof displayAs !== 'undefined' ? displayAs : optionEl.textContent;
optionText = [text];
ss.selectEl.value = value;
}
ss.$selectEl.trigger('change');
ss.$valueEl.text(optionText.join(', '));
if (ss.params.closeOnSelect && ss.inputType === 'radio') {
ss.close();
}
}
ss.attachInputsEvents = function attachInputsEvents() {
ss.$containerEl.on('change', 'input[type="checkbox"], input[type="radio"]', handleInputChange);
};
ss.detachInputsEvents = function detachInputsEvents() {
ss.$containerEl.off('change', 'input[type="checkbox"], input[type="radio"]', handleInputChange);
};
// Install Modules
ss.useModules();
// Init
ss.init();
return ss;
}
checkMaxLength() {
const ss = this;
const $containerEl = ss.$containerEl;
if (ss.selectEl.selectedOptions.length >= ss.maxLength) {
$containerEl.find('input[type="checkbox"]').each((index, inputEl) => {
if (!inputEl.checked) {
$(inputEl).parents('li').addClass('disabled');
} else {
$(inputEl).parents('li').removeClass('disabled');
}
});
} else {
$containerEl.find('.disabled').removeClass('disabled');
}
}
setValue(value) {
const ss = this;
let valueArray = [];
if (typeof value !== 'undefined') {
if (Array.isArray(value)) {
valueArray = value;
} else {
valueArray = [value];
}
} else {
ss.$selectEl.find('option').each((optionIndex, optionEl) => {
const $optionEl = $(optionEl);
if (optionEl.selected) {
const displayAs = optionEl.dataset ? optionEl.dataset.displayAs : $optionEl.data('display-value-as');
if (displayAs && typeof displayAs !== 'undefined') {
valueArray.push(displayAs);
} else {
valueArray.push(optionEl.textContent.trim());
}
}
});
}
ss.$valueEl.text(valueArray.join(', '));
}
getItemsData() {
const ss = this;
const items = [];
let previousGroupEl;
ss.$selectEl.find('option').each((index, optionEl) => {
const $optionEl = $(optionEl);
const optionData = $optionEl.dataset();
const optionImage = optionData.optionImage || ss.params.optionImage;
const optionIcon = optionData.optionIcon || ss.params.optionIcon;
const optionHasMedia = optionImage || optionIcon;
// if (material) optionHasMedia = optionImage || optionIcon;
const optionColor = optionData.optionColor;
let optionClassName = optionData.optionClass || '';
if ($optionEl[0].disabled) optionClassName += ' disabled';
const optionGroupEl = $optionEl.parent('optgroup')[0];
const optionGroupLabel = optionGroupEl && optionGroupEl.label;
let optionIsLabel = false;
if (optionGroupEl && optionGroupEl !== previousGroupEl) {
optionIsLabel = true;
previousGroupEl = optionGroupEl;
items.push({
groupLabel: optionGroupLabel,
isLabel: optionIsLabel,
});
}
items.push({
value: $optionEl[0].value,
text: $optionEl[0].textContent.trim(),
selected: $optionEl[0].selected,
groupEl: optionGroupEl,
groupLabel: optionGroupLabel,
image: optionImage,
icon: optionIcon,
color: optionColor,
className: optionClassName,
disabled: $optionEl[0].disabled,
id: ss.id,
hasMedia: optionHasMedia,
checkbox: ss.inputType === 'checkbox',
radio: ss.inputType === 'radio',
inputName: ss.inputName,
inputType: ss.inputType,
});
});
ss.items = items;
return items;
}
renderSearchbar() {
const ss = this;
if (ss.params.renderSearchbar) return ss.params.renderSearchbar.call(ss);
const searchbarHTML = `
<form class="searchbar">
<div class="searchbar-inner">
<div class="searchbar-input-wrap">
<input type="search" placeholder="${ss.params.searchbarPlaceholder}"/>
<i class="searchbar-icon"></i>
<span class="input-clear-button"></span>
</div>
<span class="searchbar-disable-button">${ss.params.searchbarDisableText}</span>
</div>
</form>
`;
return searchbarHTML;
}
renderItem(item, index) {
const ss = this;
if (ss.params.renderItem) return ss.params.renderItem.call(ss, item, index);
let itemHtml;
if (item.isLabel) {
itemHtml = `<li class="item-divider">${item.groupLabel}</li>`;
} else {
itemHtml = `
<li class="${item.className || ''}">
<label class="item-${item.inputType} item-content">
<input type="${item.inputType}" name="${item.inputName}" value="${item.value}" ${item.selected ? 'checked' : ''}/>
<i class="icon icon-${item.inputType}"></i>
${item.hasMedia ? `
<div class="item-media">
${item.icon ? `<i class="icon ${item.icon}"></i>` : ''}
${item.image ? `<img src="${item.image}">` : ''}
</div>
` : ''}
<div class="item-inner">
<div class="item-title${item.color ? ` color-${item.color}` : ''}">${item.text}</div>
</div>
</label>
</li>
`;
}
return itemHtml;
}
renderItems() {
const ss = this;
if (ss.params.renderItems) return ss.params.renderItems.call(ss, ss.items);
const itemsHtml = `
${ss.items.map((item, index) => `${ss.renderItem(item, index)}`).join('')}
`;
return itemsHtml;
}
renderPage() {
const ss = this;
if (ss.params.renderPage) return ss.params.renderPage.call(ss, ss.items);
let pageTitle = ss.params.pageTitle;
if (typeof pageTitle === 'undefined') {
pageTitle = ss.$el.find('.item-title').text().trim();
}
const pageHtml = `
<div class="page smart-select-page" data-name="smart-select-page" data-select-name="${ss.selectName}">
<div class="navbar ${ss.params.navbarColorTheme ? `color-theme-${ss.params.navbarColorTheme}` : ''}">
<div class="navbar-inner sliding ${ss.params.navbarColorTheme ? `color-theme-${ss.params.navbarColorTheme}` : ''}">
<div class="left">
<a href="#" class="link back">
<i class="icon icon-back"></i>
<span class="ios-only">${ss.params.pageBackLinkText}</span>
</a>
</div>
${pageTitle ? `<div class="title">${pageTitle}</div>` : ''}
${ss.params.searchbar ? `<div class="subnavbar">${ss.renderSearchbar()}</div>` : ''}
</div>
</div>
${ss.params.searchbar ? '<div class="searchbar-backdrop"></div>' : ''}
<div class="page-content">
<div class="list smart-select-list-${ss.id} ${ss.params.virtualList ? ' virtual-list' : ''} ${ss.params.formColorTheme ? `color-theme-${ss.params.formColorTheme}` : ''}">
<ul>${!ss.params.virtualList && ss.renderItems(ss.items)}</ul>
</div>
</div>
</div>
`;
return pageHtml;
}
renderPopup() {
const ss = this;
if (ss.params.renderPopup) return ss.params.renderPopup.call(ss, ss.items);
let pageTitle = ss.params.pageTitle;
if (typeof pageTitle === 'undefined') {
pageTitle = ss.$el.find('.item-title').text().trim();
}
const popupHtml = `
<div class="popup smart-select-popup" data-select-name="${ss.selectName}">
<div class="view">
<div class="page smart-select-page ${ss.params.searchbar ? 'page-with-subnavbar' : ''}" data-name="smart-select-page">
<div class="navbar${ss.params.navbarColorTheme ? `theme-${ss.params.navbarColorTheme}` : ''}">
<div class="navbar-inner sliding">
<div class="left">
<a href="#" class="link popup-close">
<i class="icon icon-back"></i>
<span class="ios-only">${ss.params.popupCloseLinkText}</span>
</a>
</div>
${pageTitle ? `<div class="title">${pageTitle}</div>` : ''}
${ss.params.searchbar ? `<div class="subnavbar">${ss.renderSearchbar()}</div>` : ''}
</div>
</div>
${ss.params.searchbar ? '<div class="searchbar-backdrop"></div>' : ''}
<div class="page-content">
<div class="list smart-select-list-${ss.id} ${ss.params.virtualList ? ' virtual-list' : ''}${ss.params.formColorTheme ? `theme-${ss.params.formColorTheme}` : ''}">
<ul>${!ss.params.virtualList && ss.renderItems(ss.items)}</ul>
</div>
</div>
</div>
</div>
</div>
`;
return popupHtml;
}
renderSheet() {
const ss = this;
if (ss.params.renderSheet) return ss.params.renderSheet.call(ss, ss.items);
const sheetHtml = `
<div class="sheet-modal smart-select-sheet" data-select-name="${ss.selectName}">
<div class="toolbar ${ss.params.toolbarColorTheme ? `theme-${ss.params.toolbarColorTheme}` : ''}">
<div class="toolbar-inner">
<div class="left"></div>
<div class="right">
<a class="link sheet-close">${ss.params.sheetCloseLinkText}</a>
</div>
</div>
</div>
<div class="sheet-modal-inner">
<div class="page-content">
<div class="list smart-select-list-${ss.id} ${ss.params.virtualList ? ' virtual-list' : ''}${ss.params.formColorTheme ? `theme-${ss.params.formColorTheme}` : ''}">
<ul>${!ss.params.virtualList && ss.renderItems(ss.items)}</ul>
</div>
</div>
</div>
</div>
`;
return sheetHtml;
}
renderPopover() {
const ss = this;
if (ss.params.renderPopover) return ss.params.renderPopover.call(ss, ss.items);
const popoverHtml = `
<div class="popover smart-select-popover" data-select-name="${ss.selectName}">
<div class="popover-inner">
<div class="list smart-select-list-${ss.id} ${ss.params.virtualList ? ' virtual-list' : ''}${ss.params.formColorTheme ? `theme-${ss.params.formColorTheme}` : ''}">
<ul>${!ss.params.virtualList && ss.renderItems(ss.items)}</ul>
</div>
</div>
</div>
`;
return popoverHtml;
}
onOpen(type, containerEl) {
const ss = this;
const app = ss.app;
const $containerEl = $(containerEl);
ss.$containerEl = $containerEl;
ss.openedIn = type;
ss.opened = true;
// Init VL
if (ss.params.virtualList) {
ss.vl = app.virtualList.create({
el: $containerEl.find('.virtual-list'),
items: ss.items,
renderItem: ss.renderItem.bind(ss),
height: ss.params.virtualListHeight,
searchByItem(query, item) {
if (item.text && item.text.toLowerCase().indexOf(query.trim().toLowerCase()) >= 0) return true;
return false;
},
});
}
// Init SB
if (ss.params.searchbar) {
ss.searchbar = app.searchbar.create({
el: $containerEl.find('.searchbar'),
backdropEl: $containerEl.find('.searchbar-backdrop'),
searchContainer: `.smart-select-list-${ss.id}`,
searchIn: '.item-title',
});
}
// Check for max length
if (ss.maxLength) {
ss.checkMaxLength();
}
// Close on select
if (ss.params.closeOnSelect) {
ss.$containerEl.find(`input[type="radio"][name="${ss.inputName}"]:checked`).parents('label').once('click', () => {
ss.close();
});
}
// Attach input events
ss.attachInputsEvents();
ss.$el.trigger('smartselect:open', ss);
ss.emit('local::open smartSelectOpen', ss);
}
onOpened() {
const ss = this;
ss.$el.trigger('smartselect:opened', ss);
ss.emit('local::opened smartSelectOpened', ss);
}
onClose() {
const ss = this;
if (ss.destroyed) return;
// Destroy VL
if (ss.vl && ss.vl.destroy) {
ss.vl.destroy();
ss.vl = null;
delete ss.vl;
}
// Destroy SB
if (ss.searchbar && ss.searchbar.destroy) {
ss.searchbar.destroy();
ss.searchbar = null;
delete ss.searchbar;
}
// Detach events
ss.detachInputsEvents();
ss.$el.trigger('smartselect:close', ss);
ss.emit('local::close smartSelectClose', ss);
}
onClosed() {
const ss = this;
if (ss.destroyed) return;
ss.opened = false;
ss.$containerEl = null;
delete ss.$containerEl;
ss.$el.trigger('smartselect:closed', ss);
ss.emit('local::closed smartSelectClosed', ss);
}
openPage() {
const ss = this;
if (ss.opened) return ss;
ss.getItemsData();
const pageHtml = ss.renderPage(ss.items);
ss.view.router.navigate({
url: ss.url,
route: {
content: pageHtml,
path: ss.url,
on: {
pageBeforeIn(e, page) {
ss.onOpen('page', page.el);
},
pageAfterIn(e, page) {
ss.onOpened('page', page.el);
},
pageBeforeOut(e, page) {
ss.onClose('page', page.el);
},
pageAfterOut(e, page) {
ss.onClosed('page', page.el);
},
},
},
});
return ss;
}
openPopup() {
const ss = this;
if (ss.opened) return ss;
ss.getItemsData();
const popupHtml = ss.renderPopup(ss.items);
const popupParams = {
content: popupHtml,
on: {
popupOpen(popup) {
ss.onOpen('popup', popup.el);
},
popupOpened(popup) {
ss.onOpened('popup', popup.el);
},
popupClose(popup) {
ss.onClose('popup', popup.el);
},
popupClosed(popup) {
ss.onClosed('popup', popup.el);
},
},
};
if (ss.params.routableModals) {
ss.view.router.navigate({
url: ss.url,
route: {
path: ss.url,
popup: popupParams,
},
});
} else {
ss.modal = ss.app.popup.create(popupParams).open();
}
return ss;
}
openSheet() {
const ss = this;
if (ss.opened) return ss;
ss.getItemsData();
const sheetHtml = ss.renderSheet(ss.items);
const sheetParams = {
content: sheetHtml,
backdrop: false,
scrollToEl: ss.$el,
closeByOutsideClick: true,
on: {
sheetOpen(sheet) {
ss.onOpen('sheet', sheet.el);
},
sheetOpened(sheet) {
ss.onOpened('sheet', sheet.el);
},
sheetClose(sheet) {
ss.onClose('sheet', sheet.el);
},
sheetClosed(sheet) {
ss.onClosed('sheet', sheet.el);
},
},
};
if (ss.params.routableModals) {
ss.view.router.navigate({
url: ss.url,
route: {
path: ss.url,
sheet: sheetParams,
},
});
} else {
ss.modal = ss.app.sheet.create(sheetParams).open();
}
return ss;
}
openPopover() {
const ss = this;
if (ss.opened) return ss;
ss.getItemsData();
const popoverHtml = ss.renderPopover(ss.items);
const popoverParams = {
content: popoverHtml,
targetEl: ss.$el,
on: {
popoverOpen(popover) {
ss.onOpen('popover', popover.el);
},
popoverOpened(popover) {
ss.onOpened('popover', popover.el);
},
popoverClose(popover) {
ss.onClose('popover', popover.el);
},
popoverClosed(popover) {
ss.onClosed('popover', popover.el);
},
},
};
if (ss.params.routableModals) {
ss.view.router.navigate({
url: ss.url,
route: {
path: ss.url,
popover: popoverParams,
},
});
} else {
ss.modal = ss.app.popover.create(popoverParams).open();
}
return ss;
}
open(type) {
const ss = this;
if (ss.opened) return ss;
const openIn = type || ss.params.openIn;
ss[`open${openIn.split('').map((el, index) => {
if (index === 0) return el.toUpperCase();
return el;
}).join('')}`]();
return ss;
}
close() {
const ss = this;
if (!ss.opened) return ss;
if (ss.params.routableModals || ss.openedIn === 'page') {
ss.view.router.back();
} else {
ss.modal.once('modalClosed', () => {
Utils.nextTick(() => {
ss.modal.destroy();
delete ss.modal;
});
});
ss.modal.close();
}
return ss;
}
init() {
const ss = this;
ss.attachEvents();
ss.setValue();
}
destroy() {
const ss = this;
ss.emit('local::beforeDestroy smartSelectBeforeDestroy', ss);
ss.$el.trigger('smartselect:beforedestroy', ss);
ss.detachEvents();
delete ss.$el[0].f7SmartSelect;
Utils.deleteProps(ss);
ss.destroyed = true;
}
}
var SmartSelect = {
name: 'smartSelect',
params: {
smartSelect: {
el: undefined,
valueEl: undefined,
openIn: 'page', // or 'popup' or 'sheet' or 'popover'
pageTitle: undefined,
pageBackLinkText: 'Back',
popupCloseLinkText: 'Close',
sheetCloseLinkText: 'Done',
searchbar: false,
searchbarPlaceholder: 'Search',
searchbarDisableText: 'Cancel',
closeOnSelect: false,
virtualList: false,
virtualListHeight: undefined,
formColorTheme: undefined,
navbarColorTheme: undefined,
routableModals: true,
url: 'select/',
/*
Custom render functions
*/
renderPage: undefined,
renderPopup: undefined,
renderSheet: undefined,
renderPopover: undefined,
renderItems: undefined,
renderItem: undefined,
renderSearchbar: undefined,
},
},
static: {
SmartSelect: SmartSelect$1,
},
create() {
const app = this;
app.smartSelect = Utils.extend(
ConstructorMethods({
defaultSelector: '.smart-select',
constructor: SmartSelect$1,
app,
domProp: 'f7SmartSelect',
}),
{
open(smartSelectEl) {
const ss = app.smartSelect.get(smartSelectEl);
if (ss && ss.open) return ss.open();
return undefined;
},
close(smartSelectEl) {
const ss = app.smartSelect.get(smartSelectEl);
if (ss && ss.close) return ss.close();
return undefined;
},
}
);
},
on: {
tabMounted(tabEl) {
const app = this;
$(tabEl).find('.smart-select-init').each((index, smartSelectEl) => {
app.smartSelect.create(Utils.extend({ el: smartSelectEl }, $(smartSelectEl).dataset()));
});
},
tabBeforeRemove(tabEl) {
$(tabEl).find('.smart-select-init').each((index, smartSelectEl) => {
if (smartSelectEl.f7SmartSelect && smartSelectEl.f7SmartSelect.destroy) {
smartSelectEl.f7SmartSelect.destroy();
}
});
},
pageInit(page) {
const app = this;
page.$el.find('.smart-select-init').each((index, smartSelectEl) => {
app.smartSelect.create(Utils.extend({ el: smartSelectEl }, $(smartSelectEl).dataset()));
});
},
pageBeforeRemove(page) {
page.$el.find('.smart-select-init').each((index, smartSelectEl) => {
if (smartSelectEl.f7SmartSelect && smartSelectEl.f7SmartSelect.destroy) {
smartSelectEl.f7SmartSelect.destroy();
}
});
},
},
clicks: {
'.smart-select': function open($clickedEl, data) {
const app = this;
if (!$clickedEl[0].f7SmartSelect) {
const ss = app.smartSelect.create(Utils.extend({ el: $clickedEl }, data));
ss.open();
}
},
},
};
class Calendar$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const calendar = this;
calendar.params = Utils.extend({}, app.params.calendar, params);
let $containerEl;
if (calendar.params.containerEl) {
$containerEl = $(calendar.params.containerEl);
if ($containerEl.length === 0) return calendar;
}
let $inputEl;
if (calendar.params.inputEl) {
$inputEl = $(calendar.params.inputEl);
}
let view;
if ($inputEl) {
view = $inputEl.parents('.view').length && $inputEl.parents('.view')[0].f7View;
}
if (!view) view = app.views.main;
const isHorizontal = calendar.params.direction === 'horizontal';
let inverter = 1;
if (isHorizontal) {
inverter = app.rtl ? -1 : 1;
}
Utils.extend(calendar, {
app,
$containerEl,
containerEl: $containerEl && $containerEl[0],
inline: $containerEl && $containerEl.length > 0,
$inputEl,
inputEl: $inputEl && $inputEl[0],
initialized: false,
opened: false,
url: calendar.params.url,
isHorizontal,
inverter,
view,
animating: false,
});
function onInputClick() {
calendar.open();
}
function onInputFocus(e) {
e.preventDefault();
}
function onHtmlClick(e) {
const $targetEl = $(e.target);
if (calendar.isPopover()) return;
if (!calendar.opened) return;
if ($targetEl.closest('[class*="backdrop"]').length) return;
if ($inputEl && $inputEl.length > 0) {
if ($targetEl[0] !== $inputEl[0] && $targetEl.closest('.sheet-modal, .calendar-modal').length === 0) {
calendar.close();
}
} else if ($(e.target).closest('.sheet-modal, .calendar-modal').length === 0) {
calendar.close();
}
}
// Events
Utils.extend(calendar, {
attachInputEvents() {
calendar.$inputEl.on('click', onInputClick);
if (calendar.params.inputReadOnly) {
calendar.$inputEl.on('focus mousedown', onInputFocus);
}
},
detachInputEvents() {
calendar.$inputEl.off('click', onInputClick);
if (calendar.params.inputReadOnly) {
calendar.$inputEl.off('focus mousedown', onInputFocus);
}
},
attachHtmlEvents() {
app.on('click', onHtmlClick);
},
detachHtmlEvents() {
app.off('click', onHtmlClick);
},
});
calendar.attachCalendarEvents = function attachCalendarEvents() {
let allowItemClick = true;
let isTouched;
let isMoved;
let touchStartX;
let touchStartY;
let touchCurrentX;
let touchCurrentY;
let touchStartTime;
let touchEndTime;
let currentTranslate;
let wrapperWidth;
let wrapperHeight;
let percentage;
let touchesDiff;
let isScrolling;
const { $el, $wrapperEl } = calendar;
function handleTouchStart(e) {
if (isMoved || isTouched) return;
isTouched = true;
touchStartX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchCurrentX = touchStartX;
touchStartY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
touchCurrentY = touchStartY;
touchStartTime = (new Date()).getTime();
percentage = 0;
allowItemClick = true;
isScrolling = undefined;
currentTranslate = calendar.monthsTranslate;
}
function handleTouchMove(e) {
if (!isTouched) return;
const { isHorizontal: isH } = calendar;
touchCurrentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
touchCurrentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(touchCurrentY - touchStartY) > Math.abs(touchCurrentX - touchStartX));
}
if (isH && isScrolling) {
isTouched = false;
return;
}
e.preventDefault();
if (calendar.animating) {
isTouched = false;
return;
}
allowItemClick = false;
if (!isMoved) {
// First move
isMoved = true;
wrapperWidth = $wrapperEl[0].offsetWidth;
wrapperHeight = $wrapperEl[0].offsetHeight;
$wrapperEl.transition(0);
}
touchesDiff = isH ? touchCurrentX - touchStartX : touchCurrentY - touchStartY;
percentage = touchesDiff / (isH ? wrapperWidth : wrapperHeight);
currentTranslate = ((calendar.monthsTranslate * calendar.inverter) + percentage) * 100;
// Transform wrapper
$wrapperEl.transform(`translate3d(${isH ? currentTranslate : 0}%, ${isH ? 0 : currentTranslate}%, 0)`);
}
function handleTouchEnd() {
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
isTouched = false;
isMoved = false;
touchEndTime = new Date().getTime();
if (touchEndTime - touchStartTime < 300) {
if (Math.abs(touchesDiff) < 10) {
calendar.resetMonth();
} else if (touchesDiff >= 10) {
if (app.rtl) calendar.nextMonth();
else calendar.prevMonth();
} else if (app.rtl) calendar.prevMonth();
else calendar.nextMonth();
} else if (percentage <= -0.5) {
if (app.rtl) calendar.prevMonth();
else calendar.nextMonth();
} else if (percentage >= 0.5) {
if (app.rtl) calendar.nextMonth();
else calendar.prevMonth();
} else {
calendar.resetMonth();
}
// Allow click
setTimeout(() => {
allowItemClick = true;
}, 100);
}
function handleDayClick(e) {
if (!allowItemClick) return;
let $dayEl = $(e.target).parents('.calendar-day');
if ($dayEl.length === 0 && $(e.target).hasClass('calendar-day')) {
$dayEl = $(e.target);
}
if ($dayEl.length === 0) return;
if ($dayEl.hasClass('calendar-day-disabled')) return;
if (!calendar.params.rangePicker) {
if ($dayEl.hasClass('calendar-day-next')) calendar.nextMonth();
if ($dayEl.hasClass('calendar-day-prev')) calendar.prevMonth();
}
const dateYear = $dayEl.attr('data-year');
const dateMonth = $dayEl.attr('data-month');
const dateDay = $dayEl.attr('data-day');
calendar.emit(
'local::dayClick calendarDayClick',
calendar,
$dayEl[0],
dateYear,
dateMonth,
dateDay
);
if (!$dayEl.hasClass('calendar-day-selected') || calendar.params.multiple || calendar.params.rangePicker) {
calendar.addValue(new Date(dateYear, dateMonth, dateDay, 0, 0, 0));
}
if (calendar.params.closeOnSelect) {
if (
(calendar.params.rangePicker && calendar.value.length === 2) ||
!calendar.params.rangePicker
) {
calendar.close();
}
}
}
function onNextMonthClick() {
calendar.nextMonth();
}
function onPrevMonthClick() {
calendar.prevMonth();
}
function onNextYearClick() {
calendar.nextYear();
}
function onPrevYearClick() {
calendar.prevYear();
}
const passiveListener = app.touchEvents.start === 'touchstart' && app.support.passiveListener ? { passive: true, capture: false } : false;
// Selectors clicks
$el.find('.calendar-prev-month-button').on('click', onPrevMonthClick);
$el.find('.calendar-next-month-button').on('click', onNextMonthClick);
$el.find('.calendar-prev-year-button').on('click', onPrevYearClick);
$el.find('.calendar-next-year-button').on('click', onNextYearClick);
// Day clicks
$wrapperEl.on('click', handleDayClick);
// Touch events
{
if (calendar.params.touchMove) {
$wrapperEl.on(app.touchEvents.start, handleTouchStart, passiveListener);
app.on('touchmove:active', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
}
}
calendar.detachCalendarEvents = function detachCalendarEvents() {
$el.find('.calendar-prev-month-button').off('click', onPrevMonthClick);
$el.find('.calendar-next-month-button').off('click', onNextMonthClick);
$el.find('.calendar-prev-year-button').off('click', onPrevYearClick);
$el.find('.calendar-next-year-button').off('click', onNextYearClick);
$wrapperEl.off('click', handleDayClick);
{
if (calendar.params.touchMove) {
$wrapperEl.off(app.touchEvents.start, handleTouchStart, passiveListener);
app.off('touchmove:active', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
}
}
};
};
calendar.init();
return calendar;
}
initInput() {
const calendar = this;
if (!calendar.$inputEl) return;
if (calendar.params.inputReadOnly) calendar.$inputEl.prop('readOnly', true);
}
isPopover() {
const calendar = this;
const { app, modal, params } = calendar;
if (params.openIn === 'sheet') return false;
if (modal && modal.type !== 'popover') return false;
if (!calendar.inline && calendar.inputEl) {
if (params.openIn === 'popover') return true;
else if (app.device.ios) {
return !!app.device.ipad;
} else if (app.width >= 768) {
return true;
}
}
return false;
}
formatDate(d) {
const calendar = this;
const date = new Date(d);
const year = date.getFullYear();
const month = date.getMonth();
const month1 = month + 1;
const day = date.getDate();
const weekDay = date.getDay();
const { dateFormat, monthNames, monthNamesShort, dayNames, dayNamesShort } = calendar.params;
return dateFormat
.replace(/yyyy/g, year)
.replace(/yy/g, String(year).substring(2))
.replace(/mm/g, month1 < 10 ? `0${month1}` : month1)
.replace(/m(\W+)/g, `${month1}$1`)
.replace(/MM/g, monthNames[month])
.replace(/M(\W+)/g, `${monthNamesShort[month]}$1`)
.replace(/dd/g, day < 10 ? `0${day}` : day)
.replace(/d(\W+)/g, `${day}$1`)
.replace(/DD/g, dayNames[weekDay])
.replace(/D(\W+)/g, `${dayNamesShort[weekDay]}$1`);
}
formatValue() {
const calendar = this;
const { value } = calendar;
if (calendar.params.formatValue) {
return calendar.params.formatValue.call(calendar, value);
}
return value
.map(v => calendar.formatDate(v))
.join(calendar.params.rangePicker ? ' - ' : ', ');
}
addValue(newValue) {
const calendar = this;
const { multiple, rangePicker } = calendar.params;
if (multiple) {
if (!calendar.value) calendar.value = [];
let inValuesIndex;
for (let i = 0; i < calendar.value.length; i += 1) {
if (new Date(newValue).getTime() === new Date(calendar.value[i]).getTime()) {
inValuesIndex = i;
}
}
if (typeof inValuesIndex === 'undefined') {
calendar.value.push(newValue);
} else {
calendar.value.splice(inValuesIndex, 1);
}
calendar.updateValue();
} else if (rangePicker) {
if (!calendar.value) calendar.value = [];
if (calendar.value.length === 2 || calendar.value.length === 0) {
calendar.value = [];
}
if (calendar.value[0] !== newValue) calendar.value.push(newValue);
else calendar.value = [];
calendar.value.sort((a, b) => a - b);
calendar.updateValue();
} else {
calendar.value = [newValue];
calendar.updateValue();
}
}
setValue(values) {
const calendar = this;
calendar.value = values;
calendar.updateValue();
}
getValue() {
const calendar = this;
return calendar.value;
}
updateValue(onlyHeader) {
const calendar = this;
const {
$el,
$wrapperEl,
$inputEl,
value,
params,
} = calendar;
let i;
if ($el && $el.length > 0) {
$wrapperEl.find('.calendar-day-selected').removeClass('calendar-day-selected');
let valueDate;
if (params.rangePicker && value.length === 2) {
for (i = new Date(value[0]).getTime(); i <= new Date(value[1]).getTime(); i += 24 * 60 * 60 * 1000) {
valueDate = new Date(i);
$wrapperEl.find(`.calendar-day[data-date="${valueDate.getFullYear()}-${valueDate.getMonth()}-${valueDate.getDate()}"]`).addClass('calendar-day-selected');
}
} else {
for (i = 0; i < calendar.value.length; i += 1) {
valueDate = new Date(value[i]);
$wrapperEl.find(`.calendar-day[data-date="${valueDate.getFullYear()}-${valueDate.getMonth()}-${valueDate.getDate()}"]`).addClass('calendar-day-selected');
}
}
}
calendar.emit('local::change calendarChange', calendar, value);
if (($inputEl && $inputEl.length) || params.header) {
const inputValue = calendar.formatValue(value);
if (params.header && $el && $el.length) {
$el.find('.calendar-selected-date').text(inputValue);
}
if ($inputEl && $inputEl.length && !onlyHeader) {
$inputEl.val(inputValue);
$inputEl.trigger('change');
}
}
}
updateCurrentMonthYear(dir) {
const calendar = this;
const { $months, $el, params } = calendar;
if (typeof dir === 'undefined') {
calendar.currentMonth = parseInt($months.eq(1).attr('data-month'), 10);
calendar.currentYear = parseInt($months.eq(1).attr('data-year'), 10);
} else {
calendar.currentMonth = parseInt($months.eq(dir === 'next' ? ($months.length - 1) : 0).attr('data-month'), 10);
calendar.currentYear = parseInt($months.eq(dir === 'next' ? ($months.length - 1) : 0).attr('data-year'), 10);
}
$el.find('.current-month-value').text(params.monthNames[calendar.currentMonth]);
$el.find('.current-year-value').text(calendar.currentYear);
}
update() {
const calendar = this;
const { currentYear, currentMonth, $wrapperEl } = calendar;
const currentDate = new Date(currentYear, currentMonth);
const prevMonthHtml = calendar.renderMonth(currentDate, 'prev');
const currentMonthHtml = calendar.renderMonth(currentDate);
const nextMonthHtml = calendar.renderMonth(currentDate, 'next');
$wrapperEl
.html(`${prevMonthHtml}${currentMonthHtml}${nextMonthHtml}`)
.transform('translate3d(0,0,0)');
calendar.$months = $wrapperEl.find('.calendar-month');
calendar.monthsTranslate = 0;
calendar.setMonthsTranslate();
calendar.$months.each((index, monthEl) => {
calendar.emit(
'local::monthAdd calendarMonthAdd',
monthEl
);
});
}
onMonthChangeStart(dir) {
const calendar = this;
const { $months, currentYear, currentMonth } = calendar;
calendar.updateCurrentMonthYear(dir);
$months.removeClass('calendar-month-current calendar-month-prev calendar-month-next');
const currentIndex = dir === 'next' ? $months.length - 1 : 0;
$months.eq(currentIndex).addClass('calendar-month-current');
$months.eq(dir === 'next' ? currentIndex - 1 : currentIndex + 1).addClass(dir === 'next' ? 'calendar-month-prev' : 'calendar-month-next');
calendar.emit(
'local::monthYearChangeStart calendarMonthYearChangeStart',
calendar,
currentYear,
currentMonth
);
}
onMonthChangeEnd(dir, rebuildBoth) {
const calendar = this;
const { currentYear, currentMonth, $wrapperEl, monthsTranslate } = calendar;
calendar.animating = false;
let nextMonthHtml;
let prevMonthHtml;
let currentMonthHtml;
$wrapperEl
.find('.calendar-month:not(.calendar-month-prev):not(.calendar-month-current):not(.calendar-month-next)')
.remove();
if (typeof dir === 'undefined') {
dir = 'next'; // eslint-disable-line
rebuildBoth = true; // eslint-disable-line
}
if (!rebuildBoth) {
currentMonthHtml = calendar.renderMonth(new Date(currentYear, currentMonth), dir);
} else {
$wrapperEl.find('.calendar-month-next, .calendar-month-prev').remove();
prevMonthHtml = calendar.renderMonth(new Date(currentYear, currentMonth), 'prev');
nextMonthHtml = calendar.renderMonth(new Date(currentYear, currentMonth), 'next');
}
if (dir === 'next' || rebuildBoth) {
$wrapperEl.append(currentMonthHtml || nextMonthHtml);
}
if (dir === 'prev' || rebuildBoth) {
$wrapperEl.prepend(currentMonthHtml || prevMonthHtml);
}
const $months = $wrapperEl.find('.calendar-month');
calendar.$months = $months;
calendar.setMonthsTranslate(monthsTranslate);
calendar.emit(
'local::monthAdd calendarMonthAdd',
calendar,
dir === 'next' ? $months.eq($months.length - 1)[0] : $months.eq(0)[0]
);
calendar.emit(
'local::monthYearChangeEnd calendarMonthYearChangeEnd',
calendar,
currentYear,
currentMonth
);
}
setMonthsTranslate(translate) {
const calendar = this;
const { $months, isHorizontal: isH, inverter } = calendar;
// eslint-disable-next-line
translate = translate || calendar.monthsTranslate || 0;
if (typeof calendar.monthsTranslate === 'undefined') {
calendar.monthsTranslate = translate;
}
$months.removeClass('calendar-month-current calendar-month-prev calendar-month-next');
const prevMonthTranslate = -(translate + 1) * 100 * inverter;
const currentMonthTranslate = -translate * 100 * inverter;
const nextMonthTranslate = -(translate - 1) * 100 * inverter;
$months.eq(0)
.transform(`translate3d(${isH ? prevMonthTranslate : 0}%, ${isH ? 0 : prevMonthTranslate}%, 0)`)
.addClass('calendar-month-prev');
$months.eq(1)
.transform(`translate3d(${isH ? currentMonthTranslate : 0}%, ${isH ? 0 : currentMonthTranslate}%, 0)`)
.addClass('calendar-month-current');
$months.eq(2)
.transform(`translate3d(${isH ? nextMonthTranslate : 0}%, ${isH ? 0 : nextMonthTranslate}%, 0)`)
.addClass('calendar-month-next');
}
nextMonth(transition) {
const calendar = this;
const { params, $wrapperEl, inverter, isHorizontal: isH } = calendar;
if (typeof transition === 'undefined' || typeof transition === 'object') {
transition = ''; // eslint-disable-line
if (!params.animate) transition = 0; // eslint-disable-line
}
const nextMonth = parseInt(calendar.$months.eq(calendar.$months.length - 1).attr('data-month'), 10);
const nextYear = parseInt(calendar.$months.eq(calendar.$months.length - 1).attr('data-year'), 10);
const nextDate = new Date(nextYear, nextMonth);
const nextDateTime = nextDate.getTime();
const transitionEndCallback = !calendar.animating;
if (params.maxDate) {
if (nextDateTime > new Date(params.maxDate).getTime()) {
calendar.resetMonth();
return;
}
}
calendar.monthsTranslate -= 1;
if (nextMonth === calendar.currentMonth) {
const nextMonthTranslate = -(calendar.monthsTranslate) * 100 * inverter;
const nextMonthHtml = $(calendar.renderMonth(nextDateTime, 'next'))
.transform(`translate3d(${isH ? nextMonthTranslate : 0}%, ${isH ? 0 : nextMonthTranslate}%, 0)`)
.addClass('calendar-month-next');
$wrapperEl.append(nextMonthHtml[0]);
calendar.$months = $wrapperEl.find('.calendar-month');
calendar.emit(
'local::monthAdd calendarMonthAdd',
calendar.$months.eq(calendar.$months.length - 1)[0]
);
}
calendar.animating = true;
calendar.onMonthChangeStart('next');
const translate = (calendar.monthsTranslate * 100) * inverter;
$wrapperEl.transition(transition).transform(`translate3d(${isH ? translate : 0}%, ${isH ? 0 : translate}%, 0)`);
if (transitionEndCallback) {
$wrapperEl.transitionEnd(() => {
calendar.onMonthChangeEnd('next');
});
}
if (!params.animate) {
calendar.onMonthChangeEnd('next');
}
}
prevMonth(transition) {
const calendar = this;
const { params, $wrapperEl, inverter, isHorizontal: isH } = calendar;
if (typeof transition === 'undefined' || typeof transition === 'object') {
transition = ''; // eslint-disable-line
if (!params.animate) transition = 0; // eslint-disable-line
}
const prevMonth = parseInt(calendar.$months.eq(0).attr('data-month'), 10);
const prevYear = parseInt(calendar.$months.eq(0).attr('data-year'), 10);
const prevDate = new Date(prevYear, prevMonth + 1, -1);
const prevDateTime = prevDate.getTime();
const transitionEndCallback = !calendar.animating;
if (params.minDate) {
if (prevDateTime < new Date(params.minDate).getTime()) {
calendar.resetMonth();
return;
}
}
calendar.monthsTranslate += 1;
if (prevMonth === calendar.currentMonth) {
const prevMonthTranslate = -(calendar.monthsTranslate) * 100 * inverter;
const prevMonthHtml = $(calendar.renderMonth(prevDateTime, 'prev'))
.transform(`translate3d(${isH ? prevMonthTranslate : 0}%, ${isH ? 0 : prevMonthTranslate}%, 0)`)
.addClass('calendar-month-prev');
$wrapperEl.prepend(prevMonthHtml[0]);
calendar.$months = $wrapperEl.find('.calendar-month');
calendar.emit(
'local::monthAdd calendarMonthAdd',
calendar.$months.eq(0)[0]
);
}
calendar.animating = true;
calendar.onMonthChangeStart('prev');
const translate = (calendar.monthsTranslate * 100) * inverter;
$wrapperEl
.transition(transition)
.transform(`translate3d(${isH ? translate : 0}%, ${isH ? 0 : translate}%, 0)`);
if (transitionEndCallback) {
$wrapperEl.transitionEnd(() => {
calendar.onMonthChangeEnd('prev');
});
}
if (!params.animate) {
calendar.onMonthChangeEnd('prev');
}
}
resetMonth(transition = '') {
const calendar = this;
const { $wrapperEl, inverter, isHorizontal: isH, monthsTranslate } = calendar;
const translate = (monthsTranslate * 100) * inverter;
$wrapperEl
.transition(transition)
.transform(`translate3d(${isH ? translate : 0}%, ${isH ? 0 : translate}%, 0)`);
}
// eslint-disable-next-line
setYearMonth(year, month, transition) {
const calendar = this;
const { params, isHorizontal: isH, $wrapperEl, inverter } = calendar;
// eslint-disable-next-line
if (typeof year === 'undefined') year = calendar.currentYear;
// eslint-disable-next-line
if (typeof month === 'undefined') month = calendar.currentMonth;
if (typeof transition === 'undefined' || typeof transition === 'object') {
// eslint-disable-next-line
transition = '';
// eslint-disable-next-line
if (!params.animate) transition = 0;
}
let targetDate;
if (year < calendar.currentYear) {
targetDate = new Date(year, month + 1, -1).getTime();
} else {
targetDate = new Date(year, month).getTime();
}
if (params.maxDate && targetDate > new Date(params.maxDate).getTime()) {
return false;
}
if (params.minDate && targetDate < new Date(params.minDate).getTime()) {
return false;
}
const currentDate = new Date(calendar.currentYear, calendar.currentMonth).getTime();
const dir = targetDate > currentDate ? 'next' : 'prev';
const newMonthHTML = calendar.renderMonth(new Date(year, month));
calendar.monthsTranslate = calendar.monthsTranslate || 0;
const prevTranslate = calendar.monthsTranslate;
let monthTranslate;
const transitionEndCallback = !calendar.animating;
if (targetDate > currentDate) {
// To next
calendar.monthsTranslate -= 1;
if (!calendar.animating) calendar.$months.eq(calendar.$months.length - 1).remove();
$wrapperEl.append(newMonthHTML);
calendar.$months = $wrapperEl.find('.calendar-month');
monthTranslate = -(prevTranslate - 1) * 100 * inverter;
calendar.$months
.eq(calendar.$months.length - 1)
.transform(`translate3d(${isH ? monthTranslate : 0}%, ${isH ? 0 : monthTranslate}%, 0)`)
.addClass('calendar-month-next');
} else {
// To prev
calendar.monthsTranslate += 1;
if (!calendar.animating) calendar.$months.eq(0).remove();
$wrapperEl.prepend(newMonthHTML);
calendar.$months = $wrapperEl.find('.calendar-month');
monthTranslate = -(prevTranslate + 1) * 100 * inverter;
calendar.$months
.eq(0)
.transform(`translate3d(${isH ? monthTranslate : 0}%, ${isH ? 0 : monthTranslate}%, 0)`)
.addClass('calendar-month-prev');
}
calendar.emit(
'local::monthAdd calendarMonthAdd',
dir === 'next'
? calendar.$months.eq(calendar.$months.length - 1)[0]
: calendar.$months.eq(0)[0]
);
calendar.animating = true;
calendar.onMonthChangeStart(dir);
const wrapperTranslate = (calendar.monthsTranslate * 100) * inverter;
$wrapperEl
.transition(transition)
.transform(`translate3d(${isH ? wrapperTranslate : 0}%, ${isH ? 0 : wrapperTranslate}%, 0)`);
if (transitionEndCallback) {
$wrapperEl.transitionEnd(() => {
calendar.onMonthChangeEnd(dir, true);
});
}
if (!params.animate) {
calendar.onMonthChangeEnd(dir);
}
}
nextYear() {
const calendar = this;
calendar.setYearMonth(calendar.currentYear + 1);
}
prevYear() {
const calendar = this;
calendar.setYearMonth(calendar.currentYear - 1);
}
// eslint-disable-next-line
dateInRange(dayDate, range) {
let match = false;
let i;
if (!range) return false;
if (Array.isArray(range)) {
for (i = 0; i < range.length; i += 1) {
if (range[i].from || range[i].to) {
if (range[i].from && range[i].to) {
if ((dayDate <= new Date(range[i].to).getTime()) && (dayDate >= new Date(range[i].from).getTime())) {
match = true;
}
} else if (range[i].from) {
if (dayDate >= new Date(range[i].from).getTime()) {
match = true;
}
} else if (range[i].to) {
if (dayDate <= new Date(range[i].to).getTime()) {
match = true;
}
}
} else if (dayDate === new Date(range[i]).getTime()) {
match = true;
}
}
} else if (range.from || range.to) {
if (range.from && range.to) {
if ((dayDate <= new Date(range.to).getTime()) && (dayDate >= new Date(range.from).getTime())) {
match = true;
}
} else if (range.from) {
if (dayDate >= new Date(range.from).getTime()) {
match = true;
}
} else if (range.to) {
if (dayDate <= new Date(range.to).getTime()) {
match = true;
}
}
} else if (typeof range === 'function') {
match = range(new Date(dayDate));
}
return match;
}
// eslint-disable-next-line
daysInMonth(date) {
const d = new Date(date);
return new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate();
}
renderMonths(date) {
const calendar = this;
if (calendar.params.renderMonths) {
return calendar.params.renderMonths.call(calendar, date);
}
return `
<div class="calendar-months-wrapper">
${calendar.renderMonth(date, 'prev')}
${calendar.renderMonth(date)}
${calendar.renderMonth(date, 'next')}
</div>
`.trim();
}
renderMonth(d, offset) {
const calendar = this;
const { params, value } = calendar;
if (params.renderMonth) {
return params.renderMonth.call(calendar, d, offset);
}
let date = new Date(d);
let year = date.getFullYear();
let month = date.getMonth();
if (offset === 'next') {
if (month === 11) date = new Date(year + 1, 0);
else date = new Date(year, month + 1, 1);
}
if (offset === 'prev') {
if (month === 0) date = new Date(year - 1, 11);
else date = new Date(year, month - 1, 1);
}
if (offset === 'next' || offset === 'prev') {
month = date.getMonth();
year = date.getFullYear();
}
const currentValues = [];
const today = new Date().setHours(0, 0, 0, 0);
const minDate = params.minDate ? new Date(params.minDate).getTime() : null;
const maxDate = params.maxDate ? new Date(params.maxDate).getTime() : null;
const rows = 6;
const cols = 7;
const daysInPrevMonth = calendar.daysInMonth(new Date(date.getFullYear(), date.getMonth()).getTime() - (10 * 24 * 60 * 60 * 1000));
const daysInMonth = calendar.daysInMonth(date);
const minDayNumber = params.firstDay === 6 ? 0 : 1;
let monthHtml = '';
let dayIndex = 0 + (params.firstDay - 1);
let disabled;
let hasEvent;
let firstDayOfMonthIndex = new Date(date.getFullYear(), date.getMonth()).getDay();
if (firstDayOfMonthIndex === 0) firstDayOfMonthIndex = 7;
if (value && value.length) {
for (let i = 0; i < value.length; i += 1) {
currentValues.push(new Date(value[i]).setHours(0, 0, 0, 0));
}
}
for (let row = 1; row <= rows; row += 1) {
let rowHtml = '';
for (let col = 1; col <= cols; col += 1) {
dayIndex += 1;
let dayDate;
let dayNumber = dayIndex - firstDayOfMonthIndex;
let addClass = '';
if (row === 1 && col === 1 && dayNumber > minDayNumber && params.firstDay !== 1) {
dayIndex -= 7;
dayNumber = dayIndex - firstDayOfMonthIndex;
}
const weekDayIndex = ((col - 1) + params.firstDay > 6)
? ((col - 1 - 7) + params.firstDay)
: ((col - 1) + params.firstDay);
if (dayNumber < 0) {
dayNumber = daysInPrevMonth + dayNumber + 1;
addClass += ' calendar-day-prev';
dayDate = new Date(month - 1 < 0 ? year - 1 : year, month - 1 < 0 ? 11 : month - 1, dayNumber).getTime();
} else {
dayNumber += 1;
if (dayNumber > daysInMonth) {
dayNumber -= daysInMonth;
addClass += ' calendar-day-next';
dayDate = new Date(month + 1 > 11 ? year + 1 : year, month + 1 > 11 ? 0 : month + 1, dayNumber).getTime();
} else {
dayDate = new Date(year, month, dayNumber).getTime();
}
}
// Today
if (dayDate === today) addClass += ' calendar-day-today';
// Selected
if (params.rangePicker && currentValues.length === 2) {
if (dayDate >= currentValues[0] && dayDate <= currentValues[1]) addClass += ' calendar-day-selected';
} else if (currentValues.indexOf(dayDate) >= 0) addClass += ' calendar-day-selected';
// Weekend
if (params.weekendDays.indexOf(weekDayIndex) >= 0) {
addClass += ' calendar-day-weekend';
}
// Has Events
hasEvent = false;
if (params.events) {
if (calendar.dateInRange(dayDate, params.events)) {
hasEvent = true;
}
}
if (hasEvent) {
addClass += ' calendar-day-has-events';
}
// Custom Ranges
if (params.rangesClasses) {
for (let k = 0; k < params.rangesClasses.length; k += 1) {
if (calendar.dateInRange(dayDate, params.rangesClasses[k].range)) {
addClass += ` ${params.rangesClasses[k].cssClass}`;
}
}
}
// Disabled
disabled = false;
if ((minDate && dayDate < minDate) || (maxDate && dayDate > maxDate)) {
disabled = true;
}
if (params.disabled) {
if (calendar.dateInRange(dayDate, params.disabled)) {
disabled = true;
}
}
if (disabled) {
addClass += ' calendar-day-disabled';
}
dayDate = new Date(dayDate);
const dayYear = dayDate.getFullYear();
const dayMonth = dayDate.getMonth();
rowHtml += `
<div data-year="${dayYear}" data-month="${dayMonth}" data-day="${dayNumber}" class="calendar-day${addClass}" data-date="${dayYear}-${dayMonth}-${dayNumber}">
<span>${dayNumber}</span>
</div>`.trim();
}
monthHtml += `<div class="calendar-row">${rowHtml}</div>`;
}
monthHtml = `<div class="calendar-month" data-year="${year}" data-month="${month}">${monthHtml}</div>`;
return monthHtml;
}
renderWeekHeader() {
const calendar = this;
if (calendar.params.renderWeekHeader) {
return calendar.params.renderWeekHeader.call(calendar);
}
const { params } = calendar;
let weekDaysHtml = '';
for (let i = 0; i < 7; i += 1) {
const dayIndex = (i + params.firstDay > 6)
? ((i - 7) + params.firstDay)
: (i + params.firstDay);
const dayName = params.dayNamesShort[dayIndex];
weekDaysHtml += `<div class="calendar-week-day">${dayName}</div>`;
}
return `
<div class="calendar-week-header">
${weekDaysHtml}
</div>
`.trim();
}
renderMonthSelector() {
const calendar = this;
const app = calendar.app;
if (calendar.params.renderMonthSelector) {
return calendar.params.renderMonthSelector.call(calendar);
}
let needsBlackIcon;
if (calendar.inline && calendar.$containerEl.closest('.theme-dark').length === 0) {
needsBlackIcon = true;
} else if (app.root.closest('.theme-dark').length === 0) {
needsBlackIcon = true;
}
const iconColor = app.theme === 'md' && needsBlackIcon ? 'color-black' : '';
return `
<div class="calendar-month-selector">
<a href="#" class="link icon-only calendar-prev-month-button">
<i class="icon icon-prev ${iconColor}"></i>
</a>
<span class="current-month-value"></span>
<a href="#" class="link icon-only calendar-next-month-button">
<i class="icon icon-next ${iconColor}"></i>
</a>
</div>
`.trim();
}
renderYearSelector() {
const calendar = this;
const app = calendar.app;
if (calendar.params.renderYearSelector) {
return calendar.params.renderYearSelector.call(calendar);
}
let needsBlackIcon;
if (calendar.inline && calendar.$containerEl.closest('.theme-dark').length === 0) {
needsBlackIcon = true;
} else if (app.root.closest('.theme-dark').length === 0) {
needsBlackIcon = true;
}
const iconColor = app.theme === 'md' && needsBlackIcon ? 'color-black' : '';
return `
<div class="calendar-year-selector">
<a href="#" class="link icon-only calendar-prev-year-button">
<i class="icon icon-prev ${iconColor}"></i>
</a>
<span class="current-year-value"></span>
<a href="#" class="link icon-only calendar-next-year-button">
<i class="icon icon-next ${iconColor}"></i>
</a>
</div>
`.trim();
}
renderHeader() {
const calendar = this;
if (calendar.params.renderHeader) {
return calendar.params.renderHeader.call(calendar);
}
return `
<div class="calendar-header">
<div class="calendar-selected-date">${calendar.params.headerPlaceholder}</div>
</div>
`.trim();
}
renderFooter() {
const calendar = this;
const app = calendar.app;
if (calendar.params.renderFooter) {
return calendar.params.renderFooter.call(calendar);
}
return `
<div class="calendar-footer">
<a href="#" class="${app.theme === 'md' ? 'button' : 'link'} calendar-close sheet-close popover-close">${calendar.params.toolbarCloseText}</a>
</div>
`.trim();
}
renderToolbar() {
const calendar = this;
if (calendar.params.renderToolbar) {
return calendar.params.renderToolbar.call(calendar, calendar);
}
return `
<div class="toolbar no-shadow">
<div class="toolbar-inner">
${calendar.renderMonthSelector()}
${calendar.renderYearSelector()}
</div>
</div>
`.trim();
}
// eslint-disable-next-line
renderInline() {
const calendar = this;
const { cssClass, toolbar, header, footer, rangePicker, weekHeader } = calendar.params;
const { value } = calendar;
const date = value && value.length ? value[0] : new Date().setHours(0, 0, 0);
const inlineHtml = `
<div class="calendar calendar-inline ${rangePicker ? 'calendar-range' : ''} ${cssClass || ''}">
${header ? calendar.renderHeader() : ''}
${toolbar ? calendar.renderToolbar() : ''}
${weekHeader ? calendar.renderWeekHeader() : ''}
<div class="calendar-months">
${calendar.renderMonths(date)}
</div>
${footer ? calendar.renderFooter() : ''}
</div>
`.trim();
return inlineHtml;
}
renderCustomModal() {
const calendar = this;
const { cssClass, toolbar, header, footer, rangePicker, weekHeader } = calendar.params;
const { value } = calendar;
const date = value && value.length ? value[0] : new Date().setHours(0, 0, 0);
const sheetHtml = `
<div class="calendar calendar-modal ${rangePicker ? 'calendar-range' : ''} ${cssClass || ''}">
${header ? calendar.renderHeader() : ''}
${toolbar ? calendar.renderToolbar() : ''}
${weekHeader ? calendar.renderWeekHeader() : ''}
<div class="calendar-months">
${calendar.renderMonths(date)}
</div>
${footer ? calendar.renderFooter() : ''}
</div>
`.trim();
return sheetHtml;
}
renderSheet() {
const calendar = this;
const { cssClass, toolbar, header, footer, rangePicker, weekHeader } = calendar.params;
const { value } = calendar;
const date = value && value.length ? value[0] : new Date().setHours(0, 0, 0);
const sheetHtml = `
<div class="sheet-modal calendar calendar-sheet ${rangePicker ? 'calendar-range' : ''} ${cssClass || ''}">
${header ? calendar.renderHeader() : ''}
${toolbar ? calendar.renderToolbar() : ''}
${weekHeader ? calendar.renderWeekHeader() : ''}
<div class="sheet-modal-inner calendar-months">
${calendar.renderMonths(date)}
</div>
${footer ? calendar.renderFooter() : ''}
</div>
`.trim();
return sheetHtml;
}
renderPopover() {
const calendar = this;
const { cssClass, toolbar, header, footer, rangePicker, weekHeader } = calendar.params;
const { value } = calendar;
const date = value && value.length ? value[0] : new Date().setHours(0, 0, 0);
const popoverHtml = `
<div class="popover calendar-popover">
<div class="popover-inner">
<div class="calendar ${rangePicker ? 'calendar-range' : ''} ${cssClass || ''}">
${header ? calendar.renderHeader() : ''}
${toolbar ? calendar.renderToolbar() : ''}
${weekHeader ? calendar.renderWeekHeader() : ''}
<div class="calendar-months">
${calendar.renderMonths(date)}
</div>
${footer ? calendar.renderFooter() : ''}
</div>
</div>
</div>
`.trim();
return popoverHtml;
}
render() {
const calendar = this;
const { params } = calendar;
if (params.render) return params.render.call(calendar);
if (!calendar.inline) {
let modalType = params.openIn;
if (modalType === 'auto') modalType = calendar.isPopover() ? 'popover' : 'sheet';
if (modalType === 'popover') return calendar.renderPopover();
else if (modalType === 'sheet') return calendar.renderSheet();
return calendar.renderCustomModal();
}
return calendar.renderInline();
}
onOpen() {
const calendar = this;
const { initialized, $el, app, $inputEl, inline, value, params } = calendar;
calendar.opened = true;
// Init main events
calendar.attachCalendarEvents();
const updateValue = !value && params.value;
// Set value
if (!initialized) {
if (value) calendar.setValue(value, 0);
else if (params.value) {
calendar.setValue(params.value, 0);
}
} else if (value) {
calendar.setValue(value, 0);
}
// Update current month and year
calendar.updateCurrentMonthYear();
// Set initial translate
calendar.monthsTranslate = 0;
calendar.setMonthsTranslate();
// Update input value
if (updateValue) calendar.updateValue();
else if (app.theme === 'md' && value) calendar.updateValue(true);
// Extra focus
if (!inline && $inputEl.length && app.theme === 'md') {
$inputEl.trigger('focus');
}
calendar.initialized = true;
calendar.$months.each((index, monthEl) => {
calendar.emit('local::monthAdd calendarMonthAdd', monthEl);
});
// Trigger events
if ($el) {
$el.trigger('calendar:open', calendar);
}
if ($inputEl) {
$inputEl.trigger('calendar:open', calendar);
}
calendar.emit('local::open calendarOpen', calendar);
}
onOpened() {
const calendar = this;
if (calendar.$el) {
calendar.$el.trigger('calendar:opened', calendar);
}
if (calendar.$inputEl) {
calendar.$inputEl.trigger('calendar:opened', calendar);
}
calendar.emit('local::opened calendarOpened', calendar);
}
onClose() {
const calendar = this;
const app = calendar.app;
if (calendar.$inputEl && app.theme === 'md') {
calendar.$inputEl.trigger('blur');
}
if (calendar.detachCalendarEvents) {
calendar.detachCalendarEvents();
}
if (calendar.$el) {
calendar.$el.trigger('calendar:close', calendar);
}
if (calendar.$inputEl) {
calendar.$inputEl.trigger('calendar:close', calendar);
}
calendar.emit('local::close calendarClose', calendar);
}
onClosed() {
const calendar = this;
calendar.opened = false;
if (!calendar.inline) {
Utils.nextTick(() => {
if (calendar.modal && calendar.modal.el && calendar.modal.destroy) {
if (!calendar.params.routableModals) {
calendar.modal.destroy();
}
}
delete calendar.modal;
});
}
if (calendar.$el) {
calendar.$el.trigger('calendar:closed', calendar);
}
if (calendar.$inputEl) {
calendar.$inputEl.trigger('calendar:closed', calendar);
}
calendar.emit('local::closed calendarClosed', calendar);
}
open() {
const calendar = this;
const { app, opened, inline, $inputEl, params } = calendar;
if (opened) return;
if (inline) {
calendar.$el = $(calendar.render());
calendar.$el[0].f7Calendar = calendar;
calendar.$wrapperEl = calendar.$el.find('.calendar-months-wrapper');
calendar.$months = calendar.$wrapperEl.find('.calendar-month');
calendar.$containerEl.append(calendar.$el);
calendar.onOpen();
calendar.onOpened();
return;
}
let modalType = params.openIn;
if (modalType === 'auto') {
modalType = calendar.isPopover() ? 'popover' : 'sheet';
}
const modalContent = calendar.render();
const modalParams = {
targetEl: $inputEl,
scrollToEl: calendar.params.scrollToInput ? $inputEl : undefined,
content: modalContent,
backdrop: modalType !== 'sheet',
on: {
open() {
const modal = this;
calendar.modal = modal;
calendar.$el = modalType === 'popover' ? modal.$el.find('.calendar') : modal.$el;
calendar.$wrapperEl = calendar.$el.find('.calendar-months-wrapper');
calendar.$months = calendar.$wrapperEl.find('.calendar-month');
calendar.$el[0].f7Calendar = calendar;
if (modalType === 'customModal') {
$(calendar.$el).find('.calendar-close').once('click', () => {
calendar.close();
});
}
calendar.onOpen();
},
opened() { calendar.onOpened(); },
close() { calendar.onClose(); },
closed() { calendar.onClosed(); },
},
};
if (calendar.params.routableModals) {
calendar.view.router.navigate({
url: calendar.url,
route: {
path: calendar.url,
[modalType]: modalParams,
},
});
} else {
calendar.modal = app[modalType].create(modalParams);
calendar.modal.open();
}
}
close() {
const calendar = this;
const { opened, inline } = calendar;
if (!opened) return;
if (inline) {
calendar.onClose();
calendar.onClosed();
return;
}
if (calendar.params.routableModals) {
calendar.view.router.back();
} else {
calendar.modal.close();
}
}
init() {
const calendar = this;
calendar.initInput();
if (calendar.inline) {
calendar.open();
calendar.emit('local::init calendarInit', calendar);
return;
}
if (!calendar.initialized && calendar.params.value) {
calendar.setValue(calendar.params.value);
}
// Attach input Events
if (calendar.$inputEl) {
calendar.attachInputEvents();
}
if (calendar.params.closeByOutsideClick) {
calendar.attachHtmlEvents();
}
calendar.emit('local::init calendarInit', calendar);
}
destroy() {
const calendar = this;
if (calendar.destroyed) return;
const { $el } = calendar;
calendar.emit('local::beforeDestroy calendarBeforeDestroy', calendar);
if ($el) $el.trigger('calendar:beforedestroy', calendar);
calendar.close();
// Detach Events
if (calendar.$inputEl) {
calendar.detachInputEvents();
}
if (calendar.params.closeByOutsideClick) {
calendar.detachHtmlEvents();
}
if ($el && $el.length) delete calendar.$el[0].f7Calendar;
Utils.deleteProps(calendar);
calendar.destroyed = true;
}
}
var Calendar = {
name: 'calendar',
static: {
Calendar: Calendar$1,
},
create() {
const app = this;
app.calendar = ConstructorMethods({
defaultSelector: '.calendar',
constructor: Calendar$1,
app,
domProp: 'f7Calendar',
});
app.calendar.close = function close(el = '.calendar') {
const $el = $(el);
if ($el.length === 0) return;
const calendar = $el[0].f7Calendar;
if (!calendar || (calendar && !calendar.opened)) return;
calendar.close();
};
},
params: {
calendar: {
// Calendar settings
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
firstDay: 1, // First day of the week, Monday
weekendDays: [0, 6], // Sunday and Saturday
multiple: false,
rangePicker: false,
dateFormat: 'yyyy-mm-dd',
direction: 'horizontal', // or 'vertical'
minDate: null,
maxDate: null,
disabled: null, // dates range of disabled days
events: null, // dates range of days with events
rangesClasses: null, // array with custom classes date ranges
touchMove: true,
animate: true,
closeOnSelect: false,
monthSelector: true,
yearSelector: true,
weekHeader: true,
value: null,
// Common opener settings
containerEl: null,
openIn: 'auto', // or 'popover' or 'sheet' or 'customModal'
formatValue: null,
inputEl: null,
inputReadOnly: true,
closeByOutsideClick: true,
scrollToInput: true,
header: false,
headerPlaceholder: 'Select date',
footer: false,
toolbar: true,
toolbarCloseText: 'Done',
cssClass: null,
routableModals: true,
view: null,
url: 'date/',
// Render functions
renderWeekHeader: null,
renderMonths: null,
renderMonth: null,
renderMonthSelector: null,
renderYearSelector: null,
renderHeader: null,
renderFooter: null,
renderToolbar: null,
renderInline: null,
renderPopover: null,
renderSheet: null,
render: null,
},
},
};
var pickerColumn = function (colEl, updateItems) {
const picker = this;
const app = picker.app;
const $colEl = $(colEl);
const colIndex = $colEl.index();
const col = picker.cols[colIndex];
if (col.divider) return;
col.$el = $colEl;
col.$itemsEl = col.$el.find('.picker-items');
col.items = col.$itemsEl.find('.picker-item');
let itemHeight;
let itemsHeight;
let minTranslate;
let maxTranslate;
let animationFrameId;
function updateDuringScroll() {
animationFrameId = Utils.requestAnimationFrame(() => {
col.updateItems(undefined, undefined, 0);
updateDuringScroll();
});
}
col.replaceValues = function replaceColValues(values, displayValues) {
col.detachEvents();
col.values = values;
col.displayValues = displayValues;
col.$itemsEl.html(picker.renderColumn(col, true));
col.items = col.$itemsEl.find('.picker-item');
col.calcSize();
col.setValue(col.values[0], 0, true);
col.attachEvents();
};
col.calcSize = function calcColSize() {
if (picker.params.rotateEffect) {
col.$el.removeClass('picker-column-absolute');
if (!col.width) col.$el.css({ width: '' });
}
let colWidth = 0;
const colHeight = col.$el[0].offsetHeight;
itemHeight = col.items[0].offsetHeight;
itemsHeight = itemHeight * col.items.length;
minTranslate = ((colHeight / 2) - itemsHeight) + (itemHeight / 2);
maxTranslate = (colHeight / 2) - (itemHeight / 2);
if (col.width) {
colWidth = col.width;
if (parseInt(colWidth, 10) === colWidth) colWidth += 'px';
col.$el.css({ width: colWidth });
}
if (picker.params.rotateEffect) {
if (!col.width) {
col.items.each((index, itemEl) => {
const item = $(itemEl).children('span');
colWidth = Math.max(colWidth, item[0].offsetWidth);
});
col.$el.css({ width: `${colWidth + 2}px` });
}
col.$el.addClass('picker-column-absolute');
}
};
col.setValue = function setColValue(newValue, transition = '', valueCallbacks) {
const newActiveIndex = col.$itemsEl.find(`.picker-item[data-picker-value="${newValue}"]`).index();
if (typeof newActiveIndex === 'undefined' || newActiveIndex === -1) {
return;
}
const newTranslate = (-newActiveIndex * itemHeight) + maxTranslate;
// Update wrapper
col.$itemsEl.transition(transition);
col.$itemsEl.transform(`translate3d(0,${newTranslate}px,0)`);
// Watch items
if (picker.params.updateValuesOnMomentum && col.activeIndex && col.activeIndex !== newActiveIndex) {
Utils.cancelAnimationFrame(animationFrameId);
col.$itemsEl.transitionEnd(() => {
Utils.cancelAnimationFrame(animationFrameId);
});
updateDuringScroll();
}
// Update items
col.updateItems(newActiveIndex, newTranslate, transition, valueCallbacks);
};
col.updateItems = function updateColItems(activeIndex, translate, transition, valueCallbacks) {
if (typeof translate === 'undefined') {
// eslint-disable-next-line
translate = Utils.getTranslate(col.$itemsEl[0], 'y');
}
// eslint-disable-next-line
if (typeof activeIndex === 'undefined') activeIndex = -Math.round((translate - maxTranslate) / itemHeight);
// eslint-disable-next-line
if (activeIndex < 0) activeIndex = 0;
// eslint-disable-next-line
if (activeIndex >= col.items.length) activeIndex = col.items.length - 1;
const previousActiveIndex = col.activeIndex;
col.activeIndex = activeIndex;
col.$itemsEl.find('.picker-item-selected').removeClass('picker-item-selected');
col.items.transition(transition);
const selectedItem = col.items.eq(activeIndex).addClass('picker-item-selected').transform('');
// Set 3D rotate effect
if (picker.params.rotateEffect) {
col.items.each((index, itemEl) => {
const $itemEl = $(itemEl);
const itemOffsetTop = $itemEl.index() * itemHeight;
const translateOffset = maxTranslate - translate;
const itemOffset = itemOffsetTop - translateOffset;
const percentage = itemOffset / itemHeight;
const itemsFit = Math.ceil(col.height / itemHeight / 2) + 1;
let angle = (-18 * percentage);
if (angle > 180) angle = 180;
if (angle < -180) angle = -180;
if (Math.abs(percentage) > itemsFit) {
$itemEl.addClass('picker-item-far');
} else {
$itemEl.removeClass('picker-item-far');
}
$itemEl.transform(`translate3d(0, ${-translate + maxTranslate}px, ${picker.needsOriginFix ? -110 : 0}px) rotateX(${angle}deg)`);
});
}
if (valueCallbacks || typeof valueCallbacks === 'undefined') {
// Update values
col.value = selectedItem.attr('data-picker-value');
col.displayValue = col.displayValues ? col.displayValues[activeIndex] : col.value;
// On change callback
if (previousActiveIndex !== activeIndex) {
if (col.onChange) {
col.onChange(picker, col.value, col.displayValue);
}
picker.updateValue();
}
}
};
let allowItemClick = true;
let isTouched;
let isMoved;
let touchStartY;
let touchCurrentY;
let touchStartTime;
let touchEndTime;
let startTranslate;
let returnTo;
let currentTranslate;
let prevTranslate;
let velocityTranslate;
function handleTouchStart(e) {
if (isMoved || isTouched) return;
e.preventDefault();
isTouched = true;
touchStartY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
touchCurrentY = touchStartY;
touchStartTime = (new Date()).getTime();
allowItemClick = true;
startTranslate = Utils.getTranslate(col.$itemsEl[0], 'y');
currentTranslate = startTranslate;
}
function handleTouchMove(e) {
if (!isTouched) return;
e.preventDefault();
allowItemClick = false;
touchCurrentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (!isMoved) {
// First move
Utils.cancelAnimationFrame(animationFrameId);
isMoved = true;
startTranslate = Utils.getTranslate(col.$itemsEl[0], 'y');
currentTranslate = startTranslate;
col.$itemsEl.transition(0);
}
const diff = touchCurrentY - touchStartY;
currentTranslate = startTranslate + diff;
returnTo = undefined;
// Normalize translate
if (currentTranslate < minTranslate) {
currentTranslate = minTranslate - ((minTranslate - currentTranslate) ** 0.8);
returnTo = 'min';
}
if (currentTranslate > maxTranslate) {
currentTranslate = maxTranslate + ((currentTranslate - maxTranslate) ** 0.8);
returnTo = 'max';
}
// Transform wrapper
col.$itemsEl.transform(`translate3d(0,${currentTranslate}px,0)`);
// Update items
col.updateItems(undefined, currentTranslate, 0, picker.params.updateValuesOnTouchmove);
// Calc velocity
velocityTranslate = currentTranslate - prevTranslate || currentTranslate;
prevTranslate = currentTranslate;
}
function handleTouchEnd() {
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
isTouched = false;
isMoved = false;
col.$itemsEl.transition('');
if (returnTo) {
if (returnTo === 'min') {
col.$itemsEl.transform(`translate3d(0,${minTranslate}px,0)`);
} else col.$itemsEl.transform(`translate3d(0,${maxTranslate}px,0)`);
}
touchEndTime = new Date().getTime();
let newTranslate;
if (touchEndTime - touchStartTime > 300) {
newTranslate = currentTranslate;
} else {
newTranslate = currentTranslate + (velocityTranslate * picker.params.momentumRatio);
}
newTranslate = Math.max(Math.min(newTranslate, maxTranslate), minTranslate);
// Active Index
const activeIndex = -Math.floor((newTranslate - maxTranslate) / itemHeight);
// Normalize translate
if (!picker.params.freeMode) newTranslate = (-activeIndex * itemHeight) + maxTranslate;
// Transform wrapper
col.$itemsEl.transform(`translate3d(0,${parseInt(newTranslate, 10)}px,0)`);
// Update items
col.updateItems(activeIndex, newTranslate, '', true);
// Watch items
if (picker.params.updateValuesOnMomentum) {
updateDuringScroll();
col.$itemsEl.transitionEnd(() => {
Utils.cancelAnimationFrame(animationFrameId);
});
}
// Allow click
setTimeout(() => {
allowItemClick = true;
}, 100);
}
function handleClick() {
if (!allowItemClick) return;
Utils.cancelAnimationFrame(animationFrameId);
const value = $(this).attr('data-picker-value');
col.setValue(value);
}
const activeListener = app.support.passiveListener ? { passive: false, capture: false } : false;
col.attachEvents = function attachColEvents() {
col.$el.on(app.touchEvents.start, handleTouchStart, activeListener);
app.on('touchmove:active', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
col.items.on('click', handleClick);
};
col.detachEvents = function detachColEvents() {
col.$el.off(app.touchEvents.start, handleTouchStart, activeListener);
app.off('touchmove:active', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
col.items.off('click', handleClick);
};
col.init = function initCol() {
col.calcSize();
col.$itemsEl.transform(`translate3d(0,${maxTranslate}px,0)`).transition(0);
if (colIndex === 0) col.$el.addClass('picker-column-first');
if (colIndex === picker.cols.length - 1) col.$el.addClass('picker-column-last');
// Update items on init
if (updateItems) col.updateItems(0, maxTranslate, 0);
col.attachEvents();
};
col.destroy = function destroyCol() {
col.detachEvents();
};
col.init();
};
class Picker$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const picker = this;
picker.params = Utils.extend({}, app.params.picker, params);
let $containerEl;
if (picker.params.containerEl) {
$containerEl = $(picker.params.containerEl);
if ($containerEl.length === 0) return picker;
}
let $inputEl;
if (picker.params.inputEl) {
$inputEl = $(picker.params.inputEl);
}
let view;
if ($inputEl) {
view = $inputEl.parents('.view').length && $inputEl.parents('.view')[0].f7View;
}
if (!view) view = app.views.main;
Utils.extend(picker, {
app,
$containerEl,
containerEl: $containerEl && $containerEl[0],
inline: $containerEl && $containerEl.length > 0,
needsOriginFix: app.device.ios || ((window.navigator.userAgent.toLowerCase().indexOf('safari') >= 0 && window.navigator.userAgent.toLowerCase().indexOf('chrome') < 0) && !app.device.android),
cols: [],
$inputEl,
inputEl: $inputEl && $inputEl[0],
initialized: false,
opened: false,
url: picker.params.url,
view,
});
function onResize() {
picker.resizeCols();
}
function onInputClick() {
picker.open();
}
function onInputFocus(e) {
e.preventDefault();
}
function onHtmlClick(e) {
const $targetEl = $(e.target);
if (picker.isPopover()) return;
if (!picker.opened) return;
if ($targetEl.closest('[class*="backdrop"]').length) return;
if ($inputEl && $inputEl.length > 0) {
if ($targetEl[0] !== $inputEl[0] && $targetEl.closest('.sheet-modal').length === 0) {
picker.close();
}
} else if ($(e.target).closest('.sheet-modal').length === 0) {
picker.close();
}
}
// Events
Utils.extend(picker, {
attachResizeEvent() {
app.on('resize', onResize);
},
detachResizeEvent() {
app.off('resize', onResize);
},
attachInputEvents() {
picker.$inputEl.on('click', onInputClick);
if (picker.params.inputReadOnly) {
picker.$inputEl.on('focus mousedown', onInputFocus);
}
},
detachInputEvents() {
picker.$inputEl.off('click', onInputClick);
if (picker.params.inputReadOnly) {
picker.$inputEl.off('focus mousedown', onInputFocus);
}
},
attachHtmlEvents() {
app.on('click', onHtmlClick);
},
detachHtmlEvents() {
app.off('click', onHtmlClick);
},
});
picker.init();
return picker;
}
initInput() {
const picker = this;
if (!picker.$inputEl) return;
if (picker.params.inputReadOnly) picker.$inputEl.prop('readOnly', true);
}
resizeCols() {
const picker = this;
if (!picker.opened) return;
for (let i = 0; i < picker.cols.length; i += 1) {
if (!picker.cols[i].divider) {
picker.cols[i].calcSize();
picker.cols[i].setValue(picker.cols[i].value, 0, false);
}
}
}
isPopover() {
const picker = this;
const { app, modal, params } = picker;
if (params.openIn === 'sheet') return false;
if (modal && modal.type !== 'popover') return false;
if (!picker.inline && picker.inputEl) {
if (params.openIn === 'popover') return true;
else if (app.device.ios) {
return !!app.device.ipad;
} else if (app.width >= 768) {
return true;
}
}
return false;
}
formatValue() {
const picker = this;
const { value, displayValue } = picker;
if (picker.params.formatValue) {
return picker.params.formatValue.call(picker, value, displayValue);
}
return value.join(' ');
}
setValue(values, transition) {
const picker = this;
let valueIndex = 0;
if (picker.cols.length === 0) {
picker.value = values;
picker.updateValue(values);
return;
}
for (let i = 0; i < picker.cols.length; i += 1) {
if (picker.cols[i] && !picker.cols[i].divider) {
picker.cols[i].setValue(values[valueIndex], transition);
valueIndex += 1;
}
}
}
getValue() {
const picker = this;
return picker.value;
}
updateValue(forceValues) {
const picker = this;
const newValue = forceValues || [];
const newDisplayValue = [];
let column;
if (picker.cols.length === 0) {
const noDividerColumns = picker.params.cols.filter(c => !c.divider);
for (let i = 0; i < noDividerColumns.length; i += 1) {
column = noDividerColumns[i];
if (column.displayValues !== undefined && column.values !== undefined && column.values.indexOf(newValue[i]) !== -1) {
newDisplayValue.push(column.displayValues[column.values.indexOf(newValue[i])]);
} else {
newDisplayValue.push(newValue[i]);
}
}
} else {
for (let i = 0; i < picker.cols.length; i += 1) {
if (!picker.cols[i].divider) {
newValue.push(picker.cols[i].value);
newDisplayValue.push(picker.cols[i].displayValue);
}
}
}
if (newValue.indexOf(undefined) >= 0) {
return;
}
picker.value = newValue;
picker.displayValue = newDisplayValue;
if (picker.params.onChange) {
picker.emit('local::change pickerChange', picker, picker.value, picker.displayValue);
}
if (picker.inputEl) {
picker.$inputEl.val(picker.formatValue());
picker.$inputEl.trigger('change');
}
}
initColumn(colEl, updateItems) {
const picker = this;
pickerColumn.call(picker, colEl, updateItems);
}
// eslint-disable-next-line
destroyColumn(colEl) {
const picker = this;
const $colEl = $(colEl);
const index = $colEl.index();
if (picker.cols[index] && picker.cols[index].destroy) {
picker.cols[index].destroy();
}
}
renderToolbar() {
const picker = this;
if (picker.params.renderToolbar) return picker.params.renderToolbar.call(picker, picker);
return `
<div class="toolbar no-shadow">
<div class="toolbar-inner">
<div class="left"></div>
<div class="right">
<a href="#" class="link sheet-close popover-close">${picker.params.toolbarCloseText}</a>
</div>
</div>
</div>
`.trim();
}
// eslint-disable-next-line
renderColumn(col, onlyItems) {
const colClasses = `picker-column ${col.textAlign ? `picker-column-${col.textAlign}` : ''} ${col.cssClass || ''}`;
let columnHtml;
let columnItemsHtml;
if (col.divider) {
columnHtml = `
<div class="${colClasses} picker-column-divider">${col.content}</div>
`;
} else {
columnItemsHtml = col.values.map((value, index) => `
<div class="picker-item" data-picker-value="${value}">
<span>${col.displayValues ? col.displayValues[index] : value}</span>
</div>
`).join('');
columnHtml = `
<div class="${colClasses}">
<div class="picker-items">${columnItemsHtml}</div>
</div>
`;
}
return onlyItems ? columnItemsHtml.trim() : columnHtml.trim();
}
renderInline() {
const picker = this;
const { rotateEffect, cssClass, toolbar } = picker.params;
const inlineHtml = `
<div class="picker picker-inline ${rotateEffect ? 'picker-3d' : ''} ${cssClass || ''}">
${toolbar ? picker.renderToolbar() : ''}
<div class="picker-columns">
${picker.cols.map(col => picker.renderColumn(col)).join('')}
<div class="picker-center-highlight"></div>
</div>
</div>
`.trim();
return inlineHtml;
}
renderSheet() {
const picker = this;
const { rotateEffect, cssClass, toolbar } = picker.params;
const sheetHtml = `
<div class="sheet-modal picker picker-sheet ${rotateEffect ? 'picker-3d' : ''} ${cssClass || ''}">
${toolbar ? picker.renderToolbar() : ''}
<div class="sheet-modal-inner picker-columns">
${picker.cols.map(col => picker.renderColumn(col)).join('')}
<div class="picker-center-highlight"></div>
</div>
</div>
`.trim();
return sheetHtml;
}
renderPopover() {
const picker = this;
const { rotateEffect, cssClass, toolbar } = picker.params;
const popoverHtml = `
<div class="popover picker-popover">
<div class="popover-inner">
<div class="picker ${rotateEffect ? 'picker-3d' : ''} ${cssClass || ''}">
${toolbar ? picker.renderToolbar() : ''}
<div class="picker-columns">
${picker.cols.map(col => picker.renderColumn(col)).join('')}
<div class="picker-center-highlight"></div>
</div>
</div>
</div>
</div>
`.trim();
return popoverHtml;
}
render() {
const picker = this;
if (picker.params.render) return picker.params.render.call(picker);
if (!picker.inline) {
if (picker.isPopover()) return picker.renderPopover();
return picker.renderSheet();
}
return picker.renderInline();
}
onOpen() {
const picker = this;
const { initialized, $el, app, $inputEl, inline, value, params } = picker;
picker.opened = true;
// Init main events
picker.attachResizeEvent();
// Init cols
$el.find('.picker-column').each((index, colEl) => {
let updateItems = true;
if (
(!initialized && params.value) ||
(initialized && value)
) {
updateItems = false;
}
picker.initColumn(colEl, updateItems);
});
// Set value
if (!initialized) {
if (value) picker.setValue(value, 0);
else if (params.value) {
picker.setValue(params.value, 0);
}
} else if (value) {
picker.setValue(value, 0);
}
// Extra focus
if (!inline && $inputEl.length && app.theme === 'md') {
$inputEl.trigger('focus');
}
picker.initialized = true;
// Trigger events
if ($el) {
$el.trigger('picker:open', picker);
}
if ($inputEl) {
$inputEl.trigger('picker:open', picker);
}
picker.emit('local::open pickerOpen', picker);
}
onOpened() {
const picker = this;
if (picker.$el) {
picker.$el.trigger('picker:opened', picker);
}
if (picker.$inputEl) {
picker.$inputEl.trigger('picker:opened', picker);
}
picker.emit('local::opened pickerOpened', picker);
}
onClose() {
const picker = this;
const app = picker.app;
// Detach events
picker.detachResizeEvent();
picker.cols.forEach((col) => {
if (col.destroy) col.destroy();
});
if (picker.$inputEl && app.theme === 'md') {
picker.$inputEl.trigger('blur');
}
if (picker.$el) {
picker.$el.trigger('picker:close', picker);
}
if (picker.$inputEl) {
picker.$inputEl.trigger('picker:close', picker);
}
picker.emit('local::close pickerClose', picker);
}
onClosed() {
const picker = this;
picker.opened = false;
if (!picker.inline) {
Utils.nextTick(() => {
if (picker.modal && picker.modal.el && picker.modal.destroy) {
if (!picker.params.routableModals) {
picker.modal.destroy();
}
}
delete picker.modal;
});
}
if (picker.$el) {
picker.$el.trigger('picker:closed', picker);
}
if (picker.$inputEl) {
picker.$inputEl.trigger('picker:closed', picker);
}
picker.emit('local::closed pickerClosed', picker);
}
open() {
const picker = this;
const { app, opened, inline, $inputEl } = picker;
if (opened) return;
if (picker.cols.length === 0 && picker.params.cols.length) {
picker.params.cols.forEach((col) => {
picker.cols.push(col);
});
}
if (inline) {
picker.$el = $(picker.render());
picker.$el[0].f7Picker = picker;
picker.$containerEl.append(picker.$el);
picker.onOpen();
picker.onOpened();
return;
}
const isPopover = picker.isPopover();
const modalType = isPopover ? 'popover' : 'sheet';
const modalParams = {
targetEl: $inputEl,
scrollToEl: picker.params.scrollToInput ? $inputEl : undefined,
content: picker.render(),
backdrop: isPopover,
on: {
open() {
const modal = this;
picker.modal = modal;
picker.$el = isPopover ? modal.$el.find('.picker') : modal.$el;
picker.$el[0].f7Picker = picker;
picker.onOpen();
},
opened() { picker.onOpened(); },
close() { picker.onClose(); },
closed() { picker.onClosed(); },
},
};
if (picker.params.routableModals) {
picker.view.router.navigate({
url: picker.url,
route: {
path: picker.url,
[modalType]: modalParams,
},
});
} else {
picker.modal = app[modalType].create(modalParams);
picker.modal.open();
}
}
close() {
const picker = this;
const { opened, inline } = picker;
if (!opened) return;
if (inline) {
picker.onClose();
picker.onClosed();
return;
}
if (picker.params.routableModals) {
picker.view.router.back();
} else {
picker.modal.close();
}
}
init() {
const picker = this;
picker.initInput();
if (picker.inline) {
picker.open();
picker.emit('local::init pickerInit', picker);
return;
}
if (!picker.initialized && picker.params.value) {
picker.setValue(picker.params.value);
}
// Attach input Events
if (picker.$inputEl) {
picker.attachInputEvents();
}
if (picker.params.closeByOutsideClick) {
picker.attachHtmlEvents();
}
picker.emit('local::init pickerInit', picker);
}
destroy() {
const picker = this;
if (picker.destroyed) return;
const { $el } = picker;
picker.emit('local::beforeDestroy pickerBeforeDestroy', picker);
if ($el) $el.trigger('picker:beforedestroy', picker);
picker.close();
// Detach Events
if (picker.$inputEl) {
picker.detachInputEvents();
}
if (picker.params.closeByOutsideClick) {
picker.detachHtmlEvents();
}
if ($el && $el.length) delete picker.$el[0].f7Picker;
Utils.deleteProps(picker);
picker.destroyed = true;
}
}
var Picker = {
name: 'picker',
static: {
Picker: Picker$1,
},
create() {
const app = this;
app.picker = ConstructorMethods({
defaultSelector: '.picker',
constructor: Picker$1,
app,
domProp: 'f7Picker',
});
app.picker.close = function close(el = '.picker') {
const $el = $(el);
if ($el.length === 0) return;
const picker = $el[0].f7Picker;
if (!picker || (picker && !picker.opened)) return;
picker.close();
};
},
params: {
picker: {
// Picker settings
updateValuesOnMomentum: false,
updateValuesOnTouchmove: true,
rotateEffect: false,
momentumRatio: 7,
freeMode: false,
cols: [],
// Common opener settings
containerEl: null,
openIn: 'auto', // or 'popover' or 'sheet'
formatValue: null,
inputEl: null,
inputReadOnly: true,
closeByOutsideClick: true,
scrollToInput: true,
toolbar: true,
toolbarCloseText: 'Done',
cssClass: null,
routableModals: true,
view: null,
url: 'select/',
// Render functions
renderColumn: null,
renderToolbar: null,
renderInline: null,
renderPopover: null,
renderSheet: null,
render: null,
},
},
};
const InfiniteScroll = {
handleScroll(el, e) {
const app = this;
const $el = $(el);
const scrollTop = $el[0].scrollTop;
const scrollHeight = $el[0].scrollHeight;
const height = $el[0].offsetHeight;
let distance = $el[0].getAttribute('data-infinite-distance');
const virtualListContainer = $el.find('.virtual-list');
let virtualList;
const onTop = $el.hasClass('infinite-scroll-top');
if (!distance) distance = 50;
if (typeof distance === 'string' && distance.indexOf('%') >= 0) {
distance = (parseInt(distance, 10) / 100) * height;
}
if (distance > height) distance = height;
if (onTop) {
if (scrollTop < distance) {
$el.trigger('infinite', e);
app.emit('infinite', $el[0], e);
}
} else if (scrollTop + height >= scrollHeight - distance) {
if (virtualListContainer.length > 0) {
virtualList = virtualListContainer.eq(-1)[0].f7VirtualList;
if (virtualList && !virtualList.reachEnd && !virtualList.params.updatableScroll) {
return;
}
}
$el.trigger('infinite', e);
app.emit('infinite', $el[0], e);
}
},
create(el) {
const $el = $(el);
const app = this;
$el.on('scroll', function handle(e) {
app.infiniteScroll.handle(this, e);
});
},
destroy(el) {
const $el = $(el);
$el.off('scroll');
},
};
var InfiniteScroll$1 = {
name: 'infiniteScroll',
create() {
const app = this;
Utils.extend(app, {
infiniteScroll: {
handle: InfiniteScroll.handleScroll.bind(app),
create: InfiniteScroll.create.bind(app),
destroy: InfiniteScroll.destroy.bind(app),
},
});
},
on: {
tabMounted(tabEl) {
const app = this;
const $tabEl = $(tabEl);
$tabEl.find('.infinite-scroll-content').each((index, el) => {
app.infiniteScroll.create(el);
});
},
tabBeforeRemove(tabEl) {
const $tabEl = $(tabEl);
const app = this;
$tabEl.find('.infinite-scroll-content').each((index, el) => {
app.infiniteScroll.destroy(el);
});
},
pageInit(page) {
const app = this;
page.$el.find('.infinite-scroll-content').each((index, el) => {
app.infiniteScroll.create(el);
});
},
pageBeforeRemove(page) {
const app = this;
page.$el.find('.infinite-scroll-content').each((index, el) => {
app.infiniteScroll.destroy(el);
});
},
},
};
class PullToRefresh$1 extends Framework7Class {
constructor(app, el) {
super({}, [app]);
const ptr = this;
const $el = $(el);
const $preloaderEl = $el.find('.ptr-preloader');
ptr.$el = $el;
ptr.el = $el[0];
// Extend defaults with modules params
ptr.useModulesParams({});
const isMaterial = app.theme === 'md';
// Done
ptr.done = function done() {
const $transitionTarget = isMaterial ? $preloaderEl : $el;
$transitionTarget.transitionEnd(() => {
$el.removeClass('ptr-transitioning ptr-pull-up ptr-pull-down');
$el.trigger('ptr:done');
ptr.emit('local::done ptrDone', $el[0]);
});
$el.removeClass('ptr-refreshing').addClass('ptr-transitioning');
return ptr;
};
ptr.refresh = function refresh() {
if ($el.hasClass('ptr-refreshing')) return ptr;
$el.addClass('ptr-transitioning ptr-refreshing');
$el.trigger('ptr:refresh', ptr.done);
ptr.emit('local::refresh ptrRefresh', $el[0], ptr.done);
return ptr;
};
// Events handling
let touchId;
let isTouched;
let isMoved;
const touchesStart = {};
let isScrolling;
let touchesDiff;
let refresh = false;
let useTranslate = false;
let startTranslate = 0;
let translate;
let scrollTop;
let wasScrolled;
let triggerDistance;
let dynamicTriggerDistance;
let pullStarted;
let hasNavbar = false;
const $pageEl = $el.parents('.page');
if ($pageEl.find('.navbar').length > 0 || $pageEl.parents('.view').children('.navbar').length > 0) hasNavbar = true;
if ($pageEl.hasClass('no-navbar')) hasNavbar = false;
if (!hasNavbar) $el.addClass('ptr-no-navbar');
// Define trigger distance
if ($el.attr('data-ptr-distance')) {
dynamicTriggerDistance = true;
} else {
triggerDistance = isMaterial ? 66 : 44;
}
function handleTouchStart(e) {
if (isTouched) {
if (Device.os === 'android') {
if ('targetTouches' in e && e.targetTouches.length > 1) return;
} else return;
}
if ($el.hasClass('ptr-refreshing')) {
return;
}
if ($(e.target).closest('.sortable-handler').length) return;
isMoved = false;
pullStarted = false;
isTouched = true;
isScrolling = undefined;
wasScrolled = undefined;
if (e.type === 'touchstart') touchId = e.targetTouches[0].identifier;
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
}
function handleTouchMove(e) {
if (!isTouched) return;
let pageX;
let pageY;
let touch;
if (e.type === 'touchmove') {
if (touchId && e.touches) {
for (let i = 0; i < e.touches.length; i += 1) {
if (e.touches[i].identifier === touchId) {
touch = e.touches[i];
}
}
}
if (!touch) touch = e.targetTouches[0];
pageX = touch.pageX;
pageY = touch.pageY;
} else {
pageX = e.pageX;
pageY = e.pageY;
}
if (!pageX || !pageY) return;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) > Math.abs(pageX - touchesStart.x));
}
if (!isScrolling) {
isTouched = false;
return;
}
scrollTop = $el[0].scrollTop;
if (typeof wasScrolled === 'undefined' && scrollTop !== 0) wasScrolled = true;
if (!isMoved) {
$el.removeClass('ptr-transitioning');
if (scrollTop > $el[0].offsetHeight) {
isTouched = false;
return;
}
if (dynamicTriggerDistance) {
triggerDistance = $el.attr('data-ptr-distance');
if (triggerDistance.indexOf('%') >= 0) triggerDistance = ($el[0].offsetHeight * parseInt(triggerDistance, 10)) / 100;
}
startTranslate = $el.hasClass('ptr-refreshing') ? triggerDistance : 0;
if ($el[0].scrollHeight === $el[0].offsetHeight || Device.os !== 'ios' || isMaterial) {
useTranslate = true;
} else {
useTranslate = false;
}
}
isMoved = true;
touchesDiff = pageY - touchesStart.y;
if ((touchesDiff > 0 && scrollTop <= 0) || scrollTop < 0) {
// iOS 8 fix
if (Device.os === 'ios' && parseInt(Device.osVersion.split('.')[0], 10) > 7 && scrollTop === 0 && !wasScrolled) useTranslate = true;
if (useTranslate) {
e.preventDefault();
translate = (touchesDiff ** 0.85) + startTranslate;
if (isMaterial) {
$preloaderEl.transform(`translate3d(0,${translate}px,0)`)
.find('.ptr-arrow').transform(`rotate(${(180 * (touchesDiff / 66)) + 100}deg)`);
} else {
$el.transform(`translate3d(0,${translate}px,0)`);
}
}
if ((useTranslate && (touchesDiff ** 0.85) > triggerDistance) || (!useTranslate && touchesDiff >= triggerDistance * 2)) {
refresh = true;
$el.addClass('ptr-pull-up').removeClass('ptr-pull-down');
} else {
refresh = false;
$el.removeClass('ptr-pull-up').addClass('ptr-pull-down');
}
if (!pullStarted) {
$el.trigger('ptr:pullstart');
ptr.emit('local::pullStart ptrPullStart', $el[0]);
pullStarted = true;
}
$el.trigger('ptr:pullmove', {
event: e,
scrollTop,
translate,
touchesDiff,
});
ptr.emit('local::pullMove ptrPullMove', $el[0], {
event: e,
scrollTop,
translate,
touchesDiff,
});
} else {
pullStarted = false;
$el.removeClass('ptr-pull-up ptr-pull-down');
refresh = false;
}
}
function handleTouchEnd(e) {
if (e.type === 'touchend' && e.changedTouches && e.changedTouches.length > 0 && touchId) {
if (e.changedTouches[0].identifier !== touchId) {
isTouched = false;
isScrolling = false;
isMoved = false;
touchId = null;
return;
}
}
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
if (translate) {
$el.addClass('ptr-transitioning');
translate = 0;
}
if (isMaterial) {
$preloaderEl.transform('')
.find('.ptr-arrow').transform('');
} else {
$el.transform('');
}
if (refresh) {
$el.addClass('ptr-refreshing');
$el.trigger('ptr:refresh', ptr.done);
ptr.emit('local::refresh ptrRefresh', $el[0], ptr.done);
} else {
$el.removeClass('ptr-pull-down');
}
isTouched = false;
isMoved = false;
if (pullStarted) {
$el.trigger('ptr:pullend');
ptr.emit('local::pullEnd ptrPullEnd', $el[0]);
}
}
if (!$pageEl.length || !$el.length) return ptr;
$el[0].f7PullToRefresh = ptr;
// Events
ptr.attachEvents = function attachEvents() {
const passive = Support$1.passiveListener ? { passive: true } : false;
$el.on(app.touchEvents.start, handleTouchStart, passive);
app.on('touchmove', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
};
ptr.detachEvents = function detachEvents() {
const passive = Support$1.passiveListener ? { passive: true } : false;
$el.off(app.touchEvents.start, handleTouchStart, passive);
app.off('touchmove', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
};
// Install Modules
ptr.useModules();
// Init
ptr.init();
return ptr;
}
init() {
const ptr = this;
ptr.attachEvents();
}
destroy() {
let ptr = this;
ptr.emit('local::beforeDestroy ptrBeforeDestroy', ptr);
ptr.$el.trigger('ptr:beforedestroy', ptr);
delete ptr.el.f7PullToRefresh;
ptr.detachEvents();
Utils.deleteProps(ptr);
ptr = null;
}
}
var PullToRefresh = {
name: 'pullToRefresh',
create() {
const app = this;
app.ptr = Utils.extend(
ConstructorMethods({
defaultSelector: '.ptr-content',
constructor: PullToRefresh$1,
app,
domProp: 'f7PullToRefresh',
}),
{
done(el) {
const ptr = app.ptr.get(el);
if (ptr) return ptr.done();
return undefined;
},
refresh(el) {
const ptr = app.ptr.get(el);
if (ptr) return ptr.refresh();
return undefined;
},
}
);
},
static: {
PullToRefresh: PullToRefresh$1,
},
on: {
tabMounted(tabEl) {
const app = this;
const $tabEl = $(tabEl);
$tabEl.find('.ptr-content').each((index, el) => {
app.ptr.create(el);
});
},
tabBeforeRemove(tabEl) {
const $tabEl = $(tabEl);
const app = this;
$tabEl.find('.ptr-content').each((index, el) => {
app.ptr.destroy(el);
});
},
pageInit(page) {
const app = this;
page.$el.find('.ptr-content').each((index, el) => {
app.ptr.create(el);
});
},
pageBeforeRemove(page) {
const app = this;
page.$el.find('.ptr-content').each((index, el) => {
app.ptr.destroy(el);
});
},
},
};
const Lazy = {
destroy(pageEl) {
const $pageEl = $(pageEl).closest('.page');
if (!$pageEl.length) return;
if ($pageEl[0].f7DestroyLazy) {
$pageEl[0].f7DestroyLazy();
}
},
init(pageEl) {
const app = this;
const $pageEl = $(pageEl).closest('.page').eq(0);
// Lazy images
const lazyLoadImages = $pageEl.find('.lazy');
if (lazyLoadImages.length === 0 && !$pageEl.hasClass('lazy')) return;
// Placeholder
const placeholderSrc = app.params.lazy.placeholder;
if (placeholderSrc !== false) {
lazyLoadImages.each((index, lazyEl) => {
if ($(lazyEl).attr('data-src') && !$(lazyEl).attr('src')) $(lazyEl).attr('src', placeholderSrc);
});
}
// load image
const imagesSequence = [];
let imageIsLoading = false;
function onImageComplete(lazyEl) {
if (imagesSequence.indexOf(lazyEl) >= 0) {
imagesSequence.splice(imagesSequence.indexOf(lazyEl), 1);
}
imageIsLoading = false;
if (app.params.lazy.sequential && imagesSequence.length > 0) {
imageIsLoading = true;
app.lazy.loadImage(imagesSequence[0], onImageComplete);
}
}
function lazyHandler() {
app.lazy.load($pageEl, (lazyEl) => {
if (app.params.lazy.sequential && imageIsLoading) {
if (imagesSequence.indexOf(lazyEl) < 0) imagesSequence.push(lazyEl);
return;
}
imageIsLoading = true;
app.lazy.loadImage(lazyEl, onImageComplete);
});
}
function attachEvents() {
$pageEl.on('lazy', lazyHandler);
$pageEl.on('scroll', lazyHandler, true);
$pageEl.find('.tab').on('tab:mounted tab:show', lazyHandler);
app.on('resize', lazyHandler);
}
function detachEvents() {
$pageEl.off('lazy', lazyHandler);
$pageEl.off('scroll', lazyHandler, true);
$pageEl.find('.tab').off('tab:mounted tab:show', lazyHandler);
app.off('resize', lazyHandler);
}
// Store detach function
$pageEl[0].f7DestroyLazy = detachEvents;
// Attach events
attachEvents();
// Run loader on page load/init
lazyHandler();
},
isInViewport(lazyEl) {
const app = this;
const rect = lazyEl.getBoundingClientRect();
const threshold = app.params.lazy.threshold || 0;
return (
rect.top >= (0 - threshold) &&
rect.left >= (0 - threshold) &&
rect.top <= (app.height + threshold) &&
rect.left <= (app.width + threshold)
);
},
loadImage(imageEl, callback) {
const app = this;
const $imageEl = $(imageEl);
const bg = $imageEl.attr('data-background');
const src = bg || $imageEl.attr('data-src');
if (!src) return;
function onLoad() {
$imageEl.removeClass('lazy').addClass('lazy-loaded');
if (bg) {
$imageEl.css('background-image', `url(${src})`);
} else {
$imageEl.attr('src', src);
}
if (callback) callback(imageEl);
$imageEl.trigger('lazy:loaded');
app.emit('lazyLoaded', $imageEl[0]);
}
function onError() {
$imageEl.removeClass('lazy').addClass('lazy-loaded');
if (bg) {
$imageEl.css('background-image', `url(${app.params.lazy.placeholder || ''})`);
} else {
$imageEl.attr('src', app.params.lazy.placeholder || '');
}
if (callback) callback(imageEl);
$imageEl.trigger('lazy:error');
app.emit('lazyError', $imageEl[0]);
}
const image = new window.Image();
image.onload = onLoad;
image.onerror = onError;
image.src = src;
$imageEl.removeAttr('data-src').removeAttr('data-background');
// Add loaded callback and events
$imageEl.trigger('lazy:load');
app.emit('lazyLoad', $imageEl[0]);
},
load(pageEl, callback) {
const app = this;
let $pageEl = $(pageEl);
if (!$pageEl.hasClass('page')) $pageEl = $pageEl.parents('.page').eq(0);
if ($pageEl.length === 0) {
return;
}
$pageEl.find('.lazy').each((index, lazyEl) => {
const $lazyEl = $(lazyEl);
if ($lazyEl.parents('.tab:not(.tab-active)').length > 0) {
return;
}
if (app.lazy.isInViewport(lazyEl)) {
if (callback) callback(lazyEl);
else app.lazy.loadImage(lazyEl);
}
});
},
};
var Lazy$1 = {
name: 'lazy',
params: {
lazy: {
placeholder: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEXCwsK592mkAAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==',
threshold: 0,
sequential: true,
},
},
create() {
const app = this;
Utils.extend(app, {
lazy: {
init: Lazy.init.bind(app),
destroy: Lazy.destroy.bind(app),
loadImage: Lazy.loadImage.bind(app),
load: Lazy.load.bind(app),
isInViewport: Lazy.isInViewport.bind(app),
},
});
},
on: {
pageInit(page) {
const app = this;
if (page.$el.find('.lazy').length > 0 || page.$el.hasClass('lazy')) {
app.lazy.init(page.$el);
}
},
pageAfterIn(page) {
const app = this;
if (page.$el.find('.lazy').length > 0 || page.$el.hasClass('lazy')) {
app.lazy.init(page.$el);
}
},
pageBeforeRemove(page) {
const app = this;
if (page.$el.find('.lazy').length > 0 || page.$el.hasClass('lazy')) {
app.lazy.destroy(page.$el);
}
},
tabMounted(tabEl) {
const app = this;
const $tabEl = $(tabEl);
if ($tabEl.find('.lazy').length > 0 || $tabEl.hasClass('lazy')) {
app.lazy.init($tabEl);
}
},
tabBeforeRemove(tabEl) {
const app = this;
const $tabEl = $(tabEl);
if ($tabEl.find('.lazy').length > 0 || $tabEl.hasClass('lazy')) {
app.lazy.destroy($tabEl);
}
},
},
};
class DataTable$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const table = this;
const defaults = {
};
// Extend defaults with modules params
table.useModulesParams(defaults);
table.params = Utils.extend(defaults, params);
// El
const $el = $(table.params.el);
if ($el.length === 0) return undefined;
table.$el = $el;
table.el = $el[0];
if (table.$el[0].f7DataTable) {
const instance = table.$el[0].f7DataTable;
table.destroy();
return instance;
}
table.$el[0].f7DataTable = table;
Utils.extend(table, {
collapsible: $el.hasClass('data-table-collapsible'),
// Headers
$headerEl: $el.find('.data-table-header'),
$headerSelectedEl: $el.find('.data-table-header-selected'),
});
// Events
function handleChange(e) {
if (e.detail && e.detail.sentByF7DataTable) {
// Scripted event, don't do anything
return;
}
const $inputEl = $(this);
const checked = $inputEl[0].checked;
const columnIndex = $inputEl.parents('td,th').index();
if ($inputEl.parents('thead').length > 0) {
if (columnIndex === 0) {
$el
.find('tbody tr')[checked ? 'addClass' : 'removeClass']('data-table-row-selected');
}
$el
.find(`tbody tr td:nth-child(${columnIndex + 1}) input`)
.prop('checked', checked)
.trigger('change', { sentByF7DataTable: true });
} else {
if (columnIndex === 0) {
$inputEl.parents('tr')[checked ? 'addClass' : 'removeClass']('data-table-row-selected');
}
if (!checked) {
$el.find(`thead .checkbox-cell:nth-child(${columnIndex + 1}) input[type="checkbox"]`).prop('checked', false);
} else if ($el.find(`tbody .checkbox-cell:nth-child(${columnIndex + 1}) input[type="checkbox"]:checked`).length === $el.find('tbody tr').length) {
$el.find(`thead .checkbox-cell:nth-child(${columnIndex + 1}) input[type="checkbox"]`).prop('checked', true).trigger('change', { sentByF7DataTable: true });
}
}
table.checkSelectedHeader();
}
function handleSortableClick() {
const $cellEl = $(this);
const isActive = $cellEl.hasClass('sortable-cell-active');
let currentSort;
if (isActive) {
currentSort = $cellEl.hasClass('sortable-desc') ? 'desc' : 'asc';
$cellEl.removeClass('sortable-desc sortable-asc').addClass(`sortable-${currentSort === 'desc' ? 'asc' : 'desc'}`);
} else {
$el.find('thead .sortable-cell-active').removeClass('sortable-cell-active');
$cellEl.addClass('sortable-cell-active');
}
}
table.attachEvents = function attachEvents() {
table.$el.on('change', '.checkbox-cell input[type="checkbox"]', handleChange);
table.$el.find('thead .sortable-cell').on('click', handleSortableClick);
};
table.detachEvents = function detachEvents() {
table.$el.off('change', '.checkbox-cell input[type="checkbox"]', handleChange);
table.$el.find('thead .sortable-cell').off('click', handleSortableClick);
};
// Install Modules
table.useModules();
// Init
table.init();
return table;
}
setCollapsibleLabels() {
const table = this;
if (!table.collapsible) return;
table.$el.find('tbody td:not(.checkbox-cell)').each((index, el) => {
const $el = $(el);
const elIndex = $el.index();
const collpsibleTitle = $el.attr('data-collapsible-title');
if (!collpsibleTitle && collpsibleTitle !== '') {
$el.attr('data-collapsible-title', table.$el.find('thead th').eq(elIndex).text());
}
});
}
checkSelectedHeader() {
const table = this;
if (table.$headerEl.length > 0 && table.$headerSelectedEl.length > 0) {
const checkedItems = table.$el.find('tbody .checkbox-cell input:checked').length;
table.$el[checkedItems > 0 ? 'addClass' : 'removeClass']('data-table-has-checked');
table.$headerSelectedEl.find('.data-table-selected-count').text(checkedItems);
}
}
init() {
const table = this;
table.attachEvents();
table.setCollapsibleLabels();
table.checkSelectedHeader();
}
destroy() {
let table = this;
table.$el.trigger('datatable:beforedestroy', table);
table.emit('local::beforeDestroy datatableBeforeDestroy', table);
table.attachEvents();
table.$el[0].f7DataTable = null;
delete table.$el[0].f7DataTable;
Utils.deleteProps(table);
table = null;
}
}
var DataTable = {
name: 'dataTable',
static: {
DataTable: DataTable$1,
},
create() {
const app = this;
app.dataTable = ConstructorMethods({
defaultSelector: '.data-table',
constructor: DataTable$1,
app,
domProp: 'f7DataTable',
});
},
on: {
tabBeforeRemove(tabEl) {
const app = this;
$(tabEl).find('.data-table-init').each((index, tableEl) => {
app.dataTable.destroy(tableEl);
});
},
tabMounted(tabEl) {
const app = this;
$(tabEl).find('.data-table-init').each((index, tableEl) => {
app.dataTable.create({ el: tableEl });
});
},
pageBeforeRemove(page) {
const app = this;
page.$el.find('.data-table-init').each((index, tableEl) => {
app.dataTable.destroy(tableEl);
});
},
pageInit(page) {
const app = this;
page.$el.find('.data-table-init').each((index, tableEl) => {
app.dataTable.create({ el: tableEl });
});
},
},
clicks: {
},
};
const Fab = {
morphOpen(fabEl, targetEl) {
const app = this;
const $fabEl = $(fabEl);
const $targetEl = $(targetEl);
if ($targetEl.length === 0) return;
$targetEl.transition(0).addClass('fab-morph-target-visible');
const target = {
width: $targetEl[0].offsetWidth,
height: $targetEl[0].offsetHeight,
offset: $targetEl.offset(),
borderRadius: $targetEl.css('border-radius'),
zIndex: $targetEl.css('z-index'),
};
const fab = {
width: $fabEl[0].offsetWidth,
height: $fabEl[0].offsetHeight,
offset: $fabEl.offset(),
translateX: Utils.getTranslate($fabEl[0], 'x'),
translateY: Utils.getTranslate($fabEl[0], 'y'),
};
$fabEl[0].f7FabMorphData = {
$targetEl,
target,
fab,
};
const diffX = (fab.offset.left + (fab.width / 2)) -
(target.offset.left + (target.width / 2)) -
fab.translateX;
const diffY = (fab.offset.top + (fab.height / 2)) -
(target.offset.top + (target.height / 2)) -
fab.translateY;
const scaleX = target.width / fab.width;
const scaleY = target.height / fab.height;
let borderRadius = Math.ceil(parseInt(target.borderRadius, 10) / Math.max(scaleX, scaleY));
if (borderRadius > 0) borderRadius += 2;
$fabEl[0].f7FabMorphResizeHandler = function resizeHandler() {
$fabEl.transition(0).transform('');
$targetEl.transition(0);
target.width = $targetEl[0].offsetWidth;
target.height = $targetEl[0].offsetHeight;
target.offset = $targetEl.offset();
fab.offset = $fabEl.offset();
const diffXNew = (fab.offset.left + (fab.width / 2)) -
(target.offset.left + (target.width / 2)) -
fab.translateX;
const diffYNew = (fab.offset.top + (fab.height / 2)) -
(target.offset.top + (target.height / 2)) -
fab.translateY;
const scaleXNew = target.width / fab.width;
const scaleYNew = target.height / fab.height;
$fabEl.transform(`translate3d(${-diffXNew}px, ${-diffYNew}px, 0) scale(${scaleXNew}, ${scaleYNew})`);
};
$targetEl
.css('opacity', 0)
.transform(`scale(${1 / scaleX}, ${1 / scaleY})`);
$fabEl
.addClass('fab-opened')
.css('z-index', target.zIndex - 1)
.transform(`translate3d(${-diffX}px, ${-diffY}px, 0)`);
$fabEl.transitionEnd(() => {
$targetEl.transition('');
Utils.nextTick(() => {
$targetEl.css('opacity', 1).transform('scale(1,1)');
});
$fabEl.transform(`translate3d(${-diffX}px, ${-diffY}px, 0) scale(${scaleX}, ${scaleY})`)
.css('border-radius', `${borderRadius}px`)
.css('box-shadow', 'none');
app.on('resize', $fabEl[0].f7FabMorphResizeHandler);
if ($targetEl.parents('.page-content').length > 0) {
$targetEl.parents('.page-content').on('scroll', $fabEl[0].f7FabMorphResizeHandler);
}
});
},
morphClose(fabEl) {
const app = this;
const $fabEl = $(fabEl);
const morphData = $fabEl[0].f7FabMorphData;
if (!morphData) return;
const { $targetEl, target, fab } = morphData;
if ($targetEl.length === 0) return;
const diffX = (fab.offset.left + (fab.width / 2)) -
(target.offset.left + (target.width / 2)) -
fab.translateX;
const diffY = (fab.offset.top + (fab.height / 2)) -
(target.offset.top + (target.height / 2)) -
fab.translateY;
const scaleX = target.width / fab.width;
const scaleY = target.height / fab.height;
app.off('resize', $fabEl[0].f7FabMorphResizeHandler);
if ($targetEl.parents('.page-content').length > 0) {
$targetEl.parents('.page-content').off('scroll', $fabEl[0].f7FabMorphResizeHandler);
}
$targetEl
.css('opacity', 0)
.transform(`scale(${1 / scaleX}, ${1 / scaleY})`);
$fabEl
.transition('')
.css('box-shadow', '')
.css('border-radius', '')
.transform(`translate3d(${-diffX}px, ${-diffY}px, 0)`);
$fabEl.transitionEnd(() => {
$fabEl
.css('z-index', '')
.removeClass('fab-opened')
.transform('');
Utils.nextTick(() => {
$fabEl.transitionEnd(() => {
$targetEl
.removeClass('fab-morph-target-visible')
.css('opacity', '')
.transform('')
.transition('');
});
});
});
},
open(fabEl, targetEl) {
const app = this;
const $fabEl = $(fabEl).eq(0);
const $buttonsEl = $fabEl.find('.fab-buttons');
if (!$fabEl.length) return;
if ($fabEl.hasClass('fab-opened')) return;
if (!$buttonsEl.length && !$fabEl.hasClass('fab-morph')) return;
if (app.fab.openedEl) {
if (app.fab.openedEl === $fabEl[0]) return;
app.fab.close(app.fab.openedEl);
}
app.fab.openedEl = $fabEl[0];
if ($fabEl.hasClass('fab-morph')) {
app.fab.morphOpen($fabEl, targetEl || $fabEl.attr('data-morph-to'));
} else {
$fabEl.addClass('fab-opened');
}
$fabEl.trigger('fab:open');
},
close(fabEl = '.fab-opened') {
const app = this;
const $fabEl = $(fabEl).eq(0);
const $buttonsEl = $fabEl.find('.fab-buttons');
if (!$fabEl.length) return;
if (!$fabEl.hasClass('fab-opened')) return;
if (!$buttonsEl.length && !$fabEl.hasClass('fab-morph')) return;
app.fab.openedEl = null;
if ($fabEl.hasClass('fab-morph')) {
app.fab.morphClose($fabEl);
} else {
$fabEl.removeClass('fab-opened');
}
$fabEl.trigger('fab:close');
},
toggle(fabEl) {
const app = this;
const $fabEl = $(fabEl);
if (!$fabEl.hasClass('fab-opened')) app.fab.open(fabEl);
else app.fab.close(fabEl);
},
};
var Fab$1 = {
name: 'fab',
create() {
const app = this;
Utils.extend(app, {
fab: {
openedEl: null,
morphOpen: Fab.morphOpen.bind(app),
morphClose: Fab.morphClose.bind(app),
open: Fab.open.bind(app),
close: Fab.close.bind(app),
toggle: Fab.toggle.bind(app),
},
});
},
clicks: {
'.fab > a': function open($clickedEl) {
const app = this;
app.fab.toggle($clickedEl.parents('.fab'));
},
'.fab-open': function open($clickedEl, data = {}) {
const app = this;
app.fab.open(data.fab);
},
'.fab-close': function close($clickedEl, data = {}) {
const app = this;
app.fab.close(data.fab);
},
},
};
class Searchbar$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const sb = this;
const defaults = {
el: undefined,
inputEl: undefined,
disableButton: true,
disableButtonEl: undefined,
backdropEl: undefined,
searchContainer: undefined, // container to search, HTMLElement or CSS selector
searchItem: 'li', // single item selector, CSS selector
searchIn: undefined, // where to search in item, CSS selector
ignore: '.searchbar-ignore',
foundEl: '.searchbar-found',
notFoundEl: '.searchbar-not-found',
hideOnEnableEl: '.searchbar-hide-on-enable',
hideOnSearchEl: '.searchbar-hide-on-search',
backdrop: true,
removeDiacritics: true,
customSearch: false,
hideDividers: true,
hideGroups: true,
disableOnBackdropClick: true,
expandable: false,
};
// Extend defaults with modules params
sb.useModulesParams(defaults);
sb.params = Utils.extend(defaults, params);
const $el = $(sb.params.el);
if ($el.length === 0) return sb;
$el[0].f7Searchbar = sb;
let $pageEl;
let $navbarEl;
if ($el.parents('.page').length > 0) {
$pageEl = $el.parents('.page');
} else {
$navbarEl = $el.parents('.navbar-inner');
if ($navbarEl.length > 0) {
if ($navbarEl[0].f7Page) {
$pageEl = $navbarEl[0].f7Page.$el;
} else {
const $currentPageEl = $el.parents('.view').find('.page-current');
if ($currentPageEl[0] && $currentPageEl[0].f7Page && $currentPageEl[0].f7Page.navbarEl === $navbarEl[0]) {
$pageEl = $currentPageEl;
}
}
}
}
let $foundEl;
if (params.foundEl) {
$foundEl = $(params.foundEl);
} else if (typeof sb.params.foundEl === 'string' && $pageEl) {
$foundEl = $pageEl.find(sb.params.foundEl);
}
let $notFoundEl;
if (params.notFoundEl) {
$notFoundEl = $(params.notFoundEl);
} else if (typeof sb.params.notFoundEl === 'string' && $pageEl) {
$notFoundEl = $pageEl.find(sb.params.notFoundEl);
}
let $hideOnEnableEl;
if (params.hideOnEnableEl) {
$hideOnEnableEl = $(params.hideOnEnableEl);
} else if (typeof sb.params.hideOnEnableEl === 'string' && $pageEl) {
$hideOnEnableEl = $pageEl.find(sb.params.hideOnEnableEl);
}
let $hideOnSearchEl;
if (params.hideOnSearchEl) {
$hideOnSearchEl = $(params.hideOnSearchEl);
} else if (typeof sb.params.hideOnSearchEl === 'string' && $pageEl) {
$hideOnSearchEl = $pageEl.find(sb.params.hideOnSearchEl);
}
let $backdropEl;
if (sb.params.backdrop) {
if (sb.params.backdropEl) {
$backdropEl = $(sb.params.backdropEl);
} else if ($pageEl && $pageEl.length > 0) {
$backdropEl = $pageEl.find('.searchbar-backdrop');
} else {
$backdropEl = $el.siblings('.searchbar-backdrop');
}
if ($backdropEl.length === 0) {
$backdropEl = $('<div class="searchbar-backdrop"></div>');
if ($pageEl && $pageEl.length) {
if ($el.parents($pageEl).length > 0 && $navbarEl && $el.parents($navbarEl).length === 0) {
$backdropEl.insertBefore($el);
} else {
$backdropEl.insertBefore($pageEl.find('.page-content').eq(0));
}
} else {
$backdropEl.insertBefore($el);
}
}
}
let $searchContainer;
if (sb.params.searchContainer) {
$searchContainer = $(sb.params.searchContainer);
}
let $inputEl;
if (sb.params.inputEl) {
$inputEl = $(sb.params.inputEl);
} else {
$inputEl = $el.find('input[type="search"]').eq(0);
}
let $disableButtonEl;
if (sb.params.disableButton) {
if (sb.params.disableButtonEl) {
$disableButtonEl = $(sb.params.disableButtonEl);
} else {
$disableButtonEl = $el.find('.searchbar-disable-button');
}
}
Utils.extend(sb, {
app,
view: app.views.get($el.parents('.view')),
$el,
el: $el[0],
$backdropEl,
backdropEl: $backdropEl && $backdropEl[0],
$searchContainer,
searchContainer: $searchContainer && $searchContainer[0],
$inputEl,
inputEl: $inputEl[0],
$disableButtonEl,
disableButtonEl: $disableButtonEl[0],
disableButtonHasMargin: false,
$pageEl,
pageEl: $pageEl && $pageEl[0],
$navbarEl,
navbarEl: $navbarEl && $navbarEl[0],
$foundEl,
foundEl: $foundEl && $foundEl[0],
$notFoundEl,
notFoundEl: $notFoundEl && $notFoundEl[0],
$hideOnEnableEl,
hideOnEnableEl: $hideOnEnableEl && $hideOnEnableEl[0],
$hideOnSearchEl,
hideOnSearchEl: $hideOnSearchEl && $hideOnSearchEl[0],
previousQuery: '',
query: '',
isVirtualList: $searchContainer && $searchContainer.hasClass('virtual-list'),
virtualList: undefined,
enabled: false,
expandable: sb.params.expandable || $el.hasClass('searchbar-expandable'),
});
// Events
function preventSubmit(e) {
e.preventDefault();
}
function onInputFocus(e) {
sb.enable(e);
sb.$el.addClass('searchbar-focused');
}
function onInputBlur() {
sb.$el.removeClass('searchbar-focused');
}
function onInputChange() {
const value = sb.$inputEl.val().trim();
if (
(
(sb.$searchContainer && sb.$searchContainer.length > 0) &&
(sb.params.searchIn || sb.isVirtualList)
) ||
sb.params.customSearch
) {
sb.search(value, true);
}
}
function onInputClear(e, previousValue) {
sb.$el.trigger('searchbar:clear', previousValue);
sb.emit('local::clear searchbarClear', previousValue);
}
function disableOnClick(e) {
sb.disable(e);
}
function onPageBeforeOut() {
if (!sb || (sb && !sb.$el)) return;
if (sb.enabled) {
sb.$el.removeClass('searchbar-enabled');
}
}
function onPageBeforeIn() {
if (!sb || (sb && !sb.$el)) return;
if (sb.enabled) {
sb.$el.addClass('searchbar-enabled');
}
}
sb.attachEvents = function attachEvents() {
$el.on('submit', preventSubmit);
if (sb.params.disableButton) {
sb.$disableButtonEl.on('click', disableOnClick);
}
if (sb.params.disableOnBackdropClick && sb.$backdropEl) {
sb.$backdropEl.on('click', disableOnClick);
}
if (sb.expandable && app.theme === 'ios' && sb.view && $navbarEl && sb.$pageEl) {
sb.$pageEl.on('page:beforeout', onPageBeforeOut);
sb.$pageEl.on('page:beforein', onPageBeforeIn);
}
sb.$inputEl.on('focus', onInputFocus);
sb.$inputEl.on('blur', onInputBlur);
sb.$inputEl.on('change input compositionend', onInputChange);
sb.$inputEl.on('input:clear', onInputClear);
};
sb.detachEvents = function detachEvents() {
$el.off('submit', preventSubmit);
if (sb.params.disableButton) {
sb.$disableButtonEl.off('click', disableOnClick);
}
if (sb.params.disableOnBackdropClick && sb.$backdropEl) {
sb.$backdropEl.off('click', disableOnClick);
}
if (sb.expandable && app.theme === 'ios' && sb.view && $navbarEl && sb.$pageEl) {
sb.$pageEl.on('page:beforeout', onPageBeforeOut);
sb.$pageEl.on('page:beforein', onPageBeforeIn);
}
sb.$inputEl.off('focus', onInputFocus);
sb.$inputEl.off('blur', onInputBlur);
sb.$inputEl.off('change input compositionend', onInputChange);
sb.$inputEl.off('input:clear', onInputClear);
};
// Install Modules
sb.useModules();
// Init
sb.init();
return sb;
}
clear(e) {
const sb = this;
if (!sb.query && e && $(e.target).hasClass('searchbar-clear')) {
sb.disable();
return sb;
}
const previousQuery = sb.value;
sb.$inputEl.val('').trigger('change').focus();
sb.$el.trigger('searchbar:clear', previousQuery);
sb.emit('local::clear searchbarClear', previousQuery);
return sb;
}
setDisableButtonMargin() {
const sb = this;
if (sb.expandable) return;
const app = sb.app;
sb.$disableButtonEl.transition(0).show();
sb.$disableButtonEl.css(`margin-${app.rtl ? 'left' : 'right'}`, `${-sb.disableButtonEl.offsetWidth}px`);
/* eslint no-underscore-dangle: ["error", { "allow": ["_clientLeft"] }] */
sb._clientLeft = sb.$disableButtonEl[0].clientLeft;
sb.$disableButtonEl.transition('');
sb.disableButtonHasMargin = true;
}
enable(setFocus) {
const sb = this;
if (sb.enabled) return sb;
const app = sb.app;
sb.enabled = true;
function enable() {
if (sb.$backdropEl && ((sb.$searchContainer && sb.$searchContainer.length) || sb.params.customSearch) && !sb.$el.hasClass('searchbar-enabled') && !sb.query) {
sb.backdropShow();
}
sb.$el.addClass('searchbar-enabled');
if (!sb.expandable && sb.$disableButtonEl && sb.$disableButtonEl.length > 0 && app.theme === 'ios') {
if (!sb.disableButtonHasMargin) {
sb.setDisableButtonMargin();
}
sb.$disableButtonEl.css(`margin-${app.rtl ? 'left' : 'right'}`, '0px');
}
if (sb.$hideOnEnableEl) sb.$hideOnEnableEl.hide();
sb.$el.trigger('searchbar:enable');
sb.emit('local::enable searchbarEnable');
}
let needsFocus = false;
if (setFocus === true) {
if (document.activeElement !== sb.inputEl) {
needsFocus = true;
}
}
const isIos = app.device.ios && app.theme === 'ios';
if (isIos) {
if (sb.expandable) {
if (needsFocus) sb.$inputEl.focus();
enable();
} else {
if (needsFocus) sb.$inputEl.focus();
if (setFocus && (setFocus.type === 'focus' || setFocus === true)) {
Utils.nextTick(() => {
enable();
}, 400);
} else {
enable();
}
}
} else {
if (needsFocus) sb.$inputEl.focus();
if (app.theme === 'md' && sb.expandable) {
sb.$el.parents('.navbar-inner').scrollLeft(0);
}
enable();
}
return sb;
}
disable() {
const sb = this;
if (!sb.enabled) return sb;
const app = sb.app;
sb.$inputEl.val('').trigger('change');
sb.$el.removeClass('searchbar-enabled');
sb.$el.removeClass('searchbar-focused');
if (!sb.expandable && sb.$disableButtonEl && sb.$disableButtonEl.length > 0 && app.theme === 'ios') {
sb.$disableButtonEl.css(`margin-${app.rtl ? 'left' : 'right'}`, `${-sb.disableButtonEl.offsetWidth}px`);
}
if (sb.$backdropEl && ((sb.$searchContainer && sb.$searchContainer.length) || sb.params.customSearch)) {
sb.backdropHide();
}
sb.enabled = false;
sb.$inputEl.blur();
if (sb.$hideOnEnableEl) sb.$hideOnEnableEl.show();
sb.$el.trigger('searchbar:disable');
sb.emit('local::disable searchbarDisable');
return sb;
}
toggle() {
const sb = this;
if (sb.enabled) sb.disable();
else sb.enable(true);
return sb;
}
backdropShow() {
const sb = this;
if (sb.$backdropEl) {
sb.$backdropEl.addClass('searchbar-backdrop-in');
}
return sb;
}
backdropHide() {
const sb = this;
if (sb.$backdropEl) {
sb.$backdropEl.removeClass('searchbar-backdrop-in');
}
return sb;
}
search(query, internal) {
const sb = this;
if (sb.previousQuery && query.trim() === sb.previousQuery) return sb;
if (typeof (sb.previousQuery) !== 'undefined' && sb.previousQuery.trim() === '' && query.trim() === '') return sb;
sb.previousQuery = query.trim();
if (!internal) {
if (!sb.enabled) {
sb.enable();
}
sb.$inputEl.val(query);
}
sb.query = query;
sb.value = query;
const { $searchContainer, $el, $backdropEl, $foundEl, $notFoundEl, $hideOnSearchEl, isVirtualList } = sb;
// Hide on search element
if (query.length > 0 && $hideOnSearchEl) {
$hideOnSearchEl.hide();
} else if ($hideOnSearchEl) {
$hideOnSearchEl.show();
}
// Add active/inactive classes on overlay
if (query.length === 0) {
if ($searchContainer && $searchContainer.length && $el.hasClass('searchbar-enabled') && $backdropEl) sb.backdropShow();
} else if ($searchContainer && $searchContainer.length && $el.hasClass('searchbar-enabled')) {
sb.backdropHide();
}
if (sb.params.customSearch) {
$el.trigger('searchbar:search', query, sb.previousQuery);
sb.emit('local::search searchbarSearch', query, sb.previousQuery);
return sb;
}
let foundItems = [];
let vlQuery;
if (isVirtualList) {
sb.virtualList = $searchContainer[0].f7VirtualList;
if (query.trim() === '') {
sb.virtualList.resetFilter();
if ($notFoundEl) $notFoundEl.hide();
if ($foundEl) $foundEl.show();
return sb;
}
vlQuery = sb.params.removeDiacritics ? Utils.removeDiacritics(query) : query;
if (sb.virtualList.params.searchAll) {
foundItems = sb.virtualList.params.searchAll(vlQuery, sb.virtualList.items) || [];
} else if (sb.virtualList.params.searchByItem) {
for (let i = 0; i < sb.virtualList.items.length; i += 1) {
if (sb.virtualList.params.searchByItem(vlQuery, sb.virtualList.params.items[i], i)) {
foundItems.push(i);
}
}
}
} else {
let values;
if (sb.params.removeDiacritics) values = Utils.removeDiacritics(query.trim().toLowerCase()).split(' ');
else {
values = query.trim().toLowerCase().split(' ');
}
$searchContainer.find(sb.params.searchItem).removeClass('hidden-by-searchbar').each((itemIndex, itemEl) => {
const $itemEl = $(itemEl);
let compareWithText = [];
$itemEl.find(sb.params.searchIn).each((searchInIndex, searchInEl) => {
let itemText = $(searchInEl).text().trim().toLowerCase();
if (sb.params.removeDiacritics) itemText = Utils.removeDiacritics(itemText);
compareWithText.push(itemText);
});
compareWithText = compareWithText.join(' ');
let wordsMatch = 0;
for (let i = 0; i < values.length; i += 1) {
if (compareWithText.indexOf(values[i]) >= 0) wordsMatch += 1;
}
if (wordsMatch !== values.length && !(sb.params.ignore && $itemEl.is(sb.params.ignore))) {
$itemEl.addClass('hidden-by-searchbar');
} else {
foundItems.push($itemEl[0]);
}
});
if (sb.params.hideDividers) {
$searchContainer.find('.item-divider, .list-group-title').each((titleIndex, titleEl) => {
const $titleEl = $(titleEl);
const $nextElements = $titleEl.nextAll('li');
let hide = true;
for (let i = 0; i < $nextElements.length; i += 1) {
const $nextEl = $nextElements.eq(i);
if ($nextEl.hasClass('list-group-title') || $nextEl.hasClass('item-divider')) break;
if (!$nextEl.hasClass('hidden-by-searchbar')) {
hide = false;
}
}
const ignore = sb.params.ignore && $titleEl.is(sb.params.ignore);
if (hide && !ignore) $titleEl.addClass('hidden-by-searchbar');
else $titleEl.removeClass('hidden-by-searchbar');
});
}
if (sb.params.hideGroups) {
$searchContainer.find('.list-group').each((groupIndex, groupEl) => {
const $groupEl = $(groupEl);
const ignore = sb.params.ignore && $groupEl.is(sb.params.ignore);
const notHidden = $groupEl.find('li:not(.hidden-by-searchbar)');
if (notHidden.length === 0 && !ignore) {
$groupEl.addClass('hidden-by-searchbar');
} else {
$groupEl.removeClass('hidden-by-searchbar');
}
});
}
}
if (foundItems.length === 0) {
if ($notFoundEl) $notFoundEl.show();
if ($foundEl) $foundEl.hide();
} else {
if ($notFoundEl) $notFoundEl.hide();
if ($foundEl) $foundEl.show();
}
if (isVirtualList && sb.virtualList) {
sb.virtualList.filterItems(foundItems);
}
$el.trigger('searchbar:search', query, sb.previousQuery, foundItems);
sb.emit('local::search searchbarSearch', query, sb.previousQuery, foundItems);
return sb;
}
init() {
const sb = this;
sb.attachEvents();
}
destroy() {
const sb = this;
sb.emit('local::beforeDestroy searchbarBeforeDestroy', sb);
sb.$el.trigger('searchbar:beforedestroy', sb);
sb.detachEvents();
delete sb.$el.f7Searchbar;
Utils.deleteProps(sb);
}
}
var Searchbar = {
name: 'searchbar',
static: {
Searchbar: Searchbar$1,
},
create() {
const app = this;
app.searchbar = ConstructorMethods({
defaultSelector: '.searchbar',
constructor: Searchbar$1,
app,
domProp: 'f7Searchbar',
addMethods: 'clear enable disable toggle search'.split(' '),
});
},
on: {
tabMounted(tabEl) {
const app = this;
$(tabEl).find('.searchbar-init').each((index, searchbarEl) => {
const $searchbarEl = $(searchbarEl);
app.searchbar.create(Utils.extend($searchbarEl.dataset(), { el: searchbarEl }));
});
},
tabBeforeRemove(tabEl) {
$(tabEl).find('.searchbar-init').each((index, searchbarEl) => {
if (searchbarEl.f7Searchbar && searchbarEl.f7Searchbar.destroy) {
searchbarEl.f7Searchbar.destroy();
}
});
},
pageInit(page) {
const app = this;
page.$el.find('.searchbar-init').each((index, searchbarEl) => {
const $searchbarEl = $(searchbarEl);
app.searchbar.create(Utils.extend($searchbarEl.dataset(), { el: searchbarEl }));
});
if (app.theme === 'ios' && page.view && page.view.router.separateNavbar && page.$navbarEl && page.$navbarEl.length > 0) {
page.$navbarEl.find('.searchbar-init').each((index, searchbarEl) => {
const $searchbarEl = $(searchbarEl);
app.searchbar.create(Utils.extend($searchbarEl.dataset(), { el: searchbarEl }));
});
}
},
pageBeforeRemove(page) {
const app = this;
page.$el.find('.searchbar-init').each((index, searchbarEl) => {
if (searchbarEl.f7Searchbar && searchbarEl.f7Searchbar.destroy) {
searchbarEl.f7Searchbar.destroy();
}
});
if (app.theme === 'ios' && page.view && page.view.router.separateNavbar && page.$navbarEl && page.$navbarEl.length > 0) {
page.$navbarEl.find('.searchbar-init').each((index, searchbarEl) => {
if (searchbarEl.f7Searchbar && searchbarEl.f7Searchbar.destroy) {
searchbarEl.f7Searchbar.destroy();
}
});
}
},
},
clicks: {
'.searchbar-clear': function clear($clickedEl, data = {}) {
const app = this;
const sb = app.searchbar.get(data.searchbar);
if (sb) sb.clear();
},
'.searchbar-enable': function enable($clickedEl, data = {}) {
const app = this;
const sb = app.searchbar.get(data.searchbar);
if (sb) sb.enable(true);
},
'.searchbar-disable': function disable($clickedEl, data = {}) {
const app = this;
const sb = app.searchbar.get(data.searchbar);
if (sb) sb.disable();
},
'.searchbar-toggle': function toggle($clickedEl, data = {}) {
const app = this;
const sb = app.searchbar.get(data.searchbar);
if (sb) sb.toggle();
},
},
};
class Messages$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const m = this;
const defaults = {
autoLayout: true,
messages: [],
newMessagesFirst: false,
scrollMessages: true,
scrollMessagesOnEdge: true,
firstMessageRule: undefined,
lastMessageRule: undefined,
tailMessageRule: undefined,
sameNameMessageRule: undefined,
sameHeaderMessageRule: undefined,
sameFooterMessageRule: undefined,
sameAvatarMessageRule: undefined,
customClassMessageRule: undefined,
renderMessage: undefined,
};
// Extend defaults with modules params
m.useModulesParams(defaults);
m.params = Utils.extend(defaults, params);
const $el = $(params.el).eq(0);
if ($el.length === 0) return m;
$el[0].f7Messages = m;
const $pageContentEl = $el.closest('.page-content').eq(0);
Utils.extend(m, {
messages: m.params.messages,
$el,
el: $el[0],
$pageContentEl,
pageContentEl: $pageContentEl[0],
});
// Install Modules
m.useModules();
// Init
m.init();
return m;
}
// eslint-disable-next-line
getMessageData(messageEl) {
const $messageEl = $(messageEl);
const data = {
name: $messageEl.find('.message-name').html(),
header: $messageEl.find('.message-header').html(),
textHeader: $messageEl.find('.message-text-header').html(),
textFooter: $messageEl.find('.message-text-footer').html(),
footer: $messageEl.find('.message-footer').html(),
isTitle: $messageEl.hasClass('messages-title'),
type: $messageEl.hasClass('message-sent') ? 'sent' : 'received',
text: $messageEl.find('.message-text').html(),
image: $messageEl.find('.message-image').html(),
imageSrc: $messageEl.find('.message-image img').attr('src'),
typing: $messageEl.hasClass('message-typing'),
};
if (data.isTitle) {
data.text = $messageEl.html();
}
if (data.text && data.textHeader) {
data.text = data.text.replace(`<div class="message-text-header">${data.textHeader}</div>`, '');
}
if (data.text && data.textFooter) {
data.text = data.text.replace(`<div class="message-text-footer">${data.textFooter}</div>`, '');
}
let avatar = $messageEl.find('.message-avatar').css('background-image');
if (avatar === 'none' || avatar === '') avatar = undefined;
if (avatar && typeof avatar === 'string') {
avatar = avatar.replace('url(', '').replace(')', '').replace(/"/g, '').replace(/'/g, '');
} else {
avatar = undefined;
}
data.avatar = avatar;
return data;
}
getMessagesData() {
const m = this;
const data = [];
m.$el.find('.message, .messages-title').each((index, messageEl) => {
data.push(m.getMessageData(messageEl));
});
return data;
}
renderMessage(messageToRender) {
const m = this;
const message = Utils.extend({
type: 'sent',
}, messageToRender);
if (m.params.renderMessage) {
return m.params.renderMessage(message);
}
if (message.isTitle) {
return `<div class="messages-title">${message.text}</div>`;
}
return `
<div class="message message-${message.type} ${message.isTyping ? 'message-typing' : ''}">
${message.avatar ? `
<div class="message-avatar" style="background-image:url(${message.avatar})"></div>
` : ''}
<div class="message-content">
${message.name ? `<div class="message-name">${message.name}</div>` : ''}
${message.header ? `<div class="message-header">${message.header}</div>` : ''}
<div class="message-bubble">
${message.textHeader ? `<div class="message-text-header">${message.textHeader}</div>` : ''}
${message.image ? `<div class="message-image">${message.image}</div>` : ''}
${message.imageSrc && !message.image ? `<div class="message-image"><img src="${message.imageSrc}"></div>` : ''}
${message.text || message.isTyping ? `<div class="message-text">${message.text || ''}${message.isTyping ? '<div class="message-typing-indicator"><div></div><div></div><div></div></div>' : ''}</div>` : ''}
${message.textFooter ? `<div class="message-text-footer">${message.textFooter}</div>` : ''}
</div>
${message.footer ? `<div class="message-footer">${message.footer}</div>` : ''}
</div>
</div>
`;
}
renderMessages(messagesToRender = this.messages, method = this.params.newMessagesFirst ? 'prepend' : 'append') {
const m = this;
const html = messagesToRender.map(message => m.renderMessage(message)).join('');
m.$el[method](html);
}
isFirstMessage(...args) {
const m = this;
if (m.params.firstMessageRule) return m.params.firstMessageRule(...args);
return false;
}
isLastMessage(...args) {
const m = this;
if (m.params.lastMessageRule) return m.params.lastMessageRule(...args);
return false;
}
isTailMessage(...args) {
const m = this;
if (m.params.tailMessageRule) return m.params.tailMessageRule(...args);
return false;
}
isSameNameMessage(...args) {
const m = this;
if (m.params.sameNameMessageRule) return m.params.sameNameMessageRule(...args);
return false;
}
isSameHeaderMessage(...args) {
const m = this;
if (m.params.sameHeaderMessageRule) return m.params.sameHeaderMessageRule(...args);
return false;
}
isSameFooterMessage(...args) {
const m = this;
if (m.params.sameFooterMessageRule) return m.params.sameFooterMessageRule(...args);
return false;
}
isSameAvatarMessage(...args) {
const m = this;
if (m.params.sameAvatarMessageRule) return m.params.sameAvatarMessageRule(...args);
return false;
}
isCustomClassMessage(...args) {
const m = this;
if (m.params.customClassMessageRule) return m.params.customClassMessageRule(...args);
return undefined;
}
layout() {
const m = this;
m.$el.find('.message, .messages-title').each((index, messageEl) => {
const $messageEl = $(messageEl);
if (!m.messages) {
m.messages = m.getMessagesData();
}
const classes = [];
const message = m.messages[index];
const previousMessage = m.messages[index - 1];
const nextMessage = m.messages[index + 1];
if (m.isFirstMessage(message, previousMessage, nextMessage)) {
classes.push('message-first');
}
if (m.isLastMessage(message, previousMessage, nextMessage)) {
classes.push('message-last');
}
if (m.isTailMessage(message, previousMessage, nextMessage)) {
classes.push('message-tail');
}
if (m.isSameNameMessage(message, previousMessage, nextMessage)) {
classes.push('message-same-name');
}
if (m.isSameHeaderMessage(message, previousMessage, nextMessage)) {
classes.push('message-same-header');
}
if (m.isSameFooterMessage(message, previousMessage, nextMessage)) {
classes.push('message-same-footer');
}
if (m.isSameAvatarMessage(message, previousMessage, nextMessage)) {
classes.push('message-same-avatar');
}
let customMessageClasses = m.isCustomClassMessage(message, previousMessage, nextMessage);
if (customMessageClasses && customMessageClasses.length) {
if (typeof customMessageClasses === 'string') {
customMessageClasses = customMessageClasses.split(' ');
}
customMessageClasses.forEach((customClass) => {
classes.push(customClass);
});
}
$messageEl.removeClass('message-first message-last message-tail message-same-name message-same-header message-same-footer message-same-avatar');
classes.forEach((className) => {
$messageEl.addClass(className);
});
});
}
clear() {
const m = this;
m.messages = [];
m.$el.html('');
}
removeMessage(messageToRemove, layout = true) {
const m = this;
// Index or El
let index;
let $el;
if (typeof messageToRemove === 'number') {
index = messageToRemove;
$el = m.$el.find('.message, .messages-title').eq(index);
} else {
$el = $(messageToRemove);
index = $el.index();
}
if ($el.length === 0) {
return m;
}
$el.remove();
m.messages.splice(index, 1);
if (m.params.autoLayout && layout) m.layout();
return m;
}
removeMessages(messagesToRemove, layout = true) {
const m = this;
if (Array.isArray(messagesToRemove)) {
const messagesToRemoveEls = [];
messagesToRemove.forEach((messageToRemoveIndex) => {
messagesToRemoveEls.push(m.$el.find('.message, .messages-title').eq(messageToRemoveIndex));
});
messagesToRemoveEls.forEach((messageToRemove) => {
m.removeMessage(messageToRemove, false);
});
} else {
$(messagesToRemove).each((index, messageToRemove) => {
m.removeMessage(messageToRemove, false);
});
}
if (m.params.autoLayout && layout) m.layout();
return m;
}
addMessage(...args) {
const m = this;
let messageToAdd;
let animate;
let method;
if (typeof args[1] === 'boolean') {
[messageToAdd, animate, method] = args;
} else {
[messageToAdd, method, animate] = args;
}
if (typeof animate === 'undefined') {
animate = true;
}
if (typeof method === 'undefined') {
method = m.params.newMessagesFirst ? 'prepend' : 'append';
}
return m.addMessages([messageToAdd], animate, method);
}
addMessages(...args) {
const m = this;
let messagesToAdd;
let animate;
let method;
if (typeof args[1] === 'boolean') {
[messagesToAdd, animate, method] = args;
} else {
[messagesToAdd, method, animate] = args;
}
if (typeof animate === 'undefined') {
animate = true;
}
if (typeof method === 'undefined') {
method = m.params.newMessagesFirst ? 'prepend' : 'append';
}
// Define scroll positions before new messages added
const scrollHeightBefore = m.pageContentEl.scrollHeight;
const heightBefore = m.pageContentEl.offsetHeight;
const scrollBefore = m.pageContentEl.scrollTop;
// Add message to DOM and data
let messagesHTML = '';
const typingMessage = m.messages.filter(el => el.isTyping)[0];
messagesToAdd.forEach((messageToAdd) => {
if (typingMessage) {
if (method === 'append') {
m.messages.splice(m.messages.indexOf(typingMessage), 0, messageToAdd);
} else {
m.messages.splice(m.messages.indexOf(typingMessage) + 1, 0, messageToAdd);
}
} else {
m.messages[method === 'append' ? 'push' : 'unshift'](messageToAdd);
}
messagesHTML += m.renderMessage(messageToAdd);
});
const $messagesEls = $(messagesHTML);
if (animate) {
if (method === 'append' && !m.params.newMessagesFirst) {
$messagesEls.addClass('message-appear-from-bottom');
}
if (method === 'prepend' && m.params.newMessagesFirst) {
$messagesEls.addClass('message-appear-from-top');
}
}
if (typingMessage) {
if (method === 'append') {
$messagesEls.insertBefore(m.$el.find('.message-typing'));
} else {
$messagesEls.insertAfter(m.$el.find('.message-typing'));
}
} else {
m.$el[method]($messagesEls);
}
// Layout
if (m.params.autoLayout) m.layout();
if (method === 'prepend' && !typingMessage) {
m.pageContentEl.scrollTop = scrollBefore + (m.pageContentEl.scrollHeight - scrollHeightBefore);
}
if (m.params.scrollMessages && ((method === 'append' && !m.params.newMessagesFirst) || (method === 'prepend' && m.params.newMessagesFirst && !typingMessage))) {
if (m.params.scrollMessagesOnEdge) {
let onEdge = false;
if (m.params.newMessagesFirst && scrollBefore === 0) {
onEdge = true;
}
if (!m.params.newMessagesFirst && (scrollBefore - (scrollHeightBefore - heightBefore) >= -10)) {
onEdge = true;
}
if (onEdge) m.scroll(animate ? undefined : 0);
} else {
m.scroll(animate ? undefined : 0);
}
}
return m;
}
showTyping(message = {}) {
const m = this;
const typingMessage = m.messages.filter(el => el.isTyping)[0];
if (typingMessage) {
m.removeMessage(m.messages.indexOf(typingMessage));
}
m.addMessage(Utils.extend({
type: 'received',
isTyping: true,
}, message));
return m;
}
hideTyping() {
const m = this;
let typingMessageIndex;
let typingFound;
m.messages.forEach((message, index) => {
if (message.isTyping) typingMessageIndex = index;
});
if (typeof typingMessageIndex !== 'undefined') {
if (m.$el.find('.message').eq(typingMessageIndex).hasClass('message-typing')) {
typingFound = true;
m.removeMessage(typingMessageIndex);
}
}
if (!typingFound) {
const $typingMessageEl = m.$el.find('.message-typing');
if ($typingMessageEl.length) {
m.removeMessage($typingMessageEl);
}
}
return m;
}
scroll(duration = 300, scrollTop) {
const m = this;
const currentScroll = m.pageContentEl.scrollTop;
let newScrollTop;
if (typeof scrollTop !== 'undefined') newScrollTop = scrollTop;
else {
newScrollTop = m.params.newMessagesFirst ? 0 : m.pageContentEl.scrollHeight - m.pageContentEl.offsetHeight;
if (newScrollTop === currentScroll) return m;
}
m.$pageContentEl.scrollTop(newScrollTop, duration);
return m;
}
init() {
const m = this;
if (!m.messages || m.messages.length === 0) {
m.messages = m.getMessagesData();
}
if (m.params.messages && m.params.messages.length) {
m.renderMessages();
}
if (m.params.autoLayout) m.layout();
if (m.params.scrollMessages) m.scroll(0);
}
destroy() {
const m = this;
m.emit('local::beforeDestroy messagesBeforeDestroy', m);
m.$el.trigger('messages:beforedestroy', m);
m.$el[0].f7Messages = null;
delete m.$el[0].f7Messages;
Utils.deleteProps(m);
}
}
var Messages = {
name: 'messages',
static: {
Messages: Messages$1,
},
create() {
const app = this;
app.messages = ConstructorMethods({
defaultSelector: '.messages',
constructor: Messages$1,
app,
domProp: 'f7Messages',
addMethods: 'renderMessages layout scroll clear removeMessage removeMessages addMessage addMessages'.split(' '),
});
},
on: {
tabBeforeRemove(tabEl) {
const app = this;
$(tabEl).find('.messages-init').each((index, messagesEl) => {
app.messages.destroy(messagesEl);
});
},
tabMounted(tabEl) {
const app = this;
$(tabEl).find('.messages-init').each((index, messagesEl) => {
app.messages.create({ el: messagesEl });
});
},
pageBeforeRemove(page) {
const app = this;
page.$el.find('.messages-init').each((index, messagesEl) => {
app.messages.destroy(messagesEl);
});
},
pageInit(page) {
const app = this;
page.$el.find('.messages-init').each((index, messagesEl) => {
app.messages.create({ el: messagesEl });
});
},
},
clicks: {
},
};
class Messagebar$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const messagebar = this;
const defaults = {
top: false,
topOffset: 0,
bottomOffset: 0,
attachments: [],
renderAttachments: undefined,
renderAttachment: undefined,
maxHeight: null,
resizePage: true,
};
// Extend defaults with modules params
messagebar.useModulesParams(defaults);
messagebar.params = Utils.extend(defaults, params);
// El
const $el = $(messagebar.params.el);
if ($el.length === 0) return messagebar;
$el[0].f7Messagebar = messagebar;
// Page and PageContent
const $pageEl = $el.parents('.page').eq(0);
const $pageContentEl = $pageEl.find('.page-content').eq(0);
// Area
const $areaEl = $el.find('.messagebar-area');
// Textarea
let $textareaEl;
if (messagebar.params.textareaEl) {
$textareaEl = $(messagebar.params.textareaEl);
} else {
$textareaEl = $el.find('textarea');
}
// Attachments & Library
const $attachmentsEl = $el.find('.messagebar-attachments');
const $sheetEl = $el.find('.messagebar-sheet');
if (messagebar.params.top) {
$el.addClass('messagebar-top');
}
Utils.extend(messagebar, {
$el,
el: $el[0],
$areaEl,
areaEl: $areaEl[0],
$textareaEl,
textareaEl: $textareaEl[0],
$attachmentsEl,
attachmentsEl: $attachmentsEl[0],
attachmentsVisible: $attachmentsEl.hasClass('messagebar-attachments-visible'),
$sheetEl,
sheetEl: $sheetEl[0],
sheetVisible: $sheetEl.hasClass('messagebar-sheet-visible'),
$pageEl,
pageEl: $pageEl[0],
$pageContentEl,
pageContentEl: $pageContentEl,
top: $el.hasClass('messagebar-top') || messagebar.params.top,
attachments: [],
});
// Events
function onAppResize() {
if (messagebar.params.resizePage) {
messagebar.resizePage();
}
}
function onSubmit(e) {
e.preventDefault();
}
function onAttachmentClick(e) {
const index = $(this).index();
if ($(e.target).closest('.messagebar-attachment-delete').length) {
$(this).trigger('messagebar:attachmentdelete', index);
messagebar.emit('local::attachmentDelete messagebarAttachmentDelete', this, index);
} else {
$(this).trigger('messagebar:attachmentclick', index);
messagebar.emit('local::attachmentClick messagebarAttachmentClick', this, index);
}
}
function onTextareaChange() {
messagebar.checkEmptyState();
}
function onTextareaFocus() {
messagebar.sheetHide();
}
messagebar.attachEvents = function attachEvents() {
$el.on('textarea:resize', onAppResize);
$el.on('submit', onSubmit);
$el.on('click', '.messagebar-attachment', onAttachmentClick);
$textareaEl.on('change input', onTextareaChange);
$textareaEl.on('focus', onTextareaFocus);
app.on('resize', onAppResize);
};
messagebar.detachEvents = function detachEvents() {
$el.off('textarea:resize', onAppResize);
$el.off('submit', onSubmit);
$el.off('click', '.messagebar-attachment', onAttachmentClick);
$textareaEl.off('change input', onTextareaChange);
$textareaEl.on('focus', onTextareaFocus);
app.off('resize', onAppResize);
};
// Install Modules
messagebar.useModules();
// Init
messagebar.init();
return messagebar;
}
focus() {
const messagebar = this;
messagebar.$textareaEl.focus();
return messagebar;
}
blur() {
const messagebar = this;
messagebar.$textareaEl.blur();
return messagebar;
}
clear() {
const messagebar = this;
messagebar.$textareaEl.val('').trigger('change');
return messagebar;
}
getValue() {
const messagebar = this;
return messagebar.$textareaEl.val().trim();
}
setValue(value) {
const messagebar = this;
messagebar.$textareaEl.val(value).trigger('change');
return messagebar;
}
setPlaceholder(placeholder) {
const messagebar = this;
messagebar.$textareaEl.attr('placeholder', placeholder);
return messagebar;
}
resizePage() {
const messagebar = this;
const {
params,
$el,
top,
$pageEl,
$pageContentEl,
$areaEl,
$textareaEl,
$sheetEl,
$attachmentsEl,
} = messagebar;
const elHeight = $el[0].offsetHeight;
let maxHeight = params.maxHeight;
if (top) {
/*
Disable at the moment
const requiredPaddingTop = elHeight + params.topOffset;
const currentPaddingTop = parseInt($pageContentEl.css('padding-top'), 10);
if (requiredPaddingTop !== currentPaddingTop) {
if (!maxHeight) {
maxHeight = $pageEl[0].offsetHeight - currentPaddingTop - $sheetEl.outerHeight() - $attachmentsEl.outerHeight() - parseInt($areaEl.css('margin-top'), 10) - parseInt($areaEl.css('margin-bottom'), 10);
}
$textareaEl.css('max-height', `${maxHeight}px`);
$pageContentEl.css('padding-top', `${requiredPaddingTop}px`);
$el.trigger('messagebar:resizePage');
messagebar.emit('local::resizepage messagebarResizePage');
}
*/
} else {
const currentPaddingBottom = parseInt($pageContentEl.css('padding-bottom'), 10);
const requiredPaddingBottom = elHeight + params.bottomOffset;
if (requiredPaddingBottom !== currentPaddingBottom && $pageContentEl.length) {
const currentPaddingTop = parseInt($pageContentEl.css('padding-top'), 10);
const pageScrollHeight = $pageContentEl[0].scrollHeight;
const pageOffsetHeight = $pageContentEl[0].offsetHeight;
const pageScrollTop = $pageContentEl[0].scrollTop;
const scrollOnBottom = (pageScrollTop === pageScrollHeight - pageOffsetHeight);
if (!maxHeight) {
maxHeight = $pageEl[0].offsetHeight - currentPaddingTop - $sheetEl.outerHeight() - $attachmentsEl.outerHeight() - parseInt($areaEl.css('margin-top'), 10) - parseInt($areaEl.css('margin-bottom'), 10);
}
$textareaEl.css('max-height', `${maxHeight}px`);
$pageContentEl.css('padding-bottom', `${requiredPaddingBottom}px`);
if (scrollOnBottom) {
$pageContentEl.scrollTop($pageContentEl[0].scrollHeight - pageOffsetHeight);
}
$el.trigger('messagebar:resizepage');
messagebar.emit('local::resizePage messagebarResizePage');
}
}
}
checkEmptyState() {
const messagebar = this;
const { $el, $textareaEl } = messagebar;
const value = $textareaEl.val().trim();
if (value && value.length) {
$el.addClass('messagebar-with-value');
} else {
$el.removeClass('messagebar-with-value');
}
}
attachmentsCreate(innerHTML = '') {
const messagebar = this;
const $attachmentsEl = $(`<div class="messagebar-attachments">${innerHTML}</div>`);
$attachmentsEl.insertBefore(messagebar.$textareaEl);
Utils.extend(messagebar, {
$attachmentsEl,
attachmentsEl: $attachmentsEl[0],
});
return messagebar;
}
attachmentsShow(innerHTML = '') {
const messagebar = this;
messagebar.$attachmentsEl = messagebar.$el.find('.messagebar-attachments');
if (messagebar.$attachmentsEl.length === 0) {
messagebar.attachmentsCreate(innerHTML);
}
messagebar.$el.addClass('messagebar-attachments-visible');
messagebar.attachmentsVisible = true;
if (messagebar.params.resizePage) {
messagebar.resizePage();
}
return messagebar;
}
attachmentsHide() {
const messagebar = this;
messagebar.$el.removeClass('messagebar-attachments-visible');
messagebar.attachmentsVisible = false;
if (messagebar.params.resizePage) {
messagebar.resizePage();
}
return messagebar;
}
attachmentsToggle() {
const messagebar = this;
if (messagebar.attachmentsVisible) {
messagebar.attachmentsHide();
} else {
messagebar.attachmentsShow();
}
return messagebar;
}
renderAttachment(attachment) {
const messagebar = this;
if (messagebar.params.renderAttachment) {
return messagebar.params.renderAttachment(attachment);
}
return `
<div class="messagebar-attachment">
<img src="${attachment}">
<span class="messagebar-attachment-delete"></span>
</div>
`;
}
renderAttachments() {
const messagebar = this;
let html;
if (messagebar.params.renderAttachments) {
html = messagebar.params.renderAttachments(messagebar.attachments);
} else {
html = `${messagebar.attachments.map(attachment => messagebar.renderAttachment(attachment)).join('')}`;
}
if (messagebar.$attachmentsEl.length === 0) {
messagebar.attachmentsCreate(html);
} else {
messagebar.$attachmentsEl.html(html);
}
}
sheetCreate(innerHTML = '') {
const messagebar = this;
const $sheetEl = $(`<div class="messagebar-sheet">${innerHTML}</div>`);
messagebar.$el.append($sheetEl);
Utils.extend(messagebar, {
$sheetEl,
sheetEl: $sheetEl[0],
});
return messagebar;
}
sheetShow(innerHTML = '') {
const messagebar = this;
messagebar.$sheetEl = messagebar.$el.find('.messagebar-sheet');
if (messagebar.$sheetEl.length === 0) {
messagebar.sheetCreate(innerHTML);
}
messagebar.$el.addClass('messagebar-sheet-visible');
messagebar.sheetVisible = true;
if (messagebar.params.resizePage) {
messagebar.resizePage();
}
return messagebar;
}
sheetHide() {
const messagebar = this;
messagebar.$el.removeClass('messagebar-sheet-visible');
messagebar.sheetVisible = false;
if (messagebar.params.resizePage) {
messagebar.resizePage();
}
return messagebar;
}
sheetToggle() {
const messagebar = this;
if (messagebar.sheetVisible) {
messagebar.sheetHide();
} else {
messagebar.sheetShow();
}
return messagebar;
}
init() {
const messagebar = this;
messagebar.attachEvents();
messagebar.checkEmptyState();
return messagebar;
}
destroy() {
const messagebar = this;
messagebar.emit('local::beforeDestroy messagebarBeforeDestroy', messagebar);
messagebar.$el.trigger('messagebar:beforedestroy', messagebar);
messagebar.detachEvents();
messagebar.$el[0].f7Messagebar = null;
delete messagebar.$el[0].f7Messagebar;
Utils.deleteProps(messagebar);
}
}
var Messagebar = {
name: 'messagebar',
static: {
Messagebar: Messagebar$1,
},
create() {
const app = this;
app.messagebar = ConstructorMethods({
defaultSelector: '.messagebar',
constructor: Messagebar$1,
app,
domProp: 'f7Messagebar',
addMethods: 'clear getValue setValue setPlaceholder resizePage focus blur attachmentsCreate attachmentsShow attachmentsHide attachmentsToggle renderAttachments sheetCreate sheetShow sheetHide sheetToggle'.split(' '),
});
},
on: {
tabBeforeRemove(tabEl) {
const app = this;
$(tabEl).find('.messagebar-init').each((index, messagebarEl) => {
app.messagebar.destroy(messagebarEl);
});
},
tabMounted(tabEl) {
const app = this;
$(tabEl).find('.messagebar-init').each((index, messagebarEl) => {
app.messagebar.create(Utils.extend({ el: messagebarEl }, $(messagebarEl).dataset()));
});
},
pageBeforeRemove(page) {
const app = this;
page.$el.find('.messagebar-init').each((index, messagebarEl) => {
app.messagebar.destroy(messagebarEl);
});
},
pageInit(page) {
const app = this;
page.$el.find('.messagebar-init').each((index, messagebarEl) => {
app.messagebar.create(Utils.extend({ el: messagebarEl }, $(messagebarEl).dataset()));
});
},
},
clicks: {
},
};
var updateSize = function () {
const swiper = this;
let width;
let height;
const $el = swiper.$el;
if (typeof swiper.params.width !== 'undefined') {
width = swiper.params.width;
} else {
width = $el[0].clientWidth;
}
if (typeof swiper.params.height !== 'undefined') {
height = swiper.params.height;
} else {
height = $el[0].clientHeight;
}
if ((width === 0 && swiper.isHorizontal()) || (height === 0 && swiper.isVertical())) {
return;
}
// Subtract paddings
width = width - parseInt($el.css('padding-left'), 10) - parseInt($el.css('padding-right'), 10);
height = height - parseInt($el.css('padding-top'), 10) - parseInt($el.css('padding-bottom'), 10);
Utils.extend(swiper, {
width,
height,
size: swiper.isHorizontal() ? width : height,
});
};
var updateSlides = function () {
const swiper = this;
const params = swiper.params;
const { $wrapperEl, size: swiperSize, rtl, wrongRTL } = swiper;
const slides = $wrapperEl.children(`.${swiper.params.slideClass}`);
const isVirtual = swiper.virtual && params.virtual.enabled;
const slidesLength = isVirtual ? swiper.virtual.slides.length : slides.length;
let snapGrid = [];
const slidesGrid = [];
const slidesSizesGrid = [];
let offsetBefore = params.slidesOffsetBefore;
if (typeof offsetBefore === 'function') {
offsetBefore = params.slidesOffsetBefore.call(swiper);
}
let offsetAfter = params.slidesOffsetAfter;
if (typeof offsetAfter === 'function') {
offsetAfter = params.slidesOffsetAfter.call(swiper);
}
const previousSlidesLength = slidesLength;
const previousSnapGridLength = swiper.snapGrid.length;
const previousSlidesGridLength = swiper.snapGrid.length;
let spaceBetween = params.spaceBetween;
let slidePosition = -offsetBefore;
let prevSlideSize = 0;
let index = 0;
if (typeof swiperSize === 'undefined') {
return;
}
if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) {
spaceBetween = (parseFloat(spaceBetween.replace('%', '')) / 100) * swiperSize;
}
swiper.virtualSize = -spaceBetween;
// reset margins
if (rtl) slides.css({ marginLeft: '', marginTop: '' });
else slides.css({ marginRight: '', marginBottom: '' });
let slidesNumberEvenToRows;
if (params.slidesPerColumn > 1) {
if (Math.floor(slidesLength / params.slidesPerColumn) === slidesLength / swiper.params.slidesPerColumn) {
slidesNumberEvenToRows = slidesLength;
} else {
slidesNumberEvenToRows = Math.ceil(slidesLength / params.slidesPerColumn) * params.slidesPerColumn;
}
if (params.slidesPerView !== 'auto' && params.slidesPerColumnFill === 'row') {
slidesNumberEvenToRows = Math.max(slidesNumberEvenToRows, params.slidesPerView * params.slidesPerColumn);
}
}
// Calc slides
let slideSize;
const slidesPerColumn = params.slidesPerColumn;
const slidesPerRow = slidesNumberEvenToRows / slidesPerColumn;
const numFullColumns = slidesPerRow - ((params.slidesPerColumn * slidesPerRow) - slidesLength);
for (let i = 0; i < slidesLength; i += 1) {
slideSize = 0;
const slide = slides.eq(i);
if (params.slidesPerColumn > 1) {
// Set slides order
let newSlideOrderIndex;
let column;
let row;
if (params.slidesPerColumnFill === 'column') {
column = Math.floor(i / slidesPerColumn);
row = i - (column * slidesPerColumn);
if (column > numFullColumns || (column === numFullColumns && row === slidesPerColumn - 1)) {
row += 1;
if (row >= slidesPerColumn) {
row = 0;
column += 1;
}
}
newSlideOrderIndex = column + ((row * slidesNumberEvenToRows) / slidesPerColumn);
slide
.css({
'-webkit-box-ordinal-group': newSlideOrderIndex,
'-moz-box-ordinal-group': newSlideOrderIndex,
'-ms-flex-order': newSlideOrderIndex,
'-webkit-order': newSlideOrderIndex,
order: newSlideOrderIndex,
});
} else {
row = Math.floor(i / slidesPerRow);
column = i - (row * slidesPerRow);
}
slide
.css(
`margin-${swiper.isHorizontal() ? 'top' : 'left'}`,
(row !== 0 && params.spaceBetween) && (`${params.spaceBetween}px`)
)
.attr('data-swiper-column', column)
.attr('data-swiper-row', row);
}
if (slide.css('display') === 'none') continue; // eslint-disable-line
if (params.slidesPerView === 'auto') {
slideSize = swiper.isHorizontal() ? slide.outerWidth(true) : slide.outerHeight(true);
if (params.roundLengths) slideSize = Math.floor(slideSize);
} else {
slideSize = (swiperSize - ((params.slidesPerView - 1) * spaceBetween)) / params.slidesPerView;
if (params.roundLengths) slideSize = Math.floor(slideSize);
if (slides[i]) {
if (swiper.isHorizontal()) {
slides[i].style.width = `${slideSize}px`;
} else {
slides[i].style.height = `${slideSize}px`;
}
}
}
if (slides[i]) {
slides[i].swiperSlideSize = slideSize;
}
slidesSizesGrid.push(slideSize);
if (params.centeredSlides) {
slidePosition = slidePosition + (slideSize / 2) + (prevSlideSize / 2) + spaceBetween;
if (prevSlideSize === 0 && i !== 0) slidePosition = slidePosition - (swiperSize / 2) - spaceBetween;
if (i === 0) slidePosition = slidePosition - (swiperSize / 2) - spaceBetween;
if (Math.abs(slidePosition) < 1 / 1000) slidePosition = 0;
if ((index) % params.slidesPerGroup === 0) snapGrid.push(slidePosition);
slidesGrid.push(slidePosition);
} else {
if ((index) % params.slidesPerGroup === 0) snapGrid.push(slidePosition);
slidesGrid.push(slidePosition);
slidePosition = slidePosition + slideSize + spaceBetween;
}
swiper.virtualSize += slideSize + spaceBetween;
prevSlideSize = slideSize;
index += 1;
}
swiper.virtualSize = Math.max(swiper.virtualSize, swiperSize) + offsetAfter;
let newSlidesGrid;
if (
rtl && wrongRTL && (params.effect === 'slide' || params.effect === 'coverflow')) {
$wrapperEl.css({ width: `${swiper.virtualSize + params.spaceBetween}px` });
}
if (!Support$1.flexbox || params.setWrapperSize) {
if (swiper.isHorizontal()) $wrapperEl.css({ width: `${swiper.virtualSize + params.spaceBetween}px` });
else $wrapperEl.css({ height: `${swiper.virtualSize + params.spaceBetween}px` });
}
if (params.slidesPerColumn > 1) {
swiper.virtualSize = (slideSize + params.spaceBetween) * slidesNumberEvenToRows;
swiper.virtualSize = Math.ceil(swiper.virtualSize / params.slidesPerColumn) - params.spaceBetween;
if (swiper.isHorizontal()) $wrapperEl.css({ width: `${swiper.virtualSize + params.spaceBetween}px` });
else $wrapperEl.css({ height: `${swiper.virtualSize + params.spaceBetween}px` });
if (params.centeredSlides) {
newSlidesGrid = [];
for (let i = 0; i < snapGrid.length; i += 1) {
if (snapGrid[i] < swiper.virtualSize + snapGrid[0]) newSlidesGrid.push(snapGrid[i]);
}
snapGrid = newSlidesGrid;
}
}
// Remove last grid elements depending on width
if (!params.centeredSlides) {
newSlidesGrid = [];
for (let i = 0; i < snapGrid.length; i += 1) {
if (snapGrid[i] <= swiper.virtualSize - swiperSize) {
newSlidesGrid.push(snapGrid[i]);
}
}
snapGrid = newSlidesGrid;
if (Math.floor(swiper.virtualSize - swiperSize) - Math.floor(snapGrid[snapGrid.length - 1]) > 1) {
snapGrid.push(swiper.virtualSize - swiperSize);
}
}
if (snapGrid.length === 0) snapGrid = [0];
if (params.spaceBetween !== 0) {
if (swiper.isHorizontal()) {
if (rtl) slides.css({ marginLeft: `${spaceBetween}px` });
else slides.css({ marginRight: `${spaceBetween}px` });
} else slides.css({ marginBottom: `${spaceBetween}px` });
}
Utils.extend(swiper, {
slides,
snapGrid,
slidesGrid,
slidesSizesGrid,
});
if (slidesLength !== previousSlidesLength) {
swiper.emit('slidesLengthChange');
}
if (snapGrid.length !== previousSnapGridLength) {
swiper.emit('snapGridLengthChange');
}
if (slidesGrid.length !== previousSlidesGridLength) {
swiper.emit('slidesGridLengthChange');
}
if (params.watchSlidesProgress || params.watchSlidesVisibility) {
swiper.updateSlidesOffset();
}
};
var updateAutoHeight = function () {
const swiper = this;
const activeSlides = [];
let newHeight = 0;
let i;
// Find slides currently in view
if (swiper.params.slidesPerView !== 'auto' && swiper.params.slidesPerView > 1) {
for (i = 0; i < Math.ceil(swiper.params.slidesPerView); i += 1) {
const index = swiper.activeIndex + i;
if (index > swiper.slides.length) break;
activeSlides.push(swiper.slides.eq(index)[0]);
}
} else {
activeSlides.push(swiper.slides.eq(swiper.activeIndex)[0]);
}
// Find new height from highest slide in view
for (i = 0; i < activeSlides.length; i += 1) {
if (typeof activeSlides[i] !== 'undefined') {
const height = activeSlides[i].offsetHeight;
newHeight = height > newHeight ? height : newHeight;
}
}
// Update Height
if (newHeight) swiper.$wrapperEl.css('height', `${newHeight}px`);
};
var updateSlidesOffset = function () {
const swiper = this;
const slides = swiper.slides;
for (let i = 0; i < slides.length; i += 1) {
slides[i].swiperSlideOffset = swiper.isHorizontal() ? slides[i].offsetLeft : slides[i].offsetTop;
}
};
var updateSlidesProgress = function (translate = this.translate || 0) {
const swiper = this;
const params = swiper.params;
const { slides, rtl } = swiper;
if (slides.length === 0) return;
if (typeof slides[0].swiperSlideOffset === 'undefined') swiper.updateSlidesOffset();
let offsetCenter = -translate;
if (rtl) offsetCenter = translate;
// Visible Slides
slides.removeClass(params.slideVisibleClass);
for (let i = 0; i < slides.length; i += 1) {
const slide = slides[i];
const slideProgress =
(
(offsetCenter + (params.centeredSlides ? swiper.minTranslate() : 0)) - slide.swiperSlideOffset
) / (slide.swiperSlideSize + params.spaceBetween);
if (params.watchSlidesVisibility) {
const slideBefore = -(offsetCenter - slide.swiperSlideOffset);
const slideAfter = slideBefore + swiper.slidesSizesGrid[i];
const isVisible =
(slideBefore >= 0 && slideBefore < swiper.size) ||
(slideAfter > 0 && slideAfter <= swiper.size) ||
(slideBefore <= 0 && slideAfter >= swiper.size);
if (isVisible) {
slides.eq(i).addClass(params.slideVisibleClass);
}
}
slide.progress = rtl ? -slideProgress : slideProgress;
}
};
var updateProgress = function (translate = this.translate || 0) {
const swiper = this;
const params = swiper.params;
const translatesDiff = swiper.maxTranslate() - swiper.minTranslate();
let { progress, isBeginning, isEnd } = swiper;
const wasBeginning = isBeginning;
const wasEnd = isEnd;
if (translatesDiff === 0) {
progress = 0;
isBeginning = true;
isEnd = true;
} else {
progress = (translate - swiper.minTranslate()) / (translatesDiff);
isBeginning = progress <= 0;
isEnd = progress >= 1;
}
Utils.extend(swiper, {
progress,
isBeginning,
isEnd,
});
if (params.watchSlidesProgress || params.watchSlidesVisibility) swiper.updateSlidesProgress(translate);
if (isBeginning && !wasBeginning) {
swiper.emit('reachBeginning toEdge');
}
if (isEnd && !wasEnd) {
swiper.emit('reachEnd toEdge');
}
if ((wasBeginning && !isBeginning) || (wasEnd && !isEnd)) {
swiper.emit('fromEdge');
}
swiper.emit('progress', progress);
};
var updateSlidesClasses = function () {
const swiper = this;
const { slides, params, $wrapperEl, activeIndex, realIndex } = swiper;
const isVirtual = swiper.virtual && params.virtual.enabled;
slides.removeClass(`${params.slideActiveClass} ${params.slideNextClass} ${params.slidePrevClass} ${params.slideDuplicateActiveClass} ${params.slideDuplicateNextClass} ${params.slideDuplicatePrevClass}`);
let activeSlide;
if (isVirtual) {
activeSlide = swiper.$wrapperEl.find(`.${params.slideClass}[data-swiper-slide-index="${activeIndex}"]`);
} else {
activeSlide = slides.eq(activeIndex);
}
// Active classes
activeSlide.addClass(params.slideActiveClass);
if (params.loop) {
// Duplicate to all looped slides
if (activeSlide.hasClass(params.slideDuplicateClass)) {
$wrapperEl
.children(`.${params.slideClass}:not(.${params.slideDuplicateClass})[data-swiper-slide-index="${realIndex}"]`)
.addClass(params.slideDuplicateActiveClass);
} else {
$wrapperEl
.children(`.${params.slideClass}.${params.slideDuplicateClass}[data-swiper-slide-index="${realIndex}"]`)
.addClass(params.slideDuplicateActiveClass);
}
}
// Next Slide
let nextSlide = activeSlide.nextAll(`.${params.slideClass}`).eq(0).addClass(params.slideNextClass);
if (params.loop && nextSlide.length === 0) {
nextSlide = slides.eq(0);
nextSlide.addClass(params.slideNextClass);
}
// Prev Slide
let prevSlide = activeSlide.prevAll(`.${params.slideClass}`).eq(0).addClass(params.slidePrevClass);
if (params.loop && prevSlide.length === 0) {
prevSlide = slides.eq(-1);
prevSlide.addClass(params.slidePrevClass);
}
if (params.loop) {
// Duplicate to all looped slides
if (nextSlide.hasClass(params.slideDuplicateClass)) {
$wrapperEl
.children(`.${params.slideClass}:not(.${params.slideDuplicateClass})[data-swiper-slide-index="${nextSlide.attr('data-swiper-slide-index')}"]`)
.addClass(params.slideDuplicateNextClass);
} else {
$wrapperEl
.children(`.${params.slideClass}.${params.slideDuplicateClass}[data-swiper-slide-index="${nextSlide.attr('data-swiper-slide-index')}"]`)
.addClass(params.slideDuplicateNextClass);
}
if (prevSlide.hasClass(params.slideDuplicateClass)) {
$wrapperEl
.children(`.${params.slideClass}:not(.${params.slideDuplicateClass})[data-swiper-slide-index="${prevSlide.attr('data-swiper-slide-index')}"]`)
.addClass(params.slideDuplicatePrevClass);
} else {
$wrapperEl
.children(`.${params.slideClass}.${params.slideDuplicateClass}[data-swiper-slide-index="${prevSlide.attr('data-swiper-slide-index')}"]`)
.addClass(params.slideDuplicatePrevClass);
}
}
};
var updateActiveIndex = function (newActiveIndex) {
const swiper = this;
const translate = swiper.rtl ? swiper.translate : -swiper.translate;
const { slidesGrid, snapGrid, params, activeIndex: previousIndex, realIndex: previousRealIndex, snapIndex: previousSnapIndex } = swiper;
let activeIndex = newActiveIndex;
let snapIndex;
if (typeof activeIndex === 'undefined') {
for (let i = 0; i < slidesGrid.length; i += 1) {
if (typeof slidesGrid[i + 1] !== 'undefined') {
if (translate >= slidesGrid[i] && translate < slidesGrid[i + 1] - ((slidesGrid[i + 1] - slidesGrid[i]) / 2)) {
activeIndex = i;
} else if (translate >= slidesGrid[i] && translate < slidesGrid[i + 1]) {
activeIndex = i + 1;
}
} else if (translate >= slidesGrid[i]) {
activeIndex = i;
}
}
// Normalize slideIndex
if (params.normalizeSlideIndex) {
if (activeIndex < 0 || typeof activeIndex === 'undefined') activeIndex = 0;
}
}
if (snapGrid.indexOf(translate) >= 0) {
snapIndex = snapGrid.indexOf(translate);
} else {
snapIndex = Math.floor(activeIndex / params.slidesPerGroup);
}
if (snapIndex >= snapGrid.length) snapIndex = snapGrid.length - 1;
if (activeIndex === previousIndex) {
if (snapIndex !== previousSnapIndex) {
swiper.snapIndex = snapIndex;
swiper.emit('snapIndexChange');
}
return;
}
// Get real index
const realIndex = parseInt(swiper.slides.eq(activeIndex).attr('data-swiper-slide-index') || activeIndex, 10);
Utils.extend(swiper, {
snapIndex,
realIndex,
previousIndex,
activeIndex,
});
swiper.emit('activeIndexChange');
swiper.emit('snapIndexChange');
if (previousRealIndex !== realIndex) {
swiper.emit('realIndexChange');
}
swiper.emit('slideChange');
};
var updateClickedSlide = function (e) {
const swiper = this;
const params = swiper.params;
const slide = $(e.target).closest(`.${params.slideClass}`)[0];
let slideFound = false;
if (slide) {
for (let i = 0; i < swiper.slides.length; i += 1) {
if (swiper.slides[i] === slide) slideFound = true;
}
}
if (slide && slideFound) {
swiper.clickedSlide = slide;
if (swiper.virtual && swiper.params.virtual.enabled) {
swiper.clickedIndex = parseInt($(slide).attr('data-swiper-slide-index'), 10);
} else {
swiper.clickedIndex = $(slide).index();
}
} else {
swiper.clickedSlide = undefined;
swiper.clickedIndex = undefined;
return;
}
if (params.slideToClickedSlide && swiper.clickedIndex !== undefined && swiper.clickedIndex !== swiper.activeIndex) {
swiper.slideToClickedSlide();
}
};
var update = {
updateSize,
updateSlides,
updateAutoHeight,
updateSlidesOffset,
updateSlidesProgress,
updateProgress,
updateSlidesClasses,
updateActiveIndex,
updateClickedSlide,
};
var getTranslate = function (axis = this.isHorizontal() ? 'x' : 'y') {
const swiper = this;
const { params, rtl, translate, $wrapperEl } = swiper;
if (params.virtualTranslate) {
return rtl ? -translate : translate;
}
let currentTranslate = Utils.getTranslate($wrapperEl[0], axis);
if (rtl) currentTranslate = -currentTranslate;
return currentTranslate || 0;
};
var setTranslate = function (translate, byController) {
const swiper = this;
const { rtl, params, $wrapperEl, progress } = swiper;
let x = 0;
let y = 0;
const z = 0;
if (swiper.isHorizontal()) {
x = rtl ? -translate : translate;
} else {
y = translate;
}
if (params.roundLengths) {
x = Math.floor(x);
y = Math.floor(y);
}
if (!params.virtualTranslate) {
if (Support$1.transforms3d) $wrapperEl.transform(`translate3d(${x}px, ${y}px, ${z}px)`);
else $wrapperEl.transform(`translate(${x}px, ${y}px)`);
}
swiper.translate = swiper.isHorizontal() ? x : y;
// Check if we need to update progress
let newProgress;
const translatesDiff = swiper.maxTranslate() - swiper.minTranslate();
if (translatesDiff === 0) {
newProgress = 0;
} else {
newProgress = (translate - swiper.minTranslate()) / (translatesDiff);
}
if (newProgress !== progress) {
swiper.updateProgress(translate);
}
swiper.emit('setTranslate', swiper.translate, byController);
};
var minTranslate = function () {
return (-this.snapGrid[0]);
};
var maxTranslate = function () {
return (-this.snapGrid[this.snapGrid.length - 1]);
};
var translate = {
getTranslate,
setTranslate,
minTranslate,
maxTranslate,
};
var setTransition = function (duration, byController) {
const swiper = this;
swiper.$wrapperEl.transition(duration);
swiper.emit('setTransition', duration, byController);
};
var transitionStart = function (runCallbacks = true) {
const swiper = this;
const { activeIndex, params, previousIndex } = swiper;
if (params.autoHeight) {
swiper.updateAutoHeight();
}
swiper.emit('transitionStart');
if (!runCallbacks) return;
if (activeIndex !== previousIndex) {
swiper.emit('slideChangeTransitionStart');
if (activeIndex > previousIndex) {
swiper.emit('slideNextTransitionStart');
} else {
swiper.emit('slidePrevTransitionStart');
}
}
};
var transitionEnd = function (runCallbacks = true) {
const swiper = this;
const { activeIndex, previousIndex } = swiper;
swiper.animating = false;
swiper.setTransition(0);
swiper.emit('transitionEnd');
if (runCallbacks) {
if (activeIndex !== previousIndex) {
swiper.emit('slideChangeTransitionEnd');
if (activeIndex > previousIndex) {
swiper.emit('slideNextTransitionEnd');
} else {
swiper.emit('slidePrevTransitionEnd');
}
}
}
};
var transition = {
setTransition,
transitionStart,
transitionEnd,
};
const Browser = (function Browser() {
function isIE9() {
// create temporary DIV
const div = document.createElement('div');
// add content to tmp DIV which is wrapped into the IE HTML conditional statement
div.innerHTML = '<!--[if lte IE 9]><i></i><![endif]-->';
// return true / false value based on what will browser render
return div.getElementsByTagName('i').length === 1;
}
function isSafari() {
const ua = window.navigator.userAgent.toLowerCase();
return (ua.indexOf('safari') >= 0 && ua.indexOf('chrome') < 0 && ua.indexOf('android') < 0);
}
return {
isSafari: isSafari(),
isUiWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(window.navigator.userAgent),
ie: window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
ieTouch: (window.navigator.msPointerEnabled && window.navigator.msMaxTouchPoints > 1) ||
(window.navigator.pointerEnabled && window.navigator.maxTouchPoints > 1),
lteIE9: isIE9(),
};
}());
var slideTo = function (index = 0, speed = this.params.speed, runCallbacks = true, internal) {
const swiper = this;
let slideIndex = index;
if (slideIndex < 0) slideIndex = 0;
const { params, snapGrid, slidesGrid, previousIndex, activeIndex, rtl, $wrapperEl } = swiper;
let snapIndex = Math.floor(slideIndex / params.slidesPerGroup);
if (snapIndex >= snapGrid.length) snapIndex = snapGrid.length - 1;
if ((activeIndex || params.initialSlide || 0) === (previousIndex || 0) && runCallbacks) {
swiper.emit('beforeSlideChangeStart');
}
const translate = -snapGrid[snapIndex];
// Update progress
swiper.updateProgress(translate);
// Normalize slideIndex
if (params.normalizeSlideIndex) {
for (let i = 0; i < slidesGrid.length; i += 1) {
if (-Math.floor(translate * 100) >= Math.floor(slidesGrid[i] * 100)) {
slideIndex = i;
}
}
}
// Directions locks
if (!swiper.allowSlideNext && translate < swiper.translate && translate < swiper.minTranslate()) {
return false;
}
if (!swiper.allowSlidePrev && translate > swiper.translate && translate > swiper.maxTranslate()) {
if ((activeIndex || 0) !== slideIndex) return false;
}
// Update Index
if ((rtl && -translate === swiper.translate) || (!rtl && translate === swiper.translate)) {
swiper.updateActiveIndex(slideIndex);
// Update Height
if (params.autoHeight) {
swiper.updateAutoHeight();
}
swiper.updateSlidesClasses();
if (params.effect !== 'slide') {
swiper.setTranslate(translate);
}
return false;
}
if (speed === 0 || Browser.lteIE9) {
swiper.setTransition(0);
swiper.setTranslate(translate);
swiper.updateActiveIndex(slideIndex);
swiper.updateSlidesClasses();
swiper.emit('beforeTransitionStart', speed, internal);
swiper.transitionStart(runCallbacks);
swiper.transitionEnd(runCallbacks);
} else {
swiper.setTransition(speed);
swiper.setTranslate(translate);
swiper.updateActiveIndex(slideIndex);
swiper.updateSlidesClasses();
swiper.emit('beforeTransitionStart', speed, internal);
swiper.transitionStart(runCallbacks);
if (!swiper.animating) {
swiper.animating = true;
$wrapperEl.transitionEnd(() => {
if (!swiper || swiper.destroyed) return;
swiper.transitionEnd(runCallbacks);
});
}
}
return true;
};
/* eslint no-unused-vars: "off" */
var slideNext = function (speed = this.params.speed, runCallbacks = true, internal) {
const swiper = this;
const { params, animating } = swiper;
if (params.loop) {
if (animating) return false;
swiper.loopFix();
// eslint-disable-next-line
swiper._clientLeft = swiper.$wrapperEl[0].clientLeft;
return swiper.slideTo(swiper.activeIndex + params.slidesPerGroup, speed, runCallbacks, internal);
}
return swiper.slideTo(swiper.activeIndex + params.slidesPerGroup, speed, runCallbacks, internal);
};
/* eslint no-unused-vars: "off" */
var slidePrev = function (speed = this.params.speed, runCallbacks = true, internal) {
const swiper = this;
const { params, animating } = swiper;
if (params.loop) {
if (animating) return false;
swiper.loopFix();
// eslint-disable-next-line
swiper._clientLeft = swiper.$wrapperEl[0].clientLeft;
return swiper.slideTo(swiper.activeIndex - 1, speed, runCallbacks, internal);
}
return swiper.slideTo(swiper.activeIndex - 1, speed, runCallbacks, internal);
};
/* eslint no-unused-vars: "off" */
var slideReset = function (speed = this.params.speed, runCallbacks = true, internal) {
const swiper = this;
return swiper.slideTo(swiper.activeIndex, speed, runCallbacks, internal);
};
var slideToClickedSlide = function () {
const swiper = this;
const { params, $wrapperEl } = swiper;
const slidesPerView = params.slidesPerView === 'auto' ? swiper.slidesPerViewDynamic() : params.slidesPerView;
let slideToIndex = swiper.clickedIndex;
let realIndex;
if (params.loop) {
if (swiper.animating) return;
realIndex = parseInt($(swiper.clickedSlide).attr('data-swiper-slide-index'), 10);
if (params.centeredSlides) {
if (
(slideToIndex < swiper.loopedSlides - (slidesPerView / 2)) ||
(slideToIndex > (swiper.slides.length - swiper.loopedSlides) + (slidesPerView / 2))
) {
swiper.loopFix();
slideToIndex = $wrapperEl
.children(`.${params.slideClass}[data-swiper-slide-index="${realIndex}"]:not(.${params.slideDuplicateClass})`)
.eq(0)
.index();
Utils.nextTick(() => {
swiper.slideTo(slideToIndex);
});
} else {
swiper.slideTo(slideToIndex);
}
} else if (slideToIndex > swiper.slides.length - slidesPerView) {
swiper.loopFix();
slideToIndex = $wrapperEl
.children(`.${params.slideClass}[data-swiper-slide-index="${realIndex}"]:not(.${params.slideDuplicateClass})`)
.eq(0)
.index();
Utils.nextTick(() => {
swiper.slideTo(slideToIndex);
});
} else {
swiper.slideTo(slideToIndex);
}
} else {
swiper.slideTo(slideToIndex);
}
};
var slide = {
slideTo,
slideNext,
slidePrev,
slideReset,
slideToClickedSlide,
};
var loopCreate = function () {
const swiper = this;
const { params, $wrapperEl } = swiper;
// Remove duplicated slides
$wrapperEl.children(`.${params.slideClass}.${params.slideDuplicateClass}`).remove();
let slides = $wrapperEl.children(`.${params.slideClass}`);
if (params.loopFillGroupWithBlank) {
const blankSlidesNum = params.slidesPerGroup - (slides.length % params.slidesPerGroup);
if (blankSlidesNum !== params.slidesPerGroup) {
for (let i = 0; i < blankSlidesNum; i += 1) {
const blankNode = $(document.createElement('div')).addClass(`${params.slideClass} ${params.slideBlankClass}`);
$wrapperEl.append(blankNode);
}
slides = $wrapperEl.children(`.${params.slideClass}`);
}
}
if (params.slidesPerView === 'auto' && !params.loopedSlides) params.loopedSlides = slides.length;
swiper.loopedSlides = parseInt(params.loopedSlides || params.slidesPerView, 10);
swiper.loopedSlides += params.loopAdditionalSlides;
if (swiper.loopedSlides > slides.length) {
swiper.loopedSlides = slides.length;
}
const prependSlides = [];
const appendSlides = [];
slides.each((index, el) => {
const slide = $(el);
if (index < swiper.loopedSlides) appendSlides.push(el);
if (index < slides.length && index >= slides.length - swiper.loopedSlides) prependSlides.push(el);
slide.attr('data-swiper-slide-index', index);
});
for (let i = 0; i < appendSlides.length; i += 1) {
$wrapperEl.append($(appendSlides[i].cloneNode(true)).addClass(params.slideDuplicateClass));
}
for (let i = prependSlides.length - 1; i >= 0; i -= 1) {
$wrapperEl.prepend($(prependSlides[i].cloneNode(true)).addClass(params.slideDuplicateClass));
}
};
var loopFix = function () {
const swiper = this;
const { params, activeIndex, slides, loopedSlides, allowSlidePrev, allowSlideNext } = swiper;
let newIndex;
swiper.allowSlidePrev = true;
swiper.allowSlideNext = true;
// Fix For Negative Oversliding
if (activeIndex < loopedSlides) {
newIndex = (slides.length - (loopedSlides * 3)) + activeIndex;
newIndex += loopedSlides;
swiper.slideTo(newIndex, 0, false, true);
} else if ((params.slidesPerView === 'auto' && activeIndex >= loopedSlides * 2) || (activeIndex > slides.length - (params.slidesPerView * 2))) {
// Fix For Positive Oversliding
newIndex = -slides.length + activeIndex + loopedSlides;
newIndex += loopedSlides;
swiper.slideTo(newIndex, 0, false, true);
}
swiper.allowSlidePrev = allowSlidePrev;
swiper.allowSlideNext = allowSlideNext;
};
var loopDestroy = function () {
const swiper = this;
const { $wrapperEl, params, slides } = swiper;
$wrapperEl.children(`.${params.slideClass}.${params.slideDuplicateClass}`).remove();
slides.removeAttr('data-swiper-slide-index');
};
var loop = {
loopCreate,
loopFix,
loopDestroy,
};
var setGrabCursor = function (moving) {
const swiper = this;
if (Support$1.touch || !swiper.params.simulateTouch) return;
const el = swiper.el;
el.style.cursor = 'move';
el.style.cursor = moving ? '-webkit-grabbing' : '-webkit-grab';
el.style.cursor = moving ? '-moz-grabbin' : '-moz-grab';
el.style.cursor = moving ? 'grabbing' : 'grab';
};
var unsetGrabCursor = function () {
const swiper = this;
if (Support$1.touch) return;
swiper.el.style.cursor = '';
};
var grabCursor = {
setGrabCursor,
unsetGrabCursor,
};
var appendSlide = function (slides) {
const swiper = this;
const { $wrapperEl, params } = swiper;
if (params.loop) {
swiper.loopDestroy();
}
if (typeof slides === 'object' && 'length' in slides) {
for (let i = 0; i < slides.length; i += 1) {
if (slides[i]) $wrapperEl.append(slides[i]);
}
} else {
$wrapperEl.append(slides);
}
if (params.loop) {
swiper.loopCreate();
}
if (!(params.observer && Support$1.observer)) {
swiper.update();
}
};
var prependSlide = function (slides) {
const swiper = this;
const { params, $wrapperEl, activeIndex } = swiper;
if (params.loop) {
swiper.loopDestroy();
}
let newActiveIndex = activeIndex + 1;
if (typeof slides === 'object' && 'length' in slides) {
for (let i = 0; i < slides.length; i += 1) {
if (slides[i]) $wrapperEl.prepend(slides[i]);
}
newActiveIndex = activeIndex + slides.length;
} else {
$wrapperEl.prepend(slides);
}
if (params.loop) {
swiper.loopCreate();
}
if (!(params.observer && Support$1.observer)) {
swiper.update();
}
swiper.slideTo(newActiveIndex, 0, false);
};
var removeSlide = function (slidesIndexes) {
const swiper = this;
const { params, $wrapperEl, activeIndex } = swiper;
if (params.loop) {
swiper.loopDestroy();
swiper.slides = $wrapperEl.children(`.${params.slideClass}`);
}
let newActiveIndex = activeIndex;
let indexToRemove;
if (typeof slidesIndexes === 'object' && 'length' in slidesIndexes) {
for (let i = 0; i < slidesIndexes.length; i += 1) {
indexToRemove = slidesIndexes[i];
if (swiper.slides[indexToRemove]) swiper.slides.eq(indexToRemove).remove();
if (indexToRemove < newActiveIndex) newActiveIndex -= 1;
}
newActiveIndex = Math.max(newActiveIndex, 0);
} else {
indexToRemove = slidesIndexes;
if (swiper.slides[indexToRemove]) swiper.slides.eq(indexToRemove).remove();
if (indexToRemove < newActiveIndex) newActiveIndex -= 1;
newActiveIndex = Math.max(newActiveIndex, 0);
}
if (params.loop) {
swiper.loopCreate();
}
if (!(params.observer && Support$1.observer)) {
swiper.update();
}
if (params.loop) {
swiper.slideTo(newActiveIndex + swiper.loopedSlides, 0, false);
} else {
swiper.slideTo(newActiveIndex, 0, false);
}
};
var removeAllSlides = function () {
const swiper = this;
const slidesIndexes = [];
for (let i = 0; i < swiper.slides.length; i += 1) {
slidesIndexes.push(i);
}
swiper.removeSlide(slidesIndexes);
};
var manipulation = {
appendSlide,
prependSlide,
removeSlide,
removeAllSlides,
};
var onTouchStart = function (event) {
const swiper = this;
const data = swiper.touchEventsData;
const { params, touches } = swiper;
let e = event;
if (e.originalEvent) e = e.originalEvent;
data.isTouchEvent = e.type === 'touchstart';
if (!data.isTouchEvent && 'which' in e && e.which === 3) return;
if (data.isTouched && data.isMoved) return;
if (params.noSwiping && $(e.target).closest(`.${params.noSwipingClass}`)[0]) {
swiper.allowClick = true;
return;
}
if (params.swipeHandler) {
if (!$(e).closest(params.swipeHandler)[0]) return;
}
touches.currentX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touches.currentY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
const startX = touches.currentX;
const startY = touches.currentY;
// Do NOT start if iOS edge swipe is detected. Otherwise iOS app (UIWebView) cannot swipe-to-go-back anymore
if (
Device.ios &&
!Device.cordova &&
params.iOSEdgeSwipeDetection &&
(startX <= params.iOSEdgeSwipeThreshold) &&
(startX >= window.screen.width - params.iOSEdgeSwipeThreshold)
) {
return;
}
Utils.extend(data, {
isTouched: true,
isMoved: false,
allowTouchCallbacks: true,
isScrolling: undefined,
startMoving: undefined,
});
touches.startX = startX;
touches.startY = startY;
data.touchStartTime = Utils.now();
swiper.allowClick = true;
swiper.updateSize();
swiper.swipeDirection = undefined;
if (params.threshold > 0) data.allowThresholdMove = false;
if (e.type !== 'touchstart') {
let preventDefault = true;
if ($(e.target).is(data.formElements)) preventDefault = false;
if (document.activeElement && $(document.activeElement).is(data.formElements)) {
document.activeElement.blur();
}
if (preventDefault && swiper.allowTouchMove) {
e.preventDefault();
}
}
swiper.emit('touchStart', e);
};
var onTouchMove = function (event) {
const swiper = this;
const data = swiper.touchEventsData;
const { params, touches, rtl } = swiper;
let e = event;
if (e.originalEvent) e = e.originalEvent;
if (data.isTouchEvent && e.type === 'mousemove') return;
const pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (e.preventedByNestedSwiper) {
touches.startX = pageX;
touches.startY = pageY;
return;
}
if (!swiper.allowTouchMove) {
// isMoved = true;
swiper.allowClick = false;
if (data.isTouched) {
Utils.extend(touches, {
startX: pageX,
startY: pageY,
currentX: pageX,
currentY: pageY,
});
data.touchStartTime = Utils.now();
}
return;
}
if (data.isTouchEvent && params.touchReleaseOnEdges && !params.loop) {
if (swiper.isVertical()) {
// Vertical
if (
(pageY < touches.startY && swiper.translate <= swiper.maxTranslate()) ||
(pageY > touches.startY && swiper.translate >= swiper.minTranslate())
) {
data.isTouched = false;
data.isMoved = false;
return;
}
} else if (
(pageX < touches.startX && swiper.translate <= swiper.maxTranslate()) ||
(pageX > touches.startX && swiper.translate >= swiper.minTranslate())
) {
return;
}
}
if (data.isTouchEvent && document.activeElement) {
if (e.target === document.activeElement && $(e.target).is(data.formElements)) {
data.isMoved = true;
swiper.allowClick = false;
return;
}
}
if (data.allowTouchCallbacks) {
swiper.emit('touchMove', e);
}
if (e.targetTouches && e.targetTouches.length > 1) return;
touches.currentX = pageX;
touches.currentY = pageY;
const diffX = touches.currentX - touches.startX;
const diffY = touches.currentY - touches.startY;
if (typeof data.isScrolling === 'undefined') {
let touchAngle;
if ((swiper.isHorizontal() && touches.currentY === touches.startY) || (swiper.isVertical() && touches.currentX === touches.startX)) {
data.isScrolling = false;
} else {
// eslint-disable-next-line
if ((diffX * diffX) + (diffY * diffY) >= 25) {
touchAngle = (Math.atan2(Math.abs(diffY), Math.abs(diffX)) * 180) / Math.PI;
data.isScrolling = swiper.isHorizontal() ? touchAngle > params.touchAngle : (90 - touchAngle > params.touchAngle);
}
}
}
if (data.isScrolling) {
swiper.emit('touchMoveOpposite', e);
}
if (typeof startMoving === 'undefined') {
if (touches.currentX !== touches.startX || touches.currentY !== touches.startY) {
data.startMoving = true;
}
}
if (!data.isTouched) return;
if (data.isScrolling) {
data.isTouched = false;
return;
}
if (!data.startMoving) {
return;
}
swiper.allowClick = false;
e.preventDefault();
if (params.touchMoveStopPropagation && !params.nested) {
e.stopPropagation();
}
if (!data.isMoved) {
if (params.loop) {
swiper.loopFix();
}
data.startTranslate = swiper.getTranslate();
swiper.setTransition(0);
if (swiper.animating) {
swiper.$wrapperEl.trigger('webkitTransitionEnd transitionend');
}
data.allowMomentumBounce = false;
// Grab Cursor
if (params.grabCursor && (swiper.allowSlideNext === true || swiper.allowSlidePrev === true)) {
swiper.setGrabCursor(true);
}
swiper.emit('sliderFirstMove', e);
}
swiper.emit('sliderMove', e);
data.isMoved = true;
let diff = swiper.isHorizontal() ? diffX : diffY;
touches.diff = diff;
diff *= params.touchRatio;
if (rtl) diff = -diff;
swiper.swipeDirection = diff > 0 ? 'prev' : 'next';
data.currentTranslate = diff + data.startTranslate;
let disableParentSwiper = true;
let resistanceRatio = params.resistanceRatio;
if (params.touchReleaseOnEdges) {
resistanceRatio = 0;
}
if ((diff > 0 && data.currentTranslate > swiper.minTranslate())) {
disableParentSwiper = false;
if (params.resistance) data.currentTranslate = (swiper.minTranslate() - 1) + ((-swiper.minTranslate() + data.startTranslate + diff) ** resistanceRatio);
} else if (diff < 0 && data.currentTranslate < swiper.maxTranslate()) {
disableParentSwiper = false;
if (params.resistance) data.currentTranslate = (swiper.maxTranslate() + 1) - ((swiper.maxTranslate() - data.startTranslate - diff) ** resistanceRatio);
}
if (disableParentSwiper) {
e.preventedByNestedSwiper = true;
}
// Directions locks
if (!swiper.allowSlideNext && swiper.swipeDirection === 'next' && data.currentTranslate < data.startTranslate) {
data.currentTranslate = data.startTranslate;
}
if (!swiper.allowSlidePrev && swiper.swipeDirection === 'prev' && data.currentTranslate > data.startTranslate) {
data.currentTranslate = data.startTranslate;
}
// Threshold
if (params.threshold > 0) {
if (Math.abs(diff) > params.threshold || data.allowThresholdMove) {
if (!data.allowThresholdMove) {
data.allowThresholdMove = true;
touches.startX = touches.currentX;
touches.startY = touches.currentY;
data.currentTranslate = data.startTranslate;
touches.diff = swiper.isHorizontal() ? touches.currentX - touches.startX : touches.currentY - touches.startY;
return;
}
} else {
data.currentTranslate = data.startTranslate;
return;
}
}
if (!params.followFinger) return;
// Update active index in free mode
if (params.freeMode || params.watchSlidesProgress || params.watchSlidesVisibility) {
swiper.updateActiveIndex();
swiper.updateSlidesClasses();
}
if (params.freeMode) {
// Velocity
if (data.velocities.length === 0) {
data.velocities.push({
position: touches[swiper.isHorizontal() ? 'startX' : 'startY'],
time: data.touchStartTime,
});
}
data.velocities.push({
position: touches[swiper.isHorizontal() ? 'currentX' : 'currentY'],
time: Utils.now(),
});
}
// Update progress
swiper.updateProgress(data.currentTranslate);
// Update translate
swiper.setTranslate(data.currentTranslate);
};
var onTouchEnd = function (event) {
const swiper = this;
const data = swiper.touchEventsData;
const { params, touches, rtl, $wrapperEl, slidesGrid, snapGrid } = swiper;
let e = event;
if (e.originalEvent) e = e.originalEvent;
if (data.allowTouchCallbacks) {
swiper.emit('touchEnd', e);
}
data.allowTouchCallbacks = false;
if (!data.isTouched) return;
// Return Grab Cursor
if (params.grabCursor && data.isMoved && data.isTouched && (swiper.allowSlideNext === true || swiper.allowSlidePrev === true)) {
swiper.setGrabCursor(false);
}
// Time diff
const touchEndTime = Utils.now();
const timeDiff = touchEndTime - data.touchStartTime;
// Tap, doubleTap, Click
if (swiper.allowClick) {
swiper.updateClickedSlide(e);
swiper.emit('tap', e);
if (timeDiff < 300 && (touchEndTime - data.lastClickTime) > 300) {
if (data.clickTimeout) clearTimeout(data.clickTimeout);
data.clickTimeout = Utils.nextTick(() => {
if (!swiper || swiper.destroyed) return;
swiper.emit('click', e);
}, 300);
}
if (timeDiff < 300 && (touchEndTime - data.lastClickTime) < 300) {
if (data.clickTimeout) clearTimeout(data.clickTimeout);
swiper.emit('doubleTap', e);
}
}
data.lastClickTime = Utils.now();
Utils.nextTick(() => {
if (!swiper.destroyed) swiper.allowClick = true;
});
if (!data.isTouched || !data.isMoved || !swiper.swipeDirection || touches.diff === 0 || data.currentTranslate === data.startTranslate) {
data.isTouched = false;
data.isMoved = false;
return;
}
data.isTouched = false;
data.isMoved = false;
let currentPos;
if (params.followFinger) {
currentPos = rtl ? swiper.translate : -swiper.translate;
} else {
currentPos = -data.currentTranslate;
}
if (params.freeMode) {
if (currentPos < -swiper.minTranslate()) {
swiper.slideTo(swiper.activeIndex);
return;
} else if (currentPos > -swiper.maxTranslate()) {
if (swiper.slides.length < snapGrid.length) {
swiper.slideTo(snapGrid.length - 1);
} else {
swiper.slideTo(swiper.slides.length - 1);
}
return;
}
if (params.freeModeMomentum) {
if (data.velocities.length > 1) {
const lastMoveEvent = data.velocities.pop();
const velocityEvent = data.velocities.pop();
const distance = lastMoveEvent.position - velocityEvent.position;
const time = lastMoveEvent.time - velocityEvent.time;
swiper.velocity = distance / time;
swiper.velocity /= 2;
if (Math.abs(swiper.velocity) < params.freeModeMinimumVelocity) {
swiper.velocity = 0;
}
// this implies that the user stopped moving a finger then released.
// There would be no events with distance zero, so the last event is stale.
if (time > 150 || (Utils.now() - lastMoveEvent.time) > 300) {
swiper.velocity = 0;
}
} else {
swiper.velocity = 0;
}
swiper.velocity *= params.freeModeMomentumVelocityRatio;
data.velocities.length = 0;
let momentumDuration = 1000 * params.freeModeMomentumRatio;
const momentumDistance = swiper.velocity * momentumDuration;
let newPosition = swiper.translate + momentumDistance;
if (rtl) newPosition = -newPosition;
let doBounce = false;
let afterBouncePosition;
const bounceAmount = Math.abs(swiper.velocity) * 20 * params.freeModeMomentumBounceRatio;
if (newPosition < swiper.maxTranslate()) {
if (params.freeModeMomentumBounce) {
if (newPosition + swiper.maxTranslate() < -bounceAmount) {
newPosition = swiper.maxTranslate() - bounceAmount;
}
afterBouncePosition = swiper.maxTranslate();
doBounce = true;
data.allowMomentumBounce = true;
} else {
newPosition = swiper.maxTranslate();
}
} else if (newPosition > swiper.minTranslate()) {
if (params.freeModeMomentumBounce) {
if (newPosition - swiper.minTranslate() > bounceAmount) {
newPosition = swiper.minTranslate() + bounceAmount;
}
afterBouncePosition = swiper.minTranslate();
doBounce = true;
data.allowMomentumBounce = true;
} else {
newPosition = swiper.minTranslate();
}
} else if (params.freeModeSticky) {
let nextSlide;
for (let j = 0; j < snapGrid.length; j += 1) {
if (snapGrid[j] > -newPosition) {
nextSlide = j;
break;
}
}
if (Math.abs(snapGrid[nextSlide] - newPosition) < Math.abs(snapGrid[nextSlide - 1] - newPosition) || swiper.swipeDirection === 'next') {
newPosition = snapGrid[nextSlide];
} else {
newPosition = snapGrid[nextSlide - 1];
}
newPosition = -newPosition;
}
// Fix duration
if (swiper.velocity !== 0) {
if (rtl) {
momentumDuration = Math.abs((-newPosition - swiper.translate) / swiper.velocity);
} else {
momentumDuration = Math.abs((newPosition - swiper.translate) / swiper.velocity);
}
} else if (params.freeModeSticky) {
swiper.slideReset();
return;
}
if (params.freeModeMomentumBounce && doBounce) {
swiper.updateProgress(afterBouncePosition);
swiper.setTransition(momentumDuration);
swiper.setTranslate(newPosition);
swiper.transitionStart();
swiper.animating = true;
$wrapperEl.transitionEnd(() => {
if (!swiper || swiper.destroyed || !data.allowMomentumBounce) return;
swiper.emit('momentumBounce');
swiper.setTransition(params.speed);
swiper.setTranslate(afterBouncePosition);
$wrapperEl.transitionEnd(() => {
if (!swiper || swiper.destroyed) return;
swiper.transitionEnd();
});
});
} else if (swiper.velocity) {
swiper.updateProgress(newPosition);
swiper.setTransition(momentumDuration);
swiper.setTranslate(newPosition);
swiper.transitionStart();
if (!swiper.animating) {
swiper.animating = true;
$wrapperEl.transitionEnd(() => {
if (!swiper || swiper.destroyed) return;
swiper.transitionEnd();
});
}
} else {
swiper.updateProgress(newPosition);
}
swiper.updateActiveIndex();
swiper.updateSlidesClasses();
}
if (!params.freeModeMomentum || timeDiff >= params.longSwipesMs) {
swiper.updateProgress();
swiper.updateActiveIndex();
swiper.updateSlidesClasses();
}
return;
}
// Find current slide
let stopIndex = 0;
let groupSize = swiper.slidesSizesGrid[0];
for (let i = 0; i < slidesGrid.length; i += params.slidesPerGroup) {
if (typeof slidesGrid[i + params.slidesPerGroup] !== 'undefined') {
if (currentPos >= slidesGrid[i] && currentPos < slidesGrid[i + params.slidesPerGroup]) {
stopIndex = i;
groupSize = slidesGrid[i + params.slidesPerGroup] - slidesGrid[i];
}
} else if (currentPos >= slidesGrid[i]) {
stopIndex = i;
groupSize = slidesGrid[slidesGrid.length - 1] - slidesGrid[slidesGrid.length - 2];
}
}
// Find current slide size
const ratio = (currentPos - slidesGrid[stopIndex]) / groupSize;
if (timeDiff > params.longSwipesMs) {
// Long touches
if (!params.longSwipes) {
swiper.slideTo(swiper.activeIndex);
return;
}
if (swiper.swipeDirection === 'next') {
if (ratio >= params.longSwipesRatio) swiper.slideTo(stopIndex + params.slidesPerGroup);
else swiper.slideTo(stopIndex);
}
if (swiper.swipeDirection === 'prev') {
if (ratio > (1 - params.longSwipesRatio)) swiper.slideTo(stopIndex + params.slidesPerGroup);
else swiper.slideTo(stopIndex);
}
} else {
// Short swipes
if (!params.shortSwipes) {
swiper.slideTo(swiper.activeIndex);
return;
}
if (swiper.swipeDirection === 'next') {
swiper.slideTo(stopIndex + params.slidesPerGroup);
}
if (swiper.swipeDirection === 'prev') {
swiper.slideTo(stopIndex);
}
}
};
var onResize = function () {
const swiper = this;
const { params, el } = swiper;
if (el && el.offsetWidth === 0) return;
// Breakpoints
if (params.breakpoints) {
swiper.setBreakpoint();
}
// Save locks
const { allowSlideNext, allowSlidePrev } = swiper;
// Disable locks on resize
swiper.allowSlideNext = true;
swiper.allowSlidePrev = true;
swiper.updateSize();
swiper.updateSlides();
if (params.freeMode) {
const newTranslate = Math.min(Math.max(swiper.translate, swiper.maxTranslate()), swiper.minTranslate());
swiper.setTranslate(newTranslate);
swiper.updateActiveIndex();
swiper.updateSlidesClasses();
if (params.autoHeight) {
swiper.updateAutoHeight();
}
} else {
swiper.updateSlidesClasses();
if ((params.slidesPerView === 'auto' || params.slidesPerView > 1) && swiper.isEnd && !swiper.params.centeredSlides) {
swiper.slideTo(swiper.slides.length - 1, 0, false, true);
} else {
swiper.slideTo(swiper.activeIndex, 0, false, true);
}
}
// Return locks after resize
swiper.allowSlidePrev = allowSlidePrev;
swiper.allowSlideNext = allowSlideNext;
};
var onClick = function (e) {
const swiper = this;
if (!swiper.allowClick) {
if (swiper.params.preventClicks) e.preventDefault();
if (swiper.params.preventClicksPropagation && swiper.animating) {
e.stopPropagation();
e.stopImmediatePropagation();
}
}
};
function attachEvents() {
const swiper = this;
const { params, touchEvents, el, wrapperEl } = swiper;
{
swiper.onTouchStart = onTouchStart.bind(swiper);
swiper.onTouchMove = onTouchMove.bind(swiper);
swiper.onTouchEnd = onTouchEnd.bind(swiper);
}
swiper.onClick = onClick.bind(swiper);
const target = params.touchEventsTarget === 'container' ? el : wrapperEl;
const capture = !!params.nested;
// Touch Events
{
if (Browser.ie) {
target.addEventListener(touchEvents.start, swiper.onTouchStart, false);
(Support$1.touch ? target : document).addEventListener(touchEvents.move, swiper.onTouchMove, capture);
(Support$1.touch ? target : document).addEventListener(touchEvents.end, swiper.onTouchEnd, false);
} else {
if (Support$1.touch) {
const passiveListener = touchEvents.start === 'touchstart' && Support$1.passiveListener && params.passiveListeners ? { passive: true, capture: false } : false;
target.addEventListener(touchEvents.start, swiper.onTouchStart, passiveListener);
target.addEventListener(touchEvents.move, swiper.onTouchMove, Support$1.passiveListener ? { passive: false, capture } : capture);
target.addEventListener(touchEvents.end, swiper.onTouchEnd, passiveListener);
}
if ((params.simulateTouch && !Device.ios && !Device.android) || (params.simulateTouch && !Support$1.touch && Device.ios)) {
target.addEventListener('mousedown', swiper.onTouchStart, false);
document.addEventListener('mousemove', swiper.onTouchMove, capture);
document.addEventListener('mouseup', swiper.onTouchEnd, false);
}
}
// Prevent Links Clicks
if (params.preventClicks || params.preventClicksPropagation) {
target.addEventListener('click', swiper.onClick, true);
}
}
// Resize handler
swiper.on('resize observerUpdate', onResize);
}
function detachEvents() {
const swiper = this;
const { params, touchEvents, el, wrapperEl } = swiper;
const target = params.touchEventsTarget === 'container' ? el : wrapperEl;
const capture = !!params.nested;
// Touch Events
{
if (Browser.ie) {
target.removeEventListener(touchEvents.start, swiper.onTouchStart, false);
(Support$1.touch ? target : document).removeEventListener(touchEvents.move, swiper.onTouchMove, capture);
(Support$1.touch ? target : document).removeEventListener(touchEvents.end, swiper.onTouchEnd, false);
} else {
if (Support$1.touch) {
const passiveListener = touchEvents.start === 'onTouchStart' && Support$1.passiveListener && params.passiveListeners ? { passive: true, capture: false } : false;
target.removeEventListener(touchEvents.start, swiper.onTouchStart, passiveListener);
target.removeEventListener(touchEvents.move, swiper.onTouchMove, capture);
target.removeEventListener(touchEvents.end, swiper.onTouchEnd, passiveListener);
}
if ((params.simulateTouch && !Device.ios && !Device.android) || (params.simulateTouch && !Support$1.touch && Device.ios)) {
target.removeEventListener('mousedown', swiper.onTouchStart, false);
document.removeEventListener('mousemove', swiper.onTouchMove, capture);
document.removeEventListener('mouseup', swiper.onTouchEnd, false);
}
}
// Prevent Links Clicks
if (params.preventClicks || params.preventClicksPropagation) {
target.removeEventListener('click', swiper.onClick, true);
}
}
// Resize handler
swiper.off('resize observerUpdate', onResize);
}
var events = {
attachEvents,
detachEvents,
};
var setBreakpoint = function () {
const swiper = this;
const { activeIndex, loopedSlides = 0, params } = swiper;
const breakpoints = params.breakpoints;
if (!breakpoints || (breakpoints && Object.keys(breakpoints).length === 0)) return;
// Set breakpoint for window width and update parameters
const breakpoint = swiper.getBreakpoint(breakpoints);
if (breakpoint && swiper.currentBreakpoint !== breakpoint) {
const breakPointsParams = breakpoint in breakpoints ? breakpoints[breakpoint] : swiper.originalParams;
const needsReLoop = params.loop && (breakPointsParams.slidesPerView !== params.slidesPerView);
Utils.extend(swiper.params, breakPointsParams);
Utils.extend(swiper, {
allowTouchMove: swiper.params.allowTouchMove,
allowSlideNext: swiper.params.allowSlideNext,
allowSlidePrev: swiper.params.allowSlidePrev,
});
swiper.currentBreakpoint = breakpoint;
if (needsReLoop) {
swiper.loopDestroy();
swiper.loopCreate();
swiper.updateSlides();
swiper.slideTo((activeIndex - loopedSlides) + swiper.loopedSlides, 0, false);
}
swiper.emit('breakpoint', breakPointsParams);
}
};
var getBreakpoint = function (breakpoints) {
// Get breakpoint for window width
if (!breakpoints) return undefined;
let breakpoint = false;
const points = [];
Object.keys(breakpoints).forEach((point) => {
points.push(point);
});
points.sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
for (let i = 0; i < points.length; i += 1) {
const point = points[i];
if (point >= window.innerWidth && !breakpoint) {
breakpoint = point;
}
}
return breakpoint || 'max';
};
var breakpoints = { setBreakpoint, getBreakpoint };
var addClasses = function () {
const swiper = this;
const { classNames, params, rtl, $el } = swiper;
const suffixes = [];
suffixes.push(params.direction);
if (params.freeMode) {
suffixes.push('free-mode');
}
if (!Support$1.flexbox) {
suffixes.push('no-flexbox');
}
if (params.autoHeight) {
suffixes.push('autoheight');
}
if (rtl) {
suffixes.push('rtl');
}
if (params.slidesPerColumn > 1) {
suffixes.push('multirow');
}
if (Device.android) {
suffixes.push('android');
}
if (Device.ios) {
suffixes.push('ios');
}
// WP8 Touch Events Fix
if (window.navigator.pointerEnabled || window.navigator.msPointerEnabled) {
suffixes.push(`wp8-${params.direction}`);
}
suffixes.forEach((suffix) => {
classNames.push(params.containerModifierClass + suffix);
});
$el.addClass(classNames.join(' '));
};
var removeClasses = function () {
const swiper = this;
const { $el, classNames } = swiper;
$el.removeClass(classNames.join(' '));
};
var classes = { addClasses, removeClasses };
var loadImage = function (imageEl, src, srcset, sizes, checkForComplete, callback) {
let image;
function onReady() {
if (callback) callback();
}
if (!imageEl.complete || !checkForComplete) {
if (src) {
image = new window.Image();
image.onload = onReady;
image.onerror = onReady;
if (sizes) {
image.sizes = sizes;
}
if (srcset) {
image.srcset = srcset;
}
if (src) {
image.src = src;
}
} else {
onReady();
}
} else {
// image already loaded...
onReady();
}
};
var preloadImages = function () {
const swiper = this;
swiper.imagesToLoad = swiper.$el.find('img');
function onReady() {
if (typeof swiper === 'undefined' || swiper === null || !swiper || swiper.destroyed) return;
if (swiper.imagesLoaded !== undefined) swiper.imagesLoaded += 1;
if (swiper.imagesLoaded === swiper.imagesToLoad.length) {
if (swiper.params.updateOnImagesReady) swiper.update();
swiper.emit('imagesReady');
}
}
for (let i = 0; i < swiper.imagesToLoad.length; i += 1) {
const imageEl = swiper.imagesToLoad[i];
swiper.loadImage(
imageEl,
imageEl.currentSrc || imageEl.getAttribute('src'),
imageEl.srcset || imageEl.getAttribute('srcset'),
imageEl.sizes || imageEl.getAttribute('sizes'),
true,
onReady
);
}
};
var images = {
loadImage,
preloadImages,
};
var defaults = {
init: true,
direction: 'horizontal',
touchEventsTarget: 'container',
initialSlide: 0,
speed: 300,
// To support iOS's swipe-to-go-back gesture (when being used in-app, with UIWebView).
iOSEdgeSwipeDetection: false,
iOSEdgeSwipeThreshold: 20,
// Free mode
freeMode: false,
freeModeMomentum: true,
freeModeMomentumRatio: 1,
freeModeMomentumBounce: true,
freeModeMomentumBounceRatio: 1,
freeModeMomentumVelocityRatio: 1,
freeModeSticky: false,
freeModeMinimumVelocity: 0.02,
// Autoheight
autoHeight: false,
// Set wrapper width
setWrapperSize: false,
// Virtual Translate
virtualTranslate: false,
// Effects
effect: 'slide', // 'slide' or 'fade' or 'cube' or 'coverflow' or 'flip'
// Breakpoints
breakpoints: undefined,
// Slides grid
spaceBetween: 0,
slidesPerView: 1,
slidesPerColumn: 1,
slidesPerColumnFill: 'column',
slidesPerGroup: 1,
centeredSlides: false,
slidesOffsetBefore: 0, // in px
slidesOffsetAfter: 0, // in px
normalizeSlideIndex: true,
// Round length
roundLengths: false,
// Touches
touchRatio: 1,
touchAngle: 45,
simulateTouch: true,
shortSwipes: true,
longSwipes: true,
longSwipesRatio: 0.5,
longSwipesMs: 300,
followFinger: true,
allowTouchMove: true,
threshold: 0,
touchMoveStopPropagation: true,
touchReleaseOnEdges: false,
// Unique Navigation Elements
uniqueNavElements: true,
// Resistance
resistance: true,
resistanceRatio: 0.85,
// Progress
watchSlidesProgress: false,
watchSlidesVisibility: false,
// Cursor
grabCursor: false,
// Clicks
preventClicks: true,
preventClicksPropagation: true,
slideToClickedSlide: false,
// Images
preloadImages: true,
updateOnImagesReady: true,
// loop
loop: false,
loopAdditionalSlides: 0,
loopedSlides: null,
loopFillGroupWithBlank: false,
// Swiping/no swiping
allowSlidePrev: true,
allowSlideNext: true,
swipeHandler: null, // '.swipe-handler',
noSwiping: true,
noSwipingClass: 'swiper-no-swiping',
// Passive Listeners
passiveListeners: true,
// NS
containerModifierClass: 'swiper-container-', // NEW
slideClass: 'swiper-slide',
slideBlankClass: 'swiper-slide-invisible-blank',
slideActiveClass: 'swiper-slide-active',
slideDuplicateActiveClass: 'swiper-slide-duplicate-active',
slideVisibleClass: 'swiper-slide-visible',
slideDuplicateClass: 'swiper-slide-duplicate',
slideNextClass: 'swiper-slide-next',
slideDuplicateNextClass: 'swiper-slide-duplicate-next',
slidePrevClass: 'swiper-slide-prev',
slideDuplicatePrevClass: 'swiper-slide-duplicate-prev',
wrapperClass: 'swiper-wrapper',
// Callbacks
runCallbacksOnInit: true,
};
const prototypes = {
update,
translate,
transition,
slide,
loop,
grabCursor,
manipulation,
events,
breakpoints,
classes,
images,
};
const extendedDefaults = {};
class Swiper$2 extends Framework7Class {
constructor(...args) {
let el;
let params;
if (args.length === 1 && args[0].constructor && args[0].constructor === Object) {
params = args[0];
} else {
[el, params] = args;
}
if (!params) params = {};
params = Utils.extend({}, params);
if (el && !params.el) params.el = el;
super(params);
Object.keys(prototypes).forEach((prototypeGroup) => {
Object.keys(prototypes[prototypeGroup]).forEach((protoMethod) => {
if (!Swiper$2.prototype[protoMethod]) {
Swiper$2.prototype[protoMethod] = prototypes[prototypeGroup][protoMethod];
}
});
});
// Swiper Instance
const swiper = this;
if (typeof swiper.modules === 'undefined') {
swiper.modules = {};
}
Object.keys(swiper.modules).forEach((moduleName) => {
const module = swiper.modules[moduleName];
if (module.params) {
const moduleParamName = Object.keys(module.params)[0];
const moduleParams = module.params[moduleParamName];
if (typeof moduleParams !== 'object') return;
if (!(moduleParamName in params && 'enabled' in moduleParams)) return;
if (params[moduleParamName] === true) {
params[moduleParamName] = { enabled: true };
}
if (
typeof params[moduleParamName] === 'object' &&
!('enabled' in params[moduleParamName])
) {
params[moduleParamName].enabled = true;
}
if (!params[moduleParamName]) params[moduleParamName] = { enabled: false };
}
});
// Extend defaults with modules params
const swiperParams = Utils.extend({}, defaults);
swiper.useModulesParams(swiperParams);
// Extend defaults with passed params
swiper.params = Utils.extend({}, swiperParams, extendedDefaults, params);
swiper.originalParams = Utils.extend({}, swiper.params);
swiper.passedParams = Utils.extend({}, params);
// Find el
const $el = $(swiper.params.el);
el = $el[0];
if (!el) {
return undefined;
}
if ($el.length > 1) {
const swipers = [];
$el.each((index, containerEl) => {
const newParams = Utils.extend({}, params, { el: containerEl });
swipers.push(new Swiper$2(newParams));
});
return swipers;
}
el.swiper = swiper;
$el.data('swiper', swiper);
// Find Wrapper
const $wrapperEl = $el.children(`.${swiper.params.wrapperClass}`);
// Extend Swiper
Utils.extend(swiper, {
$el,
el,
$wrapperEl,
wrapperEl: $wrapperEl[0],
// Classes
classNames: [],
// Slides
slides: $(),
slidesGrid: [],
snapGrid: [],
slidesSizesGrid: [],
// isDirection
isHorizontal() {
return swiper.params.direction === 'horizontal';
},
isVertical() {
return swiper.params.direction === 'vertical';
},
// RTL
rtl: swiper.params.direction === 'horizontal' && (el.dir.toLowerCase() === 'rtl' || $el.css('direction') === 'rtl'),
wrongRTL: $wrapperEl.css('display') === '-webkit-box',
// Indexes
activeIndex: 0,
realIndex: 0,
//
isBeginning: true,
isEnd: false,
// Props
translate: 0,
progress: 0,
velocity: 0,
animating: false,
// Locks
allowSlideNext: swiper.params.allowSlideNext,
allowSlidePrev: swiper.params.allowSlidePrev,
// Touch Events
touchEvents: (function touchEvents() {
const touch = ['touchstart', 'touchmove', 'touchend'];
let desktop = ['mousedown', 'mousemove', 'mouseup'];
if (window.navigator.pointerEnabled) {
desktop = ['pointerdown', 'pointermove', 'pointerup'];
} else if (window.navigator.msPointerEnabled) {
desktop = ['MSPointerDown', 'MsPointerMove', 'MsPointerUp'];
}
return {
start: Support$1.touch || !swiper.params.simulateTouch ? touch[0] : desktop[0],
move: Support$1.touch || !swiper.params.simulateTouch ? touch[1] : desktop[1],
end: Support$1.touch || !swiper.params.simulateTouch ? touch[2] : desktop[2],
};
}()),
touchEventsData: {
isTouched: undefined,
isMoved: undefined,
allowTouchCallbacks: undefined,
touchStartTime: undefined,
isScrolling: undefined,
currentTranslate: undefined,
startTranslate: undefined,
allowThresholdMove: undefined,
// Form elements to match
formElements: 'input, select, option, textarea, button, video',
// Last click time
lastClickTime: Utils.now(),
clickTimeout: undefined,
// Velocities
velocities: [],
allowMomentumBounce: undefined,
isTouchEvent: undefined,
startMoving: undefined,
},
// Clicks
allowClick: true,
// Touches
allowTouchMove: swiper.params.allowTouchMove,
touches: {
startX: 0,
startY: 0,
currentX: 0,
currentY: 0,
diff: 0,
},
// Images
imagesToLoad: [],
imagesLoaded: 0,
});
// Install Modules
swiper.useModules();
// Init
if (swiper.params.init) {
swiper.init();
}
// Return app instance
return swiper;
}
slidesPerViewDynamic() {
const swiper = this;
const { params, slides, slidesGrid, size: swiperSize, activeIndex } = swiper;
let spv = 1;
if (params.centeredSlides) {
let slideSize = slides[activeIndex].swiperSlideSize;
let breakLoop;
for (let i = activeIndex + 1; i < slides.length; i += 1) {
if (slides[i] && !breakLoop) {
slideSize += slides[i].swiperSlideSize;
spv += 1;
if (slideSize > swiperSize) breakLoop = true;
}
}
for (let i = activeIndex - 1; i >= 0; i -= 1) {
if (slides[i] && !breakLoop) {
slideSize += slides[i].swiperSlideSize;
spv += 1;
if (slideSize > swiperSize) breakLoop = true;
}
}
} else {
for (let i = activeIndex + 1; i < slides.length; i += 1) {
if (slidesGrid[i] - slidesGrid[activeIndex] < swiperSize) {
spv += 1;
}
}
}
return spv;
}
update() {
const swiper = this;
if (!swiper || swiper.destroyed) return;
swiper.updateSize();
swiper.updateSlides();
swiper.updateProgress();
swiper.updateSlidesClasses();
let newTranslate;
function setTranslate() {
newTranslate = Math.min(Math.max(swiper.translate, swiper.maxTranslate()), swiper.minTranslate());
swiper.setTranslate(newTranslate);
swiper.updateActiveIndex();
swiper.updateSlidesClasses();
}
let translated;
if (swiper.params.freeMode) {
setTranslate();
if (swiper.params.autoHeight) {
swiper.updateAutoHeight();
}
} else {
if ((swiper.params.slidesPerView === 'auto' || swiper.params.slidesPerView > 1) && swiper.isEnd && !swiper.params.centeredSlides) {
translated = swiper.slideTo(swiper.slides.length - 1, 0, false, true);
} else {
translated = swiper.slideTo(swiper.activeIndex, 0, false, true);
}
if (!translated) {
setTranslate();
}
}
swiper.emit('update');
}
init() {
const swiper = this;
if (swiper.initialized) return;
swiper.emit('beforeInit');
// Set breakpoint
if (swiper.params.breakpoints) {
swiper.setBreakpoint();
}
// Add Classes
swiper.addClasses();
// Create loop
if (swiper.params.loop) {
swiper.loopCreate();
}
// Update size
swiper.updateSize();
// Update slides
swiper.updateSlides();
// Set Grab Cursor
if (swiper.params.grabCursor) {
swiper.setGrabCursor();
}
if (swiper.params.preloadImages) {
swiper.preloadImages();
}
// Slide To Initial Slide
if (swiper.params.loop) {
swiper.slideTo(swiper.params.initialSlide + swiper.loopedSlides, 0, swiper.params.runCallbacksOnInit);
} else {
swiper.slideTo(swiper.params.initialSlide, 0, swiper.params.runCallbacksOnInit);
}
// Attach events
swiper.attachEvents();
// Init Flag
swiper.initialized = true;
// Emit
swiper.emit('init');
}
destroy(deleteInstance = true, cleanStyles = true) {
const swiper = this;
const { params, $el, $wrapperEl, slides } = swiper;
swiper.emit('beforeDestroy');
// Init Flag
swiper.initialized = false;
// Detach events
swiper.detachEvents();
// Destroy loop
if (params.loop) {
swiper.loopDestroy();
}
// Cleanup styles
if (cleanStyles) {
swiper.removeClasses();
$el.removeAttr('style');
$wrapperEl.removeAttr('style');
if (slides && slides.length) {
slides
.removeClass([
params.slideVisibleClass,
params.slideActiveClass,
params.slideNextClass,
params.slidePrevClass,
].join(' '))
.removeAttr('style')
.removeAttr('data-swiper-slide-index')
.removeAttr('data-swiper-column')
.removeAttr('data-swiper-row');
}
}
swiper.emit('destroy');
// Detach emitter events
Object.keys(swiper.eventsListeners).forEach((eventName) => {
swiper.off(eventName);
});
if (deleteInstance !== false) {
swiper.$el[0].swiper = null;
swiper.$el.data('swiper', null);
Utils.deleteProps(swiper);
}
swiper.destroyed = true;
}
static extendDefaults(newDefaults) {
Utils.extend(extendedDefaults, newDefaults);
}
static get extendedDefaults() {
return extendedDefaults;
}
static get defaults() {
return defaults;
}
static get Class() {
return Framework7Class;
}
static get $() {
return $;
}
}
var Device$4 = {
name: 'device',
proto: {
device: Device,
},
static: {
device: Device,
},
};
var Support$4 = {
name: 'support',
proto: {
support: Support$1,
},
static: {
support: Support$1,
},
};
var Browser$2 = {
name: 'browser',
proto: {
browser: Browser,
},
static: {
browser: Browser,
},
};
var Resize$1 = {
name: 'resize',
create() {
const swiper = this;
Utils.extend(swiper, {
resize: {
resizeHandler() {
if (!swiper || !swiper.initialized) return;
swiper.emit('resize');
},
orientationChangeHandler() {
if (!swiper || !swiper.initialized) return;
swiper.emit('orientationchange');
},
},
});
},
on: {
init() {
const swiper = this;
// Emit resize
window.addEventListener('resize', swiper.resize.resizeHandler);
// Emit orientationchange
window.addEventListener('orientationchange', swiper.resize.orientationChangeHandler);
},
destroy() {
const swiper = this;
window.removeEventListener('resize', swiper.resize.resizeHandler);
window.removeEventListener('orientationchange', swiper.resize.orientationChangeHandler);
},
},
};
const Observer = {
func: window.MutationObserver || window.WebkitMutationObserver,
attach(target, options = {}) {
const swiper = this;
const ObserverFunc = Observer.func;
const observer = new ObserverFunc((mutations) => {
mutations.forEach((mutation) => {
swiper.emit('observerUpdate', mutation);
});
});
observer.observe(target, {
attributes: typeof options.attributes === 'undefined' ? true : options.attributes,
childList: typeof options.childList === 'undefined' ? true : options.childList,
characterData: typeof options.characterData === 'undefined' ? true : options.characterData,
});
swiper.observer.observers.push(observer);
},
init() {
const swiper = this;
if (!Support$1.observer || !swiper.params.observer) return;
if (swiper.params.observeParents) {
const containerParents = swiper.$el.parents();
for (let i = 0; i < containerParents.length; i += 1) {
swiper.observer.attach(containerParents[i]);
}
}
// Observe container
swiper.observer.attach(swiper.$el[0], { childList: false });
// Observe wrapper
swiper.observer.attach(swiper.$wrapperEl[0], { attributes: false });
},
destroy() {
const swiper = this;
swiper.observer.observers.forEach((observer) => {
observer.disconnect();
});
swiper.observer.observers = [];
},
};
var Observer$1 = {
name: 'observer',
params: {
observer: false,
observeParents: false,
},
create() {
const swiper = this;
Utils.extend(swiper, {
observer: {
init: Observer.init.bind(swiper),
attach: Observer.attach.bind(swiper),
destroy: Observer.destroy.bind(swiper),
observers: [],
},
});
},
on: {
init() {
const swiper = this;
swiper.observer.init();
},
destroy() {
const swiper = this;
swiper.observer.destroy();
},
},
};
const Virtual = {
update(force) {
const swiper = this;
const { slidesPerView, slidesPerGroup, centeredSlides } = swiper.params;
const {
from: previousFrom,
to: previousTo,
slides,
slidesGrid: previousSlidesGrid,
renderSlide,
offset: previousOffset,
} = swiper.virtual;
swiper.updateActiveIndex();
const activeIndex = swiper.activeIndex || 0;
let offsetProp;
if (swiper.rtl && swiper.isHorizontal()) offsetProp = 'right';
else offsetProp = swiper.isHorizontal() ? 'left' : 'top';
let slidesAfter;
let slidesBefore;
if (centeredSlides) {
slidesAfter = Math.floor(slidesPerView / 2) + slidesPerGroup;
slidesBefore = Math.floor(slidesPerView / 2) + slidesPerGroup;
} else {
slidesAfter = slidesPerView + (slidesPerGroup - 1);
slidesBefore = slidesPerGroup;
}
const from = Math.max((activeIndex || 0) - slidesBefore, 0);
const to = Math.min((activeIndex || 0) + slidesAfter, slides.length - 1);
const offset = (swiper.slidesGrid[from] || 0) - (swiper.slidesGrid[0] || 0);
Utils.extend(swiper.virtual, {
from,
to,
offset,
slidesGrid: swiper.slidesGrid,
});
function onRendered() {
swiper.updateSlides();
swiper.updateProgress();
swiper.updateSlidesClasses();
if (swiper.lazy && swiper.params.lazy.enabled) {
swiper.lazy.load();
}
}
if (previousFrom === from && previousTo === to && !force) {
if (swiper.slidesGrid !== previousSlidesGrid && offset !== previousOffset) {
swiper.slides.css(offsetProp, `${offset}px`);
}
swiper.updateProgress();
return;
}
if (swiper.params.virtual.renderExternal) {
swiper.params.virtual.renderExternal.call(swiper, {
offset,
from,
to,
slides: (function getSlides() {
const slidesToRender = [];
for (let i = from; i <= to; i += 1) {
slidesToRender.push(slides[i]);
}
return slidesToRender;
}()),
});
onRendered();
return;
}
const prependIndexes = [];
const appendIndexes = [];
if (force) {
swiper.$wrapperEl.find(`.${swiper.params.slideClass}`).remove();
} else {
for (let i = previousFrom; i <= previousTo; i += 1) {
if (i < from || i > to) {
swiper.$wrapperEl.find(`.${swiper.params.slideClass}[data-swiper-slide-index="${i}"]`).remove();
}
}
}
for (let i = 0; i < slides.length; i += 1) {
if (i >= from && i <= to) {
if (typeof previousTo === 'undefined' || force) {
appendIndexes.push(i);
} else {
if (i > previousTo) appendIndexes.push(i);
if (i < previousFrom) prependIndexes.push(i);
}
}
}
appendIndexes.forEach((index) => {
swiper.$wrapperEl.append(renderSlide(slides[index], index));
});
prependIndexes.sort((a, b) => a < b).forEach((index) => {
swiper.$wrapperEl.prepend(renderSlide(slides[index], index));
});
swiper.$wrapperEl.children('.swiper-slide').css(offsetProp, `${offset}px`);
onRendered();
},
renderSlide(slide, index) {
const swiper = this;
const params = swiper.params.virtual;
if (params.cache && swiper.virtual.cache[index]) {
return swiper.virtual.cache[index];
}
const $slideEl = params.renderSlide
? $(params.renderSlide.call(swiper, slide, index))
: $(`<div class="${swiper.params.slideClass}" data-swiper-slide-index="${index}">${slide}</div>`);
if (!$slideEl.attr('data-swiper-slide-index')) $slideEl.attr('data-swiper-slide-index', index);
if (params.cache) swiper.virtual.cache[index] = $slideEl;
return $slideEl;
},
appendSlide(slide) {
const swiper = this;
swiper.virtual.slides.push(slide);
swiper.virtual.update(true);
},
prependSlide(slide) {
const swiper = this;
swiper.virtual.slides.unshift(slide);
if (swiper.params.virtual.cache) {
const cache = swiper.virtual.cache;
const newCache = {};
Object.keys(cache).forEach((cachedIndex) => {
newCache[cachedIndex + 1] = cache[cachedIndex];
});
swiper.virtual.cache = newCache;
}
swiper.virtual.update(true);
swiper.slideNext(0);
},
};
var Virtual$1 = {
name: 'virtual',
params: {
virtual: {
enabled: false,
slides: [],
cache: true,
renderSlide: null,
renderExternal: null,
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
virtual: {
update: Virtual.update.bind(swiper),
appendSlide: Virtual.appendSlide.bind(swiper),
prependSlide: Virtual.prependSlide.bind(swiper),
renderSlide: Virtual.renderSlide.bind(swiper),
slides: swiper.params.virtual.slides,
cache: {},
},
});
},
on: {
beforeInit() {
const swiper = this;
if (!swiper.params.virtual.enabled) return;
swiper.classNames.push(`${swiper.params.containerModifierClass}virtual`);
const overwriteParams = {
watchSlidesProgress: true,
};
Utils.extend(swiper.params, overwriteParams);
Utils.extend(swiper.originalParams, overwriteParams);
swiper.virtual.update();
},
setTranslate() {
const swiper = this;
if (!swiper.params.virtual.enabled) return;
swiper.virtual.update();
},
},
};
const Navigation = {
update() {
// Update Navigation Buttons
const swiper = this;
const params = swiper.params.navigation;
if (swiper.params.loop) return;
const { $nextEl, $prevEl } = swiper.navigation;
if ($prevEl && $prevEl.length > 0) {
if (swiper.isBeginning) {
$prevEl.addClass(params.disabledClass);
} else {
$prevEl.removeClass(params.disabledClass);
}
}
if ($nextEl && $nextEl.length > 0) {
if (swiper.isEnd) {
$nextEl.addClass(params.disabledClass);
} else {
$nextEl.removeClass(params.disabledClass);
}
}
},
init() {
const swiper = this;
const params = swiper.params.navigation;
if (!(params.nextEl || params.prevEl)) return;
let $nextEl;
let $prevEl;
if (params.nextEl) {
$nextEl = $(params.nextEl);
if (
swiper.params.uniqueNavElements &&
typeof params.nextEl === 'string' &&
$nextEl.length > 1 &&
swiper.$el.find(params.nextEl).length === 1
) {
$nextEl = swiper.$el.find(params.nextEl);
}
}
if (params.prevEl) {
$prevEl = $(params.prevEl);
if (
swiper.params.uniqueNavElements &&
typeof params.prevEl === 'string' &&
$prevEl.length > 1 &&
swiper.$el.find(params.prevEl).length === 1
) {
$prevEl = swiper.$el.find(params.prevEl);
}
}
if ($nextEl && $nextEl.length > 0) {
$nextEl.on('click', (e) => {
e.preventDefault();
if (swiper.isEnd && !swiper.params.loop) return;
swiper.slideNext();
});
}
if ($prevEl && $prevEl.length > 0) {
$prevEl.on('click', (e) => {
e.preventDefault();
if (swiper.isBeginning && !swiper.params.loop) return;
swiper.slidePrev();
});
}
Utils.extend(swiper.navigation, {
$nextEl,
nextEl: $nextEl && $nextEl[0],
$prevEl,
prevEl: $prevEl && $prevEl[0],
});
},
destroy() {
const swiper = this;
const { $nextEl, $prevEl } = swiper.navigation;
if ($nextEl && $nextEl.length) {
$nextEl.off('click');
$nextEl.removeClass(swiper.params.navigation.disabledClass);
}
if ($prevEl && $prevEl.length) {
$prevEl.off('click');
$prevEl.removeClass(swiper.params.navigation.disabledClass);
}
},
};
var Navigation$1 = {
name: 'navigation',
params: {
navigation: {
nextEl: null,
prevEl: null,
hideOnClick: false,
disabledClass: 'swiper-button-disabled',
hiddenClass: 'swiper-button-hidden',
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
navigation: {
init: Navigation.init.bind(swiper),
update: Navigation.update.bind(swiper),
destroy: Navigation.destroy.bind(swiper),
},
});
},
on: {
init() {
const swiper = this;
swiper.navigation.init();
swiper.navigation.update();
},
toEdge() {
const swiper = this;
swiper.navigation.update();
},
fromEdge() {
const swiper = this;
swiper.navigation.update();
},
destroy() {
const swiper = this;
swiper.navigation.destroy();
},
click(e) {
const swiper = this;
const { $nextEl, $prevEl } = swiper.navigation;
if (
swiper.params.navigation.hideOnClick &&
!$(e.target).is($prevEl) &&
!$(e.target).is($nextEl)
) {
if ($nextEl) $nextEl.toggleClass(swiper.params.navigation.hiddenClass);
if ($prevEl) $prevEl.toggleClass(swiper.params.navigation.hiddenClass);
}
},
},
};
const Pagination = {
update() {
// Render || Update Pagination bullets/items
const swiper = this;
const rtl = swiper.rtl;
const params = swiper.params.pagination;
if (!params.el || !swiper.pagination.el || !swiper.pagination.$el || swiper.pagination.$el.length === 0) return;
const slidesLength = swiper.virtual && swiper.params.virtual.enabled ? swiper.virtual.slides.length : swiper.slides.length;
const $el = swiper.pagination.$el;
// Current/Total
let current;
const total = swiper.params.loop ? Math.ceil((slidesLength - (swiper.loopedSlides * 2)) / swiper.params.slidesPerGroup) : swiper.snapGrid.length;
if (swiper.params.loop) {
current = Math.ceil((swiper.activeIndex - swiper.loopedSlides) / swiper.params.slidesPerGroup);
if (current > slidesLength - 1 - (swiper.loopedSlides * 2)) {
current -= (slidesLength - (swiper.loopedSlides * 2));
}
if (current > total - 1) current -= total;
if (current < 0 && swiper.params.paginationType !== 'bullets') current = total + current;
} else if (typeof swiper.snapIndex !== 'undefined') {
current = swiper.snapIndex;
} else {
current = swiper.activeIndex || 0;
}
// Types
if (params.type === 'bullets' && swiper.pagination.bullets && swiper.pagination.bullets.length > 0) {
const bullets = swiper.pagination.bullets;
if (params.dynamicBullets) {
swiper.pagination.bulletSize = bullets.eq(0)[swiper.isHorizontal() ? 'outerWidth' : 'outerHeight'](true);
$el.css(swiper.isHorizontal() ? 'width' : 'height', `${swiper.pagination.bulletSize * 5}px`);
}
bullets.removeClass(`${params.bulletActiveClass} ${params.bulletActiveClass}-next ${params.bulletActiveClass}-next-next ${params.bulletActiveClass}-prev ${params.bulletActiveClass}-prev-prev`);
if ($el.length > 1) {
bullets.each((index, bullet) => {
const $bullet = $(bullet);
if ($bullet.index() === current) {
$bullet.addClass(params.bulletActiveClass);
if (params.dynamicBullets) {
$bullet
.prev()
.addClass(`${params.bulletActiveClass}-prev`)
.prev()
.addClass(`${params.bulletActiveClass}-prev-prev`);
$bullet
.next()
.addClass(`${params.bulletActiveClass}-next`)
.next()
.addClass(`${params.bulletActiveClass}-next-next`);
}
}
});
} else {
const $bullet = bullets.eq(current);
$bullet.addClass(params.bulletActiveClass);
if (params.dynamicBullets) {
$bullet
.prev()
.addClass(`${params.bulletActiveClass}-prev`)
.prev()
.addClass(`${params.bulletActiveClass}-prev-prev`);
$bullet
.next()
.addClass(`${params.bulletActiveClass}-next`)
.next()
.addClass(`${params.bulletActiveClass}-next-next`);
}
}
if (params.dynamicBullets) {
const dynamicBulletsLength = Math.min(bullets.length, 5);
const bulletsOffset = (((swiper.pagination.bulletSize * dynamicBulletsLength) - (swiper.pagination.bulletSize)) / 2) - (current * swiper.pagination.bulletSize);
const offsetProp = rtl ? 'right' : 'left';
bullets.css(swiper.isHorizontal() ? offsetProp : 'top', `${bulletsOffset}px`);
}
}
if (params.type === 'fraction') {
$el.find(`.${params.currentClass}`).text(current + 1);
$el.find(`.${params.totalClass}`).text(total);
}
if (params.type === 'progressbar') {
const scale = (current + 1) / total;
let scaleX = scale;
let scaleY = 1;
if (!swiper.isHorizontal()) {
scaleY = scale;
scaleX = 1;
}
$el.find(`.${params.progressbarFillClass}`).transform(`translate3d(0,0,0) scaleX(${scaleX}) scaleY(${scaleY})`).transition(swiper.params.speed);
}
if (params.type === 'custom' && params.renderCustom) {
$el.html(params.renderCustom(swiper, current + 1, total));
swiper.emit('paginationRender', swiper, $el[0]);
} else {
swiper.emit('paginationUpdate', swiper, $el[0]);
}
},
render() {
// Render Container
const swiper = this;
const params = swiper.params.pagination;
if (!params.el || !swiper.pagination.el || !swiper.pagination.$el || swiper.pagination.$el.length === 0) return;
const slidesLength = swiper.virtual && swiper.params.virtual.enabled ? swiper.virtual.slides.length : swiper.slides.length;
const $el = swiper.pagination.$el;
let paginationHTML = '';
if (params.type === 'bullets') {
const numberOfBullets = swiper.params.loop ? Math.ceil((slidesLength - (swiper.loopedSlides * 2)) / swiper.params.slidesPerGroup) : swiper.snapGrid.length;
for (let i = 0; i < numberOfBullets; i += 1) {
if (params.renderBullet) {
paginationHTML += params.renderBullet.call(swiper, i, params.bulletClass);
} else {
paginationHTML += `<${params.bulletElement} class="${params.bulletClass}"></${params.bulletElement}>`;
}
}
$el.html(paginationHTML);
swiper.pagination.bullets = $el.find(`.${params.bulletClass}`);
}
if (params.type === 'fraction') {
if (params.renderFraction) {
paginationHTML = params.renderFraction.call(swiper, params.currentClass, params.totalClass);
} else {
paginationHTML =
`<span class="${params.currentClass}"></span>` +
' / ' +
`<span class="${params.totalClass}"></span>`;
}
$el.html(paginationHTML);
}
if (params.type === 'progressbar') {
if (params.renderProgressbar) {
paginationHTML = params.renderProgressbar.call(swiper, params.progressbarFillClass);
} else {
paginationHTML = `<span class="${params.progressbarFillClass}"></span>`;
}
$el.html(paginationHTML);
}
if (params.type !== 'custom') {
swiper.emit('paginationRender', swiper.pagination.$el[0]);
}
},
init() {
const swiper = this;
const params = swiper.params.pagination;
if (!params.el) return;
let $el = $(params.el);
if ($el.length === 0) return;
if (
swiper.params.uniqueNavElements &&
typeof params.el === 'string' &&
$el.length > 1 &&
swiper.$el.find(params.el).length === 1
) {
$el = swiper.$el.find(params.el);
}
if (params.type === 'bullets' && params.clickable) {
$el.addClass(params.clickableClass);
}
$el.addClass(params.modifierClass + params.type);
if (params.type === 'bullets' && params.dynamicBullets) {
$el.addClass(`${params.modifierClass}${params.type}-dynamic`);
}
if (params.clickable) {
$el.on('click', `.${params.bulletClass}`, function onClick(e) {
e.preventDefault();
let index = $(this).index() * swiper.params.slidesPerGroup;
if (swiper.params.loop) index += swiper.loopedSlides;
swiper.slideTo(index);
});
}
Utils.extend(swiper.pagination, {
$el,
el: $el[0],
});
},
destroy() {
const swiper = this;
const params = swiper.params.pagination;
if (!params.el || !swiper.pagination.el || !swiper.pagination.$el || swiper.pagination.$el.length === 0) return;
const $el = swiper.pagination.$el;
$el.removeClass(params.hiddenClass);
$el.removeClass(params.modifierClass + params.type);
if (swiper.pagination.bullets) swiper.pagination.bullets.removeClass(params.bulletActiveClass);
if (params.clickable) {
$el.off('click', `.${params.bulletClass}`);
}
},
};
var Pagination$1 = {
name: 'pagination',
params: {
pagination: {
el: null,
bulletElement: 'span',
clickable: false,
hideOnClick: false,
renderBullet: null,
renderProgressbar: null,
renderFraction: null,
renderCustom: null,
type: 'bullets', // 'bullets' or 'progressbar' or 'fraction' or 'custom'
dynamicBullets: false,
bulletClass: 'swiper-pagination-bullet',
bulletActiveClass: 'swiper-pagination-bullet-active',
modifierClass: 'swiper-pagination-', // NEW
currentClass: 'swiper-pagination-current',
totalClass: 'swiper-pagination-total',
hiddenClass: 'swiper-pagination-hidden',
progressbarFillClass: 'swiper-pagination-progressbar-fill',
clickableClass: 'swiper-pagination-clickable', // NEW
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
pagination: {
init: Pagination.init.bind(swiper),
render: Pagination.render.bind(swiper),
update: Pagination.update.bind(swiper),
destroy: Pagination.destroy.bind(swiper),
},
});
},
on: {
init() {
const swiper = this;
swiper.pagination.init();
swiper.pagination.render();
swiper.pagination.update();
},
activeIndexChange() {
const swiper = this;
if (swiper.params.loop) {
swiper.pagination.update();
} else if (typeof swiper.snapIndex === 'undefined') {
swiper.pagination.update();
}
},
snapIndexChange() {
const swiper = this;
if (!swiper.params.loop) {
swiper.pagination.update();
}
},
slidesLengthChange() {
const swiper = this;
if (swiper.params.loop) {
swiper.pagination.render();
swiper.pagination.update();
}
},
snapGridLengthChange() {
const swiper = this;
if (!swiper.params.loop) {
swiper.pagination.render();
swiper.pagination.update();
}
},
destroy() {
const swiper = this;
swiper.pagination.destroy();
},
click(e) {
const swiper = this;
if (
swiper.params.pagination.el &&
swiper.params.pagination.hideOnClick &&
swiper.pagination.$el.length > 0 &&
!$(e.target).hasClass(swiper.params.pagination.bulletClass)
) {
swiper.pagination.$el.toggleClass(swiper.params.pagination.hiddenClass);
}
},
},
};
const Scrollbar = {
setTranslate() {
const swiper = this;
if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return;
const { scrollbar, rtl, progress } = swiper;
const { dragSize, trackSize, $dragEl, $el } = scrollbar;
const params = swiper.params.scrollbar;
let newSize = dragSize;
let newPos = (trackSize - dragSize) * progress;
if (rtl && swiper.isHorizontal()) {
newPos = -newPos;
if (newPos > 0) {
newSize = dragSize - newPos;
newPos = 0;
} else if (-newPos + dragSize > trackSize) {
newSize = trackSize + newPos;
}
} else if (newPos < 0) {
newSize = dragSize + newPos;
newPos = 0;
} else if (newPos + dragSize > trackSize) {
newSize = trackSize - newPos;
}
if (swiper.isHorizontal()) {
if (Support$1.transforms3d) {
$dragEl.transform(`translate3d(${newPos}px, 0, 0)`);
} else {
$dragEl.transform(`translateX(${newPos}px)`);
}
$dragEl[0].style.width = `${newSize}px`;
} else {
if (Support$1.transforms3d) {
$dragEl.transform(`translate3d(0px, ${newPos}px, 0)`);
} else {
$dragEl.transform(`translateY(${newPos}px)`);
}
$dragEl[0].style.height = `${newSize}px`;
}
if (params.hide) {
clearTimeout(swiper.scrollbar.timeout);
$el[0].style.opacity = 1;
swiper.scrollbar.timeout = setTimeout(() => {
$el[0].style.opacity = 0;
$el.transition(400);
}, 1000);
}
},
setTransition(duration) {
const swiper = this;
if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return;
swiper.scrollbar.$dragEl.transition(duration);
},
updateSize() {
const swiper = this;
if (!swiper.params.scrollbar.el || !swiper.scrollbar.el) return;
const { scrollbar } = swiper;
const { $dragEl, $el } = scrollbar;
$dragEl[0].style.width = '';
$dragEl[0].style.height = '';
const trackSize = swiper.isHorizontal() ? $el[0].offsetWidth : $el[0].offsetHeight;
const divider = swiper.size / swiper.virtualSize;
const moveDivider = divider * (trackSize / swiper.size);
let dragSize;
if (swiper.params.scrollbar.dragSize === 'auto') {
dragSize = trackSize * divider;
} else {
dragSize = parseInt(swiper.params.scrollbar.dragSize, 10);
}
if (swiper.isHorizontal()) {
$dragEl[0].style.width = `${dragSize}px`;
} else {
$dragEl[0].style.height = `${dragSize}px`;
}
if (divider >= 1) {
$el[0].style.display = 'none';
} else {
$el[0].style.display = '';
}
if (swiper.params.scrollbarHide) {
$el[0].style.opacity = 0;
}
Utils.extend(scrollbar, {
trackSize,
divider,
moveDivider,
dragSize,
});
},
setDragPosition(e) {
const swiper = this;
const { scrollbar } = swiper;
const { $el, dragSize, trackSize } = scrollbar;
let pointerPosition;
if (swiper.isHorizontal()) {
pointerPosition = ((e.type === 'touchstart' || e.type === 'touchmove') ? e.targetTouches[0].pageX : e.pageX || e.clientX);
} else {
pointerPosition = ((e.type === 'touchstart' || e.type === 'touchmove') ? e.targetTouches[0].pageY : e.pageY || e.clientY);
}
let positionRatio;
positionRatio = ((pointerPosition) - $el.offset()[swiper.isHorizontal() ? 'left' : 'top'] - (dragSize / 2)) / (trackSize - dragSize);
positionRatio = Math.max(Math.min(positionRatio, 1), 0);
if (swiper.rtl) {
positionRatio = 1 - positionRatio;
}
const position = swiper.minTranslate() + ((swiper.maxTranslate() - swiper.minTranslate()) * positionRatio);
swiper.updateProgress(position);
swiper.setTranslate(position);
swiper.updateActiveIndex();
swiper.updateSlidesClasses();
},
onDragStart(e) {
const swiper = this;
const params = swiper.params.scrollbar;
const { scrollbar, $wrapperEl } = swiper;
const { $el, $dragEl } = scrollbar;
swiper.scrollbar.isTouched = true;
e.preventDefault();
e.stopPropagation();
$wrapperEl.transition(100);
$dragEl.transition(100);
scrollbar.setDragPosition(e);
clearTimeout(swiper.scrollbar.dragTimeout);
$el.transition(0);
if (params.hide) {
$el.css('opacity', 1);
}
swiper.emit('scrollbarDragStart', e);
},
onDragMove(e) {
const swiper = this;
const { scrollbar, $wrapperEl } = swiper;
const { $el, $dragEl } = scrollbar;
if (!swiper.scrollbar.isTouched) return;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
scrollbar.setDragPosition(e);
$wrapperEl.transition(0);
$el.transition(0);
$dragEl.transition(0);
swiper.emit('scrollbarDragMove', e);
},
onDragEnd(e) {
const swiper = this;
const params = swiper.params.scrollbar;
const { scrollbar } = swiper;
const { $el } = scrollbar;
if (!swiper.scrollbar.isTouched) return;
swiper.scrollbar.isTouched = false;
if (params.hide) {
clearTimeout(swiper.scrollbar.dragTimeout);
swiper.scrollbar.dragTimeout = Utils.nextTick(() => {
$el.css('opacity', 0);
$el.transition(400);
}, 1000);
}
swiper.emit('scrollbarDragEnd', e);
if (params.snapOnRelease) {
swiper.slideReset();
}
},
enableDraggable() {
const swiper = this;
if (!swiper.params.scrollbar.el) return;
const { scrollbar } = swiper;
const $el = scrollbar.$el;
const target = Support$1.touch ? $el[0] : document;
$el.on(swiper.scrollbar.dragEvents.start, swiper.scrollbar.onDragStart);
$(target).on(swiper.scrollbar.dragEvents.move, swiper.scrollbar.onDragMove);
$(target).on(swiper.scrollbar.dragEvents.end, swiper.scrollbar.onDragEnd);
},
disableDraggable() {
const swiper = this;
if (!swiper.params.scrollbar.el) return;
const { scrollbar } = swiper;
const $el = scrollbar.$el;
const target = Support$1.touch ? $el[0] : document;
$el.off(swiper.scrollbar.dragEvents.start);
$(target).off(swiper.scrollbar.dragEvents.move);
$(target).off(swiper.scrollbar.dragEvents.end);
},
init() {
const swiper = this;
if (!swiper.params.scrollbar.el) return;
const { scrollbar, $el: $swiperEl, touchEvents } = swiper;
const params = swiper.params.scrollbar;
let $el = $(params.el);
if (swiper.params.uniqueNavElements && typeof params.el === 'string' && $el.length > 1 && $swiperEl.find(params.el).length === 1) {
$el = $swiperEl.find(params.el);
}
let $dragEl = $el.find('.swiper-scrollbar-drag');
if ($dragEl.length === 0) {
$dragEl = $('<div class="swiper-scrollbar-drag"></div>');
$el.append($dragEl);
}
swiper.scrollbar.dragEvents = (function dragEvents() {
if ((swiper.params.simulateTouch === false && !Support$1.touch)) {
return {
start: 'mousedown',
move: 'mousemove',
end: 'mouseup',
};
}
return touchEvents;
}());
Utils.extend(scrollbar, {
$el,
el: $el[0],
$dragEl,
dragEl: $dragEl[0],
});
if (params.draggable) {
scrollbar.enableDraggable();
}
},
destroy() {
const swiper = this;
swiper.scrollbar.disableDraggable();
},
};
var Scrollbar$1 = {
name: 'scrollbar',
params: {
scrollbar: {
el: null,
dragSize: 'auto',
hide: false,
draggable: false,
snapOnRelease: true,
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
scrollbar: {
init: Scrollbar.init.bind(swiper),
destroy: Scrollbar.destroy.bind(swiper),
updateSize: Scrollbar.updateSize.bind(swiper),
setTranslate: Scrollbar.setTranslate.bind(swiper),
setTransition: Scrollbar.setTransition.bind(swiper),
enableDraggable: Scrollbar.enableDraggable.bind(swiper),
disableDraggable: Scrollbar.disableDraggable.bind(swiper),
setDragPosition: Scrollbar.setDragPosition.bind(swiper),
onDragStart: Scrollbar.onDragStart.bind(swiper),
onDragMove: Scrollbar.onDragMove.bind(swiper),
onDragEnd: Scrollbar.onDragEnd.bind(swiper),
isTouched: false,
timeout: null,
dragTimeout: null,
},
});
},
on: {
init() {
const swiper = this;
swiper.scrollbar.init();
swiper.scrollbar.updateSize();
swiper.scrollbar.setTranslate();
},
update() {
const swiper = this;
swiper.scrollbar.updateSize();
},
resize() {
const swiper = this;
swiper.scrollbar.updateSize();
},
observerUpdate() {
const swiper = this;
swiper.scrollbar.updateSize();
},
setTranslate() {
const swiper = this;
swiper.scrollbar.setTranslate();
},
setTransition(duration) {
const swiper = this;
swiper.scrollbar.setTransition(duration);
},
destroy() {
const swiper = this;
swiper.scrollbar.destroy();
},
},
};
const Parallax = {
setTransform(el, progress) {
const swiper = this;
const { rtl } = swiper;
const $el = $(el);
const rtlFactor = rtl ? -1 : 1;
const p = $el.attr('data-swiper-parallax') || '0';
let x = $el.attr('data-swiper-parallax-x');
let y = $el.attr('data-swiper-parallax-y');
const scale = $el.attr('data-swiper-parallax-scale');
const opacity = $el.attr('data-swiper-parallax-opacity');
if (x || y) {
x = x || '0';
y = y || '0';
} else if (swiper.isHorizontal()) {
x = p;
y = '0';
} else {
y = p;
x = '0';
}
if ((x).indexOf('%') >= 0) {
x = `${parseInt(x, 10) * progress * rtlFactor}%`;
} else {
x = `${x * progress * rtlFactor}px`;
}
if ((y).indexOf('%') >= 0) {
y = `${parseInt(y, 10) * progress}%`;
} else {
y = `${y * progress}px`;
}
if (typeof opacity !== 'undefined' && opacity !== null) {
const currentOpacity = opacity - ((opacity - 1) * (1 - Math.abs(progress)));
$el[0].style.opacity = currentOpacity;
}
if (typeof scale === 'undefined' || scale === null) {
$el.transform(`translate3d(${x}, ${y}, 0px)`);
} else {
const currentScale = scale - ((scale - 1) * (1 - Math.abs(progress)));
$el.transform(`translate3d(${x}, ${y}, 0px) scale(${currentScale})`);
}
},
setTranslate() {
const swiper = this;
const { $el, slides, progress, snapGrid } = swiper;
$el.children('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
.each((index, el) => {
swiper.parallax.setTransform(el, progress);
});
slides.each((slideIndex, slideEl) => {
let slideProgress = slideEl.progress;
if (swiper.params.slidesPerGroup > 1 && swiper.params.slidesPerView !== 'auto') {
slideProgress += Math.ceil(slideIndex / 2) - (progress * (snapGrid.length - 1));
}
slideProgress = Math.min(Math.max(slideProgress, -1), 1);
$(slideEl).find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
.each((index, el) => {
swiper.parallax.setTransform(el, slideProgress);
});
});
},
setTransition(duration = this.params.speed) {
const swiper = this;
const { $el } = swiper;
$el.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
.each((index, parallaxEl) => {
const $parallaxEl = $(parallaxEl);
let parallaxDuration = parseInt($parallaxEl.attr('data-swiper-parallax-duration'), 10) || duration;
if (duration === 0) parallaxDuration = 0;
$parallaxEl.transition(parallaxDuration);
});
},
};
var Parallax$1 = {
name: 'parallax',
params: {
parallax: {
enabled: false,
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
parallax: {
setTransform: Parallax.setTransform.bind(swiper),
setTranslate: Parallax.setTranslate.bind(swiper),
setTransition: Parallax.setTransition.bind(swiper),
},
});
},
on: {
beforeInit() {
const swiper = this;
swiper.params.watchSlidesProgress = true;
},
init() {
const swiper = this;
if (!swiper.params.parallax) return;
swiper.parallax.setTranslate();
},
setTranslate() {
const swiper = this;
if (!swiper.params.parallax) return;
swiper.parallax.setTranslate();
},
setTransition(duration) {
const swiper = this;
if (!swiper.params.parallax) return;
swiper.parallax.setTransition(duration);
},
},
};
const Zoom = {
// Calc Scale From Multi-touches
getDistanceBetweenTouches(e) {
if (e.targetTouches.length < 2) return 1;
const x1 = e.targetTouches[0].pageX;
const y1 = e.targetTouches[0].pageY;
const x2 = e.targetTouches[1].pageX;
const y2 = e.targetTouches[1].pageY;
const distance = Math.sqrt(((x2 - x1) ** 2) + ((y2 - y1) ** 2));
return distance;
},
// Events
onGestureStart(e) {
const swiper = this;
const params = swiper.params.zoom;
const zoom = swiper.zoom;
const { gesture } = zoom;
zoom.fakeGestureTouched = false;
zoom.fakeGestureMoved = false;
if (!Support$1.gestures) {
if (e.type !== 'touchstart' || (e.type === 'touchstart' && e.targetTouches.length < 2)) {
return;
}
zoom.fakeGestureTouched = true;
gesture.scaleStart = Zoom.getDistanceBetweenTouches(e);
}
if (!gesture.$slideEl || !gesture.$slideEl.length) {
gesture.$slideEl = $(this);
if (gesture.$slideEl.length === 0) gesture.$slideEl = swiper.slides.eq(swiper.activeIndex);
gesture.$imageEl = gesture.$slideEl.find('img, svg, canvas');
gesture.$imageWrapEl = gesture.$imageEl.parent(`.${params.containerClass}`);
gesture.maxRatio = gesture.$imageWrapEl.attr('data-swiper-zoom') || params.maxRatio;
if (gesture.$imageWrapEl.length === 0) {
gesture.$imageEl = undefined;
return;
}
}
gesture.$imageEl.transition(0);
swiper.zoom.isScaling = true;
},
onGestureChange(e) {
const swiper = this;
const params = swiper.params.zoom;
const zoom = swiper.zoom;
const { gesture } = zoom;
if (!Support$1.gestures) {
if (e.type !== 'touchmove' || (e.type === 'touchmove' && e.targetTouches.length < 2)) {
return;
}
zoom.fakeGestureMoved = true;
gesture.scaleMove = Zoom.getDistanceBetweenTouches(e);
}
if (!gesture.$imageEl || gesture.$imageEl.length === 0) return;
if (Support$1.gestures) {
swiper.zoom.scale = e.scale * zoom.currentScale;
} else {
zoom.scale = (gesture.scaleMove / gesture.scaleStart) * zoom.currentScale;
}
if (zoom.scale > gesture.maxRatio) {
zoom.scale = (gesture.maxRatio - 1) + (((zoom.scale - gesture.maxRatio) + 1) ** 0.5);
}
if (zoom.scale < params.minRatio) {
zoom.scale = (params.minRatio + 1) - (((params.minRatio - zoom.scale) + 1) ** 0.5);
}
gesture.$imageEl.transform(`translate3d(0,0,0) scale(${zoom.scale})`);
},
onGestureEnd(e) {
const swiper = this;
const params = swiper.params.zoom;
const zoom = swiper.zoom;
const { gesture } = zoom;
if (!Support$1.gestures) {
if (!zoom.fakeGestureTouched || !zoom.fakeGestureMoved) {
return;
}
if (e.type !== 'touchend' || (e.type === 'touchend' && e.changedTouches.length < 2 && !Device.android)) {
return;
}
zoom.fakeGestureTouched = false;
zoom.fakeGestureMoved = false;
}
if (!gesture.$imageEl || gesture.$imageEl.length === 0) return;
zoom.scale = Math.max(Math.min(zoom.scale, gesture.maxRatio), params.minRatio);
gesture.$imageEl.transition(swiper.params.speed).transform(`translate3d(0,0,0) scale(${zoom.scale})`);
zoom.currentScale = zoom.scale;
zoom.isScaling = false;
if (zoom.scale === 1) gesture.$slideEl = undefined;
},
onTouchStart(e) {
const swiper = this;
const zoom = swiper.zoom;
const { gesture, image } = zoom;
if (!gesture.$imageEl || gesture.$imageEl.length === 0) return;
if (image.isTouched) return;
if (Device.android) e.preventDefault();
image.isTouched = true;
image.touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
image.touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
},
onTouchMove(e) {
const swiper = this;
const zoom = swiper.zoom;
const { gesture, image, velocity } = zoom;
if (!gesture.$imageEl || gesture.$imageEl.length === 0) return;
swiper.allowClick = false;
if (!image.isTouched || !gesture.$slideEl) return;
if (!image.isMoved) {
image.width = gesture.$imageEl[0].offsetWidth;
image.height = gesture.$imageEl[0].offsetHeight;
image.startX = Utils.getTranslate(gesture.$imageWrapEl[0], 'x') || 0;
image.startY = Utils.getTranslate(gesture.$imageWrapEl[0], 'y') || 0;
gesture.slideWidth = gesture.$slideEl[0].offsetWidth;
gesture.slideHeight = gesture.$slideEl[0].offsetHeight;
gesture.$imageWrapEl.transition(0);
if (swiper.rtl) image.startX = -image.startX;
if (swiper.rtl) image.startY = -image.startY;
}
// Define if we need image drag
const scaledWidth = image.width * zoom.scale;
const scaledHeight = image.height * zoom.scale;
if (scaledWidth < gesture.slideWidth && scaledHeight < gesture.slideHeight) return;
image.minX = Math.min(((gesture.slideWidth / 2) - (scaledWidth / 2)), 0);
image.maxX = -image.minX;
image.minY = Math.min(((gesture.slideHeight / 2) - (scaledHeight / 2)), 0);
image.maxY = -image.minY;
image.touchesCurrent.x = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
image.touchesCurrent.y = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (!image.isMoved && !zoom.isScaling) {
if (
swiper.isHorizontal() &&
(
(Math.floor(image.minX) === Math.floor(image.startX) && image.touchesCurrent.x < image.touchesStart.x) ||
(Math.floor(image.maxX) === Math.floor(image.startX) && image.touchesCurrent.x > image.touchesStart.x)
)
) {
image.isTouched = false;
return;
} else if (
!swiper.isHorizontal() &&
(
(Math.floor(image.minY) === Math.floor(image.startY) && image.touchesCurrent.y < image.touchesStart.y) ||
(Math.floor(image.maxY) === Math.floor(image.startY) && image.touchesCurrent.y > image.touchesStart.y)
)
) {
image.isTouched = false;
return;
}
}
e.preventDefault();
e.stopPropagation();
image.isMoved = true;
image.currentX = (image.touchesCurrent.x - image.touchesStart.x) + image.startX;
image.currentY = (image.touchesCurrent.y - image.touchesStart.y) + image.startY;
if (image.currentX < image.minX) {
image.currentX = (image.minX + 1) - (((image.minX - image.currentX) + 1) ** 0.8);
}
if (image.currentX > image.maxX) {
image.currentX = (image.maxX - 1) + (((image.currentX - image.maxX) + 1) ** 0.8);
}
if (image.currentY < image.minY) {
image.currentY = (image.minY + 1) - (((image.minY - image.currentY) + 1) ** 0.8);
}
if (image.currentY > image.maxY) {
image.currentY = (image.maxY - 1) + (((image.currentY - image.maxY) + 1) ** 0.8);
}
// Velocity
if (!velocity.prevPositionX) velocity.prevPositionX = image.touchesCurrent.x;
if (!velocity.prevPositionY) velocity.prevPositionY = image.touchesCurrent.y;
if (!velocity.prevTime) velocity.prevTime = Date.now();
velocity.x = (image.touchesCurrent.x - velocity.prevPositionX) / (Date.now() - velocity.prevTime) / 2;
velocity.y = (image.touchesCurrent.y - velocity.prevPositionY) / (Date.now() - velocity.prevTime) / 2;
if (Math.abs(image.touchesCurrent.x - velocity.prevPositionX) < 2) velocity.x = 0;
if (Math.abs(image.touchesCurrent.y - velocity.prevPositionY) < 2) velocity.y = 0;
velocity.prevPositionX = image.touchesCurrent.x;
velocity.prevPositionY = image.touchesCurrent.y;
velocity.prevTime = Date.now();
gesture.$imageWrapEl.transform(`translate3d(${image.currentX}px, ${image.currentY}px,0)`);
},
onTouchEnd() {
const swiper = this;
const zoom = swiper.zoom;
const { gesture, image, velocity } = zoom;
if (!gesture.$imageEl || gesture.$imageEl.length === 0) return;
if (!image.isTouched || !image.isMoved) {
image.isTouched = false;
image.isMoved = false;
return;
}
image.isTouched = false;
image.isMoved = false;
let momentumDurationX = 300;
let momentumDurationY = 300;
const momentumDistanceX = velocity.x * momentumDurationX;
const newPositionX = image.currentX + momentumDistanceX;
const momentumDistanceY = velocity.y * momentumDurationY;
const newPositionY = image.currentY + momentumDistanceY;
// Fix duration
if (velocity.x !== 0) momentumDurationX = Math.abs((newPositionX - image.currentX) / velocity.x);
if (velocity.y !== 0) momentumDurationY = Math.abs((newPositionY - image.currentY) / velocity.y);
const momentumDuration = Math.max(momentumDurationX, momentumDurationY);
image.currentX = newPositionX;
image.currentY = newPositionY;
// Define if we need image drag
const scaledWidth = image.width * zoom.scale;
const scaledHeight = image.height * zoom.scale;
image.minX = Math.min(((gesture.slideWidth / 2) - (scaledWidth / 2)), 0);
image.maxX = -image.minX;
image.minY = Math.min(((gesture.slideHeight / 2) - (scaledHeight / 2)), 0);
image.maxY = -image.minY;
image.currentX = Math.max(Math.min(image.currentX, image.maxX), image.minX);
image.currentY = Math.max(Math.min(image.currentY, image.maxY), image.minY);
gesture.$imageWrapEl.transition(momentumDuration).transform(`translate3d(${image.currentX}px, ${image.currentY}px,0)`);
},
onTransitionEnd() {
const swiper = this;
const zoom = swiper.zoom;
const { gesture } = zoom;
if (gesture.$slideEl && swiper.previousIndex !== swiper.activeIndex) {
gesture.$imageEl.transform('translate3d(0,0,0) scale(1)');
gesture.$imageWrapEl.transform('translate3d(0,0,0)');
gesture.$slideEl = undefined;
gesture.$imageEl = undefined;
gesture.$imageWrapEl = undefined;
zoom.scale = 1;
zoom.currentScale = 1;
}
},
// Toggle Zoom
toggle(e) {
const swiper = this;
const zoom = swiper.zoom;
if (zoom.scale && zoom.scale !== 1) {
// Zoom Out
zoom.out();
} else {
// Zoom In
zoom.in(e);
}
},
in(e) {
const swiper = this;
const zoom = swiper.zoom;
const params = swiper.params.zoom;
const { gesture, image } = zoom;
if (!gesture.$slideEl) {
gesture.$slideEl = swiper.clickedSlide ? $(swiper.clickedSlide) : swiper.slides.eq(swiper.activeIndex);
gesture.$imageEl = gesture.$slideEl.find('img, svg, canvas');
gesture.$imageWrapEl = gesture.$imageEl.parent(`.${params.containerClass}`);
}
if (!gesture.$imageEl || gesture.$imageEl.length === 0) return;
gesture.$slideEl.addClass(`${params.zoomedSlideClass}`);
let touchX;
let touchY;
let offsetX;
let offsetY;
let diffX;
let diffY;
let translateX;
let translateY;
let imageWidth;
let imageHeight;
let scaledWidth;
let scaledHeight;
let translateMinX;
let translateMinY;
let translateMaxX;
let translateMaxY;
let slideWidth;
let slideHeight;
if (typeof image.touchesStart.x === 'undefined' && e) {
touchX = e.type === 'touchend' ? e.changedTouches[0].pageX : e.pageX;
touchY = e.type === 'touchend' ? e.changedTouches[0].pageY : e.pageY;
} else {
touchX = image.touchesStart.x;
touchY = image.touchesStart.y;
}
zoom.scale = gesture.$imageWrapEl.attr('data-swiper-zoom') || params.maxRatio;
zoom.currentScale = gesture.$imageWrapEl.attr('data-swiper-zoom') || params.maxRatio;
if (e) {
slideWidth = gesture.$slideEl[0].offsetWidth;
slideHeight = gesture.$slideEl[0].offsetHeight;
offsetX = gesture.$slideEl.offset().left;
offsetY = gesture.$slideEl.offset().top;
diffX = (offsetX + (slideWidth / 2)) - touchX;
diffY = (offsetY + (slideHeight / 2)) - touchY;
imageWidth = gesture.$imageEl[0].offsetWidth;
imageHeight = gesture.$imageEl[0].offsetHeight;
scaledWidth = imageWidth * zoom.scale;
scaledHeight = imageHeight * zoom.scale;
translateMinX = Math.min(((slideWidth / 2) - (scaledWidth / 2)), 0);
translateMinY = Math.min(((slideHeight / 2) - (scaledHeight / 2)), 0);
translateMaxX = -translateMinX;
translateMaxY = -translateMinY;
translateX = diffX * zoom.scale;
translateY = diffY * zoom.scale;
if (translateX < translateMinX) {
translateX = translateMinX;
}
if (translateX > translateMaxX) {
translateX = translateMaxX;
}
if (translateY < translateMinY) {
translateY = translateMinY;
}
if (translateY > translateMaxY) {
translateY = translateMaxY;
}
} else {
translateX = 0;
translateY = 0;
}
gesture.$imageWrapEl.transition(300).transform(`translate3d(${translateX}px, ${translateY}px,0)`);
gesture.$imageEl.transition(300).transform(`translate3d(0,0,0) scale(${zoom.scale})`);
},
out() {
const swiper = this;
const zoom = swiper.zoom;
const params = swiper.params.zoom;
const { gesture } = zoom;
if (!gesture.$slideEl) {
gesture.$slideEl = swiper.clickedSlide ? $(swiper.clickedSlide) : swiper.slides.eq(swiper.activeIndex);
gesture.$imageEl = gesture.$slideEl.find('img, svg, canvas');
gesture.$imageWrapEl = gesture.$imageEl.parent(`.${params.containerClass}`);
}
if (!gesture.$imageEl || gesture.$imageEl.length === 0) return;
zoom.scale = 1;
zoom.currentScale = 1;
gesture.$imageWrapEl.transition(300).transform('translate3d(0,0,0)');
gesture.$imageEl.transition(300).transform('translate3d(0,0,0) scale(1)');
gesture.$slideEl.removeClass(`${params.zoomedSlideClass}`);
gesture.$slideEl = undefined;
},
// Attach/Detach Events
enable() {
const swiper = this;
const zoom = swiper.zoom;
if (zoom.enabled) return;
zoom.enabled = true;
const slides = swiper.slides;
const passiveListener = swiper.touchEvents.start === 'touchstart' && Support$1.passiveListener && swiper.params.passiveListeners ? { passive: true, capture: false } : false;
// Scale image
if (Support$1.gestures) {
slides.on('gesturestart', zoom.onGestureStart, passiveListener);
slides.on('gesturechange', zoom.onGestureChange, passiveListener);
slides.on('gestureend', zoom.onGestureEnd, passiveListener);
} else if (swiper.touchEvents.start === 'touchstart') {
slides.on(swiper.touchEvents.start, zoom.onGestureStart, passiveListener);
slides.on(swiper.touchEvents.move, zoom.onGestureChange, passiveListener);
slides.on(swiper.touchEvents.end, zoom.onGestureEnd, passiveListener);
}
// Move image
swiper.slides.each((index, slideEl) => {
const $slideEl = $(slideEl);
if ($slideEl.find(`.${swiper.params.zoom.containerClass}`).length > 0) {
$slideEl.on(swiper.touchEvents.move, zoom.onTouchMove);
}
});
},
disable() {
const swiper = this;
const zoom = swiper.zoom;
if (!zoom.enabled) return;
swiper.zoom.enabled = false;
const slides = swiper.slides;
const passiveListener = swiper.touchEvents.start === 'touchstart' && Support$1.passiveListener && swiper.params.passiveListeners ? { passive: true, capture: false } : false;
// Scale image
if (Support$1.gestures) {
slides.off('gesturestart', zoom.onGestureStart, passiveListener);
slides.off('gesturechange', zoom.onGestureChange, passiveListener);
slides.off('gestureend', zoom.onGestureEnd, passiveListener);
} else if (swiper.touchEvents.start === 'touchstart') {
slides.off(swiper.touchEvents.start, zoom.onGestureStart, passiveListener);
slides.off(swiper.touchEvents.move, zoom.onGestureChange, passiveListener);
slides.off(swiper.touchEvents.end, zoom.onGestureEnd, passiveListener);
}
// Move image
swiper.slides.each((index, slideEl) => {
const $slideEl = $(slideEl);
if ($slideEl.find(`.${swiper.params.zoom.containerClass}`).length > 0) {
$slideEl.off(swiper.touchEvents.move, zoom.onTouchMove);
}
});
},
};
var Zoom$1 = {
name: 'zoom',
params: {
zoom: {
enabled: false,
maxRatio: 3,
minRatio: 1,
toggle: true,
containerClass: 'swiper-zoom-container',
zoomedSlideClass: 'swiper-slide-zoomed',
},
},
create() {
const swiper = this;
const zoom = {
enabled: false,
scale: 1,
currentScale: 1,
isScaling: false,
gesture: {
$slideEl: undefined,
slideWidth: undefined,
slideHeight: undefined,
$imageEl: undefined,
$imageWrapEl: undefined,
maxRatio: 3,
},
image: {
isTouched: undefined,
isMoved: undefined,
currentX: undefined,
currentY: undefined,
minX: undefined,
minY: undefined,
maxX: undefined,
maxY: undefined,
width: undefined,
height: undefined,
startX: undefined,
startY: undefined,
touchesStart: {},
touchesCurrent: {},
},
velocity: {
x: undefined,
y: undefined,
prevPositionX: undefined,
prevPositionY: undefined,
prevTime: undefined,
},
};
('onGestureStart onGestureChange onGestureEnd onTouchStart onTouchMove onTouchEnd onTransitionEnd toggle enable disable in out').split(' ').forEach((methodName) => {
zoom[methodName] = Zoom[methodName].bind(swiper);
});
Utils.extend(swiper, {
zoom,
});
},
on: {
init() {
const swiper = this;
if (swiper.params.zoom.enabled) {
swiper.zoom.enable();
}
},
destroy() {
const swiper = this;
swiper.zoom.disable();
},
touchStart(e) {
const swiper = this;
if (!swiper.zoom.enabled) return;
swiper.zoom.onTouchStart(e);
},
touchEnd(e) {
const swiper = this;
if (!swiper.zoom.enabled) return;
swiper.zoom.onTouchEnd(e);
},
doubleTap(e) {
const swiper = this;
if (swiper.params.zoom.enabled && swiper.zoom.enabled && swiper.params.zoom.toggle) {
swiper.zoom.toggle(e);
}
},
transitionEnd() {
const swiper = this;
if (swiper.zoom.enabled && swiper.params.zoom.enabled) {
swiper.zoom.onTransitionEnd();
}
},
},
};
const Lazy$2 = {
loadInSlide(index, loadInDuplicate = true) {
const swiper = this;
const params = swiper.params.lazy;
if (typeof index === 'undefined') return;
if (swiper.slides.length === 0) return;
const isVirtual = swiper.virtual && swiper.params.virtual.enabled;
const $slideEl = isVirtual
? swiper.$wrapperEl.children(`.${swiper.params.slideClass}[data-swiper-slide-index="${index}"]`)
: swiper.slides.eq(index);
let $images = $slideEl.find(`.${params.elementClass}:not(.${params.loadedClass}):not(.${params.loadingClass})`);
if ($slideEl.hasClass(params.elementClass) && !$slideEl.hasClass(params.loadedClass) && !$slideEl.hasClass(params.loadingClass)) {
$images = $images.add($slideEl[0]);
}
if ($images.length === 0) return;
$images.each((imageIndex, imageEl) => {
const $imageEl = $(imageEl);
$imageEl.addClass(params.loadingClass);
const background = $imageEl.attr('data-background');
const src = $imageEl.attr('data-src');
const srcset = $imageEl.attr('data-srcset');
const sizes = $imageEl.attr('data-sizes');
swiper.loadImage($imageEl[0], (src || background), srcset, sizes, false, () => {
if (typeof swiper === 'undefined' || swiper === null || !swiper || (swiper && !swiper.params) || swiper.destroyed) return;
if (background) {
$imageEl.css('background-image', `url("${background}")`);
$imageEl.removeAttr('data-background');
} else {
if (srcset) {
$imageEl.attr('srcset', srcset);
$imageEl.removeAttr('data-srcset');
}
if (sizes) {
$imageEl.attr('sizes', sizes);
$imageEl.removeAttr('data-sizes');
}
if (src) {
$imageEl.attr('src', src);
$imageEl.removeAttr('data-src');
}
}
$imageEl.addClass(params.loadedClass).removeClass(params.loadingClass);
$slideEl.find(`.${params.preloaderClass}`).remove();
if (swiper.params.loop && loadInDuplicate) {
const slideOriginalIndex = $slideEl.attr('data-swiper-slide-index');
if ($slideEl.hasClass(swiper.params.slideDuplicateClass)) {
const originalSlide = swiper.$wrapperEl.children(`[data-swiper-slide-index="${slideOriginalIndex}"]:not(.${swiper.params.slideDuplicateClass})`);
swiper.lazy.loadInSlide(originalSlide.index(), false);
} else {
const duplicatedSlide = swiper.$wrapperEl.children(`.${swiper.params.slideDuplicateClass}[data-swiper-slide-index="${slideOriginalIndex}"]`);
swiper.lazy.loadInSlide(duplicatedSlide.index(), false);
}
}
swiper.emit('lazyImageReady', $slideEl[0], $imageEl[0]);
});
swiper.emit('lazyImageLoad', $slideEl[0], $imageEl[0]);
});
},
load() {
const swiper = this;
const { $wrapperEl, params: swiperParams, slides, activeIndex } = swiper;
const isVirtual = swiper.virtual && swiperParams.virtual.enabled;
const params = swiperParams.lazy;
let slidesPerView = swiperParams.slidesPerView;
if (slidesPerView === 'auto') {
slidesPerView = 0;
}
function slideExist(index) {
if (isVirtual) {
if ($wrapperEl.children(`.${swiperParams.slideClass}[data-swiper-slide-index="${index}"]`).length) {
return true;
}
} else if (slides[index]) return true;
return false;
}
function slideIndex(slideEl) {
if (isVirtual) {
return $(slideEl).attr('data-swiper-slide-index');
}
return $(slideEl).index();
}
if (!swiper.lazy.initialImageLoaded) swiper.lazy.initialImageLoaded = true;
if (swiper.params.watchSlidesVisibility) {
$wrapperEl.children(`.${swiperParams.slideVisibleClass}`).each((elIndex, slideEl) => {
const index = isVirtual ? $(slideEl).attr('data-swiper-slide-index') : $(slideEl).index();
swiper.lazy.loadInSlide(index);
});
} else if (slidesPerView > 1) {
for (let i = activeIndex; i < activeIndex + slidesPerView; i += 1) {
if (slideExist(i)) swiper.lazy.loadInSlide(i);
}
} else {
swiper.lazy.loadInSlide(activeIndex);
}
if (params.loadPrevNext) {
if (slidesPerView > 1 || (params.loadPrevNextAmount && params.loadPrevNextAmount > 1)) {
const amount = params.loadPrevNextAmount;
const spv = slidesPerView;
const maxIndex = Math.min(activeIndex + spv + Math.max(amount, spv), slides.length);
const minIndex = Math.max(activeIndex - Math.max(spv, amount), 0);
// Next Slides
for (let i = activeIndex + slidesPerView; i < maxIndex; i += 1) {
if (slideExist(i)) swiper.lazy.loadInSlide(i);
}
// Prev Slides
for (let i = minIndex; i < activeIndex; i += 1) {
if (slideExist(i)) swiper.lazy.loadInSlide(i);
}
} else {
const nextSlide = $wrapperEl.children(`.${swiperParams.slideNextClass}`);
if (nextSlide.length > 0) swiper.lazy.loadInSlide(slideIndex(nextSlide));
const prevSlide = $wrapperEl.children(`.${swiperParams.slidePrevClass}`);
if (prevSlide.length > 0) swiper.lazy.loadInSlide(slideIndex(prevSlide));
}
}
},
};
var Lazy$3 = {
name: 'lazy',
params: {
lazy: {
enabled: false,
loadPrevNext: false,
loadPrevNextAmount: 1,
loadOnTransitionStart: false,
elementClass: 'swiper-lazy',
loadingClass: 'swiper-lazy-loading',
loadedClass: 'swiper-lazy-loaded',
preloaderClass: 'swiper-lazy-preloader',
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
lazy: {
initialImageLoaded: false,
load: Lazy$2.load.bind(swiper),
loadInSlide: Lazy$2.loadInSlide.bind(swiper),
},
});
},
on: {
beforeInit() {
const swiper = this;
if (swiper.params.lazy.enabled && swiper.params.preloadImages) {
swiper.params.preloadImages = false;
}
},
init() {
const swiper = this;
if (swiper.params.lazy.enabled && !swiper.params.loop && swiper.params.initialSlide === 0) {
swiper.lazy.load();
}
},
scroll() {
const swiper = this;
if (swiper.params.freeMode && !swiper.params.freeModeSticky) {
swiper.lazy.load();
}
},
resize() {
const swiper = this;
if (swiper.params.lazy.enabled) {
swiper.lazy.load();
}
},
scrollbarDragMove() {
const swiper = this;
if (swiper.params.lazy.enabled) {
swiper.lazy.load();
}
},
transitionStart() {
const swiper = this;
if (swiper.params.lazy.enabled) {
if (swiper.params.lazy.loadOnTransitionStart || (!swiper.params.lazy.loadOnTransitionStart && !swiper.lazy.initialImageLoaded)) {
swiper.lazy.load();
}
}
},
transitionEnd() {
const swiper = this;
if (swiper.params.lazy.enabled && !swiper.params.lazy.loadOnTransitionStart) {
swiper.lazy.load();
}
},
},
};
/* eslint no-bitwise: ["error", { "allow": [">>"] }] */
const Controller = {
LinearSpline(x, y) {
const binarySearch = (function search() {
let maxIndex;
let minIndex;
let guess;
return (array, val) => {
minIndex = -1;
maxIndex = array.length;
while (maxIndex - minIndex > 1) {
guess = maxIndex + minIndex >> 1;
if (array[guess] <= val) {
minIndex = guess;
} else {
maxIndex = guess;
}
}
return maxIndex;
};
}());
this.x = x;
this.y = y;
this.lastIndex = x.length - 1;
// Given an x value (x2), return the expected y2 value:
// (x1,y1) is the known point before given value,
// (x3,y3) is the known point after given value.
let i1;
let i3;
this.interpolate = function interpolate(x2) {
if (!x2) return 0;
// Get the indexes of x1 and x3 (the array indexes before and after given x2):
i3 = binarySearch(this.x, x2);
i1 = i3 - 1;
// We have our indexes i1 & i3, so we can calculate already:
// y2 := ((x2−x1) × (y3−y1)) ÷ (x3−x1) + y1
return (((x2 - this.x[i1]) * (this.y[i3] - this.y[i1])) / (this.x[i3] - this.x[i1])) + this.y[i1];
};
return this;
},
// xxx: for now i will just save one spline function to to
getInterpolateFunction(c) {
const swiper = this;
if (!swiper.controller.spline) {
swiper.controller.spline = swiper.params.loop ?
new Controller.LinearSpline(swiper.slidesGrid, c.slidesGrid) :
new Controller.LinearSpline(swiper.snapGrid, c.snapGrid);
}
},
setTranslate(setTranslate, byController) {
const swiper = this;
const controlled = swiper.controller.control;
let multiplier;
let controlledTranslate;
function setControlledTranslate(c) {
// this will create an Interpolate function based on the snapGrids
// x is the Grid of the scrolled scroller and y will be the controlled scroller
// it makes sense to create this only once and recall it for the interpolation
// the function does a lot of value caching for performance
const translate = c.rtl && c.params.direction === 'horizontal' ? -swiper.translate : swiper.translate;
if (swiper.params.controller.by === 'slide') {
swiper.controller.getInterpolateFunction(c);
// i am not sure why the values have to be multiplicated this way, tried to invert the snapGrid
// but it did not work out
controlledTranslate = -swiper.controller.spline.interpolate(-translate);
}
if (!controlledTranslate || swiper.params.controller.by === 'container') {
multiplier = (c.maxTranslate() - c.minTranslate()) / (swiper.maxTranslate() - swiper.minTranslate());
controlledTranslate = ((translate - swiper.minTranslate()) * multiplier) + c.minTranslate();
}
if (swiper.params.controller.inverse) {
controlledTranslate = c.maxTranslate() - controlledTranslate;
}
c.updateProgress(controlledTranslate);
c.setTranslate(controlledTranslate, swiper);
c.updateActiveIndex();
c.updateSlidesClasses();
}
if (Array.isArray(controlled)) {
for (let i = 0; i < controlled.length; i += 1) {
if (controlled[i] !== byController && controlled[i] instanceof Swiper$2) {
setControlledTranslate(controlled[i]);
}
}
} else if (controlled instanceof Swiper$2 && byController !== controlled) {
setControlledTranslate(controlled);
}
},
setTransition(duration, byController) {
const swiper = this;
const controlled = swiper.controller.control;
let i;
function setControlledTransition(c) {
c.setTransition(duration, swiper);
if (duration !== 0) {
c.transitionStart();
c.$wrapperEl.transitionEnd(() => {
if (!controlled) return;
if (c.params.loop && swiper.params.controller.by === 'slide') {
c.loopFix();
}
c.transitionEnd();
});
}
}
if (Array.isArray(controlled)) {
for (i = 0; i < controlled.length; i += 1) {
if (controlled[i] !== byController && controlled[i] instanceof Swiper$2) {
setControlledTransition(controlled[i]);
}
}
} else if (controlled instanceof Swiper$2 && byController !== controlled) {
setControlledTransition(controlled);
}
},
};
var Controller$1 = {
name: 'controller',
params: {
controller: {
control: undefined,
inverse: false,
by: 'slide', // or 'container'
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
controller: {
control: swiper.params.controller.control,
getInterpolateFunction: Controller.getInterpolateFunction.bind(swiper),
setTranslate: Controller.setTranslate.bind(swiper),
setTransition: Controller.setTransition.bind(swiper),
},
});
},
on: {
update() {
const swiper = this;
if (!swiper.controller.control) return;
if (swiper.controller.spline) {
swiper.controller.spline = undefined;
delete swiper.controller.spline;
}
},
resize() {
const swiper = this;
if (!swiper.controller.control) return;
if (swiper.controller.spline) {
swiper.controller.spline = undefined;
delete swiper.controller.spline;
}
},
observerUpdate() {
const swiper = this;
if (!swiper.controller.control) return;
if (swiper.controller.spline) {
swiper.controller.spline = undefined;
delete swiper.controller.spline;
}
},
setTranslate(translate, byController) {
const swiper = this;
if (!swiper.controller.control) return;
swiper.controller.setTranslate(translate, byController);
},
setTransition(duration, byController) {
const swiper = this;
if (!swiper.controller.control) return;
swiper.controller.setTransition(duration, byController);
},
},
};
const a11y = {
makeElFocusable($el) {
$el.attr('tabIndex', '0');
return $el;
},
addElRole($el, role) {
$el.attr('role', role);
return $el;
},
addElLabel($el, label) {
$el.attr('aria-label', label);
return $el;
},
disableEl($el) {
$el.attr('aria-disabled', true);
return $el;
},
enableEl($el) {
$el.attr('aria-disabled', false);
return $el;
},
onEnterKey(e) {
const swiper = this;
const params = swiper.params.a11y;
if (e.keyCode !== 13) return;
const $targetEl = $(e.target);
if (swiper.navigation && swiper.navigation.$nextEl && $targetEl.is(swiper.navigation.$nextEl)) {
if (!(swiper.isEnd && !swiper.params.loop)) {
swiper.slideNext();
}
if (swiper.isEnd) {
swiper.a11y.notify(params.lastSlideMessage);
} else {
swiper.a11y.notify(params.nextSlideMessage);
}
}
if (swiper.navigation && swiper.navigation.$prevEl && $targetEl.is(swiper.navigation.$prevEl)) {
if (!(swiper.isBeginning && !swiper.params.loop)) {
swiper.slidePrev();
}
if (swiper.isBeginning) {
swiper.a11y.notify(params.firstSlideMessage);
} else {
swiper.a11y.notify(params.prevSlideMessage);
}
}
if (swiper.pagination && $targetEl.is(`.${swiper.params.pagination.bulletClass}`)) {
$targetEl[0].click();
}
},
notify(message) {
const swiper = this;
const notification = swiper.a11y.liveRegion;
if (notification.length === 0) return;
notification.html('');
notification.html(message);
},
updateNavigation() {
const swiper = this;
if (swiper.params.loop) return;
const { $nextEl, $prevEl } = swiper.navigation;
if ($prevEl && $prevEl.length > 0) {
if (swiper.isBeginning) {
swiper.a11y.disableEl($prevEl);
} else {
swiper.a11y.enableEl($prevEl);
}
}
if ($nextEl && $nextEl.length > 0) {
if (swiper.isEnd) {
swiper.a11y.disableEl($nextEl);
} else {
swiper.a11y.enableEl($nextEl);
}
}
},
updatePagination() {
const swiper = this;
const params = swiper.params.a11y;
if (swiper.pagination && swiper.params.pagination.clickable && swiper.pagination.bullets && swiper.pagination.bullets.length) {
swiper.pagination.bullets.each((bulletIndex, bulletEl) => {
const $bulletEl = $(bulletEl);
swiper.a11y.makeElFocusable($bulletEl);
swiper.a11y.addElRole($bulletEl, 'button');
swiper.a11y.addElLabel($bulletEl, params.paginationBulletMessage.replace(/{{index}}/, $bulletEl.index() + 1));
});
}
},
init() {
const swiper = this;
swiper.$el.append(swiper.a11y.liveRegion);
// Navigation
const params = swiper.params.a11y;
let $nextEl;
let $prevEl;
if (swiper.navigation && swiper.navigation.$nextEl) {
$nextEl = swiper.navigation.$nextEl;
}
if (swiper.navigation && swiper.navigation.$prevEl) {
$prevEl = swiper.navigation.$prevEl;
}
if ($nextEl) {
swiper.a11y.makeElFocusable($nextEl);
swiper.a11y.addElRole($nextEl, 'button');
swiper.a11y.addElLabel($nextEl, params.nextSlideMessage);
$nextEl.on('keydown', swiper.a11y.onEnterKey);
}
if ($prevEl) {
swiper.a11y.makeElFocusable($prevEl);
swiper.a11y.addElRole($prevEl, 'button');
swiper.a11y.addElLabel($prevEl, params.prevSlideMessage);
$prevEl.on('keydown', swiper.a11y.onEnterKey);
}
// Pagination
if (swiper.pagination && swiper.params.pagination.clickable && swiper.pagination.bullets && swiper.pagination.bullets.length) {
swiper.pagination.$el.on('keydown', `.${swiper.params.pagination.bulletClass}`, swiper.a11y.onEnterKey);
}
},
destroy() {
const swiper = this;
if (swiper.a11y.liveRegion && swiper.a11y.liveRegion.length > 0) swiper.a11y.liveRegion.remove();
let $nextEl;
let $prevEl;
if (swiper.navigation && swiper.navigation.$nextEl) {
$nextEl = swiper.navigation.$nextEl;
}
if (swiper.navigation && swiper.navigation.$prevEl) {
$prevEl = swiper.navigation.$prevEl;
}
if ($nextEl) {
$nextEl.off('keydown', swiper.a11y.onEnterKey);
}
if ($prevEl) {
$prevEl.off('keydown', swiper.a11y.onEnterKey);
}
// Pagination
if (swiper.pagination && swiper.params.pagination.clickable && swiper.pagination.bullets && swiper.pagination.bullets.length) {
swiper.pagination.$el.off('keydown', `.${swiper.params.pagination.bulletClass}`, swiper.a11y.onEnterKey);
}
},
};
var A11y = {
name: 'a11y',
params: {
a11y: {
enabled: false,
notificationClass: 'swiper-notification',
prevSlideMessage: 'Previous slide',
nextSlideMessage: 'Next slide',
firstSlideMessage: 'This is the first slide',
lastSlideMessage: 'This is the last slide',
paginationBulletMessage: 'Go to slide {{index}}',
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
a11y: {
liveRegion: $(`<span class="${swiper.params.a11y.notificationClass}" aria-live="assertive" aria-atomic="true"></span>`),
},
});
Object.keys(a11y).forEach((methodName) => {
swiper.a11y[methodName] = a11y[methodName].bind(swiper);
});
},
on: {
init() {
const swiper = this;
if (!swiper.params.a11y.enabled) return;
swiper.a11y.init();
swiper.a11y.updateNavigation();
},
toEdge() {
const swiper = this;
if (!swiper.params.a11y.enabled) return;
swiper.a11y.updateNavigation();
},
fromEdge() {
const swiper = this;
if (!swiper.params.a11y.enabled) return;
swiper.a11y.updateNavigation();
},
paginationUpdate() {
const swiper = this;
if (!swiper.params.a11y.enabled) return;
swiper.a11y.updatePagination();
},
destroy() {
const swiper = this;
if (!swiper.params.a11y.enabled) return;
swiper.a11y.destroy();
},
},
};
const Autoplay = {
run() {
const swiper = this;
const $activeSlideEl = swiper.slides.eq(swiper.activeIndex);
let delay = swiper.params.autoplay.delay;
if ($activeSlideEl.attr('data-swiper-autoplay')) {
delay = $activeSlideEl.attr('data-swiper-autoplay') || swiper.params.autoplay.delay;
}
swiper.autoplay.timeout = Utils.nextTick(() => {
if (swiper.params.loop) {
swiper.loopFix();
swiper.slideNext(swiper.params.speed, true, true);
swiper.emit('autoplay');
} else if (!swiper.isEnd) {
swiper.slideNext(swiper.params.speed, true, true);
swiper.emit('autoplay');
} else if (!swiper.params.autoplay.stopOnLastSlide) {
swiper.slideTo(0, swiper.params.speed, true, true);
swiper.emit('autoplay');
} else {
swiper.autoplay.stop();
}
}, delay);
},
start() {
const swiper = this;
if (typeof swiper.autoplay.timeout !== 'undefined') return false;
if (swiper.autoplay.running) return false;
swiper.autoplay.running = true;
swiper.emit('autoplayStart');
swiper.autoplay.run();
return true;
},
stop() {
const swiper = this;
if (!swiper.autoplay.running) return false;
if (typeof swiper.autoplay.timeout === 'undefined') return false;
if (swiper.autoplay.timeout) {
clearTimeout(swiper.autoplay.timeout);
swiper.autoplay.timeout = undefined;
}
swiper.autoplay.running = false;
swiper.emit('autoplayStop');
return true;
},
pause(speed) {
const swiper = this;
if (!swiper.autoplay.running) return;
if (swiper.autoplay.paused) return;
if (swiper.autoplay.timeout) clearTimeout(swiper.autoplay.timeout);
swiper.autoplay.paused = true;
if (speed === 0) {
swiper.autoplay.paused = false;
swiper.autoplay.run();
} else {
swiper.$wrapperEl.transitionEnd(() => {
if (!swiper || swiper.destroyed) return;
swiper.autoplay.paused = false;
if (!swiper.autoplay.running) {
swiper.autoplay.stop();
} else {
swiper.autoplay.run();
}
});
}
},
};
var Autoplay$1 = {
name: 'autoplay',
params: {
autoplay: {
enabled: false,
delay: 3000,
disableOnInteraction: true,
stopOnLastSlide: false,
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
autoplay: {
running: false,
paused: false,
run: Autoplay.run.bind(swiper),
start: Autoplay.start.bind(swiper),
stop: Autoplay.stop.bind(swiper),
pause: Autoplay.pause.bind(swiper),
},
});
},
on: {
init() {
const swiper = this;
if (swiper.params.autoplay.enabled) {
swiper.autoplay.start();
}
},
beforeTransitionStart(speed, internal) {
const swiper = this;
if (swiper.autoplay.running) {
if (internal || !swiper.params.autoplay.disableOnInteraction) {
swiper.autoplay.pause(speed);
} else {
swiper.autoplay.stop();
}
}
},
sliderFirstMove() {
const swiper = this;
if (swiper.autoplay.running) {
if (swiper.params.autoplay.disableOnInteraction) {
swiper.autoplay.stop();
} else {
swiper.autoplay.pause();
}
}
},
destroy() {
const swiper = this;
if (swiper.autoplay.running) {
swiper.autoplay.stop();
}
},
},
};
const Fade = {
setTranslate() {
const swiper = this;
const { slides } = swiper;
for (let i = 0; i < slides.length; i += 1) {
const $slideEl = swiper.slides.eq(i);
const offset = $slideEl[0].swiperSlideOffset;
let tx = -offset;
if (!swiper.params.virtualTranslate) tx -= swiper.translate;
let ty = 0;
if (!swiper.isHorizontal()) {
ty = tx;
tx = 0;
}
const slideOpacity = swiper.params.fadeEffect.crossFade ?
Math.max(1 - Math.abs($slideEl[0].progress), 0) :
1 + Math.min(Math.max($slideEl[0].progress, -1), 0);
$slideEl
.css({
opacity: slideOpacity,
})
.transform(`translate3d(${tx}px, ${ty}px, 0px)`);
}
},
setTransition(duration) {
const swiper = this;
const { slides, $wrapperEl } = swiper;
slides.transition(duration);
if (swiper.params.virtualTranslate && duration !== 0) {
let eventTriggered = false;
slides.transitionEnd(() => {
if (eventTriggered) return;
if (!swiper || swiper.destroyed) return;
eventTriggered = true;
swiper.animating = false;
const triggerEvents = ['webkitTransitionEnd', 'transitionend'];
for (let i = 0; i < triggerEvents.length; i += 1) {
$wrapperEl.trigger(triggerEvents[i]);
}
});
}
},
};
var EffectFade = {
name: 'effect-fade',
params: {
fadeEffect: {
crossFade: false,
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
fadeEffect: {
setTranslate: Fade.setTranslate.bind(swiper),
setTransition: Fade.setTransition.bind(swiper),
},
});
},
on: {
beforeInit() {
const swiper = this;
if (swiper.params.effect !== 'fade') return;
swiper.classNames.push(`${swiper.params.containerModifierClass}fade`);
const overwriteParams = {
slidesPerView: 1,
slidesPerColumn: 1,
slidesPerGroup: 1,
watchSlidesProgress: true,
spaceBetween: 0,
virtualTranslate: true,
};
Utils.extend(swiper.params, overwriteParams);
Utils.extend(swiper.originalParams, overwriteParams);
},
setTranslate() {
const swiper = this;
if (swiper.params.effect !== 'fade') return;
swiper.fadeEffect.setTranslate();
},
setTransition(duration) {
const swiper = this;
if (swiper.params.effect !== 'fade') return;
swiper.fadeEffect.setTransition(duration);
},
},
};
const Cube = {
setTranslate() {
const swiper = this;
const { $el, $wrapperEl, slides, width: swiperWidth, height: swiperHeight, rtl, size: swiperSize } = swiper;
const params = swiper.params.cubeEffect;
const isHorizontal = swiper.isHorizontal();
const isVirtual = swiper.virtual && swiper.params.virtual.enabled;
let wrapperRotate = 0;
let $cubeShadowEl;
if (params.shadow) {
if (isHorizontal) {
$cubeShadowEl = $wrapperEl.find('.swiper-cube-shadow');
if ($cubeShadowEl.length === 0) {
$cubeShadowEl = $('<div class="swiper-cube-shadow"></div>');
$wrapperEl.append($cubeShadowEl);
}
$cubeShadowEl.css({ height: `${swiperWidth}px` });
} else {
$cubeShadowEl = $el.find('.swiper-cube-shadow');
if ($cubeShadowEl.length === 0) {
$cubeShadowEl = $('<div class="swiper-cube-shadow"></div>');
$el.append($cubeShadowEl);
}
}
}
for (let i = 0; i < slides.length; i += 1) {
const $slideEl = slides.eq(i);
let slideIndex = i;
if (isVirtual) {
slideIndex = parseInt($slideEl.attr('data-swiper-slide-index'), 10);
}
let slideAngle = slideIndex * 90;
let round = Math.floor(slideAngle / 360);
if (rtl) {
slideAngle = -slideAngle;
round = Math.floor(-slideAngle / 360);
}
const progress = Math.max(Math.min($slideEl[0].progress, 1), -1);
let tx = 0;
let ty = 0;
let tz = 0;
if (slideIndex % 4 === 0) {
tx = -round * 4 * swiperSize;
tz = 0;
} else if ((slideIndex - 1) % 4 === 0) {
tx = 0;
tz = -round * 4 * swiperSize;
} else if ((slideIndex - 2) % 4 === 0) {
tx = swiperSize + (round * 4 * swiperSize);
tz = swiperSize;
} else if ((slideIndex - 3) % 4 === 0) {
tx = -swiperSize;
tz = (3 * swiperSize) + (swiperSize * 4 * round);
}
if (rtl) {
tx = -tx;
}
if (!isHorizontal) {
ty = tx;
tx = 0;
}
const transform = `rotateX(${isHorizontal ? 0 : -slideAngle}deg) rotateY(${isHorizontal ? slideAngle : 0}deg) translate3d(${tx}px, ${ty}px, ${tz}px)`;
if (progress <= 1 && progress > -1) {
wrapperRotate = (slideIndex * 90) + (progress * 90);
if (rtl) wrapperRotate = (-slideIndex * 90) - (progress * 90);
}
$slideEl.transform(transform);
if (params.slideShadows) {
// Set shadows
let shadowBefore = isHorizontal ? $slideEl.find('.swiper-slide-shadow-left') : $slideEl.find('.swiper-slide-shadow-top');
let shadowAfter = isHorizontal ? $slideEl.find('.swiper-slide-shadow-right') : $slideEl.find('.swiper-slide-shadow-bottom');
if (shadowBefore.length === 0) {
shadowBefore = $(`<div class="swiper-slide-shadow-${isHorizontal ? 'left' : 'top'}"></div>`);
$slideEl.append(shadowBefore);
}
if (shadowAfter.length === 0) {
shadowAfter = $(`<div class="swiper-slide-shadow-${isHorizontal ? 'right' : 'bottom'}"></div>`);
$slideEl.append(shadowAfter);
}
if (shadowBefore.length) shadowBefore[0].style.opacity = Math.max(-progress, 0);
if (shadowAfter.length) shadowAfter[0].style.opacity = Math.max(progress, 0);
}
}
$wrapperEl.css({
'-webkit-transform-origin': `50% 50% -${swiperSize / 2}px`,
'-moz-transform-origin': `50% 50% -${swiperSize / 2}px`,
'-ms-transform-origin': `50% 50% -${swiperSize / 2}px`,
'transform-origin': `50% 50% -${swiperSize / 2}px`,
});
if (params.shadow) {
if (isHorizontal) {
$cubeShadowEl.transform(`translate3d(0px, ${(swiperWidth / 2) + params.shadowOffset}px, ${-swiperWidth / 2}px) rotateX(90deg) rotateZ(0deg) scale(${params.shadowScale})`);
} else {
const shadowAngle = Math.abs(wrapperRotate) - (Math.floor(Math.abs(wrapperRotate) / 90) * 90);
const multiplier = 1.5 - (
(Math.sin((shadowAngle * 2 * Math.PI) / 360) / 2) +
(Math.cos((shadowAngle * 2 * Math.PI) / 360) / 2)
);
const scale1 = params.shadowScale;
const scale2 = params.shadowScale / multiplier;
const offset = params.shadowOffset;
$cubeShadowEl.transform(`scale3d(${scale1}, 1, ${scale2}) translate3d(0px, ${(swiperHeight / 2) + offset}px, ${-swiperHeight / 2 / scale2}px) rotateX(-90deg)`);
}
}
const zFactor = (Browser.isSafari || Browser.isUiWebView) ? (-swiperSize / 2) : 0;
$wrapperEl
.transform(`translate3d(0px,0,${zFactor}px) rotateX(${swiper.isHorizontal() ? 0 : wrapperRotate}deg) rotateY(${swiper.isHorizontal() ? -wrapperRotate : 0}deg)`);
},
setTransition(duration) {
const swiper = this;
const { $el, slides } = swiper;
slides
.transition(duration)
.find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left')
.transition(duration);
if (swiper.params.cubeEffect.shadow && !swiper.isHorizontal()) {
$el.find('.swiper-cube-shadow').transition(duration);
}
},
};
var EffectCube = {
name: 'effect-cube',
params: {
cubeEffect: {
slideShadows: true,
shadow: true,
shadowOffset: 20,
shadowScale: 0.94,
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
cubeEffect: {
setTranslate: Cube.setTranslate.bind(swiper),
setTransition: Cube.setTransition.bind(swiper),
},
});
},
on: {
beforeInit() {
const swiper = this;
if (swiper.params.effect !== 'cube') return;
swiper.classNames.push(`${swiper.params.containerModifierClass}cube`);
swiper.classNames.push(`${swiper.params.containerModifierClass}3d`);
const overwriteParams = {
slidesPerView: 1,
slidesPerColumn: 1,
slidesPerGroup: 1,
watchSlidesProgress: true,
resistanceRatio: 0,
spaceBetween: 0,
centeredSlides: false,
virtualTranslate: true,
};
Utils.extend(swiper.params, overwriteParams);
Utils.extend(swiper.originalParams, overwriteParams);
},
setTranslate() {
const swiper = this;
if (swiper.params.effect !== 'cube') return;
swiper.cubeEffect.setTranslate();
},
setTransition(duration) {
const swiper = this;
if (swiper.params.effect !== 'cube') return;
swiper.cubeEffect.setTransition(duration);
},
},
};
const Flip = {
setTranslate() {
const swiper = this;
const { slides } = swiper;
for (let i = 0; i < slides.length; i += 1) {
const $slideEl = slides.eq(i);
let progress = $slideEl[0].progress;
if (swiper.params.flipEffect.limitRotation) {
progress = Math.max(Math.min($slideEl[0].progress, 1), -1);
}
const offset = $slideEl[0].swiperSlideOffset;
const rotate = -180 * progress;
let rotateY = rotate;
let rotateX = 0;
let tx = -offset;
let ty = 0;
if (!swiper.isHorizontal()) {
ty = tx;
tx = 0;
rotateX = -rotateY;
rotateY = 0;
} else if (swiper.rtl) {
rotateY = -rotateY;
}
$slideEl[0].style.zIndex = -Math.abs(Math.round(progress)) + slides.length;
if (swiper.params.flipEffect.slideShadows) {
// Set shadows
let shadowBefore = swiper.isHorizontal() ? $slideEl.find('.swiper-slide-shadow-left') : $slideEl.find('.swiper-slide-shadow-top');
let shadowAfter = swiper.isHorizontal() ? $slideEl.find('.swiper-slide-shadow-right') : $slideEl.find('.swiper-slide-shadow-bottom');
if (shadowBefore.length === 0) {
shadowBefore = $(`<div class="swiper-slide-shadow-${swiper.isHorizontal() ? 'left' : 'top'}"></div>`);
$slideEl.append(shadowBefore);
}
if (shadowAfter.length === 0) {
shadowAfter = $(`<div class="swiper-slide-shadow-${swiper.isHorizontal() ? 'right' : 'bottom'}"></div>`);
$slideEl.append(shadowAfter);
}
if (shadowBefore.length) shadowBefore[0].style.opacity = Math.max(-progress, 0);
if (shadowAfter.length) shadowAfter[0].style.opacity = Math.max(progress, 0);
}
$slideEl
.transform(`translate3d(${tx}px, ${ty}px, 0px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`);
}
},
setTransition(duration) {
const swiper = this;
const { slides, activeIndex, $wrapperEl } = swiper;
slides
.transition(duration)
.find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left')
.transition(duration);
if (swiper.params.virtualTranslate && duration !== 0) {
let eventTriggered = false;
// eslint-disable-next-line
slides.eq(activeIndex).transitionEnd(function onTransitionEnd() {
if (eventTriggered) return;
if (!swiper || swiper.destroyed) return;
// if (!$(this).hasClass(swiper.params.slideActiveClass)) return;
eventTriggered = true;
swiper.animating = false;
const triggerEvents = ['webkitTransitionEnd', 'transitionend'];
for (let i = 0; i < triggerEvents.length; i += 1) {
$wrapperEl.trigger(triggerEvents[i]);
}
});
}
},
};
var EffectFlip = {
name: 'effect-flip',
params: {
flipEffect: {
slideShadows: true,
limitRotation: true,
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
flipEffect: {
setTranslate: Flip.setTranslate.bind(swiper),
setTransition: Flip.setTransition.bind(swiper),
},
});
},
on: {
beforeInit() {
const swiper = this;
if (swiper.params.effect !== 'flip') return;
swiper.classNames.push(`${swiper.params.containerModifierClass}flip`);
swiper.classNames.push(`${swiper.params.containerModifierClass}3d`);
const overwriteParams = {
slidesPerView: 1,
slidesPerColumn: 1,
slidesPerGroup: 1,
watchSlidesProgress: true,
spaceBetween: 0,
virtualTranslate: true,
};
Utils.extend(swiper.params, overwriteParams);
Utils.extend(swiper.originalParams, overwriteParams);
},
setTranslate() {
const swiper = this;
if (swiper.params.effect !== 'flip') return;
swiper.flipEffect.setTranslate();
},
setTransition(duration) {
const swiper = this;
if (swiper.params.effect !== 'flip') return;
swiper.flipEffect.setTransition(duration);
},
},
};
const Coverflow = {
setTranslate() {
const swiper = this;
const { width: swiperWidth, height: swiperHeight, slides, $wrapperEl, slidesSizesGrid } = swiper;
const params = swiper.params.coverflowEffect;
const isHorizontal = swiper.isHorizontal();
const transform = swiper.translate;
const center = isHorizontal ? -transform + (swiperWidth / 2) : -transform + (swiperHeight / 2);
const rotate = isHorizontal ? params.rotate : -params.rotate;
const translate = params.depth;
// Each slide offset from center
for (let i = 0, length = slides.length; i < length; i += 1) {
const $slideEl = slides.eq(i);
const slideSize = slidesSizesGrid[i];
const slideOffset = $slideEl[0].swiperSlideOffset;
const offsetMultiplier = ((center - slideOffset - (slideSize / 2)) / slideSize) * params.modifier;
let rotateY = isHorizontal ? rotate * offsetMultiplier : 0;
let rotateX = isHorizontal ? 0 : rotate * offsetMultiplier;
// var rotateZ = 0
let translateZ = -translate * Math.abs(offsetMultiplier);
let translateY = isHorizontal ? 0 : params.stretch * (offsetMultiplier);
let translateX = isHorizontal ? params.stretch * (offsetMultiplier) : 0;
// Fix for ultra small values
if (Math.abs(translateX) < 0.001) translateX = 0;
if (Math.abs(translateY) < 0.001) translateY = 0;
if (Math.abs(translateZ) < 0.001) translateZ = 0;
if (Math.abs(rotateY) < 0.001) rotateY = 0;
if (Math.abs(rotateX) < 0.001) rotateX = 0;
const slideTransform = `translate3d(${translateX}px,${translateY}px,${translateZ}px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
$slideEl.transform(slideTransform);
$slideEl[0].style.zIndex = -Math.abs(Math.round(offsetMultiplier)) + 1;
if (params.slideShadows) {
// Set shadows
let $shadowBeforeEl = isHorizontal ? $slideEl.find('.swiper-slide-shadow-left') : $slideEl.find('.swiper-slide-shadow-top');
let $shadowAfterEl = isHorizontal ? $slideEl.find('.swiper-slide-shadow-right') : $slideEl.find('.swiper-slide-shadow-bottom');
if ($shadowBeforeEl.length === 0) {
$shadowBeforeEl = $(`<div class="swiper-slide-shadow-${isHorizontal ? 'left' : 'top'}"></div>`);
$slideEl.append($shadowBeforeEl);
}
if ($shadowAfterEl.length === 0) {
$shadowAfterEl = $(`<div class="swiper-slide-shadow-${isHorizontal ? 'right' : 'bottom'}"></div>`);
$slideEl.append($shadowAfterEl);
}
if ($shadowBeforeEl.length) $shadowBeforeEl[0].style.opacity = offsetMultiplier > 0 ? offsetMultiplier : 0;
if ($shadowAfterEl.length) $shadowAfterEl[0].style.opacity = (-offsetMultiplier) > 0 ? -offsetMultiplier : 0;
}
}
// Set correct perspective for IE10
if (Browser.ie) {
const ws = $wrapperEl[0].style;
ws.perspectiveOrigin = `${center}px 50%`;
}
},
setTransition(duration) {
const swiper = this;
swiper.slides
.transition(duration)
.find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left')
.transition(duration);
},
};
var EffectCoverflow = {
name: 'effect-coverflow',
params: {
coverflowEffect: {
rotate: 50,
stretch: 0,
depth: 100,
modifier: 1,
slideShadows: true,
},
},
create() {
const swiper = this;
Utils.extend(swiper, {
coverflowEffect: {
setTranslate: Coverflow.setTranslate.bind(swiper),
setTransition: Coverflow.setTransition.bind(swiper),
},
});
},
on: {
beforeInit() {
const swiper = this;
if (swiper.params.effect !== 'coverflow') return;
swiper.classNames.push(`${swiper.params.containerModifierClass}coverflow`);
swiper.classNames.push(`${swiper.params.containerModifierClass}3d`);
swiper.params.watchSlidesProgress = true;
swiper.originalParams.watchSlidesProgress = true;
},
setTranslate() {
const swiper = this;
if (swiper.params.effect !== 'coverflow') return;
swiper.coverflowEffect.setTranslate();
},
setTransition(duration) {
const swiper = this;
if (swiper.params.effect !== 'coverflow') return;
swiper.coverflowEffect.setTransition(duration);
},
},
};
// Swiper Class
// Core Modules
// Components
Swiper$2.use([
Device$4,
Browser$2,
Support$4,
Resize$1,
Observer$1,
Virtual$1,
Navigation$1,
Pagination$1,
Scrollbar$1,
Parallax$1,
Zoom$1,
Lazy$3,
Controller$1,
A11y,
Autoplay$1,
EffectFade,
EffectCube,
EffectFlip,
EffectCoverflow,
]);
function initSwipers(swiperEl) {
const app = this;
const $swiperEl = $(swiperEl);
if ($swiperEl.length === 0) return;
if ($swiperEl[0].swiper) return;
let initialSlide;
let params = {};
let isTabs;
let isRoutableTabs;
if ($swiperEl.hasClass('tabs-swipeable-wrap')) {
$swiperEl
.addClass('swiper-container')
.children('.tabs')
.addClass('swiper-wrapper')
.children('.tab')
.addClass('swiper-slide');
initialSlide = $swiperEl.children('.tabs').children('.tab-active').index();
isTabs = true;
isRoutableTabs = $swiperEl.find('.tabs-routable').length > 0;
}
if ($swiperEl.attr('data-swiper')) {
params = JSON.parse($swiperEl.attr('data-swiper'));
} else {
params = $swiperEl.dataset();
Object.keys(params).forEach((key) => {
const value = params[key];
if (typeof value === 'string' && value.indexOf('{') === 0 && value.indexOf('}') > 0) {
try {
params[key] = JSON.parse(value);
} catch (e) {
// not JSON
}
}
});
}
if (typeof params.initialSlide === 'undefined' && typeof initialSlide !== 'undefined') {
params.initialSlide = initialSlide;
}
const swiper = app.swiper.create($swiperEl[0], params);
if (isTabs) {
swiper.on('slideChange', () => {
if (isRoutableTabs) {
let view = app.views.get($swiperEl.parents('.view'));
if (!view) view = app.views.main;
const router = view.router;
const tabRoute = router.findTabRoute(swiper.slides.eq(swiper.activeIndex)[0]);
if (tabRoute) router.navigate(tabRoute.path);
} else {
app.tab.show({
tabEl: swiper.slides.eq(swiper.activeIndex),
});
}
});
}
}
var Swiper = {
name: 'swiper',
static: {
Swiper: Swiper$2,
},
create() {
const app = this;
app.swiper = ConstructorMethods({
defaultSelector: '.swiper-container',
constructor: Swiper$2,
domProp: 'swiper',
});
},
on: {
pageBeforeRemove(page) {
const app = this;
page.$el.find('.swiper-init, .tabs-swipeable-wrap').each((index, swiperEl) => {
app.swiper.destroy(swiperEl);
});
},
pageMounted(page) {
const app = this;
page.$el.find('.tabs-swipeable-wrap').each((index, swiperEl) => {
initSwipers.call(app, swiperEl);
});
},
pageInit(page) {
const app = this;
page.$el.find('.swiper-init, .tabs-swipeable-wrap').each((index, swiperEl) => {
initSwipers.call(app, swiperEl);
});
},
pageReinit(page) {
const app = this;
page.$el.find('.swiper-init, .tabs-swipeable-wrap').each((index, swiperEl) => {
const swiper = app.swiper.get(swiperEl);
if (swiper && swiper.update) swiper.update();
});
},
},
};
/* eslint indent: ["off"] */
class PhotoBrowser$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const pb = this;
pb.app = app;
const defaults = Utils.extend({
on: {},
}, app.params.photoBrowser);
// Extend defaults with modules params
pb.useModulesParams(defaults);
pb.params = Utils.extend(defaults, params);
Utils.extend(pb, {
exposed: false,
opened: false,
activeIndex: pb.params.swiper.initialSlide,
url: pb.params.url,
view: pb.params.view || app.views.main,
swipeToClose: {
allow: true,
isTouched: false,
diff: undefined,
start: undefined,
current: undefined,
started: false,
activeSlide: undefined,
timeStart: undefined,
},
});
// Install Modules
pb.useModules();
// Init
pb.init();
}
onSlideChange(swiper) {
const pb = this;
pb.activeIndex = swiper.activeIndex;
let current = swiper.activeIndex + 1;
let total = pb.params.virtualSlides ? pb.params.photos.length : swiper.slides.length;
if (swiper.params.loop) {
total -= 2;
current -= swiper.loopedSlides;
if (current < 1) current = total + current;
if (current > total) current -= total;
}
const $activeSlideEl = pb.params.virtualSlides
? swiper.$wrapperEl.find(`.swiper-slide[data-swiper-slide-index="${swiper.activeIndex}"]`)
: swiper.slides.eq(swiper.activeIndex);
const $previousSlideEl = pb.params.virtualSlides
? swiper.$wrapperEl.find(`.swiper-slide[data-swiper-slide-index="${swiper.previousIndex}"]`)
: swiper.slides.eq(swiper.previousIndex);
let $currentEl = pb.$containerEl.find('.photo-browser-current');
let $totalEl = pb.$containerEl.find('.photo-browser-total');
if (pb.params.type === 'page' && pb.params.navbar && $currentEl.length === 0 && pb.app.theme === 'ios') {
const navbarEl = pb.app.navbar.getElByPage(pb.$containerEl);
if (navbarEl) {
$currentEl = $(navbarEl).find('.photo-browser-current');
$totalEl = $(navbarEl).find('.photo-browser-total');
}
}
$currentEl.text(current);
$totalEl.text(total);
// Update captions
if (pb.captions.length > 0) {
const captionIndex = swiper.params.loop ? $activeSlideEl.attr('data-swiper-slide-index') : pb.activeIndex;
pb.$captionsContainerEl.find('.photo-browser-caption-active').removeClass('photo-browser-caption-active');
pb.$captionsContainerEl.find(`[data-caption-index="${captionIndex}"]`).addClass('photo-browser-caption-active');
}
// Stop Video
const previousSlideVideo = $previousSlideEl.find('video');
if (previousSlideVideo.length > 0) {
if ('pause' in previousSlideVideo[0]) previousSlideVideo[0].pause();
}
}
onTouchStart() {
const pb = this;
const swipeToClose = pb.swipeToClose;
if (!swipeToClose.allow) return;
swipeToClose.isTouched = true;
}
onTouchMove(e) {
const pb = this;
const swipeToClose = pb.swipeToClose;
if (!swipeToClose.isTouched) return;
if (!swipeToClose.started) {
swipeToClose.started = true;
swipeToClose.start = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (pb.params.virtualSlides) {
swipeToClose.activeSlide = pb.swiper.$wrapperEl.children('.swiper-slide-active');
} else {
swipeToClose.activeSlide = pb.swiper.slides.eq(pb.swiper.activeIndex);
}
swipeToClose.timeStart = Utils.now();
}
e.preventDefault();
swipeToClose.current = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
swipeToClose.diff = swipeToClose.start - swipeToClose.current;
const opacity = 1 - (Math.abs(swipeToClose.diff) / 300);
const color = pb.exposed || pb.params.theme === 'dark' ? 0 : 255;
swipeToClose.activeSlide.transform(`translate3d(0,${-swipeToClose.diff}px,0)`);
pb.swiper.$el.css('background-color', `rgba(${color}, ${color}, ${color}, ${opacity})`).transition(0);
}
onTouchEnd() {
const pb = this;
const swipeToClose = pb.swipeToClose;
swipeToClose.isTouched = false;
if (!swipeToClose.started) {
swipeToClose.started = false;
return;
}
swipeToClose.started = false;
swipeToClose.allow = false;
const diff = Math.abs(swipeToClose.diff);
const timeDiff = (new Date()).getTime() - swipeToClose.timeStart;
if ((timeDiff < 300 && diff > 20) || (timeDiff >= 300 && diff > 100)) {
Utils.nextTick(() => {
if (pb.$containerEl) {
if (swipeToClose.diff < 0) pb.$containerEl.addClass('swipe-close-to-bottom');
else pb.$containerEl.addClass('swipe-close-to-top');
}
pb.emit('local::swipeToClose', pb);
pb.close();
swipeToClose.allow = true;
});
return;
}
if (diff !== 0) {
swipeToClose.activeSlide.addClass('photo-browser-transitioning').transitionEnd(() => {
swipeToClose.allow = true;
swipeToClose.activeSlide.removeClass('photo-browser-transitioning');
});
} else {
swipeToClose.allow = true;
}
pb.swiper.$el.transition('').css('background-color', '');
swipeToClose.activeSlide.transform('');
}
// Render Functions
renderNavbar() {
const pb = this;
if (pb.params.renderNavbar) return pb.params.renderNavbar.call(pb);
let iconsColor = pb.params.iconsColor;
if (!pb.params.iconsColor && pb.params.theme === 'dark') iconsColor = 'white';
const backLinkText = pb.app.theme === 'ios' && pb.params.backLinkText ? pb.params.backLinkText : '';
const isPopup = pb.params.type !== 'page';
const navbarHtml = `
<div class="navbar">
<div class="navbar-inner sliding">
<div class="left">
<a href="#" class="link ${isPopup ? 'popup-close' : ''} ${!backLinkText ? 'icon-only' : ''} ${!isPopup ? 'back' : ''}" ${isPopup ? 'data-popup=".photo-browser-popup"' : ''}>
<i class="icon icon-back ${iconsColor ? `color-${iconsColor}` : ''}"></i>
${backLinkText ? `<span>${backLinkText}</span>` : ''}
</a>
</div>
<div class="title">
<span class="photo-browser-current"></span>
<span class="photo-browser-of">${pb.params.navbarOfText}</span>
<span class="photo-browser-total"></span>
</div>
<div class="right"></div>
</div>
</div>
`.trim();
return navbarHtml;
}
renderToolbar() {
const pb = this;
if (pb.params.renderToolbar) return pb.params.renderToolbar.call(pb);
let iconsColor = pb.params.iconsColor;
if (!pb.params.iconsColor && pb.params.theme === 'dark') iconsColor = 'white';
const toolbarHtml = `
<div class="toolbar tabbar toolbar-bottom-md">
<div class="toolbar-inner">
<a href="#" class="link photo-browser-prev">
<i class="icon icon-back ${iconsColor ? `color-${iconsColor}` : ''}"></i>
</a>
<a href="#" class="link photo-browser-next">
<i class="icon icon-forward ${iconsColor ? `color-${iconsColor}` : ''}"></i>
</a>
</div>
</div>
`.trim();
return toolbarHtml;
}
renderCaption(caption, index) {
const pb = this;
if (pb.params.renderCaption) return pb.params.renderCaption.call(pb, caption, index);
const captionHtml = `
<div class="photo-browser-caption" data-caption-index="${index}">
${caption}
</div>
`.trim();
return captionHtml;
}
renderObject(photo, index) {
const pb = this;
if (pb.params.renderObject) return pb.params.renderObject.call(pb, photo, index);
const objHtml = `
<div class="photo-browser-slide photo-browser-object-slide swiper-slide" data-swiper-slide-index="${index}">${photo.html ? photo.html : photo}</div>
`;
return objHtml;
}
renderLazyPhoto(photo, index) {
const pb = this;
if (pb.params.renderLazyPhoto) return pb.params.renderLazyPhoto.call(pb, photo, index);
const photoHtml = `
<div class="photo-browser-slide photo-browser-slide-lazy swiper-slide" data-swiper-slide-index="${index}">
<div class="preloader swiper-lazy-preloader ${pb.params.theme === 'dark' ? 'color-white' : ''}">${pb.app.theme === 'md' ? Utils.mdPreloaderContent : ''}</div>
<span class="swiper-zoom-container">
<img data-src="${photo.url ? photo.url : photo}" class="swiper-lazy">
</span>
</div>
`.trim();
return photoHtml;
}
renderPhoto(photo, index) {
const pb = this;
if (pb.params.renderPhoto) return pb.params.renderPhoto.call(pb, photo, index);
const photoHtml = `
<div class="photo-browser-slide swiper-slide" data-swiper-slide-index="${index}">
<span class="swiper-zoom-container">
<img src="${photo.url ? photo.url : photo}">
</span>
</div>
`.trim();
return photoHtml;
}
render() {
const pb = this;
if (pb.params.render) return pb.params.render.call(pb, pb.params);
const html = `
<div class="photo-browser photo-browser-${pb.params.theme}">
<div class="view">
<div class="page photo-browser-page photo-browser-page-${pb.params.theme} no-toolbar ${!pb.params.navbar ? 'no-navbar' : ''}" data-name="photo-browser-page">
${pb.params.navbar ? pb.renderNavbar() : ''}
${pb.params.toolbar ? pb.renderToolbar() : ''}
<div class="photo-browser-captions photo-browser-captions-${pb.params.captionsTheme || pb.params.theme}">
${pb.params.photos.map((photo, index) => {
if (photo.caption) return pb.renderCaption(photo.caption, index);
return '';
}).join(' ')}
</div>
<div class="photo-browser-swiper-container swiper-container">
<div class="photo-browser-swiper-wrapper swiper-wrapper">
${pb.params.virtualSlides ? '' : pb.params.photos.map((photo, index) => {
if (photo.html || ((typeof photo === 'string' || photo instanceof String) && photo.indexOf('<') >= 0 && photo.indexOf('>') >= 0)) {
return pb.renderObject(photo, index);
} else if (pb.params.swiper.lazy === true || (pb.params.swiper.lazy && pb.params.swiper.lazy.enabled)) {
return pb.renderLazyPhoto(photo, index);
}
return pb.renderPhoto(photo, index);
}).join(' ')}
</div>
</div>
</div>
</div>
</div>
`.trim();
return html;
}
renderStandalone() {
const pb = this;
if (pb.params.renderStandalone) return pb.params.renderStandalone.call(pb);
const standaloneHtml = `<div class="popup photo-browser-popup photo-browser-standalone popup-tablet-fullscreen">${pb.render()}</div>`;
return standaloneHtml;
}
renderPage() {
const pb = this;
if (pb.params.renderPage) return pb.params.renderPage.call(pb);
const pageHtml = pb.render();
return pageHtml;
}
renderPopup() {
const pb = this;
if (pb.params.renderPopup) return pb.params.renderPopup.call(pb);
const popupHtml = `<div class="popup photo-browser-popup">${pb.render()}</div>`;
return popupHtml;
}
// Callbacks
onOpen(type, containerEl) {
const pb = this;
const app = pb.app;
const $containerEl = $(containerEl);
$containerEl[0].f7PhotoBrowser = pb;
pb.$containerEl = $containerEl;
pb.openedIn = type;
pb.opened = true;
pb.$swiperContainerEl = pb.$containerEl.find('.photo-browser-swiper-container');
pb.$swiperWrapperEl = pb.$containerEl.find('.photo-browser-swiper-wrapper');
pb.slides = pb.$containerEl.find('.photo-browser-slide');
pb.$captionsContainerEl = pb.$containerEl.find('.photo-browser-captions');
pb.captions = pb.$containerEl.find('.photo-browser-caption');
// Init Swiper
const swiperParams = Utils.extend({}, pb.params.swiper, {
initialSlide: pb.activeIndex,
on: {
tap(e) {
pb.emit('local::tap', e);
},
click(e) {
if (pb.params.exposition) {
pb.expositionToggle();
}
pb.emit('local::click', e);
},
doubleTap(e) {
pb.emit('local::doubleTap', e);
},
slideChange(...args) {
const swiper = this;
pb.onSlideChange(swiper);
pb.emit('local::slideChange', ...args);
},
transitionStart(...args) {
pb.emit('local::transitionStart', ...args);
},
transitionEnd(...args) {
pb.emit('local::transitionEnd', ...args);
},
slideChangeStart(...args) {
pb.emit('local::slideChangeTransitionStart', ...args);
},
slideChangeEnd(...args) {
pb.emit('local::slideChangeTransitionEnd', ...args);
},
lazyImageLoad(...args) {
pb.emit('local::lazyImageLoad', ...args);
},
lazyImageReady(...args) {
const slideEl = args[0];
$(slideEl).removeClass('photo-browser-slide-lazy');
pb.emit('local::lazyImageReady', ...args);
},
},
});
if (pb.params.swipeToClose && pb.params.type !== 'page') {
Utils.extend(swiperParams.on, {
touchStart(e) {
pb.onTouchStart(e);
pb.emit('local::touchStart', e);
},
touchMoveOpposite(e) {
pb.onTouchMove(e);
pb.emit('local::touchMoveOpposite', e);
},
touchEnd(e) {
pb.onTouchEnd(e);
pb.emit('local::touchEnd', e);
},
});
}
if (pb.params.virtualSlides) {
Utils.extend(swiperParams, {
virtual: {
slides: pb.params.photos,
renderSlide(photo, index) {
if (photo.html || ((typeof photo === 'string' || photo instanceof String) && photo.indexOf('<') >= 0 && photo.indexOf('>') >= 0)) {
return pb.renderObject(photo, index);
} else if (pb.params.swiper.lazy === true || (pb.params.swiper.lazy && pb.params.swiper.lazy.enabled)) {
return pb.renderLazyPhoto(photo, index);
}
return pb.renderPhoto(photo, index);
},
},
});
}
pb.swiper = app.swiper.create(pb.$swiperContainerEl, swiperParams);
if (pb.activeIndex === 0) {
pb.onSlideChange(pb.swiper);
}
pb.emit('local::open photoBrowserOpen', pb);
}
onOpened() {
const pb = this;
pb.emit('local::opened photoBrowserOpened', pb);
}
onClose() {
const pb = this;
if (pb.destroyed) return;
// Destroy Swiper
if (pb.swiper && pb.swiper.destroy) {
pb.swiper.destroy(true, false);
pb.swiper = null;
delete pb.swiper;
}
pb.emit('local::close photoBrowserClose', pb);
}
onClosed() {
const pb = this;
if (pb.destroyed) return;
pb.opened = false;
pb.$containerEl = null;
delete pb.$containerEl;
pb.emit('local::closed photoBrowserClosed', pb);
}
// Open
openPage() {
const pb = this;
if (pb.opened) return pb;
const pageHtml = pb.renderPage();
pb.view.router.navigate({
url: pb.url,
route: {
content: pageHtml,
path: pb.url,
on: {
pageBeforeIn(e, page) {
pb.view.$el.addClass(`with-photo-browser-page with-photo-browser-page-${pb.params.theme}`);
pb.onOpen('page', page.el);
},
pageAfterIn(e, page) {
pb.onOpened('page', page.el);
},
pageBeforeOut(e, page) {
pb.view.$el.removeClass(`with-photo-browser-page with-photo-browser-page-exposed with-photo-browser-page-${pb.params.theme}`);
pb.onClose('page', page.el);
},
pageAfterOut(e, page) {
pb.onClosed('page', page.el);
},
},
},
});
return pb;
}
openStandalone() {
const pb = this;
if (pb.opened) return pb;
const standaloneHtml = pb.renderStandalone();
const popupParams = {
backdrop: false,
content: standaloneHtml,
on: {
popupOpen(popup) {
pb.onOpen('popup', popup.el);
},
popupOpened(popup) {
pb.onOpened('popup', popup.el);
},
popupClose(popup) {
pb.onClose('popup', popup.el);
},
popupClosed(popup) {
pb.onClosed('popup', popup.el);
},
},
};
if (pb.params.routableModals) {
pb.view.router.navigate({
url: pb.url,
route: {
path: pb.url,
popup: popupParams,
},
});
} else {
pb.modal = pb.app.popup.create(popupParams).open();
}
return pb;
}
openPopup() {
const pb = this;
if (pb.opened) return pb;
const popupHtml = pb.renderPopup();
const popupParams = {
content: popupHtml,
on: {
popupOpen(popup) {
pb.onOpen('popup', popup.el);
},
popupOpened(popup) {
pb.onOpened('popup', popup.el);
},
popupClose(popup) {
pb.onClose('popup', popup.el);
},
popupClosed(popup) {
pb.onClosed('popup', popup.el);
},
},
};
if (pb.params.routableModals) {
pb.view.router.navigate({
url: pb.url,
route: {
path: pb.url,
popup: popupParams,
},
});
} else {
pb.modal = pb.app.popup.create(popupParams).open();
}
return pb;
}
// Exposition
expositionEnable() {
const pb = this;
if (pb.params.type === 'page') {
pb.view.$el.addClass('with-photo-browser-page-exposed');
}
if (pb.$containerEl) pb.$containerEl.addClass('photo-browser-exposed');
if (pb.params.expositionHideCaptions) pb.$captionsContainerEl.addClass('photo-browser-captions-exposed');
pb.exposed = true;
return pb;
}
expositionDisable() {
const pb = this;
if (pb.params.type === 'page') {
pb.view.$el.removeClass('with-photo-browser-page-exposed');
}
if (pb.$containerEl) pb.$containerEl.removeClass('photo-browser-exposed');
if (pb.params.expositionHideCaptions) pb.$captionsContainerEl.removeClass('photo-browser-captions-exposed');
pb.exposed = false;
return pb;
}
expositionToggle() {
const pb = this;
if (pb.params.type === 'page') {
pb.view.$el.toggleClass('with-photo-browser-page-exposed');
}
if (pb.$containerEl) pb.$containerEl.toggleClass('photo-browser-exposed');
if (pb.params.expositionHideCaptions) pb.$captionsContainerEl.toggleClass('photo-browser-captions-exposed');
pb.exposed = !pb.exposed;
return pb;
}
open(index) {
const pb = this;
const type = pb.params.type;
if (pb.opened) {
if (pb.swiper && typeof index !== 'undefined') {
pb.swiper.slideTo(parseInt(index, 10));
}
return pb;
} else if (typeof index !== 'undefined') {
pb.activeIndex = index;
}
if (type === 'standalone') {
pb.openStandalone();
}
if (type === 'page') {
pb.openPage();
}
if (type === 'popup') {
pb.openPopup();
}
return pb;
}
close() {
const pb = this;
if (!pb.opened) return pb;
if (pb.params.routableModals || pb.openedIn === 'page') {
if (pb.view) pb.view.router.back();
} else {
pb.modal.once('modalClosed', () => {
Utils.nextTick(() => {
pb.modal.destroy();
delete pb.modal;
});
});
pb.modal.close();
}
return pb;
}
// eslint-disable-next-line
init() {}
destroy() {
let pb = this;
pb.emit('local::beforeDestroy photoBrowserBeforeDestroy', pb);
if (pb.$containerEl) {
pb.$containerEl.trigger('photobrowser:beforedestroy');
delete pb.$containerEl[0].f7PhotoBrowser;
}
Utils.deleteProps(pb);
pb = null;
}
}
var PhotoBrowser = {
name: 'photoBrowser',
params: {
photoBrowser: {
photos: [],
exposition: true,
expositionHideCaptions: false,
type: 'standalone',
navbar: true,
toolbar: true,
theme: 'light',
captionsTheme: undefined,
iconsColor: undefined,
swipeToClose: true,
backLinkText: 'Close',
navbarOfText: 'of',
view: undefined,
url: 'photos/',
routableModals: true,
virtualSlides: true,
renderNavbar: undefined,
renderToolbar: undefined,
renderCaption: undefined,
renderObject: undefined,
renderLazyPhoto: undefined,
renderPhoto: undefined,
renderPage: undefined,
renderPopup: undefined,
renderStandalone: undefined,
swiper: {
initialSlide: 0,
spaceBetween: 20,
speed: 300,
loop: false,
preloadImages: true,
navigation: {
nextEl: '.photo-browser-next',
prevEl: '.photo-browser-prev',
},
zoom: {
enabled: true,
maxRatio: 3,
minRatio: 1,
},
lazy: {
enabled: true,
},
},
},
},
create() {
const app = this;
app.photoBrowser = ConstructorMethods({
defaultSelector: '.photo-browser',
constructor: PhotoBrowser$1,
app,
domProp: 'f7PhotoBrowser',
});
},
static: {
PhotoBrowser: PhotoBrowser$1,
},
};
class Notification$1 extends Modal$1 {
constructor(app, params) {
const extendedParams = Utils.extend({
on: {},
}, app.params.notification, params);
// Extends with open/close Modal methods;
super(app, extendedParams);
const notification = this;
notification.app = app;
notification.params = extendedParams;
const {
icon,
title,
titleRightText,
subtitle,
text,
closeButton,
closeTimeout,
cssClass,
closeOnClick,
} = notification.params;
let $el;
if (!notification.params.el) {
// Find Element
const notificationHtml = notification.render({
icon,
title,
titleRightText,
subtitle,
text,
closeButton,
cssClass,
});
$el = $(notificationHtml);
} else {
$el = $(notification.params.el);
}
if ($el && $el.length > 0 && $el[0].f7Modal) {
return $el[0].f7Modal;
}
if ($el.length === 0) {
return notification.destroy();
}
Utils.extend(notification, {
$el,
el: $el[0],
type: 'notification',
});
$el[0].f7Modal = notification;
if (closeButton) {
$el.find('.notification-close-button').on('click', () => {
notification.close();
});
}
$el.on('click', (e) => {
if (closeButton && $(e.target).closest('.notification-close-button').length) {
return;
}
notification.emit('local::click notificationClick', notification);
if (closeOnClick) notification.close();
});
notification.on('beforeDestroy', () => {
$el.off('click');
});
/* Touch Events */
let isTouched;
let isMoved;
let isScrolling;
let touchesDiff;
let touchStartTime;
let notificationHeight;
const touchesStart = {};
function handleTouchStart(e) {
if (isTouched) return;
isTouched = true;
isMoved = false;
isScrolling = undefined;
touchStartTime = Utils.now();
touchesStart.x = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
touchesStart.y = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
}
function handleTouchMove(e) {
if (!isTouched) return;
const pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(isScrolling || Math.abs(pageY - touchesStart.y) < Math.abs(pageX - touchesStart.x));
}
if (isScrolling) {
isTouched = false;
return;
}
e.preventDefault();
if (!isMoved) {
notification.$el.removeClass('notification-transitioning');
notification.$el.transition(0);
notificationHeight = notification.$el[0].offsetHeight / 2;
}
isMoved = true;
touchesDiff = (pageY - touchesStart.y);
let newTranslate = touchesDiff;
if (touchesDiff > 0) {
newTranslate = touchesDiff ** 0.8;
}
notification.$el.transform(`translate3d(0, ${newTranslate}px, 0)`);
}
function handleTouchEnd() {
if (!isTouched || !isMoved) {
isTouched = false;
isMoved = false;
return;
}
isTouched = false;
isMoved = false;
if (touchesDiff === 0) {
return;
}
const timeDiff = Utils.now() - touchStartTime;
notification.$el.transition('');
notification.$el.addClass('notification-transitioning');
notification.$el.transform('');
if (
(touchesDiff < -10 && timeDiff < 300) ||
(-touchesDiff >= notificationHeight / 1)
) {
notification.close();
}
}
function attachTouchEvents() {
{
notification.$el.on(app.touchEvents.start, handleTouchStart, { passive: true });
app.on('touchmove:active', handleTouchMove);
app.on('touchend:passive', handleTouchEnd);
}
}
function detachTouchEvents() {
{
notification.$el.off(app.touchEvents.start, handleTouchStart, { passive: true });
app.off('touchmove:active', handleTouchMove);
app.off('touchend:passive', handleTouchEnd);
}
}
let timeoutId;
function closeOnTimeout() {
timeoutId = Utils.nextTick(() => {
if (isTouched && isMoved) {
closeOnTimeout();
return;
}
notification.close();
}, closeTimeout);
}
notification.on('open', () => {
if (notification.params.swipeToClose) {
attachTouchEvents();
}
$('.notification.modal-in').each((index, openedEl) => {
const notificationInstance = app.notification.get(openedEl);
if (openedEl !== notification.el && notificationInstance) {
notificationInstance.close();
}
});
if (closeTimeout) {
closeOnTimeout();
}
});
notification.on('close beforeDestroy', () => {
if (notification.params.swipeToClose) {
detachTouchEvents();
}
window.clearTimeout(timeoutId);
});
return notification;
}
render() {
const notification = this;
if (notification.params.render) return notification.params.render.call(notification, notification);
const { icon, title, titleRightText, subtitle, text, closeButton, cssClass } = notification.params;
return `
<div class="notification ${cssClass || ''}">
<div class="notification-header">
${icon ? `<div class="notification-icon">${icon}</div>` : ''}
${title ? `<div class="notification-title">${title}</div>` : ''}
${titleRightText ? `<div class="notification-title-right-text">${titleRightText}</div>` : ''}
${closeButton ? '<span class="notification-close-button"></span>' : ''}
</div>
<div class="notification-content">
${subtitle ? `<div class="notification-subtitle">${subtitle}</div>` : ''}
${text ? `<div class="notification-text">${text}</div>` : ''}
</div>
</div>
`.trim();
}
}
var Notification = {
name: 'notification',
static: {
Notification: Notification$1,
},
create() {
const app = this;
app.notification = Utils.extend(
{},
ModalMethods({
app,
constructor: Notification$1,
defaultSelector: '.notification.modal-in',
})
);
},
params: {
notification: {
icon: null,
title: null,
titleRightText: null,
subtitle: null,
text: null,
closeButton: false,
closeTimeout: null,
closeOnClick: false,
swipeToClose: true,
cssClass: null,
render: null,
},
},
};
/* eslint "no-useless-escape": "off" */
class Autocomplete$1 extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const ac = this;
ac.app = app;
const defaults = Utils.extend({
on: {},
}, app.modules.autocomplete.params.autocomplete);
// Extend defaults with modules params
ac.useModulesParams(defaults);
ac.params = Utils.extend(defaults, params);
let $openerEl;
if (ac.params.openerEl) {
$openerEl = $(ac.params.openerEl);
if ($openerEl.length) $openerEl[0].f7Autocomplete = ac;
}
let $inputEl;
if (ac.params.inputEl) {
$inputEl = $(ac.params.inputEl);
if ($inputEl.length) $inputEl[0].f7Autocomplete = ac;
}
let view;
if (ac.params.view) {
view = ac.params.view;
} else if ($openerEl || $inputEl) {
view = app.views.get($openerEl || $inputEl);
}
if (!view) view = app.views.main;
const id = Utils.now();
let url = params.url;
if (!url && $openerEl && $openerEl.length) {
if ($openerEl.attr('href')) url = $openerEl.attr('href');
else if ($openerEl.find('a').length > 0) {
url = $openerEl.find('a').attr('href');
}
}
if (!url || url === '#' || url === '') url = ac.params.url;
const inputType = ac.params.multiple ? 'checkbox' : 'radio';
Utils.extend(ac, {
$openerEl,
openerEl: $openerEl && $openerEl[0],
$inputEl,
inputEl: $inputEl && $inputEl[0],
id,
view,
url,
value: ac.params.value || [],
inputType,
inputName: `${inputType}-${id}`,
$modalEl: undefined,
$dropdownEl: undefined,
});
let previousQuery = '';
function onInputChange() {
let query = ac.$inputEl.val().trim();
if (!ac.params.source) return;
ac.params.source.call(ac, query, (items) => {
let itemsHTML = '';
const limit = ac.params.limit ? Math.min(ac.params.limit, items.length) : items.length;
ac.items = items;
let regExp;
if (ac.params.highlightMatches) {
query = query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
regExp = new RegExp(`(${query})`, 'i');
}
let firstValue;
let firstItem;
for (let i = 0; i < limit; i += 1) {
const itemValue = typeof items[i] === 'object' ? items[i][ac.params.valueProperty] : items[i];
const itemText = typeof items[i] === 'object' ? items[i][ac.params.textProperty] : items[i];
if (i === 0) {
firstValue = itemValue;
firstItem = ac.items[i];
}
itemsHTML += ac.renderItem({
value: itemValue,
text: ac.params.highlightMatches ? itemText.replace(regExp, '<b>$1</b>') : itemText,
}, i);
}
if (itemsHTML === '' && query === '' && ac.params.dropdownPlaceholderText) {
itemsHTML += ac.renderItem({
placeholder: true,
text: ac.params.dropdownPlaceholderText,
});
}
ac.$dropdownEl.find('ul').html(itemsHTML);
if (ac.params.typeahead) {
if (!firstValue || !firstItem) {
return;
}
if (firstValue.toLowerCase().indexOf(query.toLowerCase()) !== 0) {
return;
}
if (previousQuery.toLowerCase() === query.toLowerCase()) {
ac.value = [];
return;
}
if (previousQuery.toLowerCase().indexOf(query.toLowerCase()) === 0) {
previousQuery = query;
ac.value = [];
return;
}
$inputEl.val(firstValue);
$inputEl[0].setSelectionRange(query.length, firstValue.length);
const previousValue = typeof ac.value[0] === 'object' ? ac.value[0][ac.params.valueProperty] : ac.value[0];
if (!previousValue || firstValue.toLowerCase() !== previousValue.toLowerCase()) {
ac.value = [firstItem];
ac.emit('local::change autocompleteChange', [firstItem]);
}
}
previousQuery = query;
});
}
function onPageInputChange() {
const input = this;
const value = input.value;
const isValues = $(input).parents('.autocomplete-values').length > 0;
let item;
let itemValue;
let aValue;
if (isValues) {
if (ac.inputType === 'checkbox' && !input.checked) {
for (let i = 0; i < ac.value.length; i += 1) {
aValue = typeof ac.value[i] === 'string' ? ac.value[i] : ac.value[i][ac.params.valueProperty];
if (aValue === value || aValue * 1 === value * 1) {
ac.value.splice(i, 1);
}
}
ac.updateValues();
ac.emit('local::change autocompleteChange', ac.value);
}
return;
}
// Find Related Item
for (let i = 0; i < ac.items.length; i += 1) {
itemValue = typeof ac.items[i] === 'object' ? ac.items[i][ac.params.valueProperty] : ac.items[i];
if (itemValue === value || itemValue * 1 === value * 1) item = ac.items[i];
}
if (ac.inputType === 'radio') {
ac.value = [item];
} else if (input.checked) {
ac.value.push(item);
} else {
for (let i = 0; i < ac.value.length; i += 1) {
aValue = typeof ac.value[i] === 'object' ? ac.value[i][ac.params.valueProperty] : ac.value[i];
if (aValue === value || aValue * 1 === value * 1) {
ac.value.splice(i, 1);
}
}
}
// Update Values Block
ac.updateValues();
// On Select Callback
if (((ac.inputType === 'radio' && input.checked) || ac.inputType === 'checkbox')) {
ac.emit('local::change autocompleteChange', ac.value);
}
}
function onHtmlClick(e) {
const $targetEl = $(e.target);
if ($targetEl.is(ac.$inputEl[0]) || ($targetEl.closest(ac.$dropdownEl[0]).length)) return;
ac.close();
}
function onOpenerClick() {
ac.open();
}
function onInputFocus() {
ac.open();
}
function onInputBlur() {
if (ac.$dropdownEl.find('label.active-state').length > 0) return;
ac.close();
}
function onResize() {
ac.positionDropDown();
}
function onKeyDown(e) {
if (ac.opened && e.keyCode === 13) {
e.preventDefault();
ac.$inputEl.blur();
}
}
function onDropdownclick() {
const $clickedEl = $(this);
let clickedItem;
for (let i = 0; i < ac.items.length; i += 1) {
const itemValue = typeof ac.items[i] === 'object' ? ac.items[i][ac.params.valueProperty] : ac.items[i];
const value = $clickedEl.attr('data-value');
if (itemValue === value || itemValue * 1 === value * 1) {
clickedItem = ac.items[i];
}
}
if (ac.params.updateInputValueOnSelect) {
ac.$inputEl.val(typeof clickedItem === 'object' ? clickedItem[ac.params.valueProperty] : clickedItem);
ac.$inputEl.trigger('input change');
}
ac.value = [clickedItem];
ac.emit('local::change autocompleteChange', [clickedItem]);
ac.close();
}
ac.attachEvents = function attachEvents() {
if (ac.params.openIn !== 'dropdown' && ac.$openerEl) {
ac.$openerEl.on('click', onOpenerClick);
}
if (ac.params.openIn === 'dropdown' && ac.$inputEl) {
ac.$inputEl.on('focus', onInputFocus);
ac.$inputEl.on('input', onInputChange);
if (app.device.android) {
$('html').on('click', onHtmlClick);
} else {
ac.$inputEl.on('blur', onInputBlur);
}
if (ac.params.typeahead) {
ac.$inputEl.on('keydown', onKeyDown);
}
}
};
ac.detachEvents = function attachEvents() {
if (ac.params.openIn !== 'dropdown' && ac.$openerEl) {
ac.$openerEl.off('click', onOpenerClick);
}
if (ac.params.openIn === 'dropdown' && ac.$inputEl) {
ac.$inputEl.off('focus', onInputFocus);
ac.$inputEl.off('input', onInputChange);
if (app.device.android) {
$('html').off('click', onHtmlClick);
} else {
ac.$inputEl.off('blur', onInputBlur);
}
if (ac.params.typeahead) {
ac.$inputEl.off('keydown', onKeyDown);
}
}
};
ac.attachDropdownEvents = function attachDropdownEvents() {
ac.$dropdownEl.on('click', 'label', onDropdownclick);
app.on('resize', onResize);
};
ac.detachDropdownEvents = function detachDropdownEvents() {
ac.$dropdownEl.off('click', 'label', onDropdownclick);
app.off('resize', onResize);
};
ac.attachPageEvents = function attachPageEvents() {
ac.$containerEl.on('change', 'input[type="radio"], input[type="checkbox"]', onPageInputChange);
if (ac.params.closeOnSelect && !ac.params.multiple) {
ac.$containerEl.once('click', '.list label', () => {
Utils.nextTick(() => {
ac.close();
});
});
}
};
ac.detachPageEvents = function detachPageEvents() {
ac.$containerEl.off('change', 'input[type="radio"], input[type="checkbox"]', onPageInputChange);
};
// Install Modules
ac.useModules();
// Init
ac.init();
return ac;
}
positionDropDown() {
const ac = this;
const { $inputEl, app, $dropdownEl } = ac;
const $pageContentEl = $inputEl.parents('.page-content');
if ($pageContentEl.length === 0) return;
const inputOffset = $inputEl.offset();
const inputOffsetWidth = $inputEl[0].offsetWidth;
const inputOffsetHeight = $inputEl[0].offsetHeight;
const $listEl = $inputEl.parents('.list');
const listOffset = $listEl.offset();
const paddingBottom = parseInt($pageContentEl.css('padding-top'), 10);
const listOffsetLeft = $listEl.length > 0 ? listOffset.left - $listEl.parent().offset().left : 0;
const inputOffsetLeft = inputOffset.left - ($listEl.length > 0 ? listOffset.left : 0) - (app.rtl ? 0 : 0);
const inputOffsetTop = inputOffset.top - ($pageContentEl.offset().top - $pageContentEl[0].scrollTop);
const maxHeight = $pageContentEl[0].scrollHeight - paddingBottom - (inputOffsetTop + $pageContentEl[0].scrollTop) - $inputEl[0].offsetHeight;
const paddingProp = app.rtl ? 'padding-right' : 'padding-left';
let paddingValue;
if ($listEl.length && !ac.params.expandInput) {
paddingValue = (app.rtl ? $listEl[0].offsetWidth - inputOffsetLeft - inputOffsetWidth : inputOffsetLeft) - (app.theme === 'md' ? 16 : 15);
}
$dropdownEl.css({
left: `${$listEl.length > 0 ? listOffsetLeft : inputOffsetLeft}px`,
top: `${inputOffsetTop + $pageContentEl[0].scrollTop + inputOffsetHeight}px`,
width: `${$listEl.length > 0 ? $listEl[0].offsetWidth : inputOffsetWidth}px`,
});
$dropdownEl.children('.autocomplete-dropdown-inner').css({
maxHeight: `${maxHeight}px`,
[paddingProp]: $listEl.length > 0 && !ac.params.expandInput ? `${paddingValue}px` : '',
});
}
focus() {
const ac = this;
ac.$containerEl.find('input[type=search]').focus();
}
source(query) {
const ac = this;
if (!ac.params.source) return;
const { $containerEl } = ac;
ac.params.source.call(ac, query, (items) => {
let itemsHTML = '';
const limit = ac.params.limit ? Math.min(ac.params.limit, items.length) : items.length;
ac.items = items;
for (let i = 0; i < limit; i += 1) {
let selected = false;
const itemValue = typeof items[i] === 'object' ? items[i][ac.params.valueProperty] : items[i];
for (let j = 0; j < ac.value.length; j += 1) {
const aValue = typeof ac.value[j] === 'object' ? ac.value[j][ac.params.valueProperty] : ac.value[j];
if (aValue === itemValue || aValue * 1 === itemValue * 1) selected = true;
}
itemsHTML += ac.renderItem({
value: itemValue,
text: typeof items[i] === 'object' ? items[i][ac.params.textProperty] : items[i],
inputType: ac.inputType,
id: ac.id,
inputName: ac.inputName,
selected,
}, i);
}
$containerEl.find('.autocomplete-found ul').html(itemsHTML);
if (items.length === 0) {
if (query.length !== 0) {
$containerEl.find('.autocomplete-not-found').show();
$containerEl.find('.autocomplete-found, .autocomplete-values').hide();
} else {
$containerEl.find('.autocomplete-values').show();
$containerEl.find('.autocomplete-found, .autocomplete-not-found').hide();
}
} else {
$containerEl.find('.autocomplete-found').show();
$containerEl.find('.autocomplete-not-found, .autocomplete-values').hide();
}
});
}
updateValues() {
const ac = this;
let valuesHTML = '';
for (let i = 0; i < ac.value.length; i += 1) {
valuesHTML += ac.renderItem({
value: typeof ac.value[i] === 'object' ? ac.value[i][ac.params.valueProperty] : ac.value[i],
text: typeof ac.value[i] === 'object' ? ac.value[i][ac.params.textProperty] : ac.value[i],
inputType: ac.inputType,
id: ac.id,
inputName: `${ac.inputName}-checked}`,
selected: true,
}, i);
}
ac.$containerEl.find('.autocomplete-values ul').html(valuesHTML);
}
preloaderHide() {
const ac = this;
if (ac.params.openIn === 'dropdown' && ac.$dropdownEl) {
ac.$dropdownEl.find('.autocomplete-preloader').removeClass('autocomplete-preloader-visible');
} else {
$('.autocomplete-preloader').removeClass('autocomplete-preloader-visible');
}
}
preloaderShow() {
const ac = this;
if (ac.params.openIn === 'dropdown' && ac.$dropdownEl) {
ac.$dropdownEl.find('.autocomplete-preloader').addClass('autocomplete-preloader-visible');
} else {
$('.autocomplete-preloader').addClass('autocomplete-preloader-visible');
}
}
renderPreloader() {
const ac = this;
return `
<div class="autocomplete-preloader preloader ${ac.params.preloaderColor ? `color-${ac.params.preloaderColor}` : ''}">${ac.app.theme === 'md' ? Utils.mdPreloaderContent : ''}</div>
`.trim();
}
renderSearchbar() {
const ac = this;
if (ac.params.renderSearchbar) return ac.params.renderSearchbar.call(ac);
const searchbarHTML = `
<form class="searchbar">
<div class="searchbar-inner">
<div class="searchbar-input-wrap">
<input type="search" placeholder="${ac.params.searchbarPlaceholder}"/>
<i class="searchbar-icon"></i>
<span class="input-clear-button"></span>
</div>
<span class="searchbar-disable-button">${ac.params.searchbarDisableText}</span>
</div>
</form>
`.trim();
return searchbarHTML;
}
renderItem(item, index) {
const ac = this;
if (ac.params.renderItem) return ac.params.renderItem.call(ac, item, index);
let itemHtml;
if (ac.params.openIn !== 'dropdown') {
itemHtml = `
<li>
<label class="item-${item.inputType} item-content">
<input type="${item.inputType}" name="${item.inputName}" value="${item.value}" ${item.selected ? 'checked' : ''}>
<i class="icon icon-${item.inputType}"></i>
<div class="item-inner">
<div class="item-title">${item.text}</div>
</div>
</label>
</li>
`;
} else if (!item.placeholder) {
// Dropdown
itemHtml = `
<li>
<label class="item-radio item-content" data-value="${item.value}">
<div class="item-inner">
<div class="item-title">${item.text}</div>
</div>
</label>
</li>
`;
} else {
// Dropwdown placeholder
itemHtml = `
<li class="autocomplete-dropdown-placeholder">
<div class="item-content">
<div class="item-inner">
<div class="item-title">${item.text}</div>
</div>
</label>
</li>
`;
}
return itemHtml.trim();
}
renderNavbar() {
const ac = this;
if (ac.params.renderNavbar) return ac.params.renderNavbar.call(ac);
let pageTitle = ac.params.pageTitle;
if (typeof pageTitle === 'undefined' && ac.$openerEl && ac.$openerEl.length) {
pageTitle = ac.$openerEl.find('.item-title').text().trim();
}
const navbarHtml = `
<div class="navbar ${ac.params.navbarColorTheme ? `color-theme-${ac.params.navbarColorTheme}` : ''}">
<div class="navbar-inner ${ac.params.navbarColorTheme ? `color-theme-${ac.params.navbarColorTheme}` : ''}">
<div class="left sliding">
<a href="#" class="link ${ac.params.openIn === 'page' ? 'back' : 'popup-close'}">
<i class="icon icon-back"></i>
<span class="ios-only">${ac.params.openIn === 'page' ? ac.params.pageBackLinkText : ac.params.popupCloseLinkText}</span>
</a>
</div>
${pageTitle ? `<div class="title sliding">${pageTitle}</div>` : ''}
${ac.params.preloader ? `
<div class="right">
${ac.renderPreloader()}
</div>
` : ''}
<div class="subnavbar sliding">${ac.renderSearchbar()}</div>
</div>
</div>
`.trim();
return navbarHtml;
}
renderDropdown() {
const ac = this;
if (ac.params.renderDropdown) return ac.params.renderDropdown.call(ac, ac.items);
const dropdownHtml = `
<div class="autocomplete-dropdown">
<div class="autocomplete-dropdown-inner">
<div class="list ${!ac.params.expandInput ? 'no-ios-edge' : ''}">
<ul></ul>
</div>
</div>
${ac.params.preloader ? ac.renderPreloader() : ''}
</div>
`.trim();
return dropdownHtml;
}
renderPage() {
const ac = this;
if (ac.params.renderPage) return ac.params.renderPage.call(ac, ac.items);
const pageHtml = `
<div class="page page-with-subnavbar autocomplete-page" data-name="autocomplete-page">
${ac.renderNavbar()}
<div class="searchbar-backdrop"></div>
<div class="page-content">
<div class="list autocomplete-list autocomplete-found autocomplete-list-${ac.id} ${ac.params.formColorTheme ? `color-theme-${ac.params.formColorTheme}` : ''}">
<ul></ul>
</div>
<div class="list autocomplete-not-found">
<ul>
<li class="item-content"><div class="item-inner"><div class="item-title">${ac.params.notFoundText}</div></div></li>
</ul>
</div>
<div class="list autocomplete-values">
<ul></ul>
</div>
</div>
</div>
`.trim();
return pageHtml;
}
renderPopup() {
const ac = this;
if (ac.params.renderPopup) return ac.params.renderPopup.call(ac, ac.items);
const popupHtml = `
<div class="popup autocomplete-popup">
<div class="view">
${ac.renderPage()};
</div>
</div>
`.trim();
return popupHtml;
}
onOpen(type, containerEl) {
const ac = this;
const app = ac.app;
const $containerEl = $(containerEl);
ac.$containerEl = $containerEl;
ac.openedIn = type;
ac.opened = true;
if (ac.params.openIn === 'dropdown') {
ac.attachDropdownEvents();
ac.$dropdownEl.addClass('autocomplete-dropdown-in');
ac.$inputEl.trigger('input');
} else {
// Init SB
let $searchbarEl = $containerEl.find('.searchbar');
if (ac.params.openIn === 'page' && app.theme === 'ios' && $searchbarEl.length === 0) {
$searchbarEl = $(app.navbar.getElByPage($containerEl)).find('.searchbar');
}
ac.searchbar = app.searchbar.create({
el: $searchbarEl,
backdropEl: $containerEl.find('.searchbar-backdrop'),
customSearch: true,
on: {
searchbarSearch(query) {
if (query.length === 0 && ac.searchbar.enabled) {
ac.searchbar.backdropShow();
} else {
ac.searchbar.backdropHide();
}
ac.source(query);
},
},
});
// Attach page events
ac.attachPageEvents();
// Update Values On Page Init
ac.updateValues();
// Source on load
if (ac.params.requestSourceOnOpen) ac.source('');
}
ac.emit('local::open autocompleteOpen', ac);
}
onOpened() {
const ac = this;
if (ac.params.openIn !== 'dropdown' && ac.params.autoFocus) {
ac.autoFocus();
}
ac.emit('local::opened autocompleteOpened', ac);
}
onClose() {
const ac = this;
if (ac.destroyed) return;
// Destroy SB
if (ac.searchbar && ac.searchbar.destroy) {
ac.searchbar.destroy();
ac.searchbar = null;
delete ac.searchbar;
}
if (ac.params.openIn === 'dropdown') {
ac.detachDropdownEvents();
ac.$dropdownEl.removeClass('autocomplete-dropdown-in').remove();
ac.$inputEl.parents('.item-content-dropdown-expanded').removeClass('item-content-dropdown-expanded');
} else {
ac.detachPageEvents();
}
ac.emit('local::close autocompleteClose', ac);
}
onClosed() {
const ac = this;
if (ac.destroyed) return;
ac.opened = false;
ac.$containerEl = null;
delete ac.$containerEl;
ac.emit('local::closed autocompleteClosed', ac);
}
openPage() {
const ac = this;
if (ac.opened) return ac;
const pageHtml = ac.renderPage();
ac.view.router.navigate({
url: ac.url,
route: {
content: pageHtml,
path: ac.url,
on: {
pageBeforeIn(e, page) {
ac.onOpen('page', page.el);
},
pageAfterIn(e, page) {
ac.onOpened('page', page.el);
},
pageBeforeOut(e, page) {
ac.onClose('page', page.el);
},
pageAfterOut(e, page) {
ac.onClosed('page', page.el);
},
},
options: {
animate: ac.params.animate,
},
},
});
return ac;
}
openPopup() {
const ac = this;
if (ac.opened) return ac;
const popupHtml = ac.renderPopup();
const popupParams = {
content: popupHtml,
animate: ac.params.animate,
on: {
popupOpen(popup) {
ac.onOpen('popup', popup.el);
},
popupOpened(popup) {
ac.onOpened('popup', popup.el);
},
popupClose(popup) {
ac.onClose('popup', popup.el);
},
popupClosed(popup) {
ac.onClosed('popup', popup.el);
},
},
};
if (ac.params.routableModals) {
ac.view.router.navigate({
url: ac.url,
route: {
path: ac.url,
popup: popupParams,
},
});
} else {
ac.modal = ac.app.popup.create(popupParams).open(ac.params.animate);
}
return ac;
}
openDropdown() {
const ac = this;
if (!ac.$dropdownEl) {
ac.$dropdownEl = $(ac.renderDropdown());
}
const $listEl = ac.$inputEl.parents('.list');
if ($listEl.length && ac.$inputEl.parents('.item-content').length > 0 && ac.params.expandInput) {
ac.$inputEl.parents('.item-content').addClass('item-content-dropdown-expanded');
}
ac.positionDropDown();
const $pageContentEl = ac.$inputEl.parents('.page-content');
if (ac.params.dropdownContainerEl) {
$(ac.params.dropdownContainerEl).append(ac.$dropdownEl);
} else if ($pageContentEl.length === 0) {
ac.$dropdownEl.insertAfter(ac.$inputEl);
} else {
$pageContentEl.append(ac.$dropdownEl);
}
ac.onOpen('dropdown', ac.$dropdownEl);
ac.onOpened('dropdown', ac.$dropdownEl);
}
open() {
const ac = this;
if (ac.opened) return ac;
const openIn = ac.params.openIn;
ac[`open${openIn.split('').map((el, index) => {
if (index === 0) return el.toUpperCase();
return el;
}).join('')}`]();
return ac;
}
close() {
const ac = this;
if (!ac.opened) return ac;
if (ac.params.openIn === 'dropdown') {
ac.onClose();
ac.onClosed();
} else if (ac.params.routableModals || ac.openedIn === 'page') {
ac.view.router.back({ animate: ac.params.animate });
} else {
ac.modal.once('modalClosed', () => {
Utils.nextTick(() => {
ac.modal.destroy();
delete ac.modal;
});
});
ac.modal.close();
}
return ac;
}
init() {
const ac = this;
ac.attachEvents();
}
destroy() {
const ac = this;
ac.emit('local::beforeDestroy autocompleteBeforeDestroy', ac);
ac.detachEvents();
if (ac.$inputEl && ac.$inputEl[0]) {
delete ac.$inputEl[0].f7Autocomplete;
}
if (ac.$openerEl && ac.$openerEl[0]) {
delete ac.$openerEl[0].f7Autocomplete;
}
Utils.deleteProps(ac);
ac.destroyed = true;
}
}
var Autocomplete = {
name: 'autocomplete',
params: {
autocomplete: {
openerEl: undefined,
inputEl: undefined,
view: undefined,
// DropDown
dropdownContainerEl: undefined,
dropdownPlaceholderText: undefined,
typeahead: false,
highlightMatches: true,
expandInput: false,
updateInputValueOnSelect: true,
value: undefined,
multiple: false,
source: undefined,
limit: undefined,
valueProperty: 'id',
textProperty: 'text',
openIn: 'page', // or 'popup' or 'dropdown'
pageBackLinkText: 'Back',
popupCloseLinkText: 'Close',
searchbarPlaceholder: 'Search...',
searchbarDisableText: 'Cancel',
animate: true,
autoFocus: false,
closeOnSelect: false,
notFoundText: 'Nothing found',
requestSourceOnOpen: false,
// Preloader
preloaderColor: undefined,
preloader: false,
// Colors
formColorTheme: undefined,
navbarColorTheme: undefined,
// Routing
routableModals: true,
url: 'select',
// Custom render functions
renderDropdown: undefined,
renderPage: undefined,
renderPopup: undefined,
renderItems: undefined,
renderItem: undefined,
renderSearchbar: undefined,
renderNavbar: undefined,
},
},
static: {
Autocomplete: Autocomplete$1,
},
create() {
const app = this;
app.autocomplete = Utils.extend(
ConstructorMethods({
defaultSelector: undefined,
constructor: Autocomplete$1,
app,
domProp: 'f7Autocomplete',
}),
{
open(autocompleteEl) {
const ac = app.autocomplete.get(autocompleteEl);
if (ac && ac.open) return ac.open();
return undefined;
},
close(autocompleteEl) {
const ac = app.autocomplete.get(autocompleteEl);
if (ac && ac.close) return ac.close();
return undefined;
},
}
);
},
};
class ViAd extends Framework7Class {
constructor(app, params = {}) {
super(params, [app]);
const vi = this;
if (!window.vi) {
throw new Error('f7:vi SDK not found.');
}
let orientation;
if (typeof window.orientation !== 'undefined') {
orientation = window.orientation === -90 || window.orientation === 90 ? 'horizontal' : 'vertical';
}
const defaults = Utils.extend(
{},
app.params.vi,
{
appId: app.id,
appVer: app.version,
language: app.language,
width: app.width,
height: app.height,
os: Device.os,
osVersion: Device.osVersion,
orientation,
}
);
// Extend defaults with modules params
vi.useModulesParams(defaults);
vi.params = Utils.extend(defaults, params);
const adParams = {};
const skipParams = ('on autoplay fallbackOverlay fallbackOverlayText enabled').split(' ');
Object.keys(vi.params).forEach((paramName) => {
if (skipParams.indexOf(paramName) >= 0) return;
const paramValue = vi.params[paramName];
if ([null, undefined].indexOf(paramValue) >= 0) return;
adParams[paramName] = paramValue;
});
if (!vi.params.appId) {
throw new Error('Framework7:"app.id" is required to display an ad. Make sure you have specified it on app initialization.');
}
if (!vi.params.placementId) {
throw new Error('Framework7:"placementId" is required to display an ad.');
}
function onResize() {
const $viFrame = $('iframe#viAd');
if ($viFrame.length === 0) return;
$viFrame
.css({
width: `${app.width}px`,
height: `${app.height}px`,
});
}
function removeOverlay() {
if (!vi.$overlayEl) return;
vi.$overlayEl.off('click touchstart');
vi.$overlayEl.remove();
}
function createOverlay(videoEl) {
if (!videoEl) return;
vi.$overlayEl = $(`
<div class="vi-overlay no-fastclick">
${vi.params.fallbackOverlayText ? `<div class="vi-overlay-text">${vi.params.fallbackOverlayText}</div>` : ''}
<div class="vi-overlay-play-button"></div>
</div>
`.trim());
let touchStartTime;
vi.$overlayEl.on('touchstart', () => {
touchStartTime = Utils.now();
});
vi.$overlayEl.on('click', () => {
const timeDiff = Utils.now() - touchStartTime;
if (timeDiff > 300) return;
if (videoEl) {
videoEl.play();
removeOverlay();
return;
}
vi.start();
removeOverlay();
});
app.root.append(vi.$overlayEl);
}
// Create ad
vi.ad = new window.vi.Ad(adParams);
Utils.extend(vi.ad, {
onAdReady() {
app.on('resize', onResize);
vi.emit('local::ready');
if (vi.params.autoplay) {
vi.start();
}
},
onAdStarted() {
vi.emit('local::started');
},
onAdClick(targetUrl) {
vi.emit('local::click', targetUrl);
},
onAdImpression() {
vi.emit('local::impression');
},
onAdStopped(reason) {
app.off('resize', onResize);
removeOverlay();
vi.emit('local::stopped', reason);
if (reason === 'complete') {
vi.emit('local::complete');
}
if (reason === 'userexit') {
vi.emit('local::userexit');
}
vi.destroyed = true;
},
onAutoPlayFailed(reason, videoEl) {
vi.emit('local::autoplayFailed', reason, videoEl);
if (reason && reason.name && reason.name.indexOf('NotAllowedError') !== -1 && vi.params.fallbackOverlay) {
createOverlay(videoEl);
}
},
onAdError(msg) {
removeOverlay();
app.off('resize', onResize);
vi.emit('local::error', msg);
vi.destroyed = true;
},
});
vi.init();
Utils.extend(vi, {
app,
});
}
start() {
const vi = this;
if (vi.destroyed) return;
if (vi.ad) vi.ad.startAd();
}
pause() {
const vi = this;
if (vi.destroyed) return;
if (vi.ad) vi.ad.pauseAd();
}
resume() {
const vi = this;
if (vi.destroyed) return;
if (vi.ad) vi.ad.resumeAd();
}
stop() {
const vi = this;
if (vi.destroyed) return;
if (vi.ad) vi.ad.stopAd();
}
init() {
const vi = this;
if (vi.destroyed) return;
if (vi.ad) vi.ad.initAd();
}
destroy() {
const vi = this;
vi.destroyed = true;
vi.emit('local::beforeDestroy');
Utils.deleteProps(vi);
}
}
var Vi = {
name: 'vi',
params: {
vi: {
enabled: false,
autoplay: true,
fallbackOverlay: true,
fallbackOverlayText: 'Please watch this ad',
showMute: true,
startMuted: (Device.ios || Device.android) && !Device.cordova,
appId: null,
appVer: null,
language: null,
width: null,
height: null,
placementId: 'pltd4o7ibb9rc653x14',
videoSlot: null,
showProgress: true,
showBranding: true,
os: null,
osVersion: null,
orientation: null,
age: null,
gender: null,
advertiserId: null,
latitude: null,
longitude: null,
accuracy: null,
storeId: null,
ip: null,
manufacturer: null,
model: null,
connectionType: null,
connectionProvider: null,
},
},
create() {
const app = this;
app.vi = {
sdkReady: false,
createAd(adParams) {
return new ViAd(app, adParams);
},
loadSdk() {
if (app.vi.skdReady) return;
const script = document.createElement('script');
script.onload = function onload() {
app.emit('viSdkReady');
app.vi.skdReady = true;
};
script.src = 'http://c.vi-serve.com/viadshtml/vi.min.js';
$('head').append(script);
},
};
},
on: {
init() {
const app = this;
if (app.params.vi.enabled || (app.passedParams.vi && app.passedParams.vi.enabled !== false)) app.vi.loadSdk();
},
},
};
// F7 Class
// Core Modules
// Core Components
// Install Core Modules & Components
Framework7$1.use([
Device$2,
Support,
Utils$2,
Resize,
Request,
Touch,
Clicks,
Router,
History$2,
Storage$1,
Statusbar$1,
View$2,
Navbar$1,
Toolbar$1,
Subnavbar,
TouchRipple$$1,
Modal,
Dialog,
Popup,
LoginScreen,
Popover,
Actions,
Sheet,
Toast,
Preloader$1,
Progressbar$1,
Sortable$1,
Swipeout$1,
Accordion$1,
VirtualList,
Timeline,
Tabs,
Panel,
Card,
Chip,
Form,
Input$1,
Checkbox,
Radio,
Toggle,
Range,
SmartSelect,
Calendar,
Picker,
InfiniteScroll$1,
PullToRefresh,
Lazy$1,
DataTable,
Fab$1,
Searchbar,
Messages,
Messagebar,
Swiper,
PhotoBrowser,
Notification,
Autocomplete,
Vi
]);
export default Framework7$1;
|
require('ember-routing/ext/controller');
require('ember-routing/ext/view');
|
/* jshint -W117:false */
(function (QUnit, env) {
if (env.__quit_once_initialized) {
return;
}
env.__quit_once_initialized = true;
if (typeof QUnit !== 'object') {
throw new Error('undefined QUnit object');
}
var _module = QUnit.module;
if (typeof _module !== 'function') {
throw new Error('QUnit.module should be a function');
}
QUnit.module = function (name, config) {
if (typeof config !== 'object') {
return _module.call(QUnit, name, config);
}
(function addSetupOnce() {
if (QUnit.supports &&
QUnit.supports.setupOnce) {
return;
}
if (typeof config.setupOnce === 'function') {
var _setupOnceRan = false;
var _setup = typeof config.setup === 'function' ?
config.setup : null;
config.setup = function () {
if (!_setupOnceRan) {
config.setupOnce();
_setupOnceRan = true;
}
if (_setup) {
_setup.call(config);
}
};
}
}());
(function addTeardownOnce() {
if (QUnit.supports &&
QUnit.supports.teardownOnce) {
return;
}
function isLastTestInModule() {
if (QUnit.config && Array.isArray(QUnit.config.queue)) {
return QUnit.config.queue.length === 1;
} else {
// we cannot determine if the test is the last one in this module
return false;
}
}
if (typeof config.teardownOnce === 'function') {
var _teardown = typeof config.teardown === 'function' ?
config.teardown : null;
config.teardown = function () {
if (_teardown) {
_teardown.call(config);
}
if (isLastTestInModule()) {
config.teardownOnce();
config.teardownOnceRan = true;
}
};
// if multiple modules are used, the latest qunit
// puts everything into single queue. Figure out if
// current module is done
QUnit.moduleDone(function (details) {
// console.log('from', QUnit.config.currentModule);
// console.log('module done', details);
if (details.name === name) {
if (!config.teardownOnceRan) {
// console.log('running module teardown once');
config.teardownOnce();
config.teardownOnceRan = true;
}
}
});
}
}());
_module.call(QUnit, name, config);
};
}(QUnit, typeof global === 'object' ? global : window));
|
/* */
require('../modules/es6.object.to-string');
require('../modules/es6.string.iterator');
require('../modules/web.dom.iterable');
require('../modules/es6.promise');
module.exports = require('../modules/_core').Promise;
|
// dna.js v1.3.4 ~~ dnajs.org ~~ MIT
// Copyright (c) 2013-2017 individual contributors to dna.js
var dna = {
// API:
// dna.clone()
// dna.cloneSub()
// dna.createTemplate()
// dna.rest.get()
// dna.getModel()
// dna.empty()
// dna.refresh()
// dna.refreshAll()
// dna.destroy()
// dna.getClone()
// dna.getClones()
// dna.getIndex()
// dna.up()
// dna.down()
// dna.bye()
// dna.registerInitializer()
// dna.clearInitializers()
// dna.registerContext()
// dna.info()
// See: http://dnajs.org/docs/#api
clone: function(name, data, options) {
// Generates a copy of the template and populates the fields, attributes, and
// classes from the supplied data.
var defaults = {
fade: false,
top: false,
container: null,
empty: false,
clones: 1,
html: false,
transform: null,
callback: null
};
var settings = $.extend(defaults, options);
var template = dna.store.getTemplate(name);
if (template.nested && !settings.container)
dna.core.berserk('Container missing for nested template: ' + name);
if (settings.empty)
dna.empty(name);
var list = [];
while (settings.clones--)
list = list.concat(data);
var clones = $();
function addClone(i, d) { clones = clones.add(dna.core.replicate(template, d, i, settings)); }
$.each(list, addClone);
dna.placeholder.setup(); //TODO: optimize
var first = clones.first();
first.closest('.dna-menu, .dna-panels').each(dna.panels.refresh);
first.parents('.dna-hide').removeClass('dna-hide').addClass('dna-unhide');
return clones;
},
cloneSub: function(holderClone, arrayField, data, options) {
// Clones a sub-template to append onto an array loop.
var name = dna.compile.subTemplateName(holderClone, arrayField);
var selector = '.dna-contains-' + name;
var settings = $.extend({ container: holderClone.find(selector).addBack(selector) }, options);
dna.clone(name, data, settings);
var array = dna.getModel(holderClone)[arrayField];
function append(i, value) { array.push(value); }
$.each(data instanceof Array ? data : [data], append);
return holderClone;
},
createTemplate: function(name, html, holder) {
// Generates a template from an HTML string.
$(html).attr({ id: name }).addClass('dna-template').appendTo(holder);
return dna.store.getTemplate(name);
},
rest: {
// Makes a GET request to the url and then generates a copy of the template
// and populates the fields, attributes, and classes from the JSON response.
// NOTE: Experimental -- currently very limited functionality
get: function(name, url, options) {
function processJson(data) {
if (!data.error)
dna.clone(name, data, options);
}
return $.getJSON(url, processJson);
}
},
getModel: function(elemOrName, options) {
// Returns the underlying data of the clone.
function getOneModel(elem) {
return dna.getClone(elem, options).data('dnaModel');
}
function getAllModels(name) {
var model = [];
function addToModel(i, elem) { model.push(dna.getModel($(elem))); }
dna.getClones(name).each(addToModel);
return model;
}
return (elemOrName instanceof $ ? getOneModel : getAllModels)(elemOrName);
},
empty: function(name, options) {
// Deletes all clones generated from the template.
var settings = $.extend({ fade: false }, options);
var clones = dna.store.getTemplate(name).container.find('.dna-clone');
return settings.fade ? dna.ui.slideFadeDelete(clones) : dna.core.remove(clones);
},
refresh: function(clone, options) {
// Updates an existing clone to reflect changes to the data model.
var settings = $.extend({ html: false }, options);
var elem = dna.getClone(clone, options);
var data = settings.data ? settings.data : dna.getModel(elem);
return dna.core.inject(elem, data, null, settings);
},
refreshAll: function(name) {
// Updates all the clones of the specified template.
function refresh(i, elem) { dna.refresh($(elem)); }
return dna.getClones(name).each(refresh);
},
destroy: function(clone, options) {
// Removes an existing clone from the DOM.
var settings = $.extend({ fade: false }, options);
clone = dna.getClone(clone, options);
function removeArrayItem(field) {
dna.getModel(clone.parent())[field].splice(dna.getIndex(clone), 1);
}
if (clone.hasClass('dna-sub-clone'))
removeArrayItem(clone.data().dnaRules.array);
return settings.fade ? dna.ui.slideFadeDelete(clone) : dna.core.remove(clone);
},
getClone: function(elem, options) {
// Returns the clone (or sub-clone) for the specified element.
var settings = $.extend({ main: false }, options);
var selector = settings.main ? '.dna-clone:not(.dna-sub-clone)' : '.dna-clone';
return elem instanceof $ ? elem.closest(selector) : $();
},
getClones: function(name) {
// Returns an array of all the existing clones for the given template.
return dna.store.getTemplate(name).container.children().filter('.dna-clone');
},
getIndex: function(elem, options) {
// Returns the index of the clone.
var clone = dna.getClone(elem, options);
return clone.parent().children('.dna-clone').index(clone);
},
up: function(elemOrEventOrIndex) {
// Smoothly moves a clone up one slot effectively swapping its position with the previous
// clone.
return dna.ui.smoothMove(dna.getClone(dna.ui.toElem(elemOrEventOrIndex, this)), true);
},
down: function(elemOrEventOrIndex) {
// Smoothly moves a clone down one slot effectively swapping its position with the next
// clone.
return dna.ui.smoothMove(dna.getClone(dna.ui.toElem(elemOrEventOrIndex, this)), false);
},
bye: function(elemOrEventOrIndex) {
// Performs a sliding fade out effect on the clone and then removes the element.
return dna.destroy(dna.ui.toElem(elemOrEventOrIndex, this), { fade: true });
},
registerInitializer: function(func, options) {
// Adds a callback function to the list of initializers that are run on all DOM elements.
var settings = $.extend({ onDocumentLoad: true }, options);
if (settings.onDocumentLoad)
dna.util.apply(func, [settings.selector ? $(settings.selector).not(
'.dna-template ' + settings.selector).addClass('dna-initialized') :
$(window.document)].concat(settings.params));
return dna.events.initializers.push(
{ func: func, selector: settings.selector, params: settings.params });
},
clearInitializers: function() {
// Deletes all initializers.
dna.events.initializers = [];
},
registerContext: function(contextName, contextObjectOrFunction) {
// Registers an application object or individual function to enable it to be used for event
// callbacks. Registration is needed when global namespace is not available to dna.js, such
// as when using webpack to load dna.js as a module.
dna.events.context[contextName] = contextObjectOrFunction;
return dna.events.context;
},
info: function() {
// Returns status information about templates on the current web page.
var names = Object.keys(dna.store.templates);
function addToSum(sum, name) { return sum + dna.store.templates[name].clones; }
return {
version: '1.3.4',
templates: names.length,
clones: names.reduce(addToSum, 0),
names: names,
store: dna.store.templates,
initializers: dna.events.initializers
};
}
};
dna.array = {
find: function(array, value, key) {
// Returns the first array element with a key equal to the supplied value. The default key
// is "code".
// Example:
// var array = [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }];
// dna.array.find(array, 'b').word === 'Bat';
key = key || 'code';
function found(obj) { return obj[key] === value; }
var objs = array.filter(found);
return objs.length ? objs[0] : null;
},
fromMap: function(map, key) {
// Converts an object (hash map) into an array of objects. The default key is "code".
// var map = { a: { word: 'Ant' }, b: { word: 'Bat' } };
// var array = dna.array.fromMap(map, 'code');
// ==> [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }]
key = key || 'code';
var array = [];
function toObj(item) { return item instanceof Object ? item : { value: item }; }
for (var property in map)
array[array.push(toObj(map[property])) - 1][key] = property;
return array;
},
last: function(array) {
// Returns the last element of the array (or undefined if not possible).
// Example:
// dna.array.last([3, 21, 7]) === 7;
return array && array.length ? array[array.length - 1] : undefined;
},
toMap: function(array, key) {
// Converts an array of objects into an object (hash map). The default key is "code".
// var array = [{ code: 'a', word: 'Ant' }, { code: 'b', word: 'Bat' }];
// var map = dna.array.toMap(array, 'code');
// ==> { a: { word: 'Ant' }, b: { word: 'Bat' } }
key = key || 'code';
var map = {};
function addObj(obj) { map[obj[key]] = obj; }
array.forEach(addObj);
return map;
}
};
dna.browser = {
getUrlParams: function() {
// Returns the query parameters as an object literal.
// Example:
// http://example.com?lang=jp&code=7 ==> { lang: 'jp', code: 7 }
var params = {};
function addParam(pair) { if (pair) params[pair.split('=')[0]] = pair.split('=')[1]; }
window.location.search.slice(1).split('&').forEach(addParam);
return params;
},
iOS: function() {
// Returns a boolean indicating if the browser is running on an iOS device.
return /iPad|iPhone|iPod/.test(window.navigator.userAgent) &&
/Apple/.test(window.navigator.vendor);
}
};
dna.browser.getParams = dna.browser.getUrlParams; //DEPRECATED
dna.pageToken = {
// A simple key/value store specific to the page (URL path) that is cleared out when the
// user's browser session ends.
put: function(key, value) {
// Example:
// dna.pageToken.put('favorite', 7); //saves 7
window.sessionStorage[key + window.location.pathname] = JSON.stringify(value);
return value;
},
get: function(key, defaultValue) {
// Example:
// dna.pageToken.get('favorite', 0); //returns 0 if not set
var value = window.sessionStorage[key + window.location.pathname];
return value === undefined ? defaultValue : JSON.parse(value);
}
};
dna.ui = {
deleteElem: function(elemOrEventOrIndex) {
// A flexible function for removing a jQuery element.
// Example:
// $('.box').fadeOut(dna.ui.deleteElem);
var elem = dna.ui.toElem(elemOrEventOrIndex, this);
dna.core.remove(elem);
return elem;
},
focus: function(elem) {
// Sets focus on an element.
return elem.focus();
},
getComponent: function(elem) {
// Returns the component (container element with a <code>data-component</code> attribute) to
// which the element belongs.
return elem.closest('[data-component]');
},
pulse: function(elem, options) {
// Fades in an element after hiding it to create a smooth pulse effect. The optional
// interval fades out the element.
var settings = $.extend({ duration: 400, interval: null, out: 5000 }, options);
elem.stop(true).slideDown().css({ opacity: 0 }).animate({ opacity: 1 }, settings.duration);
if (settings.interval)
elem.delay(settings.duration + settings.interval).animate({ opacity: 0 }, settings.out);
return elem;
},
slideFade: function(elem, callback, show) {
// Smooth slide plus fade effect.
var obscure = { opacity: 0, transition: 'opacity 0s' };
var easyIn = { opacity: 1, transition: 'opacity 0.4s' };
var easyOut = { opacity: 0, transition: 'opacity 0.4s' };
var reset = { transition: 'opacity 0s' };
function clearOpacityTransition() { elem.css(reset); }
window.setTimeout(clearOpacityTransition, 1000); //keep clean for other animations
if (show)
elem.css(obscure).hide().slideDown({ complete: callback }).css(easyIn);
else
elem.css(easyOut).slideUp({ complete: callback });
return elem;
},
slideFadeIn: function(elem, callback) {
// Smooth slide plus fade effect.
return dna.ui.slideFade(elem, callback, true);
},
slideFadeOut: function(elem, callback) {
// Smooth slide plus fade effect.
return dna.ui.slideFade(elem, callback, false);
},
slideFadeToggle: function(elem, callback) {
// Smooth slide plus fade effect.
return dna.ui.slideFade(elem, callback, elem.is(':hidden'));
},
slideFadeDelete: function(elem) {
// Smooth slide plus fade effect.
return dna.ui.slideFadeOut(elem, dna.ui.deleteElem);
},
slidingFlasher: function(elem, callback) {
// Uses a smooth slide down plus fade in effect on an element if it is hidden or a smooth
// fade in flash if the element is already visible -- intended to display an error message.
return elem.is(':hidden') ? dna.ui.slideFadeIn(elem, callback) : elem.hide().fadeIn();
},
smoothHeightSetBaseline: function(container) {
// See: smoothHeightAnimate below
dna.ui.$container = container = container || $('body');
var height = container.outerHeight();
return container.css({ minHeight: height, maxHeight: height, overflow: 'hidden' });
},
smoothHeightAnimate: function(delay, container) {
// Smoothly animates the height of a container element from a beginning height to a final
// height.
container = container || dna.ui.$container;
function animate() {
container.css({ minHeight: 0, maxHeight: '100vh' });
function turnOffTransition() { container.css({ transition: 'none', maxHeight: 'none' }); }
window.setTimeout(turnOffTransition, 1000); //allow 1s transition to finish
}
window.setTimeout(animate, delay || 50); //allow container time to draw
function setAnimationLength() { container.css({ transition: 'all 1s' }); }
window.setTimeout(setAnimationLength, 10); //allow baseline to lock in height
return container;
},
smoothMove: function(elem, up) {
// Uses animation to smoothly slide an element up or down one slot amongst its siblings.
function move() {
var ghostElem = submissiveElem.clone();
if (up)
elem.after(submissiveElem.hide()).before(ghostElem);
else
elem.before(submissiveElem.hide()).after(ghostElem);
dna.ui.slideFadeIn(submissiveElem);
dna.ui.slideFadeDelete(ghostElem);
}
var submissiveElem = up ? elem.prev() : elem.next();
if (submissiveElem.length)
move();
return elem;
},
toElem: function(elemOrEventOrIndex, that) {
// A flexible way to get the jQuery element whether it is passed in directly, the target of
// an event, or comes from the jQuery context.
return elemOrEventOrIndex instanceof $ ? elemOrEventOrIndex :
$(elemOrEventOrIndex ? elemOrEventOrIndex.target : that);
}
};
dna.util = {
apply: function(fn, params) {
// Calls fn (string name or actual function) passing in params.
// Usage:
// dna.util.apply('app.cart.buy', 7); ==> app.cart.buy(7);
var args = params === undefined ? [] : [].concat(params);
var elem = args[0];
var result;
function contextApply(context, names) {
if (!context || (names.length === 1 && typeof context[names[0]] !== 'function'))
dna.core.berserk('Callback function not found: ' + fn);
else if (names.length === 1)
result = context[names[0]].apply(elem, args); //'app.cart.buy' ==> window['app']['cart']['buy']
else
contextApply(context[names[0]], names.slice(1));
}
function findFn(names) {
if (elem instanceof $)
args.push(dna.ui.getComponent(elem));
contextApply(dna.events.context[names[0]] ? dna.events.context : window, names);
}
if (elem instanceof $ && elem.length === 0) //noop for emply list of elems
result = elem;
else if (typeof fn === 'function') //run regular function with supplied arguments
result = fn.apply(elem, args);
else if (elem && elem[fn]) //run element's jQuery function
result = elem[fn](args[1], args[2], args[3]);
else if (fn === '' || { number: true, boolean: true}[typeof fn])
dna.core.berserk('Invalid callback function: ' + fn);
else if (typeof fn === 'string' && fn.length > 0)
findFn(fn.split('.'));
return result;
},
printf: function(format) {
// Builds a formatted string by replacing the format specifiers with the supplied arguments.
// Usage:
// dna.util.printf('%s: %s', 'Lives', 3) === 'Lives: 3';
var values = Array.prototype.slice.call(arguments, 1);
function insert(str, val) { return str.replace(/%s/, val); }
return values.reduce(insert, format);
},
realTruth: function(value) {
// Returns the "real" boolean truth of a value.
// Examples:
// true values ==> true, 7, '7', [5], 't', 'T', 'TRue', {}, 'Colbert'
// false values ==> false, 0, '0', [], 'f', 'F', 'faLSE', null, undefined, NaN
function falseyStr() { return /^(f|false|0)$/i.test(value); }
function emptyArray() { return value instanceof Array && value.length === 0; }
return value ? !emptyArray() && !falseyStr() : false;
},
toCamel: function(kebabStr) {
// Converts a kebab-case string (a code made of lowercase letters and dashes) to camelCase.
// Example:
// dna.util.toCamel('ready-set-go') === 'readySetGo'
function hump(match, char) { return char.toUpperCase(); }
return ('' + kebabStr).replace(/\-(.)/g, hump);
},
toKebab: function(camelStr) {
// Converts a camelCase string to kebab-case (a code made of lowercase letters and dashes).
// Example:
// dna.util.toKebab('readySetGo') === 'ready-set-go'
function dash(word) { return '-' + word.toLowerCase(); }
return ('' + camelStr).replace(/([A-Z]+)/g, dash).replace(/\s|^-/g, '');
},
value: function(data, field) {
// Returns the value of the field from the data object.
// Example:
// dna.util.value({ a: { b: 7 }}, 'a.b') === 7
if (typeof field === 'string')
field = field.split('.');
return (data === null || data === undefined || field === undefined) ? null :
(field.length === 1 ? data[field[0]] : this.value(data[field[0]], field.slice(1)));
}
};
dna.placeholder = { //TODO: optimize
// A template placeholder is only shown when its corresponding template is empty (has zero
// clones). The "data-placeholder" attribute specifies the name of the template.
setup: function() {
$('option.dna-template').closest('select').addClass('dna-hide');
function fade(i, elem) {
var input = $(elem).stop(true);
return dna.getClones(input.data().placeholder).length ? input.fadeOut() : input.fadeIn();
}
$('[data-placeholder]').each(fade);
}
};
dna.panels = {
// Each click of a menu item displays its corresponding panel and optionally passes the panel
// element and hash to the function specified by the "data-callback" attribute.
// Usage:
// <nav id={ID} class=dna-menu data-callback=app.displayPanel>
// <button>See X1</button>
// <button>See X2</button>
// </nav>
// <div id={ID}-panels class=dna-panels>
// <section data-hash=x1>The X1</section>
// <section data-hash=x2>The X2</section>
// </div>
// The optional "data-hash" attribute specifies the hash (URL fragment ID) and updates the
// location bar.
display: function(menu, loc, updateUrl) {
// Shows the panel at the given index (loc)
var panels, panel;
var key = menu.data().dnaKey;
var menuItems = menu.find('.menu-item');
if (loc === undefined)
loc = dna.pageToken.get(key, 0);
loc = Math.max(0, Math.min(loc, menuItems.length - 1));
menu[0].selectedIndex = loc; //case where menu is a drop-down elem (<select>)
menuItems.removeClass('selected').addClass('unselected')
.eq(loc).addClass('selected').removeClass('unselected');
panels = $(key).children().hide().removeClass('displayed').addClass('hidden');
panel = panels.eq(loc).fadeIn().addClass('displayed').removeClass('hidden');
var hash = panel.data().hash;
dna.pageToken.put(key, loc);
if (updateUrl && hash)
window.history.pushState(null, null, '#' + hash);
dna.util.apply(menu.data().callback, [panel, hash]);
},
clickRotate: function(event) {
// Moves to the selected panel
var item = $(event.target).closest('.menu-item');
var menu = item.closest('.dna-menu');
dna.panels.display(menu, menu.find('.menu-item').index(item), true);
},
selectRotate: function(event) {
// Moves to the selected panel
var menu = $(event.target);
dna.panels.display(menu, menu.find('option:selected').index(), true);
},
reload: function(name) {
// Refreshes the currently displayed panel
dna.panels.display($('#' + name));
},
refresh: function(i, elem) {
var menu = $(elem);
if (menu.hasClass('dna-panels')) //special case for panels that are templates
menu = $('#' + menu.attr('id').replace('-panels', ''));
var hash = window.location.hash.slice(1);
var key = menu.data().dnaKey = '#' + menu.attr('id') + '-panels';
var panels = $(key).children().addClass('panel');
if (menu.find('.menu-item').length === 0) //set .menu-item elems if not set in the html
menu.children().addClass('menu-item');
function partOfTemplate(elems) { return elems.first().closest('.dna-template').length > 0; }
function findPanelLoc(panels) {
return hash && panels.first().data().hash ?
panels.filter('[data-hash=' + hash + ']').index() : dna.pageToken.get(key, 0);
}
if (!partOfTemplate(panels) && !partOfTemplate(menu.children()))
dna.panels.display(menu, findPanelLoc(panels));
},
setup: function() {
$('.dna-menu').each(dna.panels.refresh);
$(window.document).on({ click: dna.panels.clickRotate }, '.dna-menu .menu-item');
$(window.document).on({ change: dna.panels.selectRotate }, '.dna-menu');
}
};
dna.compile = {
// Pre-compile Example Post-compile class + data().dnaRules
// ----------- -------------------------------- ------------------------------------
// template <p id=x1 class=dna-template> class=dna-clone
// array <p data-array=~~tags~~> class=dna-nucleotide + array='tags'
// field <p>~~tag~~</p> class=dna-nucleotide + text='tag'
// attribute <p id=~~num~~> class=dna-nucleotide + attrs=['id', ['', 'num', '']]
// rule <p data-truthy=~~on~~> class=dna-nucleotide + truthy='on'
// attr rule <p data-attr-src=~~url~~> class=dna-nucleotide + attrs=['src', ['', 'url', '']]
// prop rule <input data-prop-checked=~~on~~> class=dna-nucleotide + props=['checked', 'on']
// select rule <select data-option=~~day~~> class=dna-nucleotide + option='day'
// transform <p data-transform=app.enhance> class=dna-nucleotide + transform='app.enhance'
// callback <p data-callback=app.configure> class=dna-nucleotide + callback='app.configure'
//
// Rules data().dnaRules
// ----------------------------------------- ---------------
// data-class=~~field,name-true,name-false~~ class=['field','name-true','name-false']
// data-attr-{NAME}=pre~~field~~post attrs=['{NAME}', ['pre', 'field', 'post']]
// data-prop-{NAME}=pre~~field~~post props=['{NAME}', 'field']
// data-option=~~field~~ option='field'
// data-require=~~field~~ require='field'
// data-missing=~~field~~ missing='field'
// data-truthy=~~field~~ truthy='field'
// data-falsey=~~field~~ falsey='field'
// data-transform=func transform='func'
// data-callback=func callback='func'
//
regexDnaField: /^[\s]*(~~|\{\{).*(~~|\}\})[\s]*$/, //example: ~~title~~
regexDnaBasePair: /~~|{{|}}/, //matches the '~~' string
regexDnaBasePairs: /~~|\{\{|\}\}/g, //matches the two '~~' strings so they can be removed
setupNucleotide: function(elem) {
if (elem.data().dnaRules === undefined)
elem.data().dnaRules = {};
return elem.addClass('dna-nucleotide');
},
isDnaField: function(i, elem) {
var firstNode = elem.childNodes[0];
return firstNode && firstNode.nodeValue &&
firstNode.nodeValue.match(dna.compile.regexDnaField);
},
field: function(i, elem) {
// Example:
// <p>~~name~~</p> ==> <p class=dna-nucleotide data-dnaRules={ text: 'name' }></p>
elem = dna.compile.setupNucleotide($(elem));
elem.data().dnaRules.text = $.trim(elem.text()).replace(dna.compile.regexDnaBasePairs, '');
return elem.empty();
},
propsAndAttrs: function(i, elem) {
// Examples:
// <option data-prop-selected=~~set~~> ==> <option class=dna-nucleotide + data-dnaRules={ props: ['selected', 'set'] }>
// <p id=~~num~~> ==> <p class=dna-nucleotide + data-dnaRules={ attrs: ['id', ['', 'num', '']] }>
// <p data-attr-src=~~url~~> ==> <p class=dna-nucleotide + data-dnaRules={ attrs: ['src', ['', 'url', '']] }>
// <p data-tag=~~[value]~~> ==> <p class=dna-nucleotide + data-dnaRules={ attrs: ['data-tag', ['', true, '']] }>
elem = $(elem);
var props = [];
var attrs = [];
var names = [];
function compileProp(key, value) {
names.push(key);
key = key.replace(/^data-prop-/, '').toLowerCase();
value = value.replace(dna.compile.regexDnaBasePairs, '');
props.push(key, value);
if (key === 'checked' && elem.is('input'))
elem.addClass('dna-update-model').data().dnaField = value;
else if (key === 'selected' && elem.is('option'))
elem.parent().addClass('dna-update-model').end().data().dnaField = value;
}
function compileAttr(key, value) {
var parts = value.split(dna.compile.regexDnaBasePair);
if (parts[1] === '[value]')
parts[1] = true;
attrs.push(key.replace(/^data-attr-/, ''), parts);
names.push(key);
var textInput = 'input:not(:checkbox, :radio)';
if (key === 'value' && elem.is(textInput) && parts[0] === '' && parts[2] === '')
elem.addClass('dna-update-model').data().dnaField = parts[1];
}
function compile(i, attr) {
if (/^data-prop-/.test(attr.name))
compileProp(attr.name, attr.value);
else if (attr.value.split(dna.compile.regexDnaBasePair).length === 3)
compileAttr(attr.name, attr.value);
}
$.each(elem.get(0).attributes, compile);
if (props.length > 0)
dna.compile.setupNucleotide(elem).data().dnaRules.props = props;
if (attrs.length > 0)
dna.compile.setupNucleotide(elem).data().dnaRules.attrs = attrs;
if (elem.data().transform) //TODO: Determine if it's better to process only at top-level of clone
dna.compile.setupNucleotide(elem).data().dnaRules.transform = elem.data().transform; //TODO: string to fn
if (elem.data().callback)
dna.compile.setupNucleotide(elem).data().dnaRules.callback = elem.data().callback;
return elem.removeAttr(names.join(' '));
},
getDataField: function(elem, type) {
// Example:
// <p data-array=~~tags~~>, 'array' ==> 'tags'
return $.trim(elem.data(type).replace(dna.compile.regexDnaBasePairs, ''));
},
subTemplateName: function(holder, arrayField) { //holder can be element or template name
// Example:
// subTemplateName('book', 'authors') ==> 'book-authors-instance'
var mainTemplateName = holder instanceof $ ?
dna.getClone(holder).data().dnaRules.template : holder;
return mainTemplateName + '-' + arrayField + '-instance';
},
rules: function(elems, type, isList) {
// Example:
// <p data-require=~~title~~>, 'require' ==> <p data-dnaRules={ require: 'title' }>
function add(i, elem) {
elem = dna.compile.setupNucleotide($(elem));
var field = dna.compile.getDataField(elem, type);
elem.data().dnaRules[type] = isList ? field.split(',') : field;
}
return elems.filter('[data-' + type + ']').each(add).removeAttr('data-' + type);
},
separators: function(elem) {
// Convert: data-separator=", " ==> <span class=dna-separator>, </span>
function isWhitespaceNode(i, elem) { return elem.nodeType === 3 && !/\S/.test(elem.nodeValue); }
function append(templateElem, text, className) {
if (text) {
templateElem.contents().last().filter(isWhitespaceNode).remove();
templateElem.append($('<span>').addClass(className).html(text));
}
}
function processTemplate(i, elem) {
var templateElem = $(elem);
append(templateElem, templateElem.data().separator, 'dna-separator');
append(templateElem, templateElem.data().lastSeparator, 'dna-last-separator');
}
elem.find('.dna-template, .dna-sub-clone').addBack().each(processTemplate);
},
template: function(name) { //prepare and stash template so it can be cloned
var elem = $('#' + name);
if (!elem.length)
dna.core.berserk('Template not found: ' + name);
function saveName(i, elem) { $(elem).data().dnaRules = { template: $(elem).attr('id') }; }
elem.find('.dna-template').addBack().each(saveName).removeAttr('id');
var elems = elem.find('*').addBack();
elems.filter(dna.compile.isDnaField).each(dna.compile.field);
dna.compile.rules(elems, 'array').addClass('dna-sub-clone');
dna.compile.rules(elems, 'class', true);
dna.compile.rules(elems, 'require');
dna.compile.rules(elems, 'missing');
dna.compile.rules(elems, 'truthy');
dna.compile.rules(elems, 'falsey');
dna.compile.rules(elems.filter('select'), 'option').addClass('dna-update-model');
elems.each(dna.compile.propsAndAttrs);
dna.compile.separators(elem);
//support html5 values for "type" attribute
function setTypeAttr(i, elem) { $(elem).attr({ type: $(elem).data().attrType }); }
$('input[data-attr-type]').each(setTypeAttr);
return dna.store.stash(elem);
}
};
dna.store = {
// Handles storage and retrieval of templates
templates: {},
stash: function(elem) {
var name = elem.data().dnaRules.template;
function move(i, elem) {
elem = $(elem);
var name = elem.data().dnaRules.template;
var template = {
name: name,
elem: elem,
container: elem.parent().addClass('dna-container').addClass('dna-contains-' + name),
nested: elem.parent().closest('.dna-clone').length !== 0,
separators: elem.find('.dna-separator, .dna-last-separator').length,
index: elem.index(),
elemsAbove: elem.index() > 0,
elemsBelow: elem.nextAll().length > 0,
clones: 0
};
dna.store.templates[name] = template;
elem.removeClass('dna-template').addClass('dna-clone').addClass(name).detach();
}
function prepLoop(i, elem) {
// Pre (sub-template array loops -- data-array):
// class=dna-sub-clone data().dnaRules.array='field'
// Post (elem):
// data().dnaRules.template='{NAME}-{FIELD}-instance'
// Post (container)
// class=dna-nucleotide +
// data().dnaRules.loop={ name: '{NAME}-{FIELD}-instance', field: 'field' }
elem = $(elem);
var field = elem.data().dnaRules.array;
var sub = dna.compile.subTemplateName(name, field);
dna.compile.setupNucleotide(elem.parent().addClass('dna-array')).data().dnaRules.loop =
{ name: sub, field: field };
elem.data().dnaRules.template = sub;
}
elem.find('.dna-template').addBack().each(move);
elem.find('.dna-sub-clone').each(prepLoop).each(move);
return dna.store.templates[name];
},
getTemplate: function(name) {
return dna.store.templates[name] || dna.compile.template(name);
}
};
dna.events = {
context: {}, //storage to register callbacks when dna.js is module loaded without window scope (webpack)
initializers: [], //example: [{ func: 'app.bar.setup', selector: '.progress-bar' }]
elementSetup: function(root, data) {
// Example:
// <p data-on-load=app.cart.setup>
function setup(i, elem) {
elem = $(elem);
dna.util.apply(elem.data().onLoad, data ? [elem, data] : elem);
}
var selector = '[data-on-load]';
var elems = root ? root.find(selector).addBack(selector) : $(selector);
return elems.not('.dna-initialized').each(setup).addClass('dna-initialized');
},
runInitializers: function(elem, data) {
// Executes data-on-load and data-callback functions plus registered initializers
dna.events.elementSetup(elem, data);
function init(i, initializer) {
var elems = initializer.selector ?
elem.find(initializer.selector).addBack(initializer.selector) : elem;
dna.util.apply(initializer.func,
[elems.addClass('dna-initialized')].concat(initializer.params));
}
$.each(dna.events.initializers, init);
return elem;
},
setup: function() {
function runner(elem, type, event) {
// Finds elements for given event type and executes callback passing in the element,
// event, and component (container element with "data-component" attribute)
// Types: click|change|input|key-up|key-down|key-press|enter-key
elem = elem.closest('[data-' + type + ']');
var fn = elem.data(type);
if (type === 'click' && elem.prop('tagName') === 'A' && fn && fn.match(/^dna[.]/))
event.preventDefault();
return dna.util.apply(fn, [elem, event]);
}
function handle(event) {
var target = $(event.target);
function field(data) { return (data.dnaRules && data.dnaRules.option) || data.dnaField; }
function updateField(elem, calc) { dna.getModel(elem)[field(elem.data())] = calc(elem); }
function getValue(elem) { return elem.val(); }
function isChecked(elem) { return elem.is(':checked'); }
function updateOption(i, elem) { updateField($(elem), isChecked); }
function updateModel() {
var mainClone = dna.getClone(target, { main: true });
if (mainClone.length === 0) { //TODO: figure out why some events are captured on the template instead of the clone
//console.log('Error -- event not on clone:', event.timeStamp, event.type, target);
return;
}
if (target.is('input:checkbox'))
updateField(target, isChecked);
else if (target.is('input:radio'))
$('input:radio[name=' + target.attr('name') + ']').each(updateOption);
else if (target.is('input') || target.data().dnaRules.option)
updateField(target, getValue);
else if (target.is('select'))
target.find('option').each(updateOption);
dna.refresh(mainClone);
}
if (target.hasClass('dna-update-model'))
updateModel();
return runner(target, event.type.replace('key', 'key-'), event);
}
function handleEnterKey(event) {
if (event.which === 13)
runner($(event.target), 'enter-key', event);
}
function handleSmartUpdate(event) {
var defaultThrottle = 1000; //default 1 second delay between callbacks
var elem = $(event.target);
var data = elem.data();
function smartUpdate() {
function doCallback() {
data.dnaLastUpdated = Date.now();
data.dnaTimeoutId = undefined;
runner(elem, 'smart-update', event);
}
function handleChange() {
var throttle = data.smartThrottle ? +data.smartThrottle : defaultThrottle;
data.dnaLastValue = elem.val();
if (!data.dnaTimeoutId)
if (Date.now() < data.dnaLastUpdated + throttle)
data.dnaTimeoutId = window.setTimeout(doCallback, throttle);
else
doCallback();
}
if (event.type === 'keydown' && data.dnaLastValue === undefined)
data.dnaLastValue = elem.val();
if (event.type !== 'keydown' && elem.val() !== data.dnaLastValue)
handleChange();
}
if (data.smartUpdate)
smartUpdate();
}
function jumpToUrl(event) {
// Usage:
// <button data-href=http://dnajs.org>dna.js</button>
// If element (or parent) has the class "external-site", page will be opened in a new tab.
var elem = $(event.target);
var newTab = !dna.browser.iOS() && elem.closest('.external-site').length;
window.open(elem.closest('[data-href]').data().href, newTab ? '_blank' : '_self');
}
$(window.document)
.click(handle)
.change(handle)
.keyup(handle)
.keyup(handleEnterKey)
.keydown(handle)
.keypress(handle)
.keydown(handleSmartUpdate)
.keyup(handleSmartUpdate)
.change(handleSmartUpdate) //TODO: handle paste events on iOS
.on({ input: handle })
.on({ click: jumpToUrl }, '[data-href]');
dna.events.elementSetup();
}
};
dna.core = {
inject: function(clone, data, index, settings) {
// Inserts data into clone and runs rules
function injectField(elem, field) {
var value = field === '[count]' ? index + 1 : field === '[value]' ? data :
dna.util.value(data, field);
var printable = { string: true, number: true, boolean: true };
if (printable[typeof value])
elem = settings.html ? elem.html(value) : elem.text(value);
}
function injectProps(elem, props) { //example props: ['selected', 'set']
for (var prop = 0; prop < props.length/2; prop++) //each prop has a key and a field name
elem.prop(props[prop*2], dna.util.realTruth(dna.util.value(data, props[prop*2 + 1])));
}
function injectAttrs(elem, attrs) { //example attrs: ['data-tag', ['', 'tag', '']]
for (var attr = 0; attr < attrs.length / 2; attr++) { //each attr has a key and parts
var key = attrs[attr*2];
var parts = attrs[attr*2 + 1]; //example: 'J~~code.num~~' ==> ['J', 'code.num', '']
var core = parts[1] === true ? data : dna.util.value(data, parts[1]);
var value = [parts[0], core, parts[2]].join('');
elem.attr(key, value);
if (/^data-./.test(key))
elem.data(key.substring(5), value);
if (key === 'value' && value !== elem.val()) //set elem val for input fields (example: <input value=~~tag~~>)
elem.val(value);
}
}
function injectDropDown(elem, value) {
if (value !== null)
elem.val(value);
}
function injectClass(elem, classList) {
// classList = ['field', 'class-true', 'class-false']
var value = dna.util.value(data, classList[0]);
var truth = dna.util.realTruth(value);
if (classList.length === 1) {
elem.addClass(value);
}
else if (classList.length > 1) {
elem.toggleClass(classList[1], truth);
if (classList[2])
elem.toggleClass(classList[2], !truth);
}
}
function processLoop(elem, loop) {
var dataArray = dna.util.value(data, loop.field);
var subClones = elem.children('.' + loop.name.replace(/[.]/g, '\\.'));
function injectSubClone(i, elem) { dna.core.inject($(elem), dataArray[i], i, settings); }
function rebuildSubClones() {
subClones.remove();
dna.clone(loop.name, dataArray, { container: elem, html: settings.html });
}
if (!dataArray)
data[loop.field] = [];
else if (dataArray.length === subClones.length)
subClones.each(injectSubClone);
else
rebuildSubClones();
}
function process(i, elem) {
elem = $(elem);
var dnaRules = elem.data().dnaRules;
if (dnaRules.transform) //alternate version of the "transform" option
dna.util.apply(dnaRules.transform, data);
if (dnaRules.text)
injectField(elem, dnaRules.text);
if (dnaRules.props)
injectProps(elem, dnaRules.props);
if (dnaRules.attrs)
injectAttrs(elem, dnaRules.attrs);
if (dnaRules.class)
injectClass(elem, dnaRules.class);
if (dnaRules.require)
elem.toggle(dna.util.value(data, dnaRules.require) !== undefined);
if (dnaRules.missing)
elem.toggle(dna.util.value(data, dnaRules.missing) === undefined);
if (dnaRules.truthy)
elem.toggle(dna.util.realTruth(dna.util.value(data, dnaRules.truthy)));
if (dnaRules.falsey)
elem.toggle(!dna.util.realTruth(dna.util.value(data, dnaRules.falsey)));
if (dnaRules.loop)
processLoop(elem, dnaRules.loop);
if (dnaRules.option)
injectDropDown(elem, dna.util.value(data, dnaRules.option));
if (dnaRules.callback)
dna.util.apply(dnaRules.callback, elem);
}
function dig(elems) {
elems.filter('.dna-nucleotide').each(process);
if (elems.length)
dig(elems.children().not('.dna-sub-clone'));
}
if (settings.transform) //alternate version of data-transform
settings.transform(data);
dig(clone);
clone.data().dnaModel = data;
return clone;
},
replicate: function(template, data, index, settings) { //make and setup the clone
function displaySeparators() {
var clones = container.children('.' + template.name);
clones.find('.dna-separator').show().end().last().find('.dna-separator').hide();
clones.find('.dna-last-separator').hide().end().eq(-2).find('.dna-last-separator').show()
.closest('.dna-clone').find('.dna-separator').hide();
}
var clone = template.elem.clone(true, true);
template.clones++;
dna.core.inject(clone, data, index, settings);
var selector = '.dna-contains-' + template.name.replace(/[.]/g, '\\.');
var container = settings.container ?
settings.container.find(selector).addBack(selector) : template.container;
if (settings.top && !template.elemsAbove)
container.prepend(clone);
else if (!settings.top && !template.elemsBelow)
container.append(clone);
else if (settings.top)
container.children().eq(template.index - 1).after(clone);
else
container.children().eq(template.index +
container.children().filter('.dna-clone').length).before(clone);
if (template.separators)
displaySeparators();
dna.events.runInitializers(clone, data);
if (settings.callback)
settings.callback(clone, data);
if (settings.fade)
dna.ui.slideFadeIn(clone);
return clone;
},
remove: function(clone) { //TODO: optimize
clone.remove();
dna.placeholder.setup();
return clone;
},
berserk: function(message) { //oops, file a tps report
throw new Error('dna.js -> ' + message);
},
plugin: function() {
// Example:
// dna.getClone(elem).dna('up');
// Supported actions:
// 'bye', 'clone-sub', 'destroy', 'down', 'refresh', 'up'
$.fn.dna = function(action) { //any additional parameters are passed to the api call
var params = [arguments[1], arguments[2], arguments[3]];
var dnaApi = dna[dna.util.toCamel(action)];
if (!dnaApi)
dna.core.berserk('Unknown plugin action: ' + action);
function callApi(i, elem) { dnaApi($(elem), params[0], params[1], params[2]); }
return this.each(callApi);
};
},
initModule: function(thisWindow, thisJQuery) {
window = thisWindow;
$ = thisJQuery;
window.dna = dna;
dna.core.setup();
return dna;
},
setup: function() {
dna.core.plugin();
$(dna.placeholder.setup);
$(dna.panels.setup);
$(dna.events.setup);
}
};
if (typeof module === 'object') //Node.js module loading system (CommonJS)
module.exports = dna.core.initModule; //const dna = require('dna.js')(window, jQuery);
else
dna.core.setup();
|
/**
* @fileoverview Rule to flag use of eval() statement
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("../ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const candidatesOfGlobalObject = Object.freeze([
"global",
"window"
]);
/**
* Checks a given node is a Identifier node of the specified name.
*
* @param {ASTNode} node - A node to check.
* @param {string} name - A name to check.
* @returns {boolean} `true` if the node is a Identifier node of the name.
*/
function isIdentifier(node, name) {
return node.type === "Identifier" && node.name === name;
}
/**
* Checks a given node is a Literal node of the specified string value.
*
* @param {ASTNode} node - A node to check.
* @param {string} name - A name to check.
* @returns {boolean} `true` if the node is a Literal node of the name.
*/
function isConstant(node, name) {
switch (node.type) {
case "Literal":
return node.value === name;
case "TemplateLiteral":
return (
node.expressions.length === 0 &&
node.quasis[0].value.cooked === name
);
default:
return false;
}
}
/**
* Checks a given node is a MemberExpression node which has the specified name's
* property.
*
* @param {ASTNode} node - A node to check.
* @param {string} name - A name to check.
* @returns {boolean} `true` if the node is a MemberExpression node which has
* the specified name's property
*/
function isMember(node, name) {
return (
node.type === "MemberExpression" &&
(node.computed ? isConstant : isIdentifier)(node.property, name)
);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow the use of `eval()`",
category: "Best Practices",
recommended: false,
url: "https://eslint.org/docs/rules/no-eval"
},
schema: [
{
type: "object",
properties: {
allowIndirect: { type: "boolean" }
},
additionalProperties: false
}
],
messages: {
unexpected: "eval can be harmful."
}
},
create(context) {
const allowIndirect = Boolean(
context.options[0] &&
context.options[0].allowIndirect
);
const sourceCode = context.getSourceCode();
let funcInfo = null;
/**
* Pushs a variable scope (Program or Function) information to the stack.
*
* This is used in order to check whether or not `this` binding is a
* reference to the global object.
*
* @param {ASTNode} node - A node of the scope. This is one of Program,
* FunctionDeclaration, FunctionExpression, and ArrowFunctionExpression.
* @returns {void}
*/
function enterVarScope(node) {
const strict = context.getScope().isStrict;
funcInfo = {
upper: funcInfo,
node,
strict,
defaultThis: false,
initialized: strict
};
}
/**
* Pops a variable scope from the stack.
*
* @returns {void}
*/
function exitVarScope() {
funcInfo = funcInfo.upper;
}
/**
* Reports a given node.
*
* `node` is `Identifier` or `MemberExpression`.
* The parent of `node` might be `CallExpression`.
*
* The location of the report is always `eval` `Identifier` (or possibly
* `Literal`). The type of the report is `CallExpression` if the parent is
* `CallExpression`. Otherwise, it's the given node type.
*
* @param {ASTNode} node - A node to report.
* @returns {void}
*/
function report(node) {
const parent = node.parent;
const locationNode = node.type === "MemberExpression"
? node.property
: node;
const reportNode = parent.type === "CallExpression" && parent.callee === node
? parent
: node;
context.report({
node: reportNode,
loc: locationNode.loc.start,
messageId: "unexpected"
});
}
/**
* Reports accesses of `eval` via the global object.
*
* @param {eslint-scope.Scope} globalScope - The global scope.
* @returns {void}
*/
function reportAccessingEvalViaGlobalObject(globalScope) {
for (let i = 0; i < candidatesOfGlobalObject.length; ++i) {
const name = candidatesOfGlobalObject[i];
const variable = astUtils.getVariableByName(globalScope, name);
if (!variable) {
continue;
}
const references = variable.references;
for (let j = 0; j < references.length; ++j) {
const identifier = references[j].identifier;
let node = identifier.parent;
// To detect code like `window.window.eval`.
while (isMember(node, name)) {
node = node.parent;
}
// Reports.
if (isMember(node, "eval")) {
report(node);
}
}
}
}
/**
* Reports all accesses of `eval` (excludes direct calls to eval).
*
* @param {eslint-scope.Scope} globalScope - The global scope.
* @returns {void}
*/
function reportAccessingEval(globalScope) {
const variable = astUtils.getVariableByName(globalScope, "eval");
if (!variable) {
return;
}
const references = variable.references;
for (let i = 0; i < references.length; ++i) {
const reference = references[i];
const id = reference.identifier;
if (id.name === "eval" && !astUtils.isCallee(id)) {
// Is accessing to eval (excludes direct calls to eval)
report(id);
}
}
}
if (allowIndirect) {
// Checks only direct calls to eval. It's simple!
return {
"CallExpression:exit"(node) {
const callee = node.callee;
if (isIdentifier(callee, "eval")) {
report(callee);
}
}
};
}
return {
"CallExpression:exit"(node) {
const callee = node.callee;
if (isIdentifier(callee, "eval")) {
report(callee);
}
},
Program(node) {
const scope = context.getScope(),
features = context.parserOptions.ecmaFeatures || {},
strict =
scope.isStrict ||
node.sourceType === "module" ||
(features.globalReturn && scope.childScopes[0].isStrict);
funcInfo = {
upper: null,
node,
strict,
defaultThis: true,
initialized: true
};
},
"Program:exit"() {
const globalScope = context.getScope();
exitVarScope();
reportAccessingEval(globalScope);
reportAccessingEvalViaGlobalObject(globalScope);
},
FunctionDeclaration: enterVarScope,
"FunctionDeclaration:exit": exitVarScope,
FunctionExpression: enterVarScope,
"FunctionExpression:exit": exitVarScope,
ArrowFunctionExpression: enterVarScope,
"ArrowFunctionExpression:exit": exitVarScope,
ThisExpression(node) {
if (!isMember(node.parent, "eval")) {
return;
}
/*
* `this.eval` is found.
* Checks whether or not the value of `this` is the global object.
*/
if (!funcInfo.initialized) {
funcInfo.initialized = true;
funcInfo.defaultThis = astUtils.isDefaultThisBinding(
funcInfo.node,
sourceCode
);
}
if (!funcInfo.strict && funcInfo.defaultThis) {
// `this.eval` is possible built-in `eval`.
report(node.parent);
}
}
};
}
};
|
/**
* @author sunag / http://www.sunag.com.br/
*/
THREE.NodePass = function () {
THREE.ShaderPass.call( this );
this.name = "";
this.uuid = THREE.Math.generateUUID();
this.userData = {};
this.textureID = 'renderTexture';
this.fragment = new THREE.RawNode( new THREE.ScreenNode() );
this.node = new THREE.NodeMaterial();
this.node.fragment = this.fragment;
this.build();
};
THREE.NodePass.prototype = Object.create( THREE.ShaderPass.prototype );
THREE.NodePass.prototype.constructor = THREE.NodePass;
THREE.NodeMaterial.addShortcuts( THREE.NodePass.prototype, 'fragment', [ 'value' ] );
THREE.NodePass.prototype.build = function () {
this.node.build();
this.uniforms = this.node.uniforms;
this.material = this.node;
};
THREE.NodePass.prototype.toJSON = function ( meta ) {
var isRootObject = ( meta === undefined || typeof meta === 'string' );
if ( isRootObject ) {
meta = {
nodes: {}
};
}
if ( meta && ! meta.passes ) meta.passes = {};
if ( ! meta.passes[ this.uuid ] ) {
var data = {};
data.uuid = this.uuid;
data.type = "NodePass";
meta.passes[ this.uuid ] = data;
if ( this.name !== "" ) data.name = this.name;
if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
data.value = this.value.toJSON( meta ).uuid;
}
meta.pass = this.uuid;
return meta;
};
|
/**
* React v15.4.0-rc.2
*/
(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.React = 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){
/**
* Copyright 2013-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.
*
* @providesModule KeyEscapeUtils
*
*/
'use strict';
/**
* Escape and wrap key so it is safe to use as a reactid
*
* @param {string} key to be escaped.
* @return {string} the escaped key.
*/
function escape(key) {
var escapeRegex = /[=:]/g;
var escaperLookup = {
'=': '=0',
':': '=2'
};
var escapedString = ('' + key).replace(escapeRegex, function (match) {
return escaperLookup[match];
});
return '$' + escapedString;
}
/**
* Unescape and unwrap key for human-readable display
*
* @param {string} key to unescape.
* @return {string} the unescaped key.
*/
function unescape(key) {
var unescapeRegex = /(=0|=2)/g;
var unescaperLookup = {
'=0': '=',
'=2': ':'
};
var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);
return ('' + keySubstring).replace(unescapeRegex, function (match) {
return unescaperLookup[match];
});
}
var KeyEscapeUtils = {
escape: escape,
unescape: unescape
};
module.exports = KeyEscapeUtils;
},{}],2:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule PooledClass
*
*/
'use strict';
var _prodInvariant = _dereq_(24);
var invariant = _dereq_(28);
/**
* Static poolers. Several custom versions for each potential number of
* arguments. A completely generic pooler is easy to implement, but would
* require accessing the `arguments` object. In each of these, `this` refers to
* the Class itself, not an instance. If any others are needed, simply add them
* here, or in their own files.
*/
var oneArgumentPooler = function (copyFieldsFrom) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, copyFieldsFrom);
return instance;
} else {
return new Klass(copyFieldsFrom);
}
};
var twoArgumentPooler = function (a1, a2) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2);
return instance;
} else {
return new Klass(a1, a2);
}
};
var threeArgumentPooler = function (a1, a2, a3) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3);
return instance;
} else {
return new Klass(a1, a2, a3);
}
};
var fourArgumentPooler = function (a1, a2, a3, a4) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4);
return instance;
} else {
return new Klass(a1, a2, a3, a4);
}
};
var fiveArgumentPooler = function (a1, a2, a3, a4, a5) {
var Klass = this;
if (Klass.instancePool.length) {
var instance = Klass.instancePool.pop();
Klass.call(instance, a1, a2, a3, a4, a5);
return instance;
} else {
return new Klass(a1, a2, a3, a4, a5);
}
};
var standardReleaser = function (instance) {
var Klass = this;
!(instance instanceof Klass) ? "development" !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0;
instance.destructor();
if (Klass.instancePool.length < Klass.poolSize) {
Klass.instancePool.push(instance);
}
};
var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;
/**
* Augments `CopyConstructor` to be a poolable class, augmenting only the class
* itself (statically) not adding any prototypical fields. Any CopyConstructor
* you give this may have a `poolSize` property, and will look for a
* prototypical `destructor` on instances.
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function (CopyConstructor, pooler) {
// Casting as any so that flow ignores the actual implementation and trusts
// it to match the type we declared
var NewKlass = CopyConstructor;
NewKlass.instancePool = [];
NewKlass.getPooled = pooler || DEFAULT_POOLER;
if (!NewKlass.poolSize) {
NewKlass.poolSize = DEFAULT_POOL_SIZE;
}
NewKlass.release = standardReleaser;
return NewKlass;
};
var PooledClass = {
addPoolingTo: addPoolingTo,
oneArgumentPooler: oneArgumentPooler,
twoArgumentPooler: twoArgumentPooler,
threeArgumentPooler: threeArgumentPooler,
fourArgumentPooler: fourArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{"24":24,"28":28}],3:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule React
*/
'use strict';
var _assign = _dereq_(30);
var ReactChildren = _dereq_(4);
var ReactComponent = _dereq_(6);
var ReactPureComponent = _dereq_(17);
var ReactClass = _dereq_(5);
var ReactDOMFactories = _dereq_(9);
var ReactElement = _dereq_(10);
var ReactPropTypes = _dereq_(15);
var ReactVersion = _dereq_(19);
var onlyChild = _dereq_(23);
var warning = _dereq_(29);
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if ("development" !== 'production') {
var ReactElementValidator = _dereq_(12);
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var __spread = _assign;
if ("development" !== 'production') {
var warned = false;
__spread = function () {
"development" !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0;
warned = true;
return _assign.apply(null, arguments);
};
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild
},
Component: ReactComponent,
PureComponent: ReactPureComponent,
createElement: createElement,
cloneElement: cloneElement,
isValidElement: ReactElement.isValidElement,
// Classic
PropTypes: ReactPropTypes,
createClass: ReactClass.createClass,
createFactory: createFactory,
createMixin: function (mixin) {
// Currently a noop. Will be used to validate and trace mixins.
return mixin;
},
// This looks DOM specific but these are actually isomorphic helpers
// since they are just generating DOM strings.
DOM: ReactDOMFactories,
version: ReactVersion,
// Deprecated hook for JSX spread, don't use this for anything.
__spread: __spread
};
module.exports = React;
},{"10":10,"12":12,"15":15,"17":17,"19":19,"23":23,"29":29,"30":30,"4":4,"5":5,"6":6,"9":9}],4:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactChildren
*/
'use strict';
var PooledClass = _dereq_(2);
var ReactElement = _dereq_(10);
var emptyFunction = _dereq_(26);
var traverseAllChildren = _dereq_(25);
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var fourArgumentPooler = PooledClass.fourArgumentPooler;
var userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction;
this.context = forEachContext;
this.count = 0;
}
ForEachBookKeeping.prototype.destructor = function () {
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(bookKeeping, child, name) {
var func = bookKeeping.func;
var context = bookKeeping.context;
func.call(context, child, bookKeeping.count++);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult;
this.keyPrefix = keyPrefix;
this.func = mapFunction;
this.context = mapContext;
this.count = 0;
}
MapBookKeeping.prototype.destructor = function () {
this.result = null;
this.keyPrefix = null;
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
var result = bookKeeping.result;
var keyPrefix = bookKeeping.keyPrefix;
var func = bookKeeping.func;
var context = bookKeeping.context;
var mappedChild = func.call(context, child, bookKeeping.count++);
if (Array.isArray(mappedChild)) {
mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
} else if (mappedChild != null) {
if (ReactElement.isValidElement(mappedChild)) {
mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
// Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey);
}
result.push(mappedChild);
}
}
function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) {
var escapedPrefix = '';
if (prefix != null) {
escapedPrefix = escapeUserProvidedKey(prefix) + '/';
}
var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.map
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, func, context);
return result;
}
function forEachSingleChildDummy(traverseContext, child, name) {
return null;
}
/**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.count
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/
function countChildren(children, context) {
return traverseAllChildren(children, forEachSingleChildDummy, null);
}
/**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray
*/
function toArray(children) {
var result = [];
mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument);
return result;
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal,
count: countChildren,
toArray: toArray
};
module.exports = ReactChildren;
},{"10":10,"2":2,"25":25,"26":26}],5:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactClass
*/
'use strict';
var _prodInvariant = _dereq_(24),
_assign = _dereq_(30);
var ReactComponent = _dereq_(6);
var ReactElement = _dereq_(10);
var ReactPropTypeLocationNames = _dereq_(14);
var ReactNoopUpdateQueue = _dereq_(13);
var emptyObject = _dereq_(27);
var invariant = _dereq_(28);
var warning = _dereq_(29);
var MIXINS_KEY = 'mixins';
// Helper function to allow the creation of anonymous functions which do not
// have .name set to the name of the variable being assigned to.
function identity(fn) {
return fn;
}
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var injectedMixins = [];
/**
* Composite components are higher-level components that compose other composite
* or host components.
*
* To create a new type of `ReactClass`, pass a specification of
* your new class to `React.createClass`. The only requirement of your class
* specification is that you implement a `render` method.
*
* var MyComponent = React.createClass({
* render: function() {
* return <div>Hello World</div>;
* }
* });
*
* The class specification supports a specific protocol of methods that have
* special meaning (e.g. `render`). See `ReactClassInterface` for
* more the comprehensive protocol. Any other properties and methods in the
* class specification will be available on the prototype.
*
* @interface ReactClassInterface
* @internal
*/
var ReactClassInterface = {
/**
* An array of Mixin objects to include when defining your component.
*
* @type {array}
* @optional
*/
mixins: 'DEFINE_MANY',
/**
* An object containing properties and methods that should be defined on
* the component's constructor instead of its prototype (static methods).
*
* @type {object}
* @optional
*/
statics: 'DEFINE_MANY',
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: 'DEFINE_MANY',
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: 'DEFINE_MANY',
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: 'DEFINE_MANY',
// ==== Definition methods ====
/**
* Invoked when the component is mounted. Values in the mapping will be set on
* `this.props` if that prop is not specified (i.e. using an `in` check).
*
* This method is invoked before `getInitialState` and therefore cannot rely
* on `this.state` or use `this.setState`.
*
* @return {object}
* @optional
*/
getDefaultProps: 'DEFINE_MANY_MERGED',
/**
* Invoked once before the component is mounted. The return value will be used
* as the initial value of `this.state`.
*
* getInitialState: function() {
* return {
* isOn: false,
* fooBaz: new BazFoo()
* }
* }
*
* @return {object}
* @optional
*/
getInitialState: 'DEFINE_MANY_MERGED',
/**
* @return {object}
* @optional
*/
getChildContext: 'DEFINE_MANY_MERGED',
/**
* Uses props from `this.props` and state from `this.state` to render the
* structure of the component.
*
* No guarantees are made about when or how often this method is invoked, so
* it must not have side effects.
*
* render: function() {
* var name = this.props.name;
* return <div>Hello, {name}!</div>;
* }
*
* @return {ReactComponent}
* @nosideeffects
* @required
*/
render: 'DEFINE_ONCE',
// ==== Delegate methods ====
/**
* Invoked when the component is initially created and about to be mounted.
* This may have side effects, but any external subscriptions or data created
* by this method must be cleaned up in `componentWillUnmount`.
*
* @optional
*/
componentWillMount: 'DEFINE_MANY',
/**
* Invoked when the component has been mounted and has a DOM representation.
* However, there is no guarantee that the DOM node is in the document.
*
* Use this as an opportunity to operate on the DOM when the component has
* been mounted (initialized and rendered) for the first time.
*
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidMount: 'DEFINE_MANY',
/**
* Invoked before the component receives new props.
*
* Use this as an opportunity to react to a prop transition by updating the
* state using `this.setState`. Current props are accessed via `this.props`.
*
* componentWillReceiveProps: function(nextProps, nextContext) {
* this.setState({
* likesIncreasing: nextProps.likeCount > this.props.likeCount
* });
* }
*
* NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop
* transition may cause a state change, but the opposite is not true. If you
* need it, you are probably looking for `componentWillUpdate`.
*
* @param {object} nextProps
* @optional
*/
componentWillReceiveProps: 'DEFINE_MANY',
/**
* Invoked while deciding if the component should be updated as a result of
* receiving new props, state and/or context.
*
* Use this as an opportunity to `return false` when you're certain that the
* transition to the new props/state/context will not require a component
* update.
*
* shouldComponentUpdate: function(nextProps, nextState, nextContext) {
* return !equal(nextProps, this.props) ||
* !equal(nextState, this.state) ||
* !equal(nextContext, this.context);
* }
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @return {boolean} True if the component should update.
* @optional
*/
shouldComponentUpdate: 'DEFINE_ONCE',
/**
* Invoked when the component is about to update due to a transition from
* `this.props`, `this.state` and `this.context` to `nextProps`, `nextState`
* and `nextContext`.
*
* Use this as an opportunity to perform preparation before an update occurs.
*
* NOTE: You **cannot** use `this.setState()` in this method.
*
* @param {object} nextProps
* @param {?object} nextState
* @param {?object} nextContext
* @param {ReactReconcileTransaction} transaction
* @optional
*/
componentWillUpdate: 'DEFINE_MANY',
/**
* Invoked when the component's DOM representation has been updated.
*
* Use this as an opportunity to operate on the DOM when the component has
* been updated.
*
* @param {object} prevProps
* @param {?object} prevState
* @param {?object} prevContext
* @param {DOMElement} rootNode DOM element representing the component.
* @optional
*/
componentDidUpdate: 'DEFINE_MANY',
/**
* Invoked when the component is about to be removed from its parent and have
* its DOM representation destroyed.
*
* Use this as an opportunity to deallocate any external resources.
*
* NOTE: There is no `componentDidUnmount` since your component will have been
* destroyed by that point.
*
* @optional
*/
componentWillUnmount: 'DEFINE_MANY',
// ==== Advanced methods ====
/**
* Updates the component's currently mounted DOM representation.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @internal
* @overridable
*/
updateComponent: 'OVERRIDE_BASE'
};
/**
* Mapping from class specification keys to special processing functions.
*
* Although these are declared like instance properties in the specification
* when defining classes using `React.createClass`, they are actually static
* and are accessible on the constructor instead of the prototype. Despite
* being static, they must be defined outside of the "statics" key under
* which all other static methods are defined.
*/
var RESERVED_SPEC_KEYS = {
displayName: function (Constructor, displayName) {
Constructor.displayName = displayName;
},
mixins: function (Constructor, mixins) {
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
mixSpecIntoComponent(Constructor, mixins[i]);
}
}
},
childContextTypes: function (Constructor, childContextTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, childContextTypes, 'childContext');
}
Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes);
},
contextTypes: function (Constructor, contextTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, contextTypes, 'context');
}
Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes);
},
/**
* Special case getDefaultProps which should move into statics but requires
* automatic merging.
*/
getDefaultProps: function (Constructor, getDefaultProps) {
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps);
} else {
Constructor.getDefaultProps = getDefaultProps;
}
},
propTypes: function (Constructor, propTypes) {
if ("development" !== 'production') {
validateTypeDef(Constructor, propTypes, 'prop');
}
Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes);
},
statics: function (Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function () {} };
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
// use a warning instead of an invariant so components
// don't show up in prod but only in __DEV__
"development" !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0;
}
}
}
function validateMethodOverride(isAlreadyDefined, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
!(specPolicy === 'OVERRIDE_BASE') ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.', name) : _prodInvariant('73', name) : void 0;
}
// Disallow defining methods more than once unless explicitly allowed.
if (isAlreadyDefined) {
!(specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED') ? "development" !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('74', name) : void 0;
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classes.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
if ("development" !== 'production') {
var typeofSpec = typeof spec;
var isMixinValid = typeofSpec === 'object' && spec !== null;
"development" !== 'production' ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0;
}
return;
}
!(typeof spec !== 'function') ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0;
!!ReactElement.isValidElement(spec) ? "development" !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0;
var proto = Constructor.prototype;
var autoBindPairs = proto.__reactAutoBindPairs;
// By handling mixins before any other properties, we ensure the same
// chaining order is applied to methods with DEFINE_MANY policy, whether
// mixins are listed before or after these methods in the spec.
if (spec.hasOwnProperty(MIXINS_KEY)) {
RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins);
}
for (var name in spec) {
if (!spec.hasOwnProperty(name)) {
continue;
}
if (name === MIXINS_KEY) {
// We have already handled mixins in a special case above.
continue;
}
var property = spec[name];
var isAlreadyDefined = proto.hasOwnProperty(name);
validateMethodOverride(isAlreadyDefined, name);
if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {
RESERVED_SPEC_KEYS[name](Constructor, property);
} else {
// Setup methods on prototype:
// The following member methods should not be automatically bound:
// 1. Expected ReactClass methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isReactClassMethod = ReactClassInterface.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
autoBindPairs.push(name, property);
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
!(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY')) ? "development" !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0;
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === 'DEFINE_MANY_MERGED') {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === 'DEFINE_MANY') {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if ("development" !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = name in RESERVED_SPEC_KEYS;
!!isReserved ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : _prodInvariant('78', name) : void 0;
var isInherited = name in Constructor;
!!isInherited ? "development" !== 'production' ? invariant(false, 'ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('79', name) : void 0;
Constructor[name] = property;
}
}
/**
* Merge two objects, but throw if both contain the same key.
*
* @param {object} one The first object, which is mutated.
* @param {object} two The second object
* @return {object} one after it has been mutated to contain everything in two.
*/
function mergeIntoWithNoDuplicateKeys(one, two) {
!(one && two && typeof one === 'object' && typeof two === 'object') ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0;
for (var key in two) {
if (two.hasOwnProperty(key)) {
!(one[key] === undefined) ? "development" !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.', key) : _prodInvariant('81', key) : void 0;
one[key] = two[key];
}
}
return one;
}
/**
* Creates a function that invokes two functions and merges their return values.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createMergedResultFunction(one, two) {
return function mergedResult() {
var a = one.apply(this, arguments);
var b = two.apply(this, arguments);
if (a == null) {
return b;
} else if (b == null) {
return a;
}
var c = {};
mergeIntoWithNoDuplicateKeys(c, a);
mergeIntoWithNoDuplicateKeys(c, b);
return c;
};
}
/**
* Creates a function that invokes two functions and ignores their return vales.
*
* @param {function} one Function to invoke first.
* @param {function} two Function to invoke second.
* @return {function} Function that invokes the two argument functions.
* @private
*/
function createChainedFunction(one, two) {
return function chainedFunction() {
one.apply(this, arguments);
two.apply(this, arguments);
};
}
/**
* Binds a method to the component.
*
* @param {object} component Component whose method is going to be bound.
* @param {function} method Method to be bound.
* @return {function} The bound method.
*/
function bindAutoBindMethod(component, method) {
var boundMethod = method.bind(component);
if ("development" !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function (newThis) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
// User is trying to bind() an autobound method; we effectively will
// ignore the value of "this" that the user is trying to use, so
// let's warn.
if (newThis !== component && newThis !== null) {
"development" !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0;
} else if (!args.length) {
"development" !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
var pairs = component.__reactAutoBindPairs;
for (var i = 0; i < pairs.length; i += 2) {
var autoBindKey = pairs[i];
var method = pairs[i + 1];
component[autoBindKey] = bindAutoBindMethod(component, method);
}
}
/**
* Add more to the ReactClass base class. These are all legacy features and
* therefore not already part of the modern ReactComponent.
*/
var ReactClassMixin = {
/**
* TODO: This will be deprecated because state should always keep a consistent
* type signature and the only use case for this, is to avoid that.
*/
replaceState: function (newState, callback) {
this.updater.enqueueReplaceState(this, newState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'replaceState');
}
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function () {
return this.updater.isMounted(this);
}
};
var ReactClassComponent = function () {};
_assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin);
/**
* Module for creating composite components.
*
* @class ReactClass
*/
var ReactClass = {
/**
* Creates a composite component class given a class specification.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createclass
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function (spec) {
// To keep our warnings more understandable, we'll use a little hack here to
// ensure that Constructor.name !== 'Constructor'. This makes sure we don't
// unnecessarily identify a class without displayName as 'Constructor'.
var Constructor = identity(function (props, context, updater) {
// This constructor gets overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if ("development" !== 'production') {
"development" !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0;
}
// Wire up auto-binding
if (this.__reactAutoBindPairs.length) {
bindAutoBindMethods(this);
}
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
this.state = null;
// ReactClasses doesn't have constructors. Instead, they use the
// getInitialState and componentWillMount methods for initialization.
var initialState = this.getInitialState ? this.getInitialState() : null;
if ("development" !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (initialState === undefined && this.getInitialState._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
initialState = null;
}
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? "development" !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0;
this.state = initialState;
});
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
Constructor.prototype.__reactAutoBindPairs = [];
injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
mixSpecIntoComponent(Constructor, spec);
// Initialize the defaultProps property after all mixins have been merged.
if (Constructor.getDefaultProps) {
Constructor.defaultProps = Constructor.getDefaultProps();
}
if ("development" !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
!Constructor.prototype.render ? "development" !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : _prodInvariant('83') : void 0;
if ("development" !== 'production') {
"development" !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : void 0;
"development" !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0;
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactClassInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
return Constructor;
},
injection: {
injectMixin: function (mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactClass;
},{"10":10,"13":13,"14":14,"24":24,"27":27,"28":28,"29":29,"30":30,"6":6}],6:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactComponent
*/
'use strict';
var _prodInvariant = _dereq_(24);
var ReactNoopUpdateQueue = _dereq_(13);
var canDefineProperty = _dereq_(20);
var emptyObject = _dereq_(27);
var invariant = _dereq_(28);
var warning = _dereq_(29);
/**
* Base class helpers for the updating state of a component.
*/
function ReactComponent(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
ReactComponent.prototype.isReactComponent = {};
/**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
ReactComponent.prototype.setState = function (partialState, callback) {
!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? "development" !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0;
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState');
}
};
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
ReactComponent.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this);
if (callback) {
this.updater.enqueueCallback(this, callback, 'forceUpdate');
}
};
/**
* Deprecated APIs. These APIs used to exist on classic React classes but since
* we would like to deprecate them, we're not going to move them over to this
* modern base class. Instead, we define a getter that warns if it's accessed.
*/
if ("development" !== 'production') {
var deprecatedAPIs = {
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).']
};
var defineDeprecationWarning = function (methodName, info) {
if (canDefineProperty) {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function () {
"development" !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0;
return undefined;
}
});
}
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
module.exports = ReactComponent;
},{"13":13,"20":20,"24":24,"27":27,"28":28,"29":29}],7:[function(_dereq_,module,exports){
/**
* Copyright 2016-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.
*
*
* @providesModule ReactComponentTreeHook
*/
'use strict';
var _prodInvariant = _dereq_(24);
var ReactCurrentOwner = _dereq_(8);
var invariant = _dereq_(28);
var warning = _dereq_(29);
function isNative(fn) {
// Based on isNative() from Lodash
var funcToString = Function.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var reIsNative = RegExp('^' + funcToString
// Take an example native function source for comparison
.call(hasOwnProperty)
// Strip regex characters so we can use it for regex
.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
// Remove hasOwnProperty from the template to make it generic
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
try {
var source = funcToString.call(fn);
return reIsNative.test(source);
} catch (err) {
return false;
}
}
var canUseCollections =
// Array.from
typeof Array.from === 'function' &&
// Map
typeof Map === 'function' && isNative(Map) &&
// Map.prototype.keys
Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) &&
// Set
typeof Set === 'function' && isNative(Set) &&
// Set.prototype.keys
Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys);
if (canUseCollections) {
var itemMap = new Map();
var rootIDSet = new Set();
var setItem = function (id, item) {
itemMap.set(id, item);
};
var getItem = function (id) {
return itemMap.get(id);
};
var removeItem = function (id) {
itemMap['delete'](id);
};
var getItemIDs = function () {
return Array.from(itemMap.keys());
};
var addRoot = function (id) {
rootIDSet.add(id);
};
var removeRoot = function (id) {
rootIDSet['delete'](id);
};
var getRootIDs = function () {
return Array.from(rootIDSet.keys());
};
} else {
var itemByKey = {};
var rootByKey = {};
// Use non-numeric keys to prevent V8 performance issues:
// https://github.com/facebook/react/pull/7232
var getKeyFromID = function (id) {
return '.' + id;
};
var getIDFromKey = function (key) {
return parseInt(key.substr(1), 10);
};
var setItem = function (id, item) {
var key = getKeyFromID(id);
itemByKey[key] = item;
};
var getItem = function (id) {
var key = getKeyFromID(id);
return itemByKey[key];
};
var removeItem = function (id) {
var key = getKeyFromID(id);
delete itemByKey[key];
};
var getItemIDs = function () {
return Object.keys(itemByKey).map(getIDFromKey);
};
var addRoot = function (id) {
var key = getKeyFromID(id);
rootByKey[key] = true;
};
var removeRoot = function (id) {
var key = getKeyFromID(id);
delete rootByKey[key];
};
var getRootIDs = function () {
return Object.keys(rootByKey).map(getIDFromKey);
};
}
var unmountedIDs = [];
function purgeDeep(id) {
var item = getItem(id);
if (item) {
var childIDs = item.childIDs;
removeItem(id);
childIDs.forEach(purgeDeep);
}
}
function describeComponentFrame(name, source, ownerName) {
return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : '');
}
function getDisplayName(element) {
if (element == null) {
return '#empty';
} else if (typeof element === 'string' || typeof element === 'number') {
return '#text';
} else if (typeof element.type === 'string') {
return element.type;
} else {
return element.type.displayName || element.type.name || 'Unknown';
}
}
function describeID(id) {
var name = ReactComponentTreeHook.getDisplayName(id);
var element = ReactComponentTreeHook.getElement(id);
var ownerID = ReactComponentTreeHook.getOwnerID(id);
var ownerName;
if (ownerID) {
ownerName = ReactComponentTreeHook.getDisplayName(ownerID);
}
"development" !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0;
return describeComponentFrame(name, element && element._source, ownerName);
}
var ReactComponentTreeHook = {
onSetChildren: function (id, nextChildIDs) {
var item = getItem(id);
invariant(item, 'Item must have been set');
item.childIDs = nextChildIDs;
for (var i = 0; i < nextChildIDs.length; i++) {
var nextChildID = nextChildIDs[i];
var nextChild = getItem(nextChildID);
!nextChild ? "development" !== 'production' ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0;
!(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? "development" !== 'production' ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0;
!nextChild.isMounted ? "development" !== 'production' ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0;
if (nextChild.parentID == null) {
nextChild.parentID = id;
// TODO: This shouldn't be necessary but mounting a new root during in
// componentWillMount currently causes not-yet-mounted components to
// be purged from our tree data so their parent id is missing.
}
!(nextChild.parentID === id) ? "development" !== 'production' ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0;
}
},
onBeforeMountComponent: function (id, element, parentID) {
var item = {
element: element,
parentID: parentID,
text: null,
childIDs: [],
isMounted: false,
updateCount: 0
};
setItem(id, item);
},
onBeforeUpdateComponent: function (id, element) {
var item = getItem(id);
if (!item || !item.isMounted) {
// We may end up here as a result of setState() in componentWillUnmount().
// In this case, ignore the element.
return;
}
item.element = element;
},
onMountComponent: function (id) {
var item = getItem(id);
invariant(item, 'Item must have been set');
item.isMounted = true;
var isRoot = item.parentID === 0;
if (isRoot) {
addRoot(id);
}
},
onUpdateComponent: function (id) {
var item = getItem(id);
if (!item || !item.isMounted) {
// We may end up here as a result of setState() in componentWillUnmount().
// In this case, ignore the element.
return;
}
item.updateCount++;
},
onUnmountComponent: function (id) {
var item = getItem(id);
if (item) {
// We need to check if it exists.
// `item` might not exist if it is inside an error boundary, and a sibling
// error boundary child threw while mounting. Then this instance never
// got a chance to mount, but it still gets an unmounting event during
// the error boundary cleanup.
item.isMounted = false;
var isRoot = item.parentID === 0;
if (isRoot) {
removeRoot(id);
}
}
unmountedIDs.push(id);
},
purgeUnmountedComponents: function () {
if (ReactComponentTreeHook._preventPurging) {
// Should only be used for testing.
return;
}
for (var i = 0; i < unmountedIDs.length; i++) {
var id = unmountedIDs[i];
purgeDeep(id);
}
unmountedIDs.length = 0;
},
isMounted: function (id) {
var item = getItem(id);
return item ? item.isMounted : false;
},
getCurrentStackAddendum: function (topElement) {
var info = '';
if (topElement) {
var name = getDisplayName(topElement);
var owner = topElement._owner;
info += describeComponentFrame(name, topElement._source, owner && owner.getName());
}
var currentOwner = ReactCurrentOwner.current;
var id = currentOwner && currentOwner._debugID;
info += ReactComponentTreeHook.getStackAddendumByID(id);
return info;
},
getStackAddendumByID: function (id) {
var info = '';
while (id) {
info += describeID(id);
id = ReactComponentTreeHook.getParentID(id);
}
return info;
},
getChildIDs: function (id) {
var item = getItem(id);
return item ? item.childIDs : [];
},
getDisplayName: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (!element) {
return null;
}
return getDisplayName(element);
},
getElement: function (id) {
var item = getItem(id);
return item ? item.element : null;
},
getOwnerID: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (!element || !element._owner) {
return null;
}
return element._owner._debugID;
},
getParentID: function (id) {
var item = getItem(id);
return item ? item.parentID : null;
},
getSource: function (id) {
var item = getItem(id);
var element = item ? item.element : null;
var source = element != null ? element._source : null;
return source;
},
getText: function (id) {
var element = ReactComponentTreeHook.getElement(id);
if (typeof element === 'string') {
return element;
} else if (typeof element === 'number') {
return '' + element;
} else {
return null;
}
},
getUpdateCount: function (id) {
var item = getItem(id);
return item ? item.updateCount : 0;
},
getRootIDs: getRootIDs,
getRegisteredIDs: getItemIDs
};
module.exports = ReactComponentTreeHook;
},{"24":24,"28":28,"29":29,"8":8}],8:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactCurrentOwner
*
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],9:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactDOMFactories
*/
'use strict';
var ReactElement = _dereq_(10);
/**
* Create a factory that creates HTML tag elements.
*
* @private
*/
var createDOMFactory = ReactElement.createFactory;
if ("development" !== 'production') {
var ReactElementValidator = _dereq_(12);
createDOMFactory = ReactElementValidator.createFactory;
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOMFactories = {
a: createDOMFactory('a'),
abbr: createDOMFactory('abbr'),
address: createDOMFactory('address'),
area: createDOMFactory('area'),
article: createDOMFactory('article'),
aside: createDOMFactory('aside'),
audio: createDOMFactory('audio'),
b: createDOMFactory('b'),
base: createDOMFactory('base'),
bdi: createDOMFactory('bdi'),
bdo: createDOMFactory('bdo'),
big: createDOMFactory('big'),
blockquote: createDOMFactory('blockquote'),
body: createDOMFactory('body'),
br: createDOMFactory('br'),
button: createDOMFactory('button'),
canvas: createDOMFactory('canvas'),
caption: createDOMFactory('caption'),
cite: createDOMFactory('cite'),
code: createDOMFactory('code'),
col: createDOMFactory('col'),
colgroup: createDOMFactory('colgroup'),
data: createDOMFactory('data'),
datalist: createDOMFactory('datalist'),
dd: createDOMFactory('dd'),
del: createDOMFactory('del'),
details: createDOMFactory('details'),
dfn: createDOMFactory('dfn'),
dialog: createDOMFactory('dialog'),
div: createDOMFactory('div'),
dl: createDOMFactory('dl'),
dt: createDOMFactory('dt'),
em: createDOMFactory('em'),
embed: createDOMFactory('embed'),
fieldset: createDOMFactory('fieldset'),
figcaption: createDOMFactory('figcaption'),
figure: createDOMFactory('figure'),
footer: createDOMFactory('footer'),
form: createDOMFactory('form'),
h1: createDOMFactory('h1'),
h2: createDOMFactory('h2'),
h3: createDOMFactory('h3'),
h4: createDOMFactory('h4'),
h5: createDOMFactory('h5'),
h6: createDOMFactory('h6'),
head: createDOMFactory('head'),
header: createDOMFactory('header'),
hgroup: createDOMFactory('hgroup'),
hr: createDOMFactory('hr'),
html: createDOMFactory('html'),
i: createDOMFactory('i'),
iframe: createDOMFactory('iframe'),
img: createDOMFactory('img'),
input: createDOMFactory('input'),
ins: createDOMFactory('ins'),
kbd: createDOMFactory('kbd'),
keygen: createDOMFactory('keygen'),
label: createDOMFactory('label'),
legend: createDOMFactory('legend'),
li: createDOMFactory('li'),
link: createDOMFactory('link'),
main: createDOMFactory('main'),
map: createDOMFactory('map'),
mark: createDOMFactory('mark'),
menu: createDOMFactory('menu'),
menuitem: createDOMFactory('menuitem'),
meta: createDOMFactory('meta'),
meter: createDOMFactory('meter'),
nav: createDOMFactory('nav'),
noscript: createDOMFactory('noscript'),
object: createDOMFactory('object'),
ol: createDOMFactory('ol'),
optgroup: createDOMFactory('optgroup'),
option: createDOMFactory('option'),
output: createDOMFactory('output'),
p: createDOMFactory('p'),
param: createDOMFactory('param'),
picture: createDOMFactory('picture'),
pre: createDOMFactory('pre'),
progress: createDOMFactory('progress'),
q: createDOMFactory('q'),
rp: createDOMFactory('rp'),
rt: createDOMFactory('rt'),
ruby: createDOMFactory('ruby'),
s: createDOMFactory('s'),
samp: createDOMFactory('samp'),
script: createDOMFactory('script'),
section: createDOMFactory('section'),
select: createDOMFactory('select'),
small: createDOMFactory('small'),
source: createDOMFactory('source'),
span: createDOMFactory('span'),
strong: createDOMFactory('strong'),
style: createDOMFactory('style'),
sub: createDOMFactory('sub'),
summary: createDOMFactory('summary'),
sup: createDOMFactory('sup'),
table: createDOMFactory('table'),
tbody: createDOMFactory('tbody'),
td: createDOMFactory('td'),
textarea: createDOMFactory('textarea'),
tfoot: createDOMFactory('tfoot'),
th: createDOMFactory('th'),
thead: createDOMFactory('thead'),
time: createDOMFactory('time'),
title: createDOMFactory('title'),
tr: createDOMFactory('tr'),
track: createDOMFactory('track'),
u: createDOMFactory('u'),
ul: createDOMFactory('ul'),
'var': createDOMFactory('var'),
video: createDOMFactory('video'),
wbr: createDOMFactory('wbr'),
// SVG
circle: createDOMFactory('circle'),
clipPath: createDOMFactory('clipPath'),
defs: createDOMFactory('defs'),
ellipse: createDOMFactory('ellipse'),
g: createDOMFactory('g'),
image: createDOMFactory('image'),
line: createDOMFactory('line'),
linearGradient: createDOMFactory('linearGradient'),
mask: createDOMFactory('mask'),
path: createDOMFactory('path'),
pattern: createDOMFactory('pattern'),
polygon: createDOMFactory('polygon'),
polyline: createDOMFactory('polyline'),
radialGradient: createDOMFactory('radialGradient'),
rect: createDOMFactory('rect'),
stop: createDOMFactory('stop'),
svg: createDOMFactory('svg'),
text: createDOMFactory('text'),
tspan: createDOMFactory('tspan')
};
module.exports = ReactDOMFactories;
},{"10":10,"12":12}],10:[function(_dereq_,module,exports){
/**
* Copyright 2014-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.
*
* @providesModule ReactElement
*/
'use strict';
var _assign = _dereq_(30);
var ReactCurrentOwner = _dereq_(8);
var warning = _dereq_(29);
var canDefineProperty = _dereq_(20);
var hasOwnProperty = Object.prototype.hasOwnProperty;
var REACT_ELEMENT_TYPE = _dereq_(11);
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
var specialPropKeyWarningShown, specialPropRefWarningShown;
function hasValidRef(config) {
if ("development" !== 'production') {
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.ref !== undefined;
}
function hasValidKey(config) {
if ("development" !== 'production') {
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) {
return false;
}
}
}
return config.key !== undefined;
}
function defineKeyPropWarningGetter(props, displayName) {
var warnAboutAccessingKey = function () {
if (!specialPropKeyWarningShown) {
specialPropKeyWarningShown = true;
"development" !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
}
};
warnAboutAccessingKey.isReactWarning = true;
Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: true
});
}
function defineRefPropWarningGetter(props, displayName) {
var warnAboutAccessingRef = function () {
if (!specialPropRefWarningShown) {
specialPropRefWarningShown = true;
"development" !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0;
}
};
warnAboutAccessingRef.isReactWarning = true;
Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: true
});
}
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, no instanceof check
* will work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} key
* @param {string|object} ref
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @param {*} owner
* @param {*} props
* @internal
*/
var ReactElement = function (type, key, ref, self, source, owner, props) {
var element = {
// This tag allow us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
if ("development" !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._source = source;
}
if (Object.freeze) {
Object.freeze(element.props);
Object.freeze(element);
}
}
return element;
};
/**
* Create and return a new ReactElement of the given type.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createelement
*/
ReactElement.createElement = function (type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
var self = null;
var source = null;
if (config != null) {
if (hasValidRef(config)) {
ref = config.ref;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
self = config.__self === undefined ? null : config.__self;
source = config.__source === undefined ? null : config.__source;
// Remaining properties are added to a new props object
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
props[propName] = config[propName];
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
if ("development" !== 'production') {
if (Object.freeze) {
Object.freeze(childArray);
}
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
}
if ("development" !== 'production') {
if (key || ref) {
if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) {
var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
if (key) {
defineKeyPropWarningGetter(props, displayName);
}
if (ref) {
defineRefPropWarningGetter(props, displayName);
}
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
/**
* Return a function that produces ReactElements of a given type.
* See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory
*/
ReactElement.createFactory = function (type) {
var factory = ReactElement.createElement.bind(null, type);
// Expose the type on the factory and the prototype so that it can be
// easily accessed on elements. E.g. `<Foo />.type === Foo`.
// This should not be named `constructor` since this may not be the function
// that created the element, and it may not even be a constructor.
// Legacy hook TODO: Warn if this is accessed
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceKey = function (oldElement, newKey) {
var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props);
return newElement;
};
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement
*/
ReactElement.cloneElement = function (element, config, children) {
var propName;
// Original props are copied
var props = _assign({}, element.props);
// Reserved names are extracted
var key = element.key;
var ref = element.ref;
// Self is preserved since the owner is preserved.
var self = element._self;
// Source is preserved since cloneElement is unlikely to be targeted by a
// transpiler, and the original source is probably a better indicator of the
// true owner.
var source = element._source;
// Owner will be preserved, unless ref is overridden
var owner = element._owner;
if (config != null) {
if (hasValidRef(config)) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (hasValidKey(config)) {
key = '' + config.key;
}
// Remaining properties override existing props
var defaultProps;
if (element.type && element.type.defaultProps) {
defaultProps = element.type.defaultProps;
}
for (propName in config) {
if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
if (config[propName] === undefined && defaultProps !== undefined) {
// Resolve default props
props[propName] = defaultProps[propName];
} else {
props[propName] = config[propName];
}
}
}
}
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 2];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
};
/**
* Verifies the object is a ReactElement.
* See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function (object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
};
module.exports = ReactElement;
},{"11":11,"20":20,"29":29,"30":30,"8":8}],11:[function(_dereq_,module,exports){
/**
* Copyright 2014-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.
*
* @providesModule ReactElementSymbol
*
*/
'use strict';
// The Symbol used to tag the ReactElement type. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7;
module.exports = REACT_ELEMENT_TYPE;
},{}],12:[function(_dereq_,module,exports){
/**
* Copyright 2014-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.
*
* @providesModule ReactElementValidator
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
'use strict';
var ReactCurrentOwner = _dereq_(8);
var ReactComponentTreeHook = _dereq_(7);
var ReactElement = _dereq_(10);
var checkReactTypeSpec = _dereq_(21);
var canDefineProperty = _dereq_(20);
var getIteratorFn = _dereq_(22);
var warning = _dereq_(29);
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/
var ownerHasKeyUseWarning = {};
function getCurrentComponentErrorInfo(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
info = ' Check the top-level render call using <' + parentName + '>.';
}
}
return info;
}
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/
function validateExplicitKey(element, parentType) {
if (!element._store || element._store.validated || element.key != null) {
return;
}
element._store.validated = true;
var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {});
var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
if (memoizer[currentComponentErrorInfo]) {
return;
}
memoizer[currentComponentErrorInfo] = true;
// Usually the current owner is the offender, but if it accepts children as a
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
"development" !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0;
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/
function validateChildKeys(node, parentType) {
if (typeof node !== 'object') {
return;
}
if (Array.isArray(node)) {
for (var i = 0; i < node.length; i++) {
var child = node[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(node)) {
// This element was passed in a valid location.
if (node._store) {
node._store.validated = true;
}
} else if (node) {
var iteratorFn = getIteratorFn(node);
// Entry iterators provide implicit keys.
if (iteratorFn) {
if (iteratorFn !== node.entries) {
var iterator = iteratorFn.call(node);
var step;
while (!(step = iterator.next()).done) {
if (ReactElement.isValidElement(step.value)) {
validateExplicitKey(step.value, parentType);
}
}
}
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/
function validatePropTypes(element) {
var componentClass = element.type;
if (typeof componentClass !== 'function') {
return;
}
var name = componentClass.displayName || componentClass.name;
if (componentClass.propTypes) {
checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null);
}
if (typeof componentClass.getDefaultProps === 'function') {
"development" !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0;
}
}
var ReactElementValidator = {
createElement: function (type, props, children) {
var validType = typeof type === 'string' || typeof type === 'function';
// We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
"development" !== 'production' ? warning(false, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : void 0;
}
var element = ReactElement.createElement.apply(this, arguments);
// The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (element == null) {
return element;
}
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) {
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
}
validatePropTypes(element);
return element;
},
createFactory: function (type) {
var validatedFactory = ReactElementValidator.createElement.bind(null, type);
// Legacy hook TODO: Warn if this is accessed
validatedFactory.type = type;
if ("development" !== 'production') {
if (canDefineProperty) {
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
"development" !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0;
Object.defineProperty(this, 'type', {
value: type
});
return type;
}
});
}
}
return validatedFactory;
},
cloneElement: function (element, props, children) {
var newElement = ReactElement.cloneElement.apply(this, arguments);
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], newElement.type);
}
validatePropTypes(newElement);
return newElement;
}
};
module.exports = ReactElementValidator;
},{"10":10,"20":20,"21":21,"22":22,"29":29,"7":7,"8":8}],13:[function(_dereq_,module,exports){
/**
* Copyright 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.
*
* @providesModule ReactNoopUpdateQueue
*/
'use strict';
var warning = _dereq_(29);
function warnNoop(publicInstance, callerName) {
if ("development" !== 'production') {
var constructor = publicInstance.constructor;
"development" !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0;
}
}
/**
* This is the abstract API for an update queue.
*/
var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function (publicInstance) {
return false;
},
/**
* Enqueue a callback that will be executed after all the pending updates
* have processed.
*
* @param {ReactClass} publicInstance The instance to use as `this` context.
* @param {?function} callback Called after state is updated.
* @internal
*/
enqueueCallback: function (publicInstance, callback) {},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @internal
*/
enqueueForceUpdate: function (publicInstance) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @internal
*/
enqueueReplaceState: function (publicInstance, completeState) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @internal
*/
enqueueSetState: function (publicInstance, partialState) {
warnNoop(publicInstance, 'setState');
}
};
module.exports = ReactNoopUpdateQueue;
},{"29":29}],14:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
*
* @providesModule ReactPropTypeLocationNames
*/
'use strict';
var ReactPropTypeLocationNames = {};
if ("development" !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
},{}],15:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactPropTypes
*/
'use strict';
var ReactElement = _dereq_(10);
var ReactPropTypeLocationNames = _dereq_(14);
var ReactPropTypesSecret = _dereq_(16);
var emptyFunction = _dereq_(26);
var getIteratorFn = _dereq_(22);
var warning = _dereq_(29);
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if ("development" !== 'production') {
var manualPropTypeCallCache = {};
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if ("development" !== 'production') {
if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') {
var cacheKey = componentName + ':' + propName;
if (!manualPropTypeCallCache[cacheKey]) {
"development" !== 'production' ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in production with the next major version. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName) : void 0;
manualPropTypeCallCache[cacheKey] = true;
}
}
}
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + locationName + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + locationName + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
var locationName = ReactPropTypeLocationNames[location];
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns(null));
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!ReactElement.isValidElement(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
"development" !== 'production' ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
"development" !== 'production' ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || ReactElement.isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
module.exports = ReactPropTypes;
},{"10":10,"14":14,"16":16,"22":22,"26":26,"29":29}],16:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
*
* @providesModule ReactPropTypesSecret
*/
'use strict';
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
},{}],17:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactPureComponent
*/
'use strict';
var _assign = _dereq_(30);
var ReactComponent = _dereq_(6);
var ReactNoopUpdateQueue = _dereq_(13);
var emptyObject = _dereq_(27);
/**
* Base class helpers for the updating state of a component.
*/
function ReactPureComponent(props, context, updater) {
// Duplicated from ReactComponent.
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
function ComponentDummy() {}
ComponentDummy.prototype = ReactComponent.prototype;
ReactPureComponent.prototype = new ComponentDummy();
ReactPureComponent.prototype.constructor = ReactPureComponent;
// Avoid an extra prototype jump for these methods.
_assign(ReactPureComponent.prototype, ReactComponent.prototype);
ReactPureComponent.prototype.isPureReactComponent = true;
module.exports = ReactPureComponent;
},{"13":13,"27":27,"30":30,"6":6}],18:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactUMDEntry
*/
'use strict';
var _assign = _dereq_(30);
var React = _dereq_(3);
// `version` will be added here by the React module.
var ReactUMDEntry = _assign({
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {
ReactCurrentOwner: _dereq_(8)
}
}, React);
if ("development" !== 'production') {
_assign(ReactUMDEntry.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, {
// ReactComponentTreeHook should not be included in production.
ReactComponentTreeHook: _dereq_(7)
});
}
module.exports = ReactUMDEntry;
},{"3":3,"30":30,"7":7,"8":8}],19:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule ReactVersion
*/
'use strict';
module.exports = '15.4.0-rc.2';
},{}],20:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
*
* @providesModule canDefineProperty
*/
'use strict';
var canDefineProperty = false;
if ("development" !== 'production') {
try {
// $FlowFixMe https://github.com/facebook/flow/issues/285
Object.defineProperty({}, 'x', { get: function () {} });
canDefineProperty = true;
} catch (x) {
// IE will fail on defineProperty
}
}
module.exports = canDefineProperty;
},{}],21:[function(_dereq_,module,exports){
(function (process){
/**
* Copyright 2013-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.
*
* @providesModule checkReactTypeSpec
*/
'use strict';
var _prodInvariant = _dereq_(24);
var ReactPropTypeLocationNames = _dereq_(14);
var ReactPropTypesSecret = _dereq_(16);
var invariant = _dereq_(28);
var warning = _dereq_(29);
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && "development" === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeHook = _dereq_(7);
}
var loggedTypeFailures = {};
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?object} element The React element that is being type-checked
* @param {?number} debugID The React component instance that is being type-checked
* @private
*/
function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof typeSpecs[typeSpecName] === 'function') ? "development" !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0;
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
"development" !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0;
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var componentStackInfo = '';
if ("development" !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = _dereq_(7);
}
if (debugID !== null) {
componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID);
} else if (element !== null) {
componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element);
}
}
"development" !== 'production' ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0;
}
}
}
}
module.exports = checkReactTypeSpec;
}).call(this,undefined)
},{"14":14,"16":16,"24":24,"28":28,"29":29,"7":7}],22:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule getIteratorFn
*
*/
'use strict';
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
module.exports = getIteratorFn;
},{}],23:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule onlyChild
*/
'use strict';
var _prodInvariant = _dereq_(24);
var ReactElement = _dereq_(10);
var invariant = _dereq_(28);
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://facebook.github.io/react/docs/top-level-api.html#react.children.only
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/
function onlyChild(children) {
!ReactElement.isValidElement(children) ? "development" !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0;
return children;
}
module.exports = onlyChild;
},{"10":10,"24":24,"28":28}],24:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-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.
*
* @providesModule reactProdInvariant
*
*/
'use strict';
/**
* WARNING: DO NOT manually require this module.
* This is a replacement for `invariant(...)` used by the error code system
* and will _only_ be required by the corresponding babel pass.
* It always throws.
*/
function reactProdInvariant(code) {
var argCount = arguments.length - 1;
var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code;
for (var argIdx = 0; argIdx < argCount; argIdx++) {
message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]);
}
message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.';
var error = new Error(message);
error.name = 'Invariant Violation';
error.framesToPop = 1; // we don't care about reactProdInvariant's own frame
throw error;
}
module.exports = reactProdInvariant;
},{}],25:[function(_dereq_,module,exports){
/**
* Copyright 2013-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.
*
* @providesModule traverseAllChildren
*/
'use strict';
var _prodInvariant = _dereq_(24);
var ReactCurrentOwner = _dereq_(8);
var REACT_ELEMENT_TYPE = _dereq_(11);
var getIteratorFn = _dereq_(22);
var invariant = _dereq_(28);
var KeyEscapeUtils = _dereq_(1);
var warning = _dereq_(29);
var SEPARATOR = '.';
var SUBSEPARATOR = ':';
/**
* This is inlined from ReactElement since this file is shared between
* isomorphic and renderers. We could extract this to a
*
*/
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var didWarnAboutMaps = false;
/**
* Generate a key string that identifies a component within a set.
*
* @param {*} component A component that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/
function getComponentKey(component, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if (component && typeof component === 'object' && component.key != null) {
// Explicit key
return KeyEscapeUtils.escape(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* @param {?*} children Children tree container.
* @param {!string} nameSoFar Name of the key path so far.
* @param {!function} callback Callback to invoke with each child found.
* @param {?*} traverseContext Used to pass information throughout the traversal
* process.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) {
var type = typeof children;
if (type === 'undefined' || type === 'boolean') {
// All of the above are perceived as null.
children = null;
}
if (children === null || type === 'string' || type === 'number' ||
// The following is inlined from ReactElement. This means we can optimize
// some checks. React Fiber also inlines this logic for similar purposes.
type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) {
callback(traverseContext, children,
// If it's the only child, treat the name as if it was wrapped in an array
// so that it's consistent if the number of children grows.
nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar);
return 1;
}
var child;
var nextName;
var subtreeCount = 0; // Count of children found in the current subtree.
var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
child = children[i];
nextName = nextNamePrefix + getComponentKey(child, i);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
var iteratorFn = getIteratorFn(children);
if (iteratorFn) {
var iterator = iteratorFn.call(children);
var step;
if (iteratorFn !== children.entries) {
var ii = 0;
while (!(step = iterator.next()).done) {
child = step.value;
nextName = nextNamePrefix + getComponentKey(child, ii++);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
} else {
if ("development" !== 'production') {
var mapsAsChildrenAddendum = '';
if (ReactCurrentOwner.current) {
var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName();
if (mapsAsChildrenOwnerName) {
mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.';
}
}
"development" !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0;
didWarnAboutMaps = true;
}
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
child = entry[1];
nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if ("development" !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
!false ? "development" !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0;
}
}
return subtreeCount;
}
/**
* Traverses children that are typically specified as `props.children`, but
* might also be specified through attributes:
*
* - `traverseAllChildren(this.props.children, ...)`
* - `traverseAllChildren(this.props.leftPanelChildren, ...)`
*
* The `traverseContext` is an optional argument that is passed through the
* entire traversal. It can be used to store accumulations or anything else that
* the callback might find relevant.
*
* @param {?*} children Children tree object.
* @param {!function} callback To invoke upon traversing each child.
* @param {?*} traverseContext Context for traversal.
* @return {!number} The number of children in this subtree.
*/
function traverseAllChildren(children, callback, traverseContext) {
if (children == null) {
return 0;
}
return traverseAllChildrenImpl(children, '', callback, traverseContext);
}
module.exports = traverseAllChildren;
},{"1":1,"11":11,"22":22,"24":24,"28":28,"29":29,"8":8}],26:[function(_dereq_,module,exports){
"use strict";
/**
* Copyright (c) 2013-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.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
},{}],27:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-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.
*
*/
'use strict';
var emptyObject = {};
if ("development" !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],28:[function(_dereq_,module,exports){
/**
* Copyright (c) 2013-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.
*
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if ("development" !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
},{}],29:[function(_dereq_,module,exports){
/**
* Copyright 2014-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 emptyFunction = _dereq_(26);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if ("development" !== 'production') {
(function () {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// 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);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
})();
}
module.exports = warning;
},{"26":26}],30:[function(_dereq_,module,exports){
'use strict';
/* eslint-disable no-unused-vars */
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (e) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (Object.getOwnPropertySymbols) {
symbols = Object.getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
},{}]},{},[18])(18)
});
|
// Copyright (c) the Contributors as noted in the AUTHORS file.
// This file is part of node-ninja.
//
// 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 path = require('path')
, log = require('npmlog')
function findNodeDirectory(scriptLocation, processObj) {
// set dirname and process if not passed in
// this facilitates regression tests
if (scriptLocation === undefined) {
scriptLocation = __dirname
}
if (processObj === undefined) {
processObj = process
}
// Have a look to see what is above us, to try and work out where we are
npm_parent_directory = path.join(scriptLocation, '../../../..')
log.verbose('node-ninja root', 'npm_parent_directory is '
+ path.basename(npm_parent_directory))
node_root_dir = ""
log.verbose('node-ninja root', 'Finding node root directory')
if (path.basename(npm_parent_directory) === 'deps') {
// We are in a build directory where this script lives in
// deps/npm/node_modules/node-ninja/lib
node_root_dir = path.join(npm_parent_directory, '..')
log.verbose('node-ninja root', 'in build directory, root = '
+ node_root_dir)
} else if (path.basename(npm_parent_directory) === 'node_modules') {
// We are in a node install directory where this script lives in
// lib/node_modules/npm/node_modules/node-ninja/lib or
// node_modules/npm/node_modules/node-ninja/lib depending on the
// platform
if (processObj.platform === 'win32') {
node_root_dir = path.join(npm_parent_directory, '..')
} else {
node_root_dir = path.join(npm_parent_directory, '../..')
}
log.verbose('node-ninja root', 'in install directory, root = '
+ node_root_dir)
} else {
// We don't know where we are, try working it out from the location
// of the node binary
var node_dir = path.dirname(processObj.execPath)
var directory_up = path.basename(node_dir)
if (directory_up === 'bin') {
node_root_dir = path.join(node_dir, '..')
} else if (directory_up === 'Release' || directory_up === 'Debug') {
// If we are a recently built node, and the directory structure
// is that of a repository. If we are on Windows then we only need
// to go one level up, everything else, two
if (processObj.platform === 'win32') {
node_root_dir = path.join(node_dir, '..')
} else {
node_root_dir = path.join(node_dir, '../..')
}
}
// Else return the default blank, "".
}
return node_root_dir
}
module.exports = findNodeDirectory
|
/*******************************************************************************
* KindEditor - WYSIWYG HTML Editor for Internet
* Copyright (C) 2006-2011 kindsoft.net
*
* @author Roddy <luolonghao@gmail.com>
* @site http://www.kindsoft.net/
* @licence http://www.kindsoft.net/license.php
*******************************************************************************/
KindEditor.plugin('media', function(K) {
var self = this, name = 'media', lang = self.lang(name + '.'),
allowMediaUpload = K.undef(self.allowMediaUpload, true),
allowFileManager = K.undef(self.allowFileManager, false),
formatUploadUrl = K.undef(self.formatUploadUrl, true),
uploadJson = K.undef(self.uploadJson, self.basePath + 'php/upload_json.php');
self.plugin.media = {
edit : function() {
var html = [
'<div style="padding:20px;">',
//url
'<div class="ke-dialog-row">',
'<label for="keUrl" style="width:60px;">' + lang.url + '</label>',
'<input class="ke-input-text" type="text" id="keUrl" name="url" value="" style="width:160px;" /> ',
'<input type="button" class="ke-upload-button" value="' + lang.upload + '" /> ',
'<span class="ke-button-common ke-button-outer">',
'<input type="button" class="ke-button-common ke-button" name="viewServer" value="' + lang.viewServer + '" />',
'</span>',
'</div>',
//width
'<div class="ke-dialog-row">',
'<label for="keWidth" style="width:60px;">' + lang.width + '</label>',
'<input type="text" id="keWidth" class="ke-input-text ke-input-number" name="width" value="550" maxlength="4" />',
'</div>',
//height
'<div class="ke-dialog-row">',
'<label for="keHeight" style="width:60px;">' + lang.height + '</label>',
'<input type="text" id="keHeight" class="ke-input-text ke-input-number" name="height" value="400" maxlength="4" />',
'</div>',
//autostart
'<div class="ke-dialog-row">',
'<label for="keAutostart">' + lang.autostart + '</label>',
'<input type="checkbox" id="keAutostart" name="autostart" value="" /> ',
'</div>',
'</div>'
].join('');
var dialog = self.createDialog({
name : name,
width : 450,
height : 230,
title : self.lang(name),
body : html,
yesBtn : {
name : self.lang('yes'),
click : function(e) {
var url = K.trim(urlBox.val()),
width = widthBox.val(),
height = heightBox.val();
if (url == 'http://' || K.invalidUrl(url)) {
alert(self.lang('invalidUrl'));
urlBox[0].focus();
return;
}
if (!/^\d*$/.test(width)) {
alert(self.lang('invalidWidth'));
widthBox[0].focus();
return;
}
if (!/^\d*$/.test(height)) {
alert(self.lang('invalidHeight'));
heightBox[0].focus();
return;
}
var html = K.mediaImg(self.themesPath + 'common/blank.gif', {
src : url,
type : K.mediaType(url),
width : width,
height : height,
autostart : autostartBox[0].checked ? 'true' : 'false',
loop : 'true'
});
self.insertHtml(html).hideDialog().focus();
}
}
}),
div = dialog.div,
urlBox = K('[name="url"]', div),
viewServerBtn = K('[name="viewServer"]', div),
widthBox = K('[name="width"]', div),
heightBox = K('[name="height"]', div),
autostartBox = K('[name="autostart"]', div);
urlBox.val('http://');
if (allowMediaUpload) {
var uploadbutton = K.uploadbutton({
button : K('.ke-upload-button', div)[0],
fieldName : 'imgFile',
url : K.addParam(uploadJson, 'dir=media'),
afterUpload : function(data) {
dialog.hideLoading();
if (data.error === 0) {
var url = data.url;
if (formatUploadUrl) {
url = K.formatUrl(url, 'absolute');
}
urlBox.val(url);
if (self.afterUpload) {
self.afterUpload.call(self, url);
}
alert(self.lang('uploadSuccess'));
} else {
alert(data.message);
}
},
afterError : function(html) {
dialog.hideLoading();
self.errorDialog(html);
}
});
uploadbutton.fileBox.change(function(e) {
dialog.showLoading(self.lang('uploadLoading'));
uploadbutton.submit();
});
} else {
K('.ke-upload-button', div).hide();
}
if (allowFileManager) {
viewServerBtn.click(function(e) {
self.loadPlugin('filemanager', function() {
self.plugin.filemanagerDialog({
viewType : 'LIST',
dirName : 'media',
clickFn : function(url, title) {
if (self.dialogs.length > 1) {
K('[name="url"]', div).val(url);
self.hideDialog();
}
}
});
});
});
} else {
viewServerBtn.hide();
}
var img = self.plugin.getSelectedMedia();
if (img) {
var attrs = K.mediaAttrs(img.attr('data-ke-tag'));
urlBox.val(attrs.src);
widthBox.val(K.removeUnit(img.css('width')) || attrs.width || 0);
heightBox.val(K.removeUnit(img.css('height')) || attrs.height || 0);
autostartBox[0].checked = (attrs.autostart === 'true');
}
urlBox[0].focus();
urlBox[0].select();
},
'delete' : function() {
self.plugin.getSelectedMedia().remove();
}
};
self.clickToolbar(name, self.plugin.media.edit);
});
|
// src/server/index.ts
import {executionAsyncId, createHook} from "node:async_hooks";
import {virtualSheet} from "twind/sheets";
export * from "twind";
export * from "twind/sheets";
var asyncVirtualSheet = () => {
const sheet = virtualSheet();
const initial = sheet.reset();
const store = new Map();
const asyncHook = createHook({
init(asyncId, type, triggerAsyncId) {
const snapshot = store.get(triggerAsyncId);
if (snapshot) {
store.set(asyncId, snapshot);
}
},
before(asyncId) {
const snapshot = store.get(asyncId);
if (snapshot) {
sheet.reset(snapshot.state);
}
},
after(asyncId) {
const snapshot = store.get(asyncId);
if (snapshot) {
snapshot.state = sheet.reset(initial);
}
},
destroy(asyncId) {
store.delete(asyncId);
}
}).enable();
return {
get target() {
return sheet.target;
},
insert: sheet.insert,
init: sheet.init,
reset: () => {
const asyncId = executionAsyncId();
const snapshot = store.get(asyncId);
if (snapshot) {
snapshot.state = void 0;
} else {
store.set(asyncId, {state: void 0});
}
sheet.reset();
},
enable: () => asyncHook.enable(),
disable: () => asyncHook.disable()
};
};
export {
asyncVirtualSheet
};
//# sourceMappingURL=server.esnext.js.map
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(86)
var __weex_script__ = __webpack_require__(87)
__weex_define__('@weex-component/c1a5ee0b8eec58d4b53a6bf8756f068b', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
})
__weex_bootstrap__('@weex-component/c1a5ee0b8eec58d4b53a6bf8756f068b',undefined,undefined)
/***/ },
/* 1 */,
/* 2 */,
/* 3 */,
/* 4 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(5);
__webpack_require__(9);
__webpack_require__(13);
__webpack_require__(17);
__webpack_require__(21);
__webpack_require__(25);
__webpack_require__(66);
__webpack_require__(70);
__webpack_require__(74);
__webpack_require__(78);
__webpack_require__(79);
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(6)
var __weex_style__ = __webpack_require__(7)
var __weex_script__ = __webpack_require__(8)
__weex_define__('@weex-component/wxc-button', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 6 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": function () {return ['btn', 'btn-' + (this.type), 'btn-sz-' + (this.size)]},
"children": [
{
"type": "text",
"classList": function () {return ['btn-txt', 'btn-txt-' + (this.type), 'btn-txt-sz-' + (this.size)]},
"attr": {
"value": function () {return this.value}
}
}
]
}
/***/ },
/* 7 */
/***/ function(module, exports) {
module.exports = {
"btn": {
"marginBottom": 0,
"alignItems": "center",
"justifyContent": "center",
"borderWidth": 1,
"borderStyle": "solid",
"borderColor": "#333333"
},
"btn-default": {
"color": "rgb(51,51,51)"
},
"btn-primary": {
"backgroundColor": "rgb(40,96,144)",
"borderColor": "rgb(40,96,144)"
},
"btn-success": {
"backgroundColor": "rgb(92,184,92)",
"borderColor": "rgb(76,174,76)"
},
"btn-info": {
"backgroundColor": "rgb(91,192,222)",
"borderColor": "rgb(70,184,218)"
},
"btn-warning": {
"backgroundColor": "rgb(240,173,78)",
"borderColor": "rgb(238,162,54)"
},
"btn-danger": {
"backgroundColor": "rgb(217,83,79)",
"borderColor": "rgb(212,63,58)"
},
"btn-link": {
"borderColor": "rgba(0,0,0,0)",
"borderRadius": 0
},
"btn-txt-default": {
"color": "rgb(51,51,51)"
},
"btn-txt-primary": {
"color": "rgb(255,255,255)"
},
"btn-txt-success": {
"color": "rgb(255,255,255)"
},
"btn-txt-info": {
"color": "rgb(255,255,255)"
},
"btn-txt-warning": {
"color": "rgb(255,255,255)"
},
"btn-txt-danger": {
"color": "rgb(255,255,255)"
},
"btn-txt-link": {
"color": "rgb(51,122,183)"
},
"btn-sz-large": {
"width": 300,
"height": 100,
"paddingTop": 25,
"paddingBottom": 25,
"paddingLeft": 40,
"paddingRight": 40,
"borderRadius": 15
},
"btn-sz-middle": {
"width": 240,
"height": 80,
"paddingTop": 15,
"paddingBottom": 15,
"paddingLeft": 30,
"paddingRight": 30,
"borderRadius": 10
},
"btn-sz-small": {
"width": 170,
"height": 60,
"paddingTop": 12,
"paddingBottom": 12,
"paddingLeft": 25,
"paddingRight": 25,
"borderRadius": 7
},
"btn-txt-sz-large": {
"fontSize": 45
},
"btn-txt-sz-middle": {
"fontSize": 35
},
"btn-txt-sz-small": {
"fontSize": 30
}
}
/***/ },
/* 8 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
type: 'default',
size: 'large',
value: ''
}},
methods: {}
};}
/* generated by weex-loader */
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(10)
var __weex_style__ = __webpack_require__(11)
var __weex_script__ = __webpack_require__(12)
__weex_define__('@weex-component/wxc-hn', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 10 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": function () {return ['h' + (this.level)]},
"style": {
"justifyContent": "center"
},
"children": [
{
"type": "text",
"classList": function () {return ['txt-h' + (this.level)]},
"attr": {
"value": function () {return this.value}
}
}
]
}
/***/ },
/* 11 */
/***/ function(module, exports) {
module.exports = {
"h1": {
"height": 110,
"paddingTop": 20,
"paddingBottom": 20
},
"h2": {
"height": 110,
"paddingTop": 20,
"paddingBottom": 20
},
"h3": {
"height": 110,
"paddingTop": 20,
"paddingBottom": 20
},
"txt-h1": {
"fontSize": 70
},
"txt-h2": {
"fontSize": 52
},
"txt-h3": {
"fontSize": 42
}
}
/***/ },
/* 12 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
level: 1,
value: ''
}},
methods: {}
};}
/* generated by weex-loader */
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(14)
var __weex_style__ = __webpack_require__(15)
var __weex_script__ = __webpack_require__(16)
__weex_define__('@weex-component/wxc-list-item', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 14 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"item"
],
"events": {
"touchstart": "touchstart",
"touchend": "touchend"
},
"style": {
"backgroundColor": function () {return this.bgColor}
},
"children": [
{
"type": "content"
}
]
}
/***/ },
/* 15 */
/***/ function(module, exports) {
module.exports = {
"item": {
"paddingTop": 25,
"paddingBottom": 25,
"paddingLeft": 35,
"paddingRight": 35,
"height": 160,
"justifyContent": "center",
"borderBottomWidth": 1,
"borderColor": "#dddddd"
}
}
/***/ },
/* 16 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
bgColor: '#ffffff'
}},
methods: {
touchstart: function touchstart() {},
touchend: function touchend() {}
}
};}
/* generated by weex-loader */
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(18)
var __weex_style__ = __webpack_require__(19)
var __weex_script__ = __webpack_require__(20)
__weex_define__('@weex-component/wxc-panel', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 18 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": function () {return ['panel', 'panel-' + (this.type)]},
"style": {
"borderWidth": function () {return this.border}
},
"children": [
{
"type": "text",
"classList": function () {return ['panel-header', 'panel-header-' + (this.type)]},
"style": {
"paddingTop": function () {return this.paddingHead},
"paddingBottom": function () {return this.paddingHead},
"paddingLeft": function () {return this.paddingHead*1.5},
"paddingRight": function () {return this.paddingHead*1.5}
},
"attr": {
"value": function () {return this.title}
}
},
{
"type": "div",
"classList": function () {return ['panel-body', 'panel-body-' + (this.type)]},
"style": {
"paddingTop": function () {return this.paddingBody},
"paddingBottom": function () {return this.paddingBody},
"paddingLeft": function () {return this.paddingBody*1.5},
"paddingRight": function () {return this.paddingBody*1.5}
},
"children": [
{
"type": "content"
}
]
}
]
}
/***/ },
/* 19 */
/***/ function(module, exports) {
module.exports = {
"panel": {
"marginBottom": 20,
"backgroundColor": "#ffffff",
"borderColor": "#dddddd",
"borderWidth": 1
},
"panel-primary": {
"borderColor": "rgb(40,96,144)"
},
"panel-success": {
"borderColor": "rgb(76,174,76)"
},
"panel-info": {
"borderColor": "rgb(70,184,218)"
},
"panel-warning": {
"borderColor": "rgb(238,162,54)"
},
"panel-danger": {
"borderColor": "rgb(212,63,58)"
},
"panel-header": {
"backgroundColor": "#f5f5f5",
"fontSize": 40,
"color": "#333333"
},
"panel-header-primary": {
"backgroundColor": "rgb(40,96,144)",
"color": "#ffffff"
},
"panel-header-success": {
"backgroundColor": "rgb(92,184,92)",
"color": "#ffffff"
},
"panel-header-info": {
"backgroundColor": "rgb(91,192,222)",
"color": "#ffffff"
},
"panel-header-warning": {
"backgroundColor": "rgb(240,173,78)",
"color": "#ffffff"
},
"panel-header-danger": {
"backgroundColor": "rgb(217,83,79)",
"color": "#ffffff"
}
}
/***/ },
/* 20 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
type: 'default',
title: '',
paddingBody: 20,
paddingHead: 20,
dataClass: '',
border: 0
}},
ready: function ready() {}
};}
/* generated by weex-loader */
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(22)
var __weex_style__ = __webpack_require__(23)
var __weex_script__ = __webpack_require__(24)
__weex_define__('@weex-component/wxc-tip', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 22 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": function () {return ['tip', 'tip-' + (this.type)]},
"children": [
{
"type": "text",
"classList": function () {return ['tip-txt', 'tip-txt-' + (this.type)]},
"attr": {
"value": function () {return this.value}
}
}
]
}
/***/ },
/* 23 */
/***/ function(module, exports) {
module.exports = {
"tip": {
"paddingLeft": 36,
"paddingRight": 36,
"paddingTop": 36,
"paddingBottom": 36,
"borderRadius": 10
},
"tip-txt": {
"fontSize": 28
},
"tip-success": {
"backgroundColor": "#dff0d8",
"borderColor": "#d6e9c6"
},
"tip-txt-success": {
"color": "#3c763d"
},
"tip-info": {
"backgroundColor": "#d9edf7",
"borderColor": "#bce8f1"
},
"tip-txt-info": {
"color": "#31708f"
},
"tip-warning": {
"backgroundColor": "#fcf8e3",
"borderColor": "#faebcc"
},
"tip-txt-warning": {
"color": "#8a6d3b"
},
"tip-danger": {
"backgroundColor": "#f2dede",
"borderColor": "#ebccd1"
},
"tip-txt-danger": {
"color": "#a94442"
}
}
/***/ },
/* 24 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
type: 'success',
value: ''
}}
};}
/* generated by weex-loader */
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(26)
var __weex_style__ = __webpack_require__(27)
var __weex_script__ = __webpack_require__(28)
__weex_define__('@weex-component/wxc-countdown', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 26 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"style": {
"overflow": "hidden",
"flexDirection": "row"
},
"events": {
"appear": "appeared",
"disappear": "disappeared"
},
"children": [
{
"type": "content"
}
]
}
/***/ },
/* 27 */
/***/ function(module, exports) {
module.exports = {
"wrap": {
"overflow": "hidden"
}
}
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
module.exports = function(module, exports, __weex_require__){'use strict';
var _assign = __webpack_require__(29);
var _assign2 = _interopRequireDefault(_assign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = {
data: function () {return {
now: 0,
remain: 0,
time: {
elapse: 0,
D: '0',
DD: '0',
h: '0',
hh: '00',
H: '0',
HH: '0',
m: '0',
mm: '00',
M: '0',
MM: '0',
s: '0',
ss: '00',
S: '0',
SS: '0'
},
outofview: false
}},
ready: function ready() {
if (this.remain <= 0) {
return;
}
this.now = Date.now();
this.nextTick();
},
methods: {
nextTick: function nextTick() {
if (this.outofview) {
setTimeout(this.nextTick.bind(this), 1000);
} else {
this.time.elapse = parseInt((Date.now() - this.now) / 1000);
if (this.calc()) {
this.$emit('tick', (0, _assign2.default)({}, this.time));
setTimeout(this.nextTick.bind(this), 1000);
} else {
this.$emit('alarm', (0, _assign2.default)({}, this.time));
}
this._app.updateActions();
}
},
format: function format(str) {
if (str.length >= 2) {
return str;
} else {
return '0' + str;
}
},
calc: function calc() {
var remain = this.remain - this.time.elapse;
if (remain < 0) {
remain = 0;
}
this.time.D = String(parseInt(remain / 86400));
this.time.DD = this.format(this.time.D);
this.time.h = String(parseInt((remain - parseInt(this.time.D) * 86400) / 3600));
this.time.hh = this.format(this.time.h);
this.time.H = String(parseInt(remain / 3600));
this.time.HH = this.format(this.time.H);
this.time.m = String(parseInt((remain - parseInt(this.time.H) * 3600) / 60));
this.time.mm = this.format(this.time.m);
this.time.M = String(parseInt(remain / 60));
this.time.MM = this.format(this.time.M);
this.time.s = String(remain - parseInt(this.time.M) * 60);
this.time.ss = this.format(this.time.s);
this.time.S = String(remain);
this.time.SS = this.format(this.time.S);
return remain > 0;
},
appeared: function appeared() {
this.outofview = false;
},
disappeared: function disappeared() {
this.outofview = true;
}
}
};}
/* generated by weex-loader */
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(30), __esModule: true };
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(31);
module.exports = __webpack_require__(34).Object.assign;
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(32);
$export($export.S + $export.F, 'Object', {assign: __webpack_require__(47)});
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(33)
, core = __webpack_require__(34)
, ctx = __webpack_require__(35)
, hide = __webpack_require__(37)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ },
/* 33 */
/***/ function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ },
/* 34 */
/***/ function(module, exports) {
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(36);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 36 */
/***/ function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(38)
, createDesc = __webpack_require__(46);
module.exports = __webpack_require__(42) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(39)
, IE8_DOM_DEFINE = __webpack_require__(41)
, toPrimitive = __webpack_require__(45)
, dP = Object.defineProperty;
exports.f = __webpack_require__(42) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(40);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ },
/* 40 */
/***/ function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(42) && !__webpack_require__(43)(function(){
return Object.defineProperty(__webpack_require__(44)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(43)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 43 */
/***/ function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(40)
, document = __webpack_require__(33).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(40);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ },
/* 46 */
/***/ function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(48)
, gOPS = __webpack_require__(63)
, pIE = __webpack_require__(64)
, toObject = __webpack_require__(65)
, IObject = __webpack_require__(52)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(43)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(49)
, enumBugKeys = __webpack_require__(62);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var has = __webpack_require__(50)
, toIObject = __webpack_require__(51)
, arrayIndexOf = __webpack_require__(55)(false)
, IE_PROTO = __webpack_require__(59)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ },
/* 50 */
/***/ function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(52)
, defined = __webpack_require__(54);
module.exports = function(it){
return IObject(defined(it));
};
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(53);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ },
/* 53 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ },
/* 54 */
/***/ function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(51)
, toLength = __webpack_require__(56)
, toIndex = __webpack_require__(58);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(57)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ },
/* 57 */
/***/ function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(57)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
var shared = __webpack_require__(60)('keys')
, uid = __webpack_require__(61);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(33)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 61 */
/***/ function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ },
/* 62 */
/***/ function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ },
/* 63 */
/***/ function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ },
/* 64 */
/***/ function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(54);
module.exports = function(it){
return Object(defined(it));
};
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(67)
var __weex_style__ = __webpack_require__(68)
var __weex_script__ = __webpack_require__(69)
__weex_define__('@weex-component/wxc-marquee', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 67 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"wrap"
],
"events": {
"appear": "appeared",
"disappear": "disappeared"
},
"children": [
{
"type": "div",
"id": "anim",
"classList": [
"anim"
],
"children": [
{
"type": "content"
}
]
}
]
}
/***/ },
/* 68 */
/***/ function(module, exports) {
module.exports = {
"wrap": {
"overflow": "hidden",
"position": "relative"
},
"anim": {
"flexDirection": "column",
"position": "absolute",
"transform": "translateY(0) translateZ(0)"
}
}
/***/ },
/* 69 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
step: 0,
count: 0,
index: 1,
duration: 0,
interval: 0,
outofview: false
}},
ready: function ready() {
if (this.interval > 0 && this.step > 0 && this.duration > 0) {
this.nextTick();
}
},
methods: {
nextTick: function nextTick() {
var self = this;
if (this.outofview) {
setTimeout(self.nextTick.bind(self), self.interval);
} else {
setTimeout(function () {
self.animation(self.nextTick.bind(self));
}, self.interval);
}
},
animation: function animation(cb) {
var self = this;
var offset = -self.step * self.index;
var $animation = __weex_require__('@weex-module/animation');
$animation.transition(this.$el('anim'), {
styles: {
transform: 'translateY(' + String(offset) + 'px) translateZ(0)'
},
timingFunction: 'ease',
duration: self.duration
}, function () {
self.index = (self.index + 1) % self.count;
self.$emit('change', {
index: self.index,
count: self.count
});
cb && cb();
});
},
appeared: function appeared() {
this.outofview = false;
},
disappeared: function disappeared() {
this.outofview = true;
}
}
};}
/* generated by weex-loader */
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(71)
var __weex_style__ = __webpack_require__(72)
var __weex_script__ = __webpack_require__(73)
__weex_define__('@weex-component/wxc-navbar', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 71 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"container"
],
"style": {
"height": function () {return this.height},
"backgroundColor": function () {return this.backgroundColor}
},
"attr": {
"dataRole": function () {return this.dataRole}
},
"children": [
{
"type": "text",
"classList": [
"right-text"
],
"style": {
"color": function () {return this.rightItemColor}
},
"attr": {
"naviItemPosition": "right",
"value": function () {return this.rightItemTitle}
},
"shown": function () {return !this.rightItemSrc},
"events": {
"click": "onclickrightitem"
}
},
{
"type": "image",
"classList": [
"right-image"
],
"attr": {
"naviItemPosition": "right",
"src": function () {return this.rightItemSrc}
},
"shown": function () {return this.rightItemSrc},
"events": {
"click": "onclickrightitem"
}
},
{
"type": "text",
"classList": [
"left-text"
],
"style": {
"color": function () {return this.leftItemColor}
},
"attr": {
"naviItemPosition": "left",
"value": function () {return this.leftItemTitle}
},
"shown": function () {return !this.leftItemSrc},
"events": {
"click": "onclickleftitem"
}
},
{
"type": "image",
"classList": [
"left-image"
],
"attr": {
"naviItemPosition": "left",
"src": function () {return this.leftItemSrc}
},
"shown": function () {return this.leftItemSrc},
"events": {
"click": "onclickleftitem"
}
},
{
"type": "text",
"classList": [
"center-text"
],
"style": {
"color": function () {return this.titleColor}
},
"attr": {
"naviItemPosition": "center",
"value": function () {return this.title}
}
}
]
}
/***/ },
/* 72 */
/***/ function(module, exports) {
module.exports = {
"container": {
"flexDirection": "row",
"position": "fixed",
"top": 0,
"left": 0,
"right": 0,
"width": 750
},
"right-text": {
"position": "absolute",
"bottom": 28,
"right": 32,
"textAlign": "right",
"fontSize": 32,
"fontFamily": "'Open Sans', sans-serif"
},
"left-text": {
"position": "absolute",
"bottom": 28,
"left": 32,
"textAlign": "left",
"fontSize": 32,
"fontFamily": "'Open Sans', sans-serif"
},
"center-text": {
"position": "absolute",
"bottom": 25,
"left": 172,
"right": 172,
"textAlign": "center",
"fontSize": 36,
"fontWeight": "bold"
},
"left-image": {
"position": "absolute",
"bottom": 20,
"left": 28,
"width": 50,
"height": 50
},
"right-image": {
"position": "absolute",
"bottom": 20,
"right": 28,
"width": 50,
"height": 50
}
}
/***/ },
/* 73 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
dataRole: 'navbar',
backgroundColor: 'black',
height: 88,
title: "",
titleColor: 'black',
rightItemSrc: '',
rightItemTitle: '',
rightItemColor: 'black',
leftItemSrc: '',
leftItemTitle: '',
leftItemColor: 'black'
}},
methods: {
onclickrightitem: function onclickrightitem(e) {
this.$dispatch('naviBar.rightItem.click', {});
},
onclickleftitem: function onclickleftitem(e) {
this.$dispatch('naviBar.leftItem.click', {});
}
}
};}
/* generated by weex-loader */
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(70)
var __weex_template__ = __webpack_require__(75)
var __weex_style__ = __webpack_require__(76)
var __weex_script__ = __webpack_require__(77)
__weex_define__('@weex-component/wxc-navpage', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 75 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"wrapper"
],
"children": [
{
"type": "wxc-navbar",
"attr": {
"dataRole": function () {return this.dataRole},
"height": function () {return this.height},
"backgroundColor": function () {return this.backgroundColor},
"title": function () {return this.title},
"titleColor": function () {return this.titleColor},
"leftItemSrc": function () {return this.leftItemSrc},
"leftItemTitle": function () {return this.leftItemTitle},
"leftItemColor": function () {return this.leftItemColor},
"rightItemSrc": function () {return this.rightItemSrc},
"rightItemTitle": function () {return this.rightItemTitle},
"rightItemColor": function () {return this.rightItemColor}
}
},
{
"type": "div",
"classList": [
"wrapper"
],
"style": {
"marginTop": function () {return this.height}
},
"children": [
{
"type": "content"
}
]
}
]
}
/***/ },
/* 76 */
/***/ function(module, exports) {
module.exports = {
"wrapper": {
"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"bottom": 0,
"width": 750
}
}
/***/ },
/* 77 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
dataRole: 'navbar',
backgroundColor: 'black',
height: 88,
title: "",
titleColor: 'black',
rightItemSrc: '',
rightItemTitle: '',
rightItemColor: 'black',
leftItemSrc: '',
leftItemTitle: '',
leftItemColor: 'black'
}}
};}
/* generated by weex-loader */
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(79)
var __weex_template__ = __webpack_require__(83)
var __weex_style__ = __webpack_require__(84)
var __weex_script__ = __webpack_require__(85)
__weex_define__('@weex-component/wxc-tabbar', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(80)
var __weex_style__ = __webpack_require__(81)
var __weex_script__ = __webpack_require__(82)
__weex_define__('@weex-component/wxc-tabitem', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
/***/ },
/* 80 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"container"
],
"style": {
"backgroundColor": function () {return this.backgroundColor}
},
"events": {
"click": "onclickitem"
},
"children": [
{
"type": "image",
"classList": [
"top-line"
],
"attr": {
"src": "http://gtms03.alicdn.com/tps/i3/TB1mdsiMpXXXXXpXXXXNw4JIXXX-640-4.png"
}
},
{
"type": "image",
"classList": [
"tab-icon"
],
"attr": {
"src": function () {return this.icon}
}
},
{
"type": "text",
"classList": [
"tab-text"
],
"style": {
"color": function () {return this.titleColor}
},
"attr": {
"value": function () {return this.title}
}
}
]
}
/***/ },
/* 81 */
/***/ function(module, exports) {
module.exports = {
"container": {
"flex": 1,
"flexDirection": "column",
"alignItems": "center",
"justifyContent": "center",
"height": 88
},
"top-line": {
"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"height": 2
},
"tab-icon": {
"marginTop": 5,
"width": 40,
"height": 40
},
"tab-text": {
"marginTop": 5,
"textAlign": "center",
"fontSize": 20
}
}
/***/ },
/* 82 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
index: 0,
title: '',
titleColor: '#000000',
icon: '',
backgroundColor: '#ffffff'
}},
methods: {
onclickitem: function onclickitem(e) {
var vm = this;
var params = {
index: vm.index
};
vm.$dispatch('tabItem.onClick', params);
}
}
};}
/* generated by weex-loader */
/***/ },
/* 83 */
/***/ function(module, exports) {
module.exports = {
"type": "div",
"classList": [
"wrapper"
],
"children": [
{
"type": "embed",
"classList": [
"content"
],
"style": {
"visibility": function () {return this.visibility}
},
"repeat": function () {return this.tabItems},
"attr": {
"src": function () {return this.src},
"type": "weex"
}
},
{
"type": "div",
"classList": [
"tabbar"
],
"append": "tree",
"children": [
{
"type": "wxc-tabitem",
"repeat": function () {return this.tabItems},
"attr": {
"index": function () {return this.index},
"icon": function () {return this.icon},
"title": function () {return this.title},
"titleColor": function () {return this.titleColor}
}
}
]
}
]
}
/***/ },
/* 84 */
/***/ function(module, exports) {
module.exports = {
"wrapper": {
"width": 750,
"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"bottom": 0
},
"content": {
"position": "absolute",
"top": 0,
"left": 0,
"right": 0,
"bottom": 0,
"marginTop": 0,
"marginBottom": 88
},
"tabbar": {
"flexDirection": "row",
"position": "fixed",
"bottom": 0,
"left": 0,
"right": 0,
"height": 88
}
}
/***/ },
/* 85 */
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
tabItems: [],
selectedIndex: 0,
selectedColor: '#ff0000',
unselectedColor: '#000000'
}},
created: function created() {
this.selected(this.selectedIndex);
this.$on('tabItem.onClick', function (e) {
var detail = e.detail;
this.selectedIndex = detail.index;
this.selected(detail.index);
var params = {
index: detail.index
};
this.$dispatch('tabBar.onClick', params);
});
},
methods: {
selected: function selected(index) {
for (var i = 0; i < this.tabItems.length; i++) {
var tabItem = this.tabItems[i];
if (i == index) {
tabItem.icon = tabItem.selectedImage;
tabItem.titleColor = this.selectedColor;
tabItem.visibility = 'visible';
} else {
tabItem.icon = tabItem.image;
tabItem.titleColor = this.unselectedColor;
tabItem.visibility = 'hidden';
}
}
}
}
};}
/* generated by weex-loader */
/***/ },
/* 86 */
/***/ function(module, exports) {
module.exports = {
"type": "scroller",
"children": [
{
"type": "wxc-panel",
"attr": {
"title": "Hyperlink",
"type": "primary"
},
"children": [
{
"type": "a",
"attr": {
"href": "http://g.tbcdn.cn/ali-wireless-h5/res/0.0.16/hello.js"
},
"children": [
{
"type": "wxc-tip",
"attr": {
"type": "info",
"value": "Click me to see how 'A' element opens a new world."
},
"style": {
"marginBottom": 20
}
}
]
}
]
}
]
}
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
module.exports = function(module, exports, __weex_require__){'use strict';
__webpack_require__(4);
module.exports = {
data: function () {return {
img: '//gw.alicdn.com/tps/i2/TB1DpsmMpXXXXabaXXX20ySQVXX-512-512.png_400x400.jpg'
}}
};}
/* generated by weex-loader */
/***/ }
/******/ ]);
|
var urlService = require('../../../services/url'),
sitemapsUtils;
sitemapsUtils = {
getDeclarations: function () {
var baseUrl = urlService.utils.urlFor('sitemap_xsl', true);
baseUrl = baseUrl.replace(/^(http:|https:)/, '');
return '<?xml version="1.0" encoding="UTF-8"?>' +
'<?xml-stylesheet type="text/xsl" href="' + baseUrl + '"?>';
}
};
module.exports = sitemapsUtils;
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'forms', 'vi', {
button: {
title: 'Thuộc tính của nút',
text: 'Chuỗi hiển thị (giá trị)',
type: 'Kiểu',
typeBtn: 'Nút bấm',
typeSbm: 'Nút gửi',
typeRst: 'Nút nhập lại'
},
checkboxAndRadio: {
checkboxTitle: 'Thuộc tính nút kiểm',
radioTitle: 'Thuộc tính nút chọn',
value: 'Giá trị',
selected: 'Được chọn',
required: 'Required' // MISSING
},
form: {
title: 'Thuộc tính biểu mẫu',
menu: 'Thuộc tính biểu mẫu',
action: 'Hành động',
method: 'Phương thức',
encoding: 'Bảng mã'
},
hidden: {
title: 'Thuộc tính trường ẩn',
name: 'Tên',
value: 'Giá trị'
},
select: {
title: 'Thuộc tính ô chọn',
selectInfo: 'Thông tin',
opAvail: 'Các tùy chọn có thể sử dụng',
value: 'Giá trị',
size: 'Kích cỡ',
lines: 'dòng',
chkMulti: 'Cho phép chọn nhiều',
required: 'Required', // MISSING
opText: 'Văn bản',
opValue: 'Giá trị',
btnAdd: 'Thêm',
btnModify: 'Thay đổi',
btnUp: 'Lên',
btnDown: 'Xuống',
btnSetValue: 'Giá trị được chọn',
btnDelete: 'Nút xoá'
},
textarea: {
title: 'Thuộc tính vùng văn bản',
cols: 'Số cột',
rows: 'Số hàng'
},
textfield: {
title: 'Thuộc tính trường văn bản',
name: 'Tên',
value: 'Giá trị',
charWidth: 'Độ rộng của ký tự',
maxChars: 'Số ký tự tối đa',
required: 'Required', // MISSING
type: 'Kiểu',
typeText: 'Ký tự',
typePass: 'Mật khẩu',
typeEmail: 'Email',
typeSearch: 'Tìm kiếm',
typeTel: 'Số điện thoại',
typeUrl: 'URL'
}
} );
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.