code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
'use strict'; /** * Module dependencies. */ const fs = require('fs'), arrowStack = require('./ArrStack'), path = require('path'), express = require('express'), _ = require('lodash'), Promise = require('bluebird'), RedisCache = require("./RedisCache"), installLog = require("./logger").init, logger = require('./logger'), __ = require("./global_function"), EventEmitter = require('events').EventEmitter, r = require('nunjucks').runtime, DefaultManager = require("../manager/DefaultManager"), ConfigManager = require("../manager/ConfigManager"), buildStructure = require("./buildStructure"), socket_io = require('socket.io'), http = require('http'), socketRedisAdapter = require('socket.io-redis'), ViewEngine = require("../libs/ViewEngine"), fsExtra = require('fs-extra'), loadingLanguage = require("./i18n").loadLanguage; let eventEmitter; /** * ArrowApplication is a singleton object. It is heart of Arrowjs.io web app. it wraps Express and adds following functions: * support Redis, multi-languages, passport, check permission and socket.io / websocket */ class ArrowApplication { /** * * @param {object} setting - {passport: bool ,role : bool, order :bool} * <ul> * <li>passport: true, turn on authentication using Passport module</li> * <li>role: true, turn on permission checking, RBAC</li> * <li>order: true, order router priority rule.</li> * </ul> */ constructor(setting) { //if NODE_ENV does not exist, use development by default /* istanbul ignore next */ process.env.NODE_ENV = process.env.NODE_ENV || 'development'; this.beforeAuth = []; //add middle-wares before user authenticates this.afterAuth = []; //add middle-ware after user authenticates this.plugins = []; //add middle-ware after user authenticates let app = express(); global.Arrow = {}; this.arrowErrorLink = {}; //Move all functions of express to ArrowApplication //So we can call ArrowApplication.listen(port) _.assign(this, app); this.expressApp = function (req, res, next) { this.handle(req, res, next); }.bind(this); // 0 : location of this file // 1 : location of index.js (module file) // 2 : location of server.js file let requester = arrowStack(2); this.arrFolder = path.dirname(requester) + '/'; //assign current Arrowjs application folder to global variable global.__base = this.arrFolder; //Read config/config.js into this._config this._config = __.getRawConfig(); //Read and parse config/structure.js /* buildStructure() takes input as an object -> returns an array * __.getStructure() reads file config/structure.js and returns the struc obj */ this.structure = buildStructure(__.getStructure()); //display longer stack trace in console if (this._config.long_stack) { require('longjohn') } installLog(this); this.logger = logger; this.middleware = Object.create(null); //Add passport and its authentication strategies this.middleware.passport = require("../config/middleware/loadPassport").bind(this); //Display flash message when user reloads view this.middleware.flashMessage = require("../config/middleware/flashMessage").bind(this); //Use middleware express-session to store user session this.middleware.session = require("../config/middleware/useSession").bind(this); //Serve static resources when not using Nginx. //See config/view.js section resource this.middleware.serveStatic = require("../config/middleware/staticResource").bind(this); this.middleware.helmet = require("helmet"); this.middleware.bodyParser = require("body-parser"); this.middleware.cookieParser = require("cookie-parser"); this.middleware.morgan = require("morgan"); this.middleware.methodOverride = require('method-override'); //Load available languages. See libs/i18n.js and folder /lang loadingLanguage(this._config); //Bind all global functions to ArrowApplication object loadingGlobalFunction(this); //Declare _arrRoutes to store all routes of features this._arrRoutes = Object.create(null); this.utils = Object.create(null); this.utils.dotChain = getDataByDotNotation; // not found this.utils.fs = fsExtra; this.utils.loadAndCreate = loadSetting.bind(this); // not found this.utils.markSafe = r.markSafe; this.arrowSettings = Object.create(null); } /** * When user requests an URL, execute this function before server checks in session if user has authenticates * If web app does not require authentication, beforeAuthenticate and afterAuthenticate are same. <br> * beforeAuthenticate > authenticate > afterAuthenticate * @param {function} func - function that executes before authentication */ beforeAuthenticate(func) { let self = this; /* istanbul ignore next */ return new Promise(function (fulfill, reject) { if (typeof func == "function") { self.beforeAuth.push(func.bind(self)); fulfill() } else { reject(new Error("Cant beforeAuthenticate: not an function")); } }); } /** * When user requests an URL, execute this function after server checks in session if user has authenticates * This function always runs regardless user has authenticated or not * @param {function} func - function that executes after authentication */ afterAuthenticate(func) { let self = this; /* istanbul ignore next */ return new Promise(function (fulfill, reject) { if (typeof func == "function") { self.afterAuth.push(func.bind(self)); fulfill() } else { reject(new Error("Cant afterAuthenticate: not an function")); } }) } /** * Turn object to become property of ArrowApplication * @param {object} obj - object parameter */ addGlobal(obj) { /* istanbul ignore next */ return new Promise(function (fulfill, reject) { if (_.isObject(obj)) { _.assign(Arrow, obj); fulfill() } else { reject(new Error("Cant addGlobal: not an Object")); } }); } /** * Add plugin function to ArrowApplication.plugins, bind this plugin function to ArrowApplication object * @param {function} plugin - plugin function * <p><a target="_blank" href="http://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/">See more about bind</a></p> */ addPlugin(plugin) { let self = this; /* istanbul ignore next */ return new Promise(function (fulfill, reject) { if (_.isFunction(plugin)) { self.plugins.push(plugin.bind(self)); fulfill() } else { reject(new Error("Cant addPlugin: not an Function")); } }) } /** * Kick start express application and listen at default port * @param {object} setting - {passport: boolean, role: boolean} */ start(setting) { let self = this; self.arrowSettings = setting; let stackBegin; return Promise.resolve() .then(function connectRedis() { //Redis connection let redisConfig = self._config.redis || {}; return RedisCache(redisConfig); }) .then(function (redisFunction) { //Make redis cache /* istanbul ignore next */ let redisConfig = self._config.redis || {}; let redisClient = redisFunction(redisConfig); let redisSubscriber = redisFunction.bind(null, redisConfig); self.redisClient = redisClient; self.redisSubscriber = redisSubscriber; }) .then(function connectDatabase() { return require('./database').connectDB(self) }) .then(function setupManager() { //Share eventEmitter among all kinds of Managers. This helps Manager object notifies each other //when configuration is changed eventEmitter = new EventEmitter(); self.configManager = new ConfigManager(self, "config"); //subscribes to get notification from shared eventEmitter object self.configManager.eventHook(eventEmitter); //Create shortcut call self.addConfig = addConfig.bind(self); self.addConfigFile = addConfigFile.bind(self); self.getConfig = self.configManager.getConfig.bind(self.configManager); self.setConfig = self.configManager.setConfig.bind(self.configManager); self.updateConfig = self.configManager.updateConfig.bind(self.configManager); //_componentList contains name property of composite features, singleton features, widgets, plugins self._componentList = []; Object.keys(self.structure).map(function (managerKey) { let key = managerKey; let managerName = managerKey + "Manager"; self[managerName] = new DefaultManager(self, key); self[managerName].eventHook(eventEmitter); //load sub components of self[managerName].loadComponents(key); self[key] = self[managerName]["_" + key]; self._componentList.push(key); }.bind(self)); }) .then(function configRenderLayout() { let viewEngineSetting = _.assign(self._config.nunjuckSettings || {}, {express: self._expressApplication}); let applicationView = ViewEngine(self.arrFolder, viewEngineSetting, self); self.applicationENV = applicationView; self.render = function (view, options, callback) { let application = self; var done = callback; var opts = options || {}; /* istanbul ignore else */ if (typeof options === "function") { done = options; opts = {}; } _.assign(opts, application.locals); if (application._config.viewExtension && view.indexOf(application._config.viewExtension) === -1 && view.indexOf(".") === -1) { view += "." + application._config.viewExtension; } let arrayPart = view.split(path.sep); arrayPart = arrayPart.map(function (key) { if (key[0] === ":") { key = key.replace(":", ""); return application.getConfig(key); } else { return key } }); let newLink = arrayPart.join(path.sep); newLink = path.normalize(application.arrFolder + newLink); application.applicationENV.loaders[0].pathsToNames = {}; application.applicationENV.loaders[0].cache = {}; application.applicationENV.loaders[0].searchPaths = [path.dirname(newLink) + path.sep]; return application.applicationENV.render(newLink, opts, done); }.bind(self); self.renderString = applicationView.renderString.bind(applicationView); }) .then(function () { let resolve = Promise.resolve(); self.plugins.map(function (plug) { resolve = resolve.then(function () { return plug() }) }); return resolve }) .then(function () { addRoles(self); if (self.getConfig("redis.type") !== "fakeredis") { let resolve = self.configManager.getCache(); self._componentList.map(function (key) { let managerName = key + "Manager"; resolve = resolve.then(function () { return self[managerName].getCache() }) }); return resolve } else { return Promise.resolve(); } }) .then(function () { //init Express app return configureExpressApp(self, self.getConfig(), setting) }) .then(function () { return associateModels(self); }) .then(function () { return circuit_breaker(self) }) .then(function () { if (setting && setting.order) { stackBegin = self._router.stack.length; } return loadRoute_Render(self, setting); }) .then(function () { if (setting && setting.order) { let coreRoute = self._router.stack.slice(0, stackBegin); let newRoute = self._router.stack.slice(stackBegin); newRoute = newRoute.sort(function (a, b) { if (a.handle.order) { if (b.handle.order) { if (a.handle.order > b.handle.order) { return 1 } else if (a.handle.order < b.handle.order) { return -1 } else { return 0 } } else { return 0 } } else { if (b.handle.order) { return 1 } else { return 0 } } }); coreRoute = coreRoute.concat(newRoute); self._router.stack = coreRoute } return handleError(self) }) .then(function () { return http.createServer(self.expressApp); }) .then(function (server) { self.httpServer = server; if (self.getConfig('websocket_enable') && self.getConfig('websocket_folder')) { let io = socket_io(server); if (self.getConfig('redis.type') !== 'fakeredis') { let redisConf = {host: self.getConfig('redis.host'), port: self.getConfig('redis.port')}; io.adapter(socketRedisAdapter(redisConf)); } self.io = io; __.getGlobbedFiles(path.normalize(self.arrFolder + self.getConfig('websocket_folder'))).map(function (link) { let socketFunction = require(link); /* istanbul ignore else */ if (_.isFunction(socketFunction)) { socketFunction(io); } }) } server.listen(self.getConfig("port"), function () { logger.info('Application loaded using the "' + process.env.NODE_ENV + '" environment configuration'); logger.info('Application started on port ' + self.getConfig("port"), ', Process ID: ' + process.pid); }); /* istanbul ignore next */ }) .catch(function (err) { logger.error(err) }); } close() { var self = this; return new Promise(function (fulfill, reject) { /* istanbul ignore else */ if (self.httpServer) { self.httpServer.close(function (err) { /* istanbul ignore if */ if (err) { reject(err) } else { fulfill(self.httpServer) } }) } else { fulfill(self.httpServer) } }) } } /** * Associate all models that are loaded into ArrowApplication.models. Associate logic defined in /config/database.js * @param {ArrowApplication} arrow * @return {ArrowApplication} arrow */ function associateModels(arrow) { let defaultDatabase = require('./database').db(); if (arrow.models && Object.keys(arrow.models).length > 0) { /* istanbul ignore next */ let defaultQueryResolve = function () { return new Promise(function (fulfill, reject) { fulfill("No models") }) }; //Load model associate rules defined in /config/database.js let databaseFunction = require(arrow.arrFolder + "config/database"); Object.keys(arrow.models).forEach(function (modelName) { if ("associate" in arrow.models[modelName]) { arrow.models[modelName].associate(arrow.models); } }); /* istanbul ignore else */ if (databaseFunction.associate) { let resolve = Promise.resolve(); resolve.then(function () { //Execute models associate logic in /config/database.js return databaseFunction.associate(arrow.models) }).then(function () { defaultDatabase.sync(); //Sequelize.sync: sync all defined models to the DB. }) } //Assign raw query function of Sequelize to arrow.models object //See Sequelize raw query http://docs.sequelizejs.com/en/latest/docs/raw-queries/ /* istanbul ignore next */ if (defaultDatabase.query) { arrow.models.rawQuery = defaultDatabase.query.bind(defaultDatabase); _.merge(arrow.models, defaultDatabase); } else { arrow.models.rawQuery = defaultQueryResolve; } } return arrow } /** * load feature's routes and render * @param {ArrowApplication } arrow * @param {object} userSetting */ function loadRoute_Render(arrow, userSetting) { arrow._componentList.map(function (key) { Object.keys(arrow[key]).map(function (componentKey) { /** display loaded feature in console log when booting Arrowjs application */ logger.info("Arrow loaded: '" + key + "' - '" + componentKey + "'"); let routeConfig = arrow[key][componentKey]._structure.route; if (routeConfig) { Object.keys(routeConfig.path).map(function (second_key) { let defaultRouteConfig = routeConfig.path[second_key]; if (arrow[key][componentKey].routes[second_key]) { let componentRouteSetting = arrow[key][componentKey].routes[second_key]; handleComponentRouteSetting(arrow, componentRouteSetting, defaultRouteConfig, key, userSetting, componentKey); } else { let componentRouteSetting = arrow[key][componentKey].routes; //Handle Route Path; handleComponentRouteSetting(arrow, componentRouteSetting, defaultRouteConfig, key, userSetting, componentKey); } }); } }) }); return arrow; } /** * Run /config/express.js to configure Express object * @param app - ArrowApplication object * @param config - this.configManager.getConfig * @param setting - parameters in application.start(setting); */ function configureExpressApp(app, config, setting) { return new Promise(function (fulfill, reject) { let expressFunction; /* istanbul ignore else */ if (fs.existsSync(path.resolve(app.arrFolder + "config/express.js"))) { expressFunction = require(app.arrFolder + "config/express"); } else { reject(new Error("Cant find express.js in folder config")) } fulfill(expressFunction(app, config, setting)); }); } /** * * @param arrow * @param componentRouteSetting * @param defaultRouteConfig * @param key * @param setting * @param componentKey */ function handleComponentRouteSetting(arrow, componentRouteSetting, defaultRouteConfig, key, setting, componentKey) { let component = arrow[key][componentKey]; let componentName = arrow[key][componentKey].name; let viewInfo = arrow[key][componentKey].views; //Handle Route Path; let route = express.Router(); route.componentName = componentName; Object.keys(componentRouteSetting).map(function (path_name) { //Check path_name /* istanbul ignore next */ let routePath = path_name[0] === "/" ? path_name : "/" + componentName + "/" + path_name; //handle prefix /* istanbul ignore if */ if (defaultRouteConfig.prefix && defaultRouteConfig.prefix[0] !== "/") { defaultRouteConfig.prefix = "/" + defaultRouteConfig.prefix } let prefix = defaultRouteConfig.prefix || "/"; let arrayMethod = Object.keys(componentRouteSetting[path_name]).filter(function (method) { if (componentRouteSetting[path_name][method].name) { arrow._arrRoutes[componentRouteSetting[path_name][method].name] = path.normalize(prefix + routePath); } //handle function let routeHandler; componentRouteSetting[path_name][method].handler = componentRouteSetting[path_name][method].handler || function (req, res, next) { next(new Error("Cant find controller")); }; routeHandler = componentRouteSetting[path_name][method].handler; let authenticate = componentRouteSetting[path_name][method].authenticate !== undefined ? componentRouteSetting[path_name][method].authenticate : defaultRouteConfig.authenticate; let arrayHandler = []; if (arrayHandler && _.isArray(routeHandler)) { arrayHandler = routeHandler.filter(function (func) { if (_.isFunction(func)) { return func } }); } else if (_.isFunction(routeHandler)) { arrayHandler.push(routeHandler) } else if (!_.isString(authenticate)) { return } //Add viewRender if (!_.isEmpty(viewInfo) && !_.isString(authenticate)) { arrayHandler.splice(0, 0, overrideViewRender(arrow, viewInfo, componentName, component, key)) } //handle role if (setting && setting.role) { let permissions = componentRouteSetting[path_name][method].permissions; if (permissions && !_.isString(authenticate)) { arrayHandler.splice(0, 0, arrow.passportSetting.handlePermission); arrayHandler.splice(0, 0, handleRole(arrow, permissions, componentName, key)) } } //add middleware after authenticate; if (!_.isEmpty(arrow.afterAuth)) { arrow.afterAuth.map(function (func) { arrayHandler.splice(0, 0, func) }) } //handle Authenticate if (setting && setting.passport) { if (authenticate) { arrayHandler.splice(0, 0, handleAuthenticate(arrow, authenticate)) } } //add middleware before authenticate; if (!_.isEmpty(arrow.beforeAuth)) { arrow.beforeAuth.map(function (func) { arrayHandler.splice(0, 0, func) }) } //Add to route if (method === "param") { if (_.isString(componentRouteSetting[path_name][method].key) && !_.isArray(componentRouteSetting[path_name][method].handler)) { return route.param(componentRouteSetting[path_name][method].key, componentRouteSetting[path_name][method].handler); } } else if (method === 'all') { return route.route(routePath) [method](arrayHandler); } else if (route[method] && ['route', 'use'].indexOf(method) === -1) { if (componentRouteSetting[path_name][method].order) { let newRoute = express.Router(); newRoute.componentName = componentName; newRoute.order = componentRouteSetting[path_name][method].order; newRoute.route(routePath) [method](arrayHandler); arrow.use(prefix, newRoute) } return route.route(routePath) [method](arrayHandler) } }); !_.isEmpty(arrayMethod) && arrow.use(prefix, route); }); return arrow } /** * * @param application * @param componentView * @param componentName * @param component * @returns {Function} */ function overrideViewRender(application, componentView, componentName, component, key) { return function (req, res, next) { // Grab reference of render req.arrowUrl = key + "." + componentName; let _render = res.render; let self = this; if (_.isArray(componentView)) { res.render = makeRender(req, res, application, componentView, componentName, component); } else { Object.keys(componentView).map(function (key) { res[key] = res[key] || {}; res[key].render = makeRender(req, res, application, componentView[key], componentName, component[key]); }); res.render = res[Object.keys(componentView)[0]].render } next(); } } /** * * @param req * @param res * @param application * @param componentView * @param componentName * @param component * @returns {Function} */ function makeRender(req, res, application, componentView, componentName, component) { return function (view, options, callback) { var done = callback; var opts = {}; //remove flash message delete req.session.flash; // merge res.locals _.assign(opts, application.locals); _.assign(opts, res.locals); // support callback function as second arg /* istanbul ignore if */ if (typeof options === 'function') { done = options; } else { _.assign(opts, options); } // default callback to respond done = done || function (err, str) { if (err) return req.next(err); res.send(str); }; if (application._config.viewExtension && view.indexOf(application._config.viewExtension) === -1 && view.indexOf(".") === -1) { view += "." + application._config.viewExtension; } component.viewEngine.loaders[0].pathsToNames = {}; component.viewEngine.loaders[0].cache = {}; component.viewEngine.loaders[0].searchPaths = componentView.map(function (obj) { return handleView(obj, application, componentName); }); component.viewEngine.render(view, opts, done); }; } /** * * @param obj * @param application * @param componentName * @returns {*} */ function handleView(obj, application, componentName) { let miniPath = obj.func(application._config, componentName); let normalizePath; /* istanbul ignore if */ if (miniPath[0] === path.sep) { normalizePath = path.normalize(obj.base + path.sep + miniPath); } else { normalizePath = path.normalize(obj.fatherBase + path.sep + miniPath) } return normalizePath } /* istanbul ignore next */ function handleAuthenticate(application, name) { let passport = application.passport; if (_.isString(name)) { if (application.passportSetting[name]) { let strategy = application.passportSetting[name].strategy || name; let callback = application.passportSetting[name].callback; let option = application.passportSetting[name].option || {}; if (callback) return passport.authenticate(strategy, option, callback); return passport.authenticate(strategy, option); } } else if (_.isBoolean(name)) { if (application.passportSetting.checkAuthenticate && _.isFunction(application.passportSetting.checkAuthenticate)) { return application.passportSetting.checkAuthenticate } } return function (req, res, next) { next() } } /** * * @param application * @param permissions * @param componentName * @param key * @returns {handleRoles} */ /* istanbul ignore next */ function handleRole(application, permissions, componentName, key) { let arrayPermissions = []; if (_.isArray(permissions)) { arrayPermissions = permissions } else { arrayPermissions.push(permissions); } return function handleRoles(req, res, next) { req.permissions = req.session.permissions; if (req.permissions && req.permissions[key] && req.permissions[key][componentName]) { let checkedPermission = req.permissions[key][componentName].filter(function (key) { if (arrayPermissions.indexOf(key.name) > -1) { return key } }).map(function (data) { return data.name }); if (!_.isEmpty(checkedPermission)) { req.permissions = checkedPermission; req.hasPermission = true } } else { req.hasPermission = false; } next(); } } /** * Load global functions then append to global.ArrowHelper * bind global function to ArrowApplication object so dev can this keyword in that function to refer * ArrowApplication object * @param self: ArrowApplication object */ function loadingGlobalFunction(self) { global.ArrowHelper = {}; __.getGlobbedFiles(path.resolve(__dirname, "..", "helpers/*.js")).map(function (link) { let arrowObj = require(link); Object.keys(arrowObj).map(function (key) { /* istanbul ignore else */ if (_.isFunction(arrowObj[key])) { ArrowHelper[key] = arrowObj[key].bind(self) } else { ArrowHelper[key] = arrowObj[key] } }) }); __.getGlobbedFiles(path.normalize(__base + self._config.ArrowHelper + "*.js")).map(function (link) { let arrowObj = require(link); Object.keys(arrowObj).map(function (key) { if (_.isFunction(arrowObj[key])) { ArrowHelper[key] = arrowObj[key].bind(self) } else { ArrowHelper[key] = arrowObj[key] } }) }); //Add some support function global.__ = ArrowHelper.__; return self } function addRoles(self) { self.permissions = {}; self._componentList.map(function (key) { let managerName = key + "Manager"; self.permissions[key] = self[managerName].getPermissions(); }); return self } /** * Redirect url when meet same error. * @param app * @returns {*} */ function circuit_breaker(app) { if (app.getConfig('fault_tolerant.enable')) { app.use(function (req, res, next) { if (app.arrowErrorLink[req.url]) { let redirectLink = app.getConfig('fault_tolerant.redirect'); redirectLink = _.isString(redirectLink) ? redirectLink : "404"; res.redirect(path.normalize(path.sep + redirectLink)); } else { next(); } }) } return app } /** * Handle Error and redirect error * @param app */ /* istanbul ignore next */ function handleError(app) { /** Assume 'not found' in the error msg is a 404. * This is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. */ app.use(function (err, req, res, next) { // If the error object doesn't exists let error = {}; if (!err) return next(); if (app.getConfig('fault_tolerant.enable')) { app.arrowErrorLink[req.url] = true; error[req.url] = {}; error[req.url].error = err.stack; error[req.url].time = Date.now(); let arrayInfo = app.getConfig('fault_tolerant.logdata'); if (_.isArray(arrayInfo)) { arrayInfo.map(function (key) { error[req.url][key] = req[key]; }) } } else { error.error = err.stack; error.time = Date.now(); let arrayInfo = app.getConfig('fault_tolerant.logdata'); if (_.isArray(arrayInfo)) { arrayInfo.map(function (key) { error[key] = req[key]; }) } } if (app.getConfig('fault_tolerant.log')) { logger.error(error); } let renderSetting = app.getConfig('fault_tolerant.render'); if (_.isString(renderSetting)) { let arrayPart = renderSetting.split(path.sep); arrayPart = arrayPart.map(function (key) { if (key[0] === ":") { key = key.replace(":", ""); return app.getConfig(key); } else { return key } }); let link = arrayPart.join(path.sep); app.render(path.normalize(app.arrFolder + link), {error: error}, function (err, html) { if (err) { res.send(err) } else { res.send(html) } }); } else { res.send(error) } }); if (app.getConfig("error")) { Object.keys(app.getConfig("error")).map(function (link) { let errorConfig = app.getConfig("error"); if (errorConfig[link].render) { if (_.isString(errorConfig[link].render)) { app.get(path.normalize(path.sep + link + `(.html)?`), function (req, res) { app.render(errorConfig[link].render, function (err, html) { if (err) { res.send(err.toString()) } else { res.send(html) } }); }) } else if (_.isObject(errorConfig[link].render)) { app.get(link, function (req, res) { res.send(errorConfig[link].render) }) } else if (_.isNumber(errorConfig[link].render)) { app.get(link, function (req, res) { res.sendStatus(errorConfig[link].render) }) } else { app.get(link, function (req, res) { res.send(link) }) } } }) } if (app.getConfig("error")) { Object.keys(app.getConfig("error")).map(function (link) { let errorConfig = app.getConfig("error"); if (errorConfig[link] && errorConfig[link].prefix) { app.use(errorConfig[link].prefix, function (req, res) { res.redirect(path.normalize(path.sep + link)) }) } }) } app.use("*", function (req, res) { let h = req.header("Accept"); try { if (h.indexOf('text/html') > -1) { res.redirect('/404'); } else { res.sendStatus(404); } } catch (err) { res.sendStatus(404); } }); return app } function getDataByDotNotation(obj, key) { if (_.isString(key)) { if (key.indexOf(".") > 0) { let arrayKey = key.split("."); let self = obj; let result; arrayKey.map(function (name) { if (self[name]) { result = self[name]; self = result; } else { result = null } }); return result } else { return obj[key]; } } else { return null } } /* istanbul ignore next */ function loadSetting(des, source) { let baseFolder = this.arrFolder; let setting = {}; let filePath = path.normalize(baseFolder + des); try { fs.accessSync(filePath); _.assign(setting, require(filePath)); } catch (err) { if (err.code === 'ENOENT') { fsExtra.copySync(path.resolve(source), filePath); _.assign(setting, require(filePath)); } else { throw err } } return setting; } function addConfig(obj) { let config = this._config; if (_.isObject(obj)) { _.assign(config, obj); } } /* istanbul ignore next */ function addConfigFile(filename) { let app = this; let configFile = path.normalize(app.arrFolder + "/" + filename); fs.readFile(configFile, 'utf8', function (err, data) { if (err) throw err; let obj = JSON.parse(data); app.updateConfig(obj); }); fs.watch(configFile, function (event, filename) { if (event === "change") { fs.readFile(configFile, 'utf8', function (err, data) { if (err) throw err; let obj = JSON.parse(data); app.updateConfig(obj); }); } }) } module.exports = ArrowApplication;
arrowjs/ArrowjsCore
libs/ArrowApplication.js
JavaScript
mit
38,892
/*global describe, beforeEach, it*/ 'use strict'; var assert = require('assert'); describe('mean-app generator', function () { it('can be imported without blowing up', function () { var app = require('../app'); assert(app !== undefined); }); });
toyamarinyon/generator-mean-app
test/test-load.js
JavaScript
mit
272
/* eslint-disable react/jsx-filename-extension, no-unused-expressions, func-names, prefer-arrow-callback */ import { Meteor } from 'meteor/meteor'; if (Meteor.isClient) { import React from 'react'; import faker from 'faker'; import { shallow } from 'enzyme'; import { chai } from 'meteor/practicalmeteor:chai'; import { sinon } from 'meteor/practicalmeteor:sinon'; import { JustifiedGroupLayout } from './index'; import { Title } from './GroupLayout.style'; const expect = chai.expect; const generateImages = (len) => { const images = []; for (let i = 0; i < len; i += 1) { images[i] = { user: faker.internet.userName(), collection: faker.random.word(), name: faker.random.uuid(), type: 'jpg', dimension: [1280, 1280], }; } return images; }; const setup = (group = {}, counter = 0) => { const actions = { selectCounter: sinon.spy(), selectGroupCounter: sinon.spy(), photoSwipeOpen: sinon.spy(), }; const component = shallow( <JustifiedGroupLayout isEditing groupName="2016-12-31" groupImages={generateImages(4)} total={6} groupTotal={4} group={group} counter={counter} {...actions} />, ); const anotherComponent = shallow( <JustifiedGroupLayout isEditing groupName="2016-12-30" groupImages={generateImages(2)} total={6} groupTotal={2} group={group} counter={counter} {...actions} />, ); return { actions, component, anotherComponent, }; }; describe('GroupLayout', () => { it('should isGroupSelect state behave right when counter change', () => { const { component } = setup(); component.setProps({ counter: 6 }); expect(component.state('isGroupSelect')).to.equal(true, 'When counter prop equal total prop'); component.setProps({ counter: 0 }); expect(component.state('isGroupSelect')).to.equal(false, 'When counter prop is 0'); }); it('should isGroupSelect state behave right when group\'s key change', () => { const { component, anotherComponent } = setup(); expect(component.state('isGroupSelect')) .to.equal(false, 'When group prop is {} -- empty Object'); component.setProps({ group: { '2016-12-31': 4 }, counter: 4 }); anotherComponent.setProps({ group: { '2016-12-31': 4 }, counter: 4 }); expect(component.state('isGroupSelect')).to.equal(true, '当前组需要高亮当只有当前组被全选时'); expect(anotherComponent.state('isGroupSelect')).to.equal(false, '其他组不能高亮当其他组没有被全选时'); component.setProps({ group: { '2016-12-30': 2 }, counter: 2 }); anotherComponent.setProps({ group: { '2016-12-30': 2 }, counter: 2 }); expect(anotherComponent.state('isGroupSelect')).to.equal(true, '其他组需要高亮当只有其他组被全选时'); expect(component.state('isGroupSelect')).to.equal(false, '当前组不能高亮当当前组没有被全选时'); }); it('should isGroupSelect state behave right when group\'s value change', () => { const { component, anotherComponent } = setup(); expect(anotherComponent.state('isGroupSelect')) .to.equal(false, 'Initial isGroupSelect state must be false'); component.setProps({ group: { '2016-12-31': 4, '2016-12-30': 2 }, counter: 6 }); anotherComponent.setProps({ group: { '2016-12-31': 4, '2016-12-30': 2 }, counter: 6 }); expect(component.state('isGroupSelect')).to.equal(true, '当前组被选中且所有图片都被选中时'); expect(anotherComponent.state('isGroupSelect')).to.equal(true, '其他组被选中且所有图片都被选中时'); component.setProps({ group: { '2016-12-31': 3, '2016-12-30': 2 }, counter: 2 }); anotherComponent.setProps({ group: { '2016-12-31': 3, '2016-12-30': 2 }, counter: 2 }); expect(component.state('isGroupSelect')).to.equal(false, '当前组有图片被选中但没有被全选时'); expect(anotherComponent.state('isGroupSelect')).to.equal(true, '当group属性更改但当前组仍全选时'); component.setProps({ group: { '2016-12-31': 4 }, counter: 4 }); expect(component.state('isGroupSelect')).to.equal(true, '只有当前组被全选时'); }); it('should have toggle button dispatch selectGroupCounter action', () => { const { actions, component } = setup(); const props = component.instance().props; const toggleBtn = component.find(Title); expect(toggleBtn).to.have.length(1); toggleBtn.simulate('touchTap'); sinon.assert.calledWith(actions.selectGroupCounter, { selectImages: props.groupImages, group: props.groupName, counter: props.groupTotal, }); // have to set it by self without redux mock store component.setState({ isGroupSelect: true }); toggleBtn.simulate('touchTap'); sinon.assert.calledWith(actions.selectGroupCounter, { selectImages: props.groupImages, group: props.groupName, counter: -props.groupTotal, }); }); }); }
ShinyLeee/meteor-album-app
imports/ui/components/JustifiedLayout/components/GroupLayout/GroupLayout.spec.js
JavaScript
mit
5,244
var classCSF_1_1Zpt_1_1SourceAnnotation_1_1SourceInfoTidyUpVisitor = [ [ "VisitContext", "classCSF_1_1Zpt_1_1SourceAnnotation_1_1SourceInfoTidyUpVisitor.html#aec5a924d9ecc9a438168b0ba77cb2386", null ] ];
csf-dev/ZPT-Sharp
docs/_legacy/v1.x/api/classCSF_1_1Zpt_1_1SourceAnnotation_1_1SourceInfoTidyUpVisitor.js
JavaScript
mit
207
const NeDB = require('nedb'); const path = require('path'); module.exports = function (app) { const dbPath = app.get('nedb'); const Model = new NeDB({ filename: path.join(dbPath, 'articles.db'), autoload: true }); return Model; };
NathanLc/my-news
src/models/articles.model.js
JavaScript
mit
249
search_result['943']=["topic_000000000000021C.html","RecruitmentPlanningController.GetData Method",""];
asiboro/asiboro.github.io
vsdoc/search--/s_943.js
JavaScript
mit
103
// Protractor configuration // https://github.com/angular/protractor/blob/master/referenceConf.js 'use strict'; exports.config = { // The timeout for each script run on the browser. This should be longer // than the maximum time your application needs to stabilize between tasks. allScriptsTimeout: 110000, // A base URL for your application under test. Calls to protractor.get() // with relative paths will be prepended with this. baseUrl: 'http://localhost:' + ( process.env.PORT || '9000' ), // If true, only chromedriver will be started, not a standalone selenium. // Tests for browsers other than chrome will not run. directConnect: true, // list of files / patterns to load in the browser // specs: [ // 'e2e/**/*.spec.js' // ], suites: { Login: 'e2e/Login/**/*.spec.js', Dashboard: 'e2e/Dashboard/**/*.spec.js', Accounts: 'e2e/Accounts/**/*.spec.js', Transfer: 'e2e/Transfer/**/*spec.js', Payment: 'e2e/Payment/**/*.spec.js', BillerPayment: 'e2e/BillerPayment/**/*.spec.js', Biller: 'e2e/Biller/**/*.spec.js', Beneficiary: 'e2e/Beneficiary/**/*.spec.js', BeneficiaryGroups: 'e2e/BeneficiaryGroups/**/*.spec.js', BillerGroups: 'e2e/BillerGroups/**/*.spec.js', Signout: 'e2e/Signout/**/*.spec.js', BuyAirtime: 'e2e/BuyAirtime/**/*.spec.js', Redeem: 'e2e/Redeem/**/*.spec.js', Registration: 'e2e/Registration/**/*.spec.js', InternationalPayment: 'e2e/InternationalPayment/**/*.spec.js', ProfilesAndSettings: 'e2e/ProfilesAndSettings/**/*.spec.js', RemitaPayment: 'e2e/RemitaPayments/**/*.spec.js', ServiceRequest: 'e2e/ServiceRequest/**/*.spec.js', Receipts: 'e2e/Receipts/**/*.spec.js', ScheduledTransaction: 'e2e/ScheduledTransaction/**/*.spec.js', KongaPayment: 'e2e/KongaPayment/**/*.spec.js', MobileWalletPayment: 'e2e/MobileWalletPayment/**/*.spec.js', MobileWallet: 'e2e/MobileWallet/**/*.spec.js', MobileWalletGroups: 'e2e/MobileWalletGroups/**/*.spec.js' }, // Patterns to exclude. exclude: [], onPrepare: function() { browser.driver.manage().window().setSize( 1366, 1000 ); // The require statement must be down here, since jasmine-reporters // needs jasmine to be in the global and protractor does not guarantee // this until inside the onPrepare function. require( './node_modules/jasmine-reporters' ); jasmine.getEnv().addReporter( new jasmine.JUnitXmlReporter( "test_results/functional", true, true ) ); }, // ----- Capabilities to be passed to the webdriver instance ---- // // For a full list of available capabilities, see // https://code.google.com/p/selenium/wiki/DesiredCapabilities // and // https://code.google.com/p/selenium/source/browse/javascript/webdriver/capabilities.js capabilities: { 'browserName': 'chrome' }, // multiCapabilities: [ // { // 'browserName': 'firefox' // }, // { // 'browserName': 'chrome' // }], // ----- The test framework ----- // // Jasmine and Cucumber are fully supported as a test and assertion framework. // Mocha has limited beta support. You will need to include your own // assertion framework if working with mocha. framework: 'jasmine2', // ----- Options to be passed to minijasminenode ----- // // See the full list at https://github.com/juliemr/minijasminenode jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };
lawrencepn/mcc
protractor.conf.js
JavaScript
mit
3,650
var searchData= [ ['server',['Server',['../class_server.html',1,'']]], ['setupconnection',['SetupConnection',['../class_setup_connection.html',1,'']]] ];
dawidd6/qtictactoe
docs/search/classes_5.js
JavaScript
mit
158
import {Locale} from "../../../locale/LocaleManager.js"; import {ChangeAction} from "../../../history/action/ChangeAction.js"; import {Editor} from "../../../Editor.js"; import {Slider} from "../../../components/input/Slider.js"; import {NumberBox} from "../../../components/input/NumberBox.js"; import {CheckBox} from "../../../components/input/CheckBox.js"; import {TextureEditor} from "./TextureEditor.js"; function VideoTextureEditor(parent, closeable, container, index) { TextureEditor.call(this, parent, closeable, container, index); var self = this; // Volume this.form.addText(Locale.volume); this.volume = new Slider(this.form); this.volume.size.set(80, 18); this.volume.setRange(0, 1); this.volume.setStep(0.01); this.volume.setOnChange(function() { self.texture.setVolume(self.volume.getValue()); }); this.form.add(this.volume); this.form.nextRow(); // Playback Rate this.form.addText("Playback Rate"); this.playbackRate = new NumberBox(this.form); this.playbackRate.size.set(60, 18); this.playbackRate.setStep(0.1); this.playbackRate.setRange(0, Number.MAX_SAFE_INTEGER); this.playbackRate.setOnChange(function() { self.texture.setPlaybackRate(self.playbackRate.getValue()); }); this.form.add(this.playbackRate); this.form.nextRow(); // Autoplay this.autoplay = new CheckBox(this.form); this.form.addText("Autoplay"); this.autoplay.size.set(18, 18); this.autoplay.setOnChange(function() { Editor.addAction(new ChangeAction(self.texture, "autoplay", self.autoplay.getValue())); }); this.form.add(this.autoplay); this.form.nextRow(); // Loop this.loop = new CheckBox(this.form); this.form.addText(Locale.loop); this.loop.size.set(18, 18); this.loop.setOnChange(function() { self.texture.setLoop(self.loop.getValue()); }); this.form.add(this.loop); this.form.nextRow(); } VideoTextureEditor.prototype = Object.create(TextureEditor.prototype); VideoTextureEditor.prototype.attach = function(texture) { TextureEditor.prototype.attach.call(this, texture); this.volume.setValue(this.texture.volume); this.autoplay.setValue(this.texture.autoplay); this.loop.setValue(this.texture.loop); this.playbackRate.setValue(this.texture.playbackRate); }; export {VideoTextureEditor};
tentone/nunuStudio
source/editor/gui/tab/texture/VideoTextureEditor.js
JavaScript
mit
2,318
'use strict'; var util = require('util'); var Pseudonym = require('../lib/pseudonym.min'); console.log('pseudonym', util.inspect(Pseudonym, { showHidden: true, depth: null })); var Person = Pseudonym({ firstName: 'f', lastName: 'l' }); function Employee() { Person.apply(this, arguments); } Person.extend(Employee); Employee.fieldMap.add('company', 'c'); Employee.prototype.serialize = function () { var str = 'Hi, my name is ' + this.firstName + ' ' + this.lastName + '.\n'; str += 'I work at ' + this.company + '.'; return str; }; describe('Base class', function () { it('should create a person instance', function (done) { var person = new Person(); person.firstName = 'John'; person.lastName = 'Smith'; console.log(person.serialize()); done(); }); it('should create a person instance 2', function (done) { var person = new Person({ f: 'John', l: 'Smith' }, true); console.log(person.serialize()); done(); }); it('should create an employee instance', function (done) { var employee = new Employee(); employee.firstName = 'John'; employee.lastName = 'Smith'; employee.company = 'Acme'; console.log(employee.serialize()); done(); }); it('should create an employee instance 2', function (done) { var employee = new Employee({ f: 'John', l: 'Smith', c: 'Acme' }, true); console.log(employee.serialize()); done(); }); });
frisb/pseudonym
test/test.js
JavaScript
mit
1,409
export default (options, extOptions) => { /* eslint-disable no-unused-vars */ let { test, Vue, snapshot, component, name, formValue1, formValue2, formValueInvalid1, formValueInvalid2, attrs, uiid, delVmEl, _baseTestHookCustomMount, _formValueChangeSkipInvalidValueEmitTest, _formValueChangeSkipValueFilterEmitTest } = options; /* eslint-enable no-unused-vars */ test.serial('slot is dynamic', async t => { let vm = new Vue({ template : ` <ui-${name}> <div ${attrs} v-for="scope in scopes"> CONTENT : {{scope.name}} </div> </ui-${name}> `, data : { scopes : [{ name : 'first' }, { name : 'second' }, { name : 'third' }] }, components : { [`ui-${name}`] : component } }); vm.$mount(); t.plan(extOptions.testNum); await new Promise(resolve => { Vue.nextTick(() => { extOptions.firstCheck(t, vm); vm.scopes = [{ name : '4th' }, { name : '5th' }]; resolve(); }); }); await new Promise(resolve => { vm.$children[0].$mount(); Vue.nextTick(() => { extOptions.secondCheck(t, vm); vm.scopes.pop(); vm.scopes.pop(); vm.scopes.push({ name : '6th' }); resolve(); }); }); await new Promise(resolve => { vm.$children[0].$mount(); Vue.nextTick(() => { extOptions.thirdCheck(t, vm); resolve(); }); }); }); };
Morning-UI/morning-ui
test/common/unit/componentDynamicSlot.js
JavaScript
mit
2,037
'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _stylePropable = require('./mixins/style-propable'); var _stylePropable2 = _interopRequireDefault(_stylePropable); var _colors = require('./styles/colors'); var _colors2 = _interopRequireDefault(_colors); var _lightRawTheme = require('./styles/raw-themes/light-raw-theme'); var _lightRawTheme2 = _interopRequireDefault(_lightRawTheme); var _themeManager = require('./styles/theme-manager'); var _themeManager2 = _interopRequireDefault(_themeManager); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var Avatar = _react2.default.createClass({ displayName: 'Avatar', propTypes: { /** * The backgroundColor of the avatar. Does not apply to image avatars. */ backgroundColor: _react2.default.PropTypes.string, /** * Can be used, for instance, to render a letter inside the avatar. */ children: _react2.default.PropTypes.node, /** * The css class name of the root `div` or `img` element. */ className: _react2.default.PropTypes.string, /** * The icon or letter's color. */ color: _react2.default.PropTypes.string, /** * This is the SvgIcon or FontIcon to be used inside the avatar. */ icon: _react2.default.PropTypes.element, /** * This is the size of the avatar in pixels. */ size: _react2.default.PropTypes.number, /** * If passed in, this component will render an img element. Otherwise, a div will be rendered. */ src: _react2.default.PropTypes.string, /** * Override the inline-styles of the root element. */ style: _react2.default.PropTypes.object }, contextTypes: { muiTheme: _react2.default.PropTypes.object }, //for passing default theme context to children childContextTypes: { muiTheme: _react2.default.PropTypes.object }, mixins: [_stylePropable2.default], getDefaultProps: function getDefaultProps() { return { backgroundColor: _colors2.default.grey400, color: _colors2.default.white, size: 40 }; }, getInitialState: function getInitialState() { return { muiTheme: this.context.muiTheme ? this.context.muiTheme : _themeManager2.default.getMuiTheme(_lightRawTheme2.default) }; }, getChildContext: function getChildContext() { return { muiTheme: this.state.muiTheme }; }, //to update theme inside state whenever a new theme is passed down //from the parent / owner using context componentWillReceiveProps: function componentWillReceiveProps(nextProps, nextContext) { var newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme; this.setState({ muiTheme: newMuiTheme }); }, render: function render() { var _props = this.props; var backgroundColor = _props.backgroundColor; var color = _props.color; var icon = _props.icon; var size = _props.size; var src = _props.src; var style = _props.style; var className = _props.className; var other = _objectWithoutProperties(_props, ['backgroundColor', 'color', 'icon', 'size', 'src', 'style', 'className']); var styles = { root: { height: size, width: size, userSelect: 'none', borderRadius: '50%', display: 'inline-block' } }; if (src) { var borderColor = this.state.muiTheme.avatar.borderColor; if (borderColor) { styles.root = this.mergeStyles(styles.root, { height: size - 2, width: size - 2, border: 'solid 1px ' + borderColor }); } return _react2.default.createElement('img', _extends({}, other, { src: src, style: this.prepareStyles(styles.root, style), className: className })); } else { styles.root = this.mergeStyles(styles.root, { backgroundColor: backgroundColor, textAlign: 'center', lineHeight: size + 'px', fontSize: size / 2 + 4, color: color }); var styleIcon = { margin: 8 }; var iconElement = icon ? _react2.default.cloneElement(icon, { color: color, style: this.mergeStyles(styleIcon, icon.props.style) }) : null; return _react2.default.createElement( 'div', _extends({}, other, { style: this.prepareStyles(styles.root, style), className: className }), iconElement, this.props.children ); } } }); exports.default = Avatar; module.exports = exports['default'];
aykutyaman/meteor1.3-react-flowrouter-demo
node_modules/material-ui/lib/avatar.js
JavaScript
mit
5,210
angular .module('admin') .config(AdminConfig) .controller('AdminController', AdminController) .component('admin', { templateUrl:'components/admin/admin.template.html', controller: 'AdminController' }); function AdminController($firebaseObject, $firebaseArray){ var ctrl = this; ctrl.$onInit = function(){ console.log('admin component'); } } function AdminConfig($stateProvider){ var adminState = { name: 'admin', url: '/admin', component: 'admin' }; $stateProvider.state(adminState); }
krllus/vitrine-primavera
app/components/admin/admin.component.js
JavaScript
mit
552
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const DashboardPlugin = require('webpack-dashboard/plugin'); // const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const hotMiddlewareScript = 'webpack-hot-middleware/client'; const reactHotLoaderScript = 'react-hot-loader/patch'; module.exports = { entry: { bundle: [ hotMiddlewareScript, reactHotLoaderScript, './src/index.js', ], }, output: { filename: 'bundle.js', path: path.join(__dirname, 'public'), publicPath: '/', }, devtool: 'eval', module: { loaders: [ { test: /\.json$/, loader: 'json-loader', }, { test: /\.js$/, loaders: ['react-hot-loader/webpack', 'babel'], exclude: /node_modules/, }, { test: /\.scss$/, loader: 'style!css!sass', }, ], }, plugins: [ // new BundleAnalyzerPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new HtmlWebpackPlugin({ template: './src/template.html', filename: 'index.html', }), new DashboardPlugin(), ], };
Scya597/Caltcha
webpack.dev.config.js
JavaScript
mit
1,239
/*! * pool * https://github.com/Voliware/Util * Licensed under the MIT license. */ /** * Generic object pool for * limiting memory usage */ class Pool { /** * Constructor * @param {*} object - object to alloc in the pool * @returns {Pool} */ constructor(object) { this.object = object; this.totalAlloc = 0; this.totalFree = 0; this.pool = []; return this; } /** * Clear pool totalAlloc and totalFree * @returns {Pool} * @private */ _clearStats() { var inUse = this.totalAlloc - this.totalFree; this.totalAlloc = inUse || 0; this.totalFree = 0; return this; } /** * Allocate space in the pool * @returns {*} */ alloc() { var obj; if (this.pool.length === 0) { obj = new this.object; this.totalAlloc++; } else { obj = this.pool.pop(); this.totalFree--; } return obj; } /** * Free space in the pool by * returning an object to it * @param {*} obj * @returns {Pool} */ free(obj) { this.pool.push(obj); this.totalFree++; return this; } /** * Collect all objects in the pool * and clear current stats * @returns {Pool} */ collect() { this.pool = []; this._clearStats(); return this; } }
Voliware/WebUtil
src/js/pool.js
JavaScript
mit
1,201
// 一个账户及文件管理 var Account = { createNew: function (name) { var self = {}; // 账户名称 self.name = name; // 根文件树 id="" self.rootFile = Fileinfo.createNew("", "", ""); // 当前显示的文件树(实际显示的是file.children) self.curFile = self.rootFile; // 设置数据 // @param id 所属的文件号,如果是""则是根目录 // @param filelist 文件列表,已设置好的fileinfo列表 self.setData = function (id, filelist) { var target = self.searchFile(id, null); // 没有找到对应的文件,则无效 if (target == null) { console.log("no file id " + id); return; } // 要把之前的列表先清空 target.children = []; for (var i = 0; i < filelist.length; i++) { var file = filelist[i]; target.addChild(file); } } // 选择文件,显示其children self.selectFile = function (id) { self.curFile = self.searchFile(id, null); } // 通过id找到对应的文件 // @param file 要查找的文件树 null则是从根目录开始查 // @return 返回找到的文件树,没有找到返回null self.searchFile = function (id, file) { if (file == null) { file = self.rootFile; } if (id == file.id) { return file; } for (var i = 0; i < file.children.length; i++) { var f = file.children[i]; // 在子列表中查找 f1 = self.searchFile(id, f); if (f1 != null) { return f1; } } return null; } return self; } }
leitwolf/PiToolbox
html/js/c/account.js
JavaScript
mit
1,926
// setup ====================================================================== var express = require('express'), app = express(), mongoose = require('mongoose'), database = require('./config/database'), morgan = require('morgan'), bodyParser = require('body-parser'), methodOverride = require('method-override'), errorHandler = require('error-handler'), http = require('http'), path = require('path'); mongoose.connect(database.url); app.set('port', process.env.PORT || 8080); app.use(express.static(__dirname + '/public')); app.use(morgan('dev')); app.use(bodyParser.urlencoded({'extended':'true'})); app.use(bodyParser.json()); app.use(bodyParser.json({ type: 'application/vnd.api+json' })); app.use(methodOverride()); require('./app/routes')(app); http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });
nickollascoelho/bravi-schoolapp
server.js
JavaScript
mit
925
/** * Achievement API */ var url = require('url'); var battle = require('./region-host'); var helper = require('./helper'); var config = require('./config'); // Query data about an individual achievement. exports.getAchievementDataByLocale = function(locale, achievementID) { return helper.get(url.format({ protocol: config.protocol, host: battle.getHostByLocale(locale), pathname: config.pathPrefix.ACHIEVEMENT + achievementID, port: config.port })); };
zhongsp/wow-community-web-api-nodejs
lib/achievement.js
JavaScript
mit
481
'use strict' /*! * imports. */ var test = require('tape-catch') var path = require('path') /*! * imports (local). */ var autorun = require('./') /*! * default test file fixtures. */ var fixtures = [ { name: './test', file: 'root-test.test.js' }, { name: './lib', file: 'lib-sub-test.tests.js' }, { name: './app', file: 'tests.js' } ] /*! * autorun files. */ var autorunFiles = autorun().map(basename) /*! * tests. */ test('autorun() locates test files in default locations', function (t) { t.plan(fixtures.length) fixtures.forEach(function (f) { t.assert(exists(f.file), f.name) }) }) /*! * Whether file exists. * * @param {String} file * @return {Boolean} */ function exists (file) { return !!~autorunFiles.indexOf(file) } /*! * Return file's basename. * * @param {String} file * @return {String} */ function basename (file) { return path.basename(file) }
wilmoore/node-tape-runner
test.js
JavaScript
mit
912
// TODO reconsider the use of `fired` (spies are better I believe) describe('Class.EventEmitter', function () { var evtEmitter, fired; xit('should be defined on BaseClass', function () { expect(BaseClass.EventEmitter).toBeDefined(); }); beforeEach(function () { evtEmitter = new EventEmitter(); fired = 0; }); describe('on', function () { it('should allow you to add a listener to an event', function () { var context = {}; evtEmitter.on('event', function () { fired++; expect(this).toBe(context); }, context); evtEmitter.emit('event'); expect(fired).toBe(1); evtEmitter.emit('event'); expect(fired).toBe(2); }); it('should accept an object of events and listeners', function () { var context = {}; evtEmitter.on({ event1: function () { fired++; expect(this).toBe(context); }, event2: function () { fired++; expect(this).toBe(context); } }, context); evtEmitter.emit('event1'); expect(fired).toBe(1); evtEmitter.emit('event2'); expect(fired).toBe(2); evtEmitter.emit('event1'); evtEmitter.emit('event2'); expect(fired).toBe(4); }); }); describe('off', function () { it('should allow you to remove a listener to an event', function () { var context = {}, listener; evtEmitter.on('event', listener = function () { fired++; expect(this).toBe(context); }, context); evtEmitter.emit('event'); expect(fired).toBe(1); evtEmitter.off('event', listener); evtEmitter.emit('event'); expect(fired).toBe(1); }); }); describe('once', function () { it('should allow you to add a listener that will fire once', function () { var context = {}; evtEmitter.once('event', function () { fired++; expect(this).toBe(context); }, context); evtEmitter.emit('event'); expect(fired).toBe(1); evtEmitter.emit('event'); expect(fired).toBe(1); }); }); describe('emit', function () { it('should invoke any listener', function () { evtEmitter.on('event', function () { fired++; }); evtEmitter.emit('event'); expect(fired).toBe(1); }); it('should invoke a listener even if it gets removed in the current pass', function () { function toBeRemoved1() { fired++; } function toBeRemoved2() { fired++; } evtEmitter.on('event', function () { evtEmitter.off('event', toBeRemoved1); }); evtEmitter.on('event', toBeRemoved1); evtEmitter.on('event', toBeRemoved2); evtEmitter.on('event', function () { evtEmitter.off('event', toBeRemoved2); }); evtEmitter.emit('event'); expect(fired).toBe(2); evtEmitter.emit('event'); expect(fired).toBe(2); }) }); describe('removeAllListeners', function () { it('should allow you to remove all listener of an event', function () { var context = {}; function listener() { fired++; expect(this).toBe(context); } evtEmitter .on('event', listener, context) .on('event', listener, context); evtEmitter.emit('event'); expect(fired).toBe(2); evtEmitter.removeAllListeners('event'); evtEmitter.emit('event'); expect(fired).toBe(2); }); it('should allow you to remove all listeners', function () { var context = {}; function listener() { fired++; expect(this).toBe(context); } evtEmitter .on('event1', listener, context) .on('event2', listener, context); evtEmitter.emit('event1').emit('event2'); expect(fired).toBe(2); evtEmitter.removeAllListeners(); evtEmitter.emit('event1').emit('event2'); expect(fired).toBe(2); }); }); describe('aliases', function () { it('.addListener is an alias to .on', function () { expect(evtEmitter.addListener).toBe(evtEmitter.on); }); it('.removeListener is an alias to .off', function () { expect(evtEmitter.removeListener).toBe(evtEmitter.off); }); it('.trigger is an alias to .emit', function () { expect(evtEmitter.trigger).toBe(evtEmitter.emit); }); }); });
rodyhaddad/classicaljs
test/spec/EventEmitterSpec.js
JavaScript
mit
5,133
import fs from 'fs' import path from 'path' import logo from './logo' import download from './download' import autoUpdate from './autoUpdate' import contextMenu from './contextMenu' import { app, BrowserWindow, shell, ipcMain } from 'electron' let lastUrl let time = Date.now() /** * 打开外部链接 * @param {String} url */ function openExternal (url) { if (url === 'about:blank') return if (url === 'https://im.dingtalk.com/') return if (url.indexOf('https://space.dingtalk.com/auth/download') === 0) return if (url.indexOf('https://space.dingtalk.com/attachment') === 0) return // 防止短时间快速点击链接 if (lastUrl === url && Date.now() - time < 800) return lastUrl = url time = Date.now() shell.openExternal(url) } export default dingtalk => () => { if (dingtalk.$mainWin) { dingtalk.showMainWin() return } // 创建浏览器窗口 const $win = new BrowserWindow({ title: '钉钉', width: 960, height: 600, minWidth: 720, minHeight: 450, useContentSize: true, center: true, frame: false, show: false, backgroundColor: '#5a83b7', icon: logo, resizable: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }) /** * 优雅的显示窗口 */ $win.once('ready-to-show', () => { $win.show() $win.focus() /** * 先让主窗口显示后在执行检查更新 * 防止对话框跑到主窗口后面 * 导致窗口点击不了 * https://github.com/nashaofu/dingtalk/issues/186 */ autoUpdate(dingtalk) }) /** * 窗体关闭事件处理 * 默认只会隐藏窗口 */ $win.on('close', e => { e.preventDefault() $win.hide() }) $win.webContents.on('dom-ready', () => { // 页面初始化图标不跳动 if (dingtalk.$tray) dingtalk.$tray.flicker(false) const filename = path.join(app.getAppPath(), './dist/preload/mainWin.js') // 读取js文件并执行 fs.access(filename, fs.constants.R_OK, err => { if (err) return fs.readFile(filename, (error, data) => { if (error || $win.webContents.isDestroyed()) return $win.webContents.executeJavaScript(data.toString()).then(() => { if (!$win.webContents.isDestroyed()) { $win.webContents.send('dom-ready') } }) }) }) }) // 右键菜单 $win.webContents.on('context-menu', (e, params) => { e.preventDefault() contextMenu($win, params) }) // 浏览器中打开链接 $win.webContents.on('new-window', (e, url) => { e.preventDefault() openExternal(url) }) // 主窗口导航拦截 $win.webContents.on('will-navigate', (e, url) => { e.preventDefault() openExternal(url) }) ipcMain.on('MAINWIN:window-minimize', () => $win.minimize()) ipcMain.on('MAINWIN:window-maximization', () => { if ($win.isMaximized()) { $win.unmaximize() } else { $win.maximize() } }) ipcMain.on('MAINWIN:window-close', () => $win.hide()) ipcMain.on('MAINWIN:open-email', (e, url) => dingtalk.showEmailWin(url)) ipcMain.on('MAINWIN:logout', () => $win.reload()) ipcMain.on('MAINWIN:window-show', () => { $win.show() $win.focus() }) ipcMain.on('MAINWIN:badge', (e, count) => { app.setBadgeCount(count) if (dingtalk.$tray) dingtalk.$tray.flicker(!!count) if (app.dock) { app.dock.show() app.dock.bounce('critical') } }) download($win) // 加载URL地址 $win.loadURL('https://im.dingtalk.com/') return $win }
nashaofu/dingtalk
src/main/mainWin.js
JavaScript
mit
3,574
var containerNavbar = { HTML : '\ <div class="navBar">\ <div class="tcell"></div>\ <div class="tcell w60">\ <button class="toggleControlPanel">open</button>\ </div>\ </div>\ ' }; var containerControlpanel = { HTML : '\ <div class="navBar">\ <div class="tcell"></div>\ <div class="tcell w60">\ <button class="toggleControlPanel">close</button>\ </div>\ </div>\ <div class="table">\ <div class="trow">\ <div class="tcell border"> content here</div>\ </div>\ </div>\ ' }; var controlpanel = { containerNavbar : document.createElement('div'), containerControlpanel : document.createElement('div'), containerControlpanelText : "", containerControlpanelVisible : false, toggleContainerControlpanelVisible : function () { containerControlpanelVisible = !containerControlpanelVisible; if (containerControlpanelVisible) { containerControlpanel.style.display = "block"; } else { containerControlpanel.style.display = "none"; } }, run : function () { console.log("running controlpanel"); var parent; // nav bar container this.containerNavbar.setAttribute('class','containerNavbar'); parent = document.body || document.querySelector('body'); parent.insertBefore(this.containerNavbar, parent.firstChild); // control panel this.containerControlpanel.setAttribute('id','containerControlpanel'); parent = document.body || document.querySelector('body'); parent.insertBefore(this.containerControlpanel, parent.firstChild); // inline console this.refresh(); this.addFunctions(); }, refresh : function () { this.containerNavbar.innerHTML = containerNavbar.HTML; this.containerControlpanel.innerHTML = containerControlpanel.HTML; }, addFunctions : function () { // toggleContainerControlpanelVisible let functionElements = document.querySelectorAll('.toggleContainerControlpanelVisible'); for (let i = 0; i < functionElements.length; i++) { functionElements[i].addEventListener ("click", () => {gui.toggleContainerControlpanelVisible();}, false); } } };
Jinyo-Robin/ultivis
controlpanel.js
JavaScript
mit
2,202
/** * Module dependencies. */ var db = require('../../config/sequelize'); /** * Find item by id * Note: This is called every time that the parameter :itemId is used in a URL. * Its purpose is to preload the item on the req object then call the next function. */ exports.item = function(req, res, next, id) { console.log('id => ' + id); db.Item.find({ where: {id: id}, include: [db.User]}).success(function(item){ if(!item) { console.log('Failed to load item'); return next(new Error('Failed to load item ' + id)); } else { req.item = item; return next(); } }).error(function(err){ return next(err); }); }; /** * Create a item */ exports.create = function(req, res) { // augment the item by adding the UserId req.body.UserId = req.user.id; // save and return and instance of item on the res object. db.Item.create(req.body).success(function(item){ if(!item){ return res.send('users/signup', {errors: err}); } else { return res.jsonp(item); } }).error(function(err){ return res.send('users/signup', { errors: err, status: 500 }); }); }; /** * Update a item */ exports.update = function(req, res) { // create a new variable to hold the item that was placed on the req object. var item = req.item; item.updateAttributes({ title: req.body.title, description: req.body.description }).success(function(a){ return res.jsonp(a); }).error(function(err){ return res.render('error', { error: err, status: 500 }); }); }; exports.bid = function(req, res) { // create a new variable to hold the item that was placed on the req object. var item = req.item; console.log("here", req.body.current_bid ); item.updateAttributes({ current_bid: req.body.current_bid, buyer_id: req.body.buyer_id }).success(function(a){ return res.jsonp(a); }).error(function(err){ return res.render('error', { error: err, status: 500 }); }); }; /** * Delete an item */ exports.destroy = function(req, res) { // create a new variable to hold the item that was placed on the req object. var item = req.item; item.destroy().success(function(){ return res.jsonp(item); }).error(function(err){ return res.render('error', { error: err, status: 500 }); }); }; /** * Show an item */ exports.show = function(req, res) { // Sending down the item that was just preloaded by the items.item function // and saves item on the req object. return res.jsonp(req.item); }; /** * List of items */ exports.all = function(req, res) { db.Item.findAll({include: [db.User]}).success(function(items){ return res.jsonp(items); }).error(function(err){ return res.render('error', { error: err, status: 500 }); }); };
SAGEsoft/e-Auction
app/controllers/items.js
JavaScript
mit
3,123
'use strict'; var React = require('react-native'); var { StyleSheet, Text, View, Image, TouchableHighlight } = React; var { Icon, } = require('react-native-icons'); var NavigationBar = require('react-native-navbar'); var ArticleView = require('./ArticleView'); var FeedItem = React.createClass({ _onPressArticle : function(href){ var nav = this.props.nav; var element = this.props.elem; var title = element.title.text; if(title.length >30){ title = title.substring(0,30) + '...'; }else{ title = title.substring(0,30); } nav.push({ navigationBar: <NavigationBar title={title} prevTitle = "<" titleColor="#FFFFFF" backgroundColor="#CBBCDF" />, component: ArticleView, url: href }); }, _onPressComment : function(href){ console.log(href); var nav = this.props.nav; var element = this.props.elem; var title = 'Comments : '+element.title.text; if(title.length >30){ title = title.substring(0,30) + '...'; }else{ title = title.substring(0,30); } nav.push({ navigationBar: <NavigationBar title={title} titleColor="#FFFFFF" backgroundColor="#CBBCDF" />, component: ArticleView, url: href }); }, render: function () { var element = this.props.elem; return ( <View> <View style={styles.container}> <TouchableHighlight style={styles.touchContainer} onPress={this._onPressArticle.bind(this,element.title.href)}> <View style={styles.leftContainer}> <Text style={styles.title}> {element.title.text} </Text> <View style={styles.bottomContainer}> <Text style={styles.upvotes}> {element.upvotes.text} </Text> <Text style={styles.creator}> {element.creator.text} </Text> </View> <View style={styles.bottomContainer}> <Icon name='ion|ios-world-outline' size={globeDiameter} color={textColor} style={styles.globe}/> <Text style={styles.orginalSite}> {element.orginalSite.text} </Text> </View> </View> </TouchableHighlight> <TouchableHighlight onPress={this._onPressComment.bind(this,element.numComments.href)}> <View style={styles.rightContainer}> <Icon name='ion|ios-chatbubble-outline' size={commentDiameter} color={textColor} style={styles.commentBubble}/> <Text style={styles.comments}>{element.numComments.text}</Text> </View> </TouchableHighlight> </View> </View> ); } }); var textColor = '#5B3B86'; var globeDiameter = 15; var commentDiameter = 15; var styles = StyleSheet.create({ container: { flex: 1, marginBottom: 15, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', borderBottomColor: '#EBE5F4', borderBottomWidth: 1 }, touchContainer : { flex: 1, marginBottom: -5, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }, topContainer : { flex: 4, flexDirection: 'row', alignItems: 'center', marginBottom: 5, }, bottomContainer : { flex: 4, flexDirection: 'row', alignItems: 'center', marginBottom: 5, }, leftContainer : { flex: 4, }, rightContainer: { height:100, flexDirection: 'row', alignItems: 'center', flex: 1, paddingRight:20, }, thumbnail: { width: 53, height: 81, }, title: { fontSize: 13, marginTop: 5, marginBottom: 10, marginLeft: 15, textAlign: 'left', }, comments: { flex: 1, backgroundColor: 'transparent', marginRight: 0, color: textColor, }, commentBubble: { flex: 1, width: commentDiameter, height: commentDiameter, backgroundColor: 'transparent', marginLeft: 15, }, upvotes: { flex: 1, fontSize: 12, marginLeft: 15, color: textColor, textAlign: 'center', }, creator: { flex: 9, textAlign: 'left', fontSize: 12, color: textColor, }, orginalSite : { flex: 9, textAlign: 'left', color: textColor, fontSize: 12, }, globe : { flex: 1, marginLeft: 15, width: globeDiameter, height: globeDiameter, } }); module.exports = FeedItem;
KFoxder/crater-news-feed
source/js/components/FeedItem.js
JavaScript
mit
4,751
/* global toastr:false, OAuth:false, moment:false */ (function() { 'use strict'; angular .module('nowplaying') .constant('toastr', toastr) .constant('OAuth', OAuth) .constant('tUser', 'dev+biplaying@bunnyinc.com') .constant('tUsername', 'BInowplaying') .constant('tKey', 'gEFEbGdkVTDfzVgyiiCbzUImi') .constant('oAuthKey', '80l_rz7SK-Vx2N-D938yl2A3FOw') .constant('moment', moment); })();
leomoreno/NowPlaying
src/app/index.constants.js
JavaScript
mit
426
/* global module */ module.exports = function (grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), yuidoc: { all: { name: '<%= pkg.name %>', description: '<%= pkg.description %>', version: '<%= pkg.version %>', url: '<%= pkg.homepage %>', options: { exclude: 'build,dist,doc', paths: ['./', 'lib/'], outdir: 'doc/' } } }, concat: { options: { separator: ';', }, dist: { src: ['lib/nbodycalc.js'], dest: '<%= pkg.name %>.js', }, }, jshint: { all: ['lib/*.js'] }, mochaTest: { test: { options: { reporter: 'spec', captureFile: 'results.txt', // Optionally capture the reporter output to a file quiet: false, // Optionally suppress output to standard out (defaults to false) clearRequireCache: false // Optionally clear the require cache before running tests (defaults to false) }, src: ['test/**/*.js'] } }, env: { coverage: { APP_DIR_FOR_CODE_COVERAGE: '../coverage/instrument/lib/' } }, instrument: { files: 'lib/*.js', options: { lazy: true, basePath: 'coverage/instrument/' } }, storeCoverage: { options: { dir: 'coverage/reports' } }, makeReport: { src: 'coverage/reports/**/*.json', options: { type: 'cobertura', dir: 'coverage/reports', print: 'detail' } }, mochacli: { options: { reporter: "list", ui: "tdd" }, all: ["test/*.js"] }, uglify: { options: { // banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> Copyright by <%= pkg.author.name %> <%= pkg.author.email %> */$ }, build: { src: '<%= pkg.name %>.js', dest: '<%= pkg.name %>.min.js' } } }); grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-yuidoc'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-istanbul'); grunt.loadNpmTasks('grunt-env'); grunt.registerTask('check', ['jshint']); grunt.registerTask('test', ['mochaTest']); grunt.registerTask('coverage', ['jshint', 'env:coverage', 'instrument', 'mochaTest', 'storeCoverage', 'makeReport']); grunt.registerTask('jenkins', ['jshint', 'env:coverage', 'instrument', 'mochaTest', 'storeCoverage', 'makeReport']); grunt.registerTask('default', ['jshint', 'mochaTest', 'concat', 'yuidoc', 'uglify']); };
lethexa/lethexa-nbodycalc
Gruntfile.js
JavaScript
mit
3,137
/* Stored Validations / This is a sample file provided to give an example of how to store a validation script / for multiple executions. */ if(typeof storedValidations == "undefined"){ storedValidations = {}; } storedValidations.exampleValidation = function(dataObject){ mC.clear(); mC.sBO({name:"tw.local.request", value: dataObject}); mC.aOV("address", ["address1", "city", "state", "zip"]); mC.sBO({name:"tw.local.request.customer", value: dataObject.customer}); mC.aFV("email", [], "email"); if(dataObject.customer.accountingEmail != ""){ mC.aFV("accountingEmail", [], "email"); } mC.val(); /* / In the above example we've: / - Cleared previous stuff for saftey / - Set the base object to the tw.local.request variable / - This script assums that dataObject = tw.local.request / - Checks an address object for 4 required fields / - Switches the base object down to the the child customer completx object / - Validates the email with and email regex / - Conditionaly validates the accountingEmail variable if it is provided / - Then the validation executes */ }; storedValidations.exampleValidation2 = function(dataObject){ mC.clear(); mC.mC.sBO({name:"tw.local.request", value: dataObject}); mC.aFV("email", [], "email"); mC.val(); }; /* / In this example I wrote a validation for one coach but then wanted to use it again for another coach downstream. / Now instead of copying and pasting the code I can store it in this file and simply call: / mC.exec("exampleValidation", tw.local.request); /// OR / motoChecker.executeStoredValidation("exampleValidation", tw.local.request); / in my both coaches. This helps ensure that your validation stays consistent. / / This storedValidations file should be uploaded as a server file just like motoChecker.js. / The variable "storedValidations" connot exist twice. So to add additional stored validations to the object like an array. */
Cleanshooter/motoValidation
storedValidations.js
JavaScript
mit
1,927
var chai = require('chai'); var expect = chai.expect; var sinon = require('sinon'); var sinonChai = require("sinon-chai"); var chaiAsPromised = require('chai-as-promised'); var process = require('child_process'); var mockSpawn = require('mock-spawn'); chai.use(sinonChai); chai.use(chaiAsPromised); describe('AdHoc command', function() { var mySpawn = mockSpawn(); var oldSpawn = process.spawn; var spawnSpy; var default_env = { env: { PYTHONUNBUFFERED: "1" } }; before(function() { process.spawn = mySpawn; spawnSpy = sinon.spy(process, 'spawn'); }) beforeEach(function() { spawnSpy.reset(); }) var AdHoc = require("../index").AdHoc; describe('with no structured args and freeform arg', function() { it('should be translated successfully to ansible command', function(done) { var command = new AdHoc().module('shell').hosts('local').args("echo 'hello'"); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'']); done(); }).done(); }) }) describe('with no hosts', function() { it('should be rejected', function() { var command = new AdHoc().module('shell').args("echo 'hello'"); expect(command.exec()).to.be.rejected; }) it('should include reason in rejection', function(done) { var command = new AdHoc().module('shell').args(null, "echo 'hello'"); expect(command.exec()).to.be.rejected.then(function(error) { expect(error).to.have.property('reason'); expect(error.reason).to.be.array; expect(error.reason).to.have.length(1); done(); }) }) }) describe('with no module', function() { it('should be rejected', function() { var command = new AdHoc().hosts('local').args("echo 'hello'"); expect(command.exec()).to.be.rejected; }) }) describe('with forks', function() { it('should contain forks flag in execution', function(done) { var command = new AdHoc().module('shell').hosts('local').args("echo 'hello'").forks(10); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'', '-f', 10]); done(); }).done(); }) }) describe('with verbose', function() { it('should contain verbose flag in execution', function(done) { var command = new AdHoc().module('shell').hosts('local').args("echo 'hello'").verbose("vvv"); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'', '-vvv']); done(); }).done(); }) }) describe('with user', function() { it('should contain user flag in execution', function(done) { var command = new AdHoc().module('shell').hosts('local').args("echo 'hello'").user("root"); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'', '-u', 'root']); done(); }).done(); }) }) describe('as sudo user', function() { it('should contain sudo user flag in execution', function(done) { var command = new AdHoc().module('shell').hosts('local').args("echo 'hello'").asSudo(); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'', '-s']); done(); }).done(); }) }) describe('with sudo user specified', function() { it('should contain sudo user flag in execution', function(done) { var command = new AdHoc().module('shell').hosts('local').args("echo 'hello'").su('root'); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'', '-U', 'root']); done(); }).done(); }) }) describe('with inventory', function() { it('should contain inventory flag in execution', function(done) { var command = new AdHoc().module('shell').hosts('local').args("echo 'hello'").inventory("/etc/my/hosts"); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'', '-i', '/etc/my/hosts']); done(); }).done(); }) }) describe('with inventory subset', function() { it('should execute the playbook with specified inventory subset limit', function (done) { var command = new AdHoc().module('shell').hosts('local').inventory('/etc/my/hosts').limit('localhost').args("echo 'hello'"); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'', '-i', '/etc/my/hosts', '-l', 'localhost']); done(); }).done(); }) }) describe('with private key', function() { it('should contain private key flag in execution', function(done) { var command = new AdHoc().module('shell').hosts('local').args("echo 'hello'").privateKey("/home/user/.ssh/id_rsa"); expect(command.exec()).to.be.fulfilled.then(function() { expect(spawnSpy).to.be.calledWith('ansible', ['local', '-m', 'shell', '-a', 'echo \'hello\'', '--private-key', '"/home/user/.ssh/id_rsa"']); done(); }).done(); }) }) after(function() { process.spawn = oldSpawn; spawnSpy.restore(); }) })
shaharke/node-ansible
test/adhoc.spec.js
JavaScript
mit
5,649
//This requires the following javascript to be included: //http://js.arcgis.com/3.9compact/ "use strict"; //*******MAP WIDGET*************** //This object-oriented approach needs refinement. Currently does not behave properly if multiple versions of a map are instantiated in the same document. function WMLMap() { var self = this; this.mapDiv = null; this.map = null; this.chartVariableName = null; this.basemaps = ["http://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer", "http://hydrology.esri.com:6080/arcgis/rest/services/WorldHydroReferenceOverlay/MapServer"]; this.featureServices = []; this.query = null; this.queryTask= null; this.init = function() { wmlviewer.curMap = self; CreateMap(self.mapDiv, self.basemaps, self.featureServices); } this.AddFeatureService = function(featureService) { wmlviewer.curMap = self; AddFeatureService(featureService); self.featureServices.push(featureService); } } //*********END MAP WIDGET********************* //**********MAP METHODS*********************** function CreateMap(div, basemapList, featureServiceList){ require([ "esri/map", "esri/layers/ArcGISTiledMapServiceLayer", "esri/geometry/Extent" ], function (Map, ArcGISTiledMapServiceLayer, Extent) { // Define the default extent for the map var initialExtent = wmlviewer.initialExtent; var extent = new Extent({"spatialReference":{"wkid":4326}}); var basemap; // If client didn't provide a default, then cover the width, but not necessarily the height, of the full extent if (initialExtent === undefined || ( initialExtent.xmin === undefined && initialExtent.ymin === undefined && initialExtent.xmin === undefined && initialExtent.ymin === undefined)) { extent.xmin = -180; extent.xmax = 180; } else { if ('xmin' in initialExtent) {extent.xmin = initialExtent.xmin;} if ('ymin' in initialExtent) {extent.ymin = initialExtent.ymin;} if ('xmax' in initialExtent) {extent.xmax = initialExtent.xmax;} if ('ymax' in initialExtent) {extent.ymax = initialExtent.ymax;} } wmlviewer.curMap.map = new Map(div,{extent: extent}); for (var i=0;i<basemapList.length;i++){ basemap = new ArcGISTiledMapServiceLayer(basemapList[i]); wmlviewer.curMap.map.addLayer(basemap); } for (var i=0;i<featureServiceList.length;i++){ AddFeatureService(featureServiceList[i]); } }) } function AddFeatureService(featureService){ //Takes a URL to a non cached map service. require([ "esri/layers/ArcGISDynamicMapServiceLayer", "esri/tasks/query", "esri/tasks/QueryTask", "esri/layers/FeatureLayer", "esri/layers/ImageParameters" ], function (ArcGISDynamicMapServiceLayer, Query, QueryTask, FeatureLayer, ImageParameters) { var layer; var imgParams = new ImageParameters(); imgParams.format = "png32"; // Honors transparency set by map service var service = new ArcGISDynamicMapServiceLayer(featureService, {imageParameters: imgParams}); wmlviewer.curMap.map.addLayer(service); //Define click behavior dojo.connect(wmlviewer.curMap.map, "onClick", executeQueryTask); layer = featureService + "/0"; wmlviewer.curMap.queryTask = new QueryTask(layer); wmlviewer.curMap.query = new Query(); wmlviewer.curMap.query.outFields = ["SiteName", "WaterML", "Source"]; }) } //********END MAP METHODS******************** //********QUERY FUNCTIONS*********************** function executeQueryTask(evt) { var centerPoint = new esri.geometry.Point (evt.mapPoint.x,evt.mapPoint.y,evt.mapPoint.spatialReference); var querybox; querybox = pointToExtent(wmlviewer.curMap.map,centerPoint, 10); wmlviewer.curMap.query.geometry = querybox; //Execute task and call showResults on completion wmlviewer.curMap.queryTask.execute(wmlviewer.curMap.query, function(fset) { if (fset.features.length === 1) { showFeature(fset.features[0],evt); } else if (fset.features.length !== 0) { showFeatureSet(fset,evt); } }); } function pointToExtent(/*esri.Map*/ map, /*esri.geometry.Point (in map coords)*/ point, /*Number*/ toleranceInPixel) { //create a bounding box around a point to use as a query extent //calculate map coords represented per pixel var pixelWidth = map.extent.getWidth() / map.width; //calculate map coords for tolerance in pixel var toleranceInMapCoords = toleranceInPixel * pixelWidth; //calculate & return computed extent var box; box = new esri.geometry.Extent(point.x - toleranceInMapCoords, point.y - toleranceInMapCoords, point.x + toleranceInMapCoords, point.y + toleranceInMapCoords, map.spatialReference); return box; } //********END QUERY FUNCTIONS************* //********DIALOGUE BOXES*************** function showFeature(feature,evt) { //When single feature is selected, provide user with metadata and option to add time series to chart //Note: this requires a separate js file defining AddWaterML dojo.require("dijit/form/Button"); wmlviewer.curMap.map.graphics.clear(); //construct infowindow title and content var title = ""; var content; var siteNameLabel = 'Site Name: ' + feature.attributes.SiteName + '</br>'; var dataProviderLabel = 'Data Provider: ' + feature.attributes.Source + '</br>'; var addToChartButtonLabel = '<button dojoType="dijit.form.Button" type="button" style="width:100%" onClick="javascript:wmlviewer.' + wmlviewer.curMap.chartVariableName + '.AddLink(' + "'" + feature.attributes.WaterML + "'" + ');CloseWindow();">Add to Chart</button></br>'; var dataSourceButtonLabel = '<a href="' + feature.attributes.WaterML + '" target="_blank"><button style="width:50%">Data Source</button></a>'; var closeButton = '<button dojoType="dijit.form.Button" type="button" style="width:50%" onClick="javascript:CloseWindow();">Close</button>' if (wmlviewer.curMap.chartVariableName) { content = siteNameLabel + dataProviderLabel + addToChartButtonLabel + dataSourceButtonLabel + closeButton; } else { content = siteNameLabel + dataProviderLabel + dataSourceButtonLabel + closeButton; } wmlviewer.curMap.map.infoWindow.setTitle(title); wmlviewer.curMap.map.infoWindow.setContent(content); (evt) ? wmlviewer.curMap.map.infoWindow.show(evt.screenPoint,wmlviewer.curMap.map.getInfoWindowAnchor(evt.screenPoint)) : null; } function showFeatureSet(fset,evt) { //When user click returns multiple nearby features, resolve to a single feature via dialogue box var screenPoint = evt.screenPoint; var numFeatures = fset.features.length; wmlviewer.featureSet = fset; //QueryTask returns a featureSet. Loop through features in the featureSet and add them to the infowindow. var title = "You have selected " + numFeatures + " fields."; var content = "Please select desired field from the list below.<br />"; for (var i=0; i<numFeatures; i++) { var graphic = fset.features[i]; content = content + graphic.attributes.SiteName + " Field (<span class='wmlPopupLink' onclick='showFeature(wmlviewer.featureSet.features[" + i + "]);'>show</span>)<br/>"; } wmlviewer.curMap.map.infoWindow.setTitle(title); wmlviewer.curMap.map.infoWindow.setContent(content); wmlviewer.curMap.map.infoWindow.show(screenPoint,wmlviewer.curMap.map.getInfoWindowAnchor(evt.screenPoint)); } function CloseWindow(){ wmlviewer.curMap.map.infoWindow.hide(); } //************END DIALOGE BOXES**************
crwr/wmlviewer
wmlviewer/wml-map.js
JavaScript
mit
7,957
/*global require:true*/ /*global phantom:true*/ /*global window:true*/ (function(){ "use strict"; var page = require( 'webpage' ).create(); var system = require( 'system' ); var uncomment = require( './uncomment' ); var onError = function(msg, trace) { var msgStack = ['PHANTOM ERROR: ' + msg]; if (trace && trace.length) { msgStack.push('TRACE:'); trace.forEach(function(t) { msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : '')); }); } system.stderr.write( msgStack.join('\n') ); phantom.exit(1); }; phantom.onError = onError; page.onError = onError; page.onConsoleMessage = function( msg ){ system.stderr.write( msg + "\n" ); }; var fileContents = decodeURI(system.args[1]); var name = system.args[2]; var color = system.args[3]; page.onLoadFinished = function( status ){ if( status !== "success" ){ throw new Error( "Page did not load in Phantom" ); } var svg = page.evaluate(function(name, color){ var document = window.document; var els = document.querySelectorAll( "svg :not([fill=none])" ); var ret = {}; Array.prototype.forEach.call(els, function(el){ el.setAttribute( "fill", color ); }); els = document.querySelectorAll( "svg [stroke]:not([stroke=none])" ); Array.prototype.forEach.call(els, function(el){ el.setAttribute( "stroke", color ); }); ret[ name ] = document.querySelector( ".container" ).innerHTML; return ret; }, name, color); for( var i in svg ){ if( svg.hasOwnProperty( i ) ){ svg[i] = uncomment.XMLHeader( svg[i] ); } } system.stdout.write(encodeURI(JSON.stringify(svg))); phantom.exit(0); }; page.content = "<html><head></head><body><div class='container'>" + fileContents + "</div></body></html>"; }());
filamentgroup/directory-colorfy
lib/phantomscript.js
JavaScript
mit
1,831
// Polyfills to support IE11. // - The polyfills are only executed when required (i.e. the implementation does not exist, is buggy, or does not // support all features). // - Modified from react-app-polyfill IE11 support (react-app-polyfill/ie11.js) to include support for // Promise.prototype.catch and Promise.prototype.finally. These are available in core-js/fn/promise. // - We are using the same version of core-js as react-app-polyfill. When this is upgraded to use core-js v.3, // the correct import syntax will be core-js/stable instead of core-js/fn or core-js/es6 for most imports. If the // imports require additional features then the correct import syntax will be core-js/es6. import 'core-js/fn/promise'; if (typeof window !== 'undefined') { // Avoid importing fetch() in a Node test environment require('whatwg-fetch'); } Object.assign = require('object-assign'); // Object.assign() polyfill require('core-js/es6/symbol'); // Includes for...of polyfill require('core-js/fn/array/from'); // Includes iterable spread polyfill (...Set, ...Map)
MicroFocus/CX
aaf-enrollment/src/polyfills.js
JavaScript
mit
1,075
/* Copyright (c) 2015-present NAVER Corp. name: @egjs/flicking license: MIT author: NAVER Corp. repository: https://github.com/naver/egjs-flicking version: 3.4.3 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@egjs/component'), require('@egjs/axes')) : typeof define === 'function' && define.amd ? define(['@egjs/component', '@egjs/axes'], factory) : (global = global || self, (global.eg = global.eg || {}, global.eg.Flicking = factory(global.eg.Component, global.eg.Axes))); }(this, function (Component, Axes) { '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 = function (d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var MOVE_TYPE = { SNAP: "snap", FREE_SCROLL: "freeScroll" }; var DEFAULT_MOVE_TYPE_OPTIONS = { snap: { type: "snap", count: 1 }, freeScroll: { type: "freeScroll" } }; var isBrowser = typeof document !== "undefined"; /** * Default options for creating Flicking. * @ko 플리킹을 만들 때 사용하는 기본 옵션들 * @private * @memberof eg.Flicking */ var DEFAULT_OPTIONS = { classPrefix: "eg-flick", deceleration: 0.0075, horizontal: true, circular: false, infinite: false, infiniteThreshold: 0, lastIndex: Infinity, threshold: 40, duration: 100, panelEffect: function (x) { return 1 - Math.pow(1 - x, 3); }, defaultIndex: 0, inputType: ["touch", "mouse"], thresholdAngle: 45, bounce: 10, autoResize: false, adaptive: false, zIndex: 2000, bound: false, overflow: false, hanger: "50%", anchor: "50%", gap: 0, moveType: DEFAULT_MOVE_TYPE_OPTIONS.snap, useOffset: false, isEqualSize: false, isConstantSize: false, renderOnlyVisible: false, renderExternal: false, collectStatistics: true }; var DEFAULT_VIEWPORT_CSS = { position: "relative", zIndex: DEFAULT_OPTIONS.zIndex, overflow: "hidden" }; var DEFAULT_CAMERA_CSS = { width: "100%", height: "100%", willChange: "transform" }; var DEFAULT_PANEL_CSS = { position: "absolute" }; var EVENTS = { HOLD_START: "holdStart", HOLD_END: "holdEnd", MOVE_START: "moveStart", MOVE: "move", MOVE_END: "moveEnd", CHANGE: "change", RESTORE: "restore", SELECT: "select", NEED_PANEL: "needPanel", VISIBLE_CHANGE: "visibleChange" }; var AXES_EVENTS = { HOLD: "hold", CHANGE: "change", RELEASE: "release", ANIMATION_END: "animationEnd", FINISH: "finish" }; var STATE_TYPE = { IDLE: 0, HOLDING: 1, DRAGGING: 2, ANIMATING: 3, DISABLED: 4 }; var DIRECTION = { PREV: "PREV", NEXT: "NEXT" }; var FLICKING_METHODS = { prev: true, next: true, moveTo: true, getIndex: true, getAllPanels: true, getCurrentPanel: true, getElement: true, getPanel: true, getPanelCount: true, getStatus: true, getVisiblePanels: true, setLastIndex: true, enableInput: true, disableInput: true, destroy: true, resize: true, setStatus: true, addPlugins: true, removePlugins: true, isPlaying: true, getLastIndex: true }; // Check whether browser supports transform: translate3d // https://stackoverflow.com/questions/5661671/detecting-transform-translate3d-support var checkTranslateSupport = function () { var transforms = { webkitTransform: "-webkit-transform", msTransform: "-ms-transform", MozTransform: "-moz-transform", OTransform: "-o-transform", transform: "transform" }; if (!isBrowser) { return { name: transforms.transform, has3d: true }; } var supportedStyle = document.documentElement.style; var transformName = ""; for (var prefixedTransform in transforms) { if (prefixedTransform in supportedStyle) { transformName = prefixedTransform; } } if (!transformName) { throw new Error("Browser doesn't support CSS3 2D Transforms."); } var el = document.createElement("div"); document.documentElement.insertBefore(el, null); el.style[transformName] = "translate3d(1px, 1px, 1px)"; var styleVal = window.getComputedStyle(el).getPropertyValue(transforms[transformName]); el.parentElement.removeChild(el); var transformInfo = { name: transformName, has3d: styleVal.length > 0 && styleVal !== "none" }; checkTranslateSupport = function () { return transformInfo; }; return transformInfo; }; var TRANSFORM = checkTranslateSupport(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ function merge(target) { var srcs = []; for (var _i = 1; _i < arguments.length; _i++) { srcs[_i - 1] = arguments[_i]; } srcs.forEach(function (source) { Object.keys(source).forEach(function (key) { var value = source[key]; target[key] = value; }); }); return target; } function parseElement(element) { if (!Array.isArray(element)) { element = [element]; } var elements = []; element.forEach(function (el) { if (isString(el)) { var tempDiv = document.createElement("div"); tempDiv.innerHTML = el; elements.push.apply(elements, toArray(tempDiv.children)); while (tempDiv.firstChild) { tempDiv.removeChild(tempDiv.firstChild); } } else { elements.push(el); } }); return elements; } function isString(value) { return typeof value === "string"; } // Get class list of element as string array function addClass(element, className) { if (element.classList) { element.classList.add(className); } else { if (!hasClass(element, className)) { element.className = (element.className + " " + className).replace(/\s{2,}/g, " "); } } } function hasClass(element, className) { if (element.classList) { return element.classList.contains(className); } else { return element.className.split(" ").indexOf(className) >= 0; } } function applyCSS(element, cssObj) { Object.keys(cssObj).forEach(function (property) { element.style[property] = cssObj[property]; }); } function clamp(val, min, max) { return Math.max(Math.min(val, max), min); } // Min: inclusive, Max: exclusive function isBetween(val, min, max) { return val >= min && val <= max; } function toArray(iterable) { return [].slice.call(iterable); } function isArray(arr) { return arr && arr.constructor === Array; } function parseArithmeticExpression(cssValue, base, defaultVal) { // Set base / 2 to default value, if it's undefined var defaultValue = defaultVal != null ? defaultVal : base / 2; var cssRegex = /(?:(\+|\-)\s*)?(\d+(?:\.\d+)?(%|px)?)/g; if (typeof cssValue === "number") { return clamp(cssValue, 0, base); } var idx = 0; var calculatedValue = 0; var matchResult = cssRegex.exec(cssValue); while (matchResult != null) { var sign = matchResult[1]; var value = matchResult[2]; var unit = matchResult[3]; var parsedValue = parseFloat(value); if (idx <= 0) { sign = sign || "+"; } // Return default value for values not in good form if (!sign) { return defaultValue; } if (unit === "%") { parsedValue = parsedValue / 100 * base; } calculatedValue += sign === "+" ? parsedValue : -parsedValue; // Match next occurrence ++idx; matchResult = cssRegex.exec(cssValue); } // None-matched if (idx === 0) { return defaultValue; } // Clamp between 0 ~ base return clamp(calculatedValue, 0, base); } function getProgress(pos, range) { // start, anchor, end // -1 , 0 , 1 var min = range[0], center = range[1], max = range[2]; if (pos > center && max - center) { // 0 ~ 1 return (pos - center) / (max - center); } else if (pos < center && center - min) { // -1 ~ 0 return (pos - center) / (center - min); } else if (pos !== center && max - min) { return (pos - min) / (max - min); } return 0; } function findIndex(iterable, callback) { for (var i = 0; i < iterable.length; i += 1) { var element = iterable[i]; if (element && callback(element)) { return i; } } return -1; } // return [0, 1, ...., max - 1] function counter(max) { var counterArray = []; for (var i = 0; i < max; i += 1) { counterArray[i] = i; } return counterArray; } // Circulate number between range [min, max] /* * "indexed" means min and max is not same, so if it's true "min - 1" should be max * While if it's false, "min - 1" should be "max - 1" * use `indexed: true` when it should be used for circulating integers like index * or `indexed: false` when it should be used for something like positions. */ function circulate(value, min, max, indexed) { var size = indexed ? max - min + 1 : max - min; if (value < min) { var offset = indexed ? (min - value - 1) % size : (min - value) % size; value = max - offset; } else if (value > max) { var offset = indexed ? (value - max - 1) % size : (value - max) % size; value = min + offset; } return value; } function restoreStyle(element, originalStyle) { originalStyle.className ? element.setAttribute("class", originalStyle.className) : element.removeAttribute("class"); originalStyle.style ? element.setAttribute("style", originalStyle.style) : element.removeAttribute("style"); } /** * Decorator that makes the method of flicking available in the framework. * @ko 프레임워크에서 플리킹의 메소드를 사용할 수 있게 하는 데코레이터. * @memberof eg.Flicking * @private * @example * ```js * import Flicking, { withFlickingMethods } from "@egjs/flicking"; * * class Flicking extends React.Component<Partial<FlickingProps & FlickingOptions>> { * &#64;withFlickingMethods * private flicking: Flicking; * } * ``` */ function withFlickingMethods(prototype, flickingName) { Object.keys(FLICKING_METHODS).forEach(function (name) { if (prototype[name]) { return; } prototype[name] = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var result = (_a = this[flickingName])[name].apply(_a, args); // fix `this` type to return your own `flicking` instance to the instance using the decorator. if (result === this[flickingName]) { return this; } else { return result; } var _a; }; }); } function getBbox(element, useOffset) { var bbox; if (useOffset) { bbox = { x: 0, y: 0, width: element.offsetWidth, height: element.offsetHeight }; } else { var clientRect = element.getBoundingClientRect(); bbox = { x: clientRect.left, y: clientRect.top, width: clientRect.width, height: clientRect.height }; } return bbox; } /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var Panel = /*#__PURE__*/ function () { function Panel(element, index, viewport) { this.viewport = viewport; this.prevSibling = null; this.nextSibling = null; this.clonedPanels = []; this.state = { index: index, position: 0, relativeAnchorPosition: 0, size: 0, isClone: false, isVirtual: false, cloneIndex: -1, originalStyle: { className: "", style: "" }, cachedBbox: null }; this.setElement(element); } var __proto = Panel.prototype; __proto.resize = function (givenBbox) { var state = this.state; var options = this.viewport.options; var bbox = givenBbox ? givenBbox : this.getBbox(); this.state.cachedBbox = bbox; var prevSize = state.size; state.size = options.horizontal ? bbox.width : bbox.height; if (prevSize !== state.size) { state.relativeAnchorPosition = parseArithmeticExpression(options.anchor, state.size); } if (!state.isClone) { this.clonedPanels.forEach(function (panel) { var cloneState = panel.state; cloneState.size = state.size; cloneState.cachedBbox = state.cachedBbox; cloneState.relativeAnchorPosition = state.relativeAnchorPosition; }); } }; __proto.unCacheBbox = function () { this.state.cachedBbox = null; }; __proto.getProgress = function () { var viewport = this.viewport; var options = viewport.options; var panelCount = viewport.panelManager.getPanelCount(); var scrollAreaSize = viewport.getScrollAreaSize(); var relativeIndex = (options.circular ? Math.floor(this.getPosition() / scrollAreaSize) * panelCount : 0) + this.getIndex(); var progress = relativeIndex - viewport.getCurrentProgress(); return progress; }; __proto.getOutsetProgress = function () { var viewport = this.viewport; var outsetRange = [-this.getSize(), viewport.getRelativeHangerPosition() - this.getRelativeAnchorPosition(), viewport.getSize()]; var relativePanelPosition = this.getPosition() - viewport.getCameraPosition(); var outsetProgress = getProgress(relativePanelPosition, outsetRange); return outsetProgress; }; __proto.getVisibleRatio = function () { var viewport = this.viewport; var panelSize = this.getSize(); var relativePanelPosition = this.getPosition() - viewport.getCameraPosition(); var rightRelativePanelPosition = relativePanelPosition + panelSize; var visibleSize = Math.min(viewport.getSize(), rightRelativePanelPosition) - Math.max(relativePanelPosition, 0); var visibleRatio = visibleSize >= 0 ? visibleSize / panelSize : 0; return visibleRatio; }; __proto.focus = function (duration) { var viewport = this.viewport; var currentPanel = viewport.getCurrentPanel(); var hangerPosition = viewport.getHangerPosition(); var anchorPosition = this.getAnchorPosition(); if (hangerPosition === anchorPosition || !currentPanel) { return; } var currentPosition = currentPanel.getPosition(); var eventType = currentPosition === this.getPosition() ? "" : EVENTS.CHANGE; viewport.moveTo(this, viewport.findEstimatedPosition(this), eventType, null, duration); }; __proto.update = function (updateFunction, shouldResize) { if (updateFunction === void 0) { updateFunction = null; } if (shouldResize === void 0) { shouldResize = true; } var identicalPanels = this.getIdenticalPanels(); if (updateFunction) { identicalPanels.forEach(function (eachPanel) { updateFunction(eachPanel.getElement()); }); } if (shouldResize) { identicalPanels.forEach(function (eachPanel) { eachPanel.unCacheBbox(); }); this.viewport.addVisiblePanel(this); this.viewport.resize(); } }; __proto.prev = function () { var viewport = this.viewport; var options = viewport.options; var prevSibling = this.prevSibling; if (!prevSibling) { return null; } var currentIndex = this.getIndex(); var currentPosition = this.getPosition(); var prevPanelIndex = prevSibling.getIndex(); var prevPanelPosition = prevSibling.getPosition(); var prevPanelSize = prevSibling.getSize(); var hasEmptyPanelBetween = currentIndex - prevPanelIndex > 1; var notYetMinPanel = options.infinite && currentIndex > 0 && prevPanelIndex > currentIndex; if (hasEmptyPanelBetween || notYetMinPanel) { // Empty panel exists between return null; } var newPosition = currentPosition - prevPanelSize - options.gap; var prevPanel = prevSibling; if (prevPanelPosition !== newPosition) { prevPanel = prevSibling.clone(prevSibling.getCloneIndex(), true); prevPanel.setPosition(newPosition); } return prevPanel; }; __proto.next = function () { var viewport = this.viewport; var options = viewport.options; var nextSibling = this.nextSibling; var lastIndex = viewport.panelManager.getLastIndex(); if (!nextSibling) { return null; } var currentIndex = this.getIndex(); var currentPosition = this.getPosition(); var nextPanelIndex = nextSibling.getIndex(); var nextPanelPosition = nextSibling.getPosition(); var hasEmptyPanelBetween = nextPanelIndex - currentIndex > 1; var notYetMaxPanel = options.infinite && currentIndex < lastIndex && nextPanelIndex < currentIndex; if (hasEmptyPanelBetween || notYetMaxPanel) { return null; } var newPosition = currentPosition + this.getSize() + options.gap; var nextPanel = nextSibling; if (nextPanelPosition !== newPosition) { nextPanel = nextSibling.clone(nextSibling.getCloneIndex(), true); nextPanel.setPosition(newPosition); } return nextPanel; }; __proto.insertBefore = function (element) { var viewport = this.viewport; var parsedElements = parseElement(element); var firstPanel = viewport.panelManager.firstPanel(); var prevSibling = this.prevSibling; // Finding correct inserting index // While it should insert removing empty spaces, // It also should have to be bigger than prevSibling' s index var targetIndex = prevSibling && firstPanel.getIndex() !== this.getIndex() ? Math.max(prevSibling.getIndex() + 1, this.getIndex() - parsedElements.length) : Math.max(this.getIndex() - parsedElements.length, 0); return viewport.insert(targetIndex, parsedElements); }; __proto.insertAfter = function (element) { return this.viewport.insert(this.getIndex() + 1, element); }; __proto.remove = function () { this.viewport.remove(this.getIndex()); return this; }; __proto.destroy = function (option) { if (!option.preserveUI) { var originalStyle = this.state.originalStyle; restoreStyle(this.element, originalStyle); } // release resources for (var x in this) { this[x] = null; } }; __proto.getElement = function () { return this.element; }; __proto.getAnchorPosition = function () { return this.state.position + this.state.relativeAnchorPosition; }; __proto.getRelativeAnchorPosition = function () { return this.state.relativeAnchorPosition; }; __proto.getIndex = function () { return this.state.index; }; __proto.getPosition = function () { return this.state.position; }; __proto.getSize = function () { return this.state.size; }; __proto.getBbox = function () { var state = this.state; var viewport = this.viewport; var element = this.element; var options = viewport.options; if (!element) { state.cachedBbox = { x: 0, y: 0, width: 0, height: 0 }; } else if (!state.cachedBbox) { var wasVisible = Boolean(element.parentNode); var cameraElement = viewport.getCameraElement(); if (!wasVisible) { cameraElement.appendChild(element); viewport.addVisiblePanel(this); } state.cachedBbox = getBbox(element, options.useOffset); if (!wasVisible && viewport.options.renderExternal) { cameraElement.removeChild(element); } } return state.cachedBbox; }; __proto.isClone = function () { return this.state.isClone; }; __proto.getOverlappedClass = function (classes) { var element = this.element; for (var _i = 0, classes_1 = classes; _i < classes_1.length; _i++) { var className = classes_1[_i]; if (hasClass(element, className)) { return className; } } }; __proto.getCloneIndex = function () { return this.state.cloneIndex; }; __proto.getClonedPanels = function () { var state = this.state; return state.isClone ? this.original.getClonedPanels() : this.clonedPanels; }; __proto.getIdenticalPanels = function () { var state = this.state; return state.isClone ? this.original.getIdenticalPanels() : [this].concat(this.clonedPanels); }; __proto.getOriginalPanel = function () { return this.state.isClone ? this.original : this; }; __proto.setIndex = function (index) { var state = this.state; state.index = index; this.clonedPanels.forEach(function (panel) { return panel.state.index = index; }); }; __proto.setPosition = function (pos) { this.state.position = pos; return this; }; __proto.setPositionCSS = function (offset) { if (offset === void 0) { offset = 0; } if (!this.element) { return; } var state = this.state; var pos = state.position; var options = this.viewport.options; var elementStyle = this.element.style; var currentElementStyle = options.horizontal ? elementStyle.left : elementStyle.top; var styleToApply = pos - offset + "px"; if (!state.isVirtual && currentElementStyle !== styleToApply) { options.horizontal ? elementStyle.left = styleToApply : elementStyle.top = styleToApply; } }; __proto.clone = function (cloneIndex, isVirtual, element) { if (isVirtual === void 0) { isVirtual = false; } var state = this.state; var viewport = this.viewport; var cloneElement = element; if (!cloneElement && this.element) { cloneElement = isVirtual ? this.element : this.element.cloneNode(true); } var clonedPanel = new Panel(cloneElement, state.index, viewport); var clonedState = clonedPanel.state; clonedPanel.original = state.isClone ? this.original : this; clonedState.isClone = true; clonedState.isVirtual = isVirtual; clonedState.cloneIndex = cloneIndex; // Inherit some state values clonedState.size = state.size; clonedState.relativeAnchorPosition = state.relativeAnchorPosition; clonedState.originalStyle = state.originalStyle; clonedState.cachedBbox = state.cachedBbox; if (!isVirtual) { this.clonedPanels.push(clonedPanel); } else { clonedPanel.prevSibling = this.prevSibling; clonedPanel.nextSibling = this.nextSibling; } return clonedPanel; }; __proto.removeElement = function () { if (!this.viewport.options.renderExternal) { var element = this.element; element.parentNode.removeChild(element); } // Do the same thing for clones if (!this.state.isClone) { this.removeClonedPanelsAfter(0); } }; __proto.removeClonedPanelsAfter = function (start) { var options = this.viewport.options; var removingPanels = this.clonedPanels.splice(start); if (!options.renderExternal && !options.renderOnlyVisible) { removingPanels.forEach(function (panel) { panel.removeElement(); }); } }; __proto.setElement = function (element) { if (!element) { return; } var currentElement = this.element; if (element !== currentElement) { var options = this.viewport.options; if (currentElement) { if (options.horizontal) { element.style.left = currentElement.style.left; } else { element.style.top = currentElement.style.top; } } else { var originalStyle = this.state.originalStyle; originalStyle.className = element.getAttribute("class"); originalStyle.style = element.getAttribute("style"); } this.element = element; if (options.classPrefix) { addClass(element, options.classPrefix + "-panel"); } // Update size info after applying panel css applyCSS(this.element, DEFAULT_PANEL_CSS); } }; return Panel; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var PanelManager = /*#__PURE__*/ function () { function PanelManager(cameraElement, options) { this.cameraElement = cameraElement; this.panels = []; this.clones = []; this.range = { min: -1, max: -1 }; this.length = 0; this.cloneCount = 0; this.options = options; this.lastIndex = options.lastIndex; } var __proto = PanelManager.prototype; __proto.firstPanel = function () { return this.panels[this.range.min]; }; __proto.lastPanel = function () { return this.panels[this.range.max]; }; __proto.allPanels = function () { return this.panels.concat(this.clones.reduce(function (allClones, clones) { return allClones.concat(clones); }, [])); }; __proto.originalPanels = function () { return this.panels; }; __proto.clonedPanels = function () { return this.clones; }; __proto.replacePanels = function (newPanels, newClones) { this.panels = newPanels; this.clones = newClones; this.range = { min: findIndex(newPanels, function (panel) { return Boolean(panel); }), max: newPanels.length - 1 }; this.length = newPanels.filter(function (panel) { return Boolean(panel); }).length; }; __proto.has = function (index) { return !!this.panels[index]; }; __proto.get = function (index) { return this.panels[index]; }; __proto.getPanelCount = function () { return this.length; }; __proto.getLastIndex = function () { return this.lastIndex; }; __proto.getRange = function () { return this.range; }; __proto.getCloneCount = function () { return this.cloneCount; }; __proto.setLastIndex = function (lastIndex) { this.lastIndex = lastIndex; var firstPanel = this.firstPanel(); var lastPanel = this.lastPanel(); if (!firstPanel || !lastPanel) { return; // no meaning of updating range & length } // Remove panels above new last index var range = this.range; if (lastPanel.getIndex() > lastIndex) { var removingPanels = this.panels.splice(lastIndex + 1); this.length -= removingPanels.length; var firstRemovedPanel = removingPanels.filter(function (panel) { return !!panel; })[0]; var possibleLastPanel = firstRemovedPanel.prevSibling; if (possibleLastPanel) { range.max = possibleLastPanel.getIndex(); } else { range.min = -1; range.max = -1; } if (this.shouldRender()) { removingPanels.forEach(function (panel) { return panel.removeElement(); }); } } }; __proto.setCloneCount = function (cloneCount) { this.cloneCount = cloneCount; }; // Insert at index // Returns pushed elements from index, inserting at 'empty' position doesn't push elements behind it __proto.insert = function (index, newPanels) { var panels = this.panels; var range = this.range; var isCircular = this.options.circular; var lastIndex = this.lastIndex; // Find first panel that index is greater than inserting index var nextSibling = this.findFirstPanelFrom(index); // if it's null, element will be inserted at last position // https://developer.mozilla.org/ko/docs/Web/API/Node/insertBefore#Syntax var firstPanel = this.firstPanel(); var siblingElement = nextSibling ? nextSibling.getElement() : isCircular && firstPanel ? firstPanel.getClonedPanels()[0].getElement() : null; // Insert panels before sibling element this.insertNewPanels(newPanels, siblingElement); var pushedIndex = newPanels.length; // Like when setting index 50 while visible panels are 0, 1, 2 if (index > range.max) { newPanels.forEach(function (panel, offset) { panels[index + offset] = panel; }); } else { var panelsAfterIndex = panels.slice(index, index + newPanels.length); // Find empty from beginning var emptyPanelCount = findIndex(panelsAfterIndex, function (panel) { return !!panel; }); if (emptyPanelCount < 0) { // All empty emptyPanelCount = panelsAfterIndex.length; } pushedIndex = newPanels.length - emptyPanelCount; // Insert removing empty panels panels.splice.apply(panels, [index, emptyPanelCount].concat(newPanels)); // Remove panels after last index if (panels.length > lastIndex + 1) { var removedPanels = panels.splice(lastIndex + 1).filter(function (panel) { return Boolean(panel); }); this.length -= removedPanels.length; // Find first var newLastIndex = lastIndex - findIndex(this.panels.concat().reverse(), function (panel) { return !!panel; }); // Can be filled with empty after newLastIndex this.panels.splice(newLastIndex + 1); this.range.max = newLastIndex; if (this.shouldRender()) { removedPanels.forEach(function (panel) { return panel.removeElement(); }); } } } // Update index of previous panels if (pushedIndex > 0) { panels.slice(index + newPanels.length).forEach(function (panel) { panel.setIndex(panel.getIndex() + pushedIndex); }); } // Update state this.length += newPanels.length; this.updateIndex(index); if (isCircular) { this.addNewClones(index, newPanels, newPanels.length - pushedIndex, nextSibling); var clones = this.clones; var panelCount_1 = this.panels.length; if (clones[0] && clones[0].length > lastIndex + 1) { clones.forEach(function (cloneSet) { cloneSet.splice(panelCount_1); }); } } return pushedIndex; }; __proto.replace = function (index, newPanels) { var panels = this.panels; var range = this.range; var options = this.options; var isCircular = options.circular; // Find first panel that index is greater than inserting index var nextSibling = this.findFirstPanelFrom(index + newPanels.length); // if it's null, element will be inserted at last position // https://developer.mozilla.org/ko/docs/Web/API/Node/insertBefore#Syntax var firstPanel = this.firstPanel(); var siblingElement = nextSibling ? nextSibling.getElement() : isCircular && firstPanel ? firstPanel.getClonedPanels()[0].getElement() : null; // Insert panels before sibling element this.insertNewPanels(newPanels, siblingElement); if (index > range.max) { // Temporarily insert null at index to use splice() panels[index] = null; } var replacedPanels = panels.splice.apply(panels, [index, newPanels.length].concat(newPanels)); var wasNonEmptyCount = replacedPanels.filter(function (panel) { return Boolean(panel); }).length; // Suppose inserting [1, 2, 3] at 0 position when there were [empty, 1] // So length should be increased by 3(inserting panels) - 1(non-empty panels) this.length += newPanels.length - wasNonEmptyCount; this.updateIndex(index); if (isCircular) { this.addNewClones(index, newPanels, newPanels.length, nextSibling); } if (this.shouldRender()) { replacedPanels.forEach(function (panel) { return panel && panel.removeElement(); }); } return replacedPanels; }; __proto.remove = function (index, deleteCount) { if (deleteCount === void 0) { deleteCount = 1; } var isCircular = this.options.circular; var panels = this.panels; var clones = this.clones; // Delete count should be equal or larger than 0 deleteCount = Math.max(deleteCount, 0); var deletedPanels = panels.splice(index, deleteCount).filter(function (panel) { return !!panel; }); if (this.shouldRender()) { deletedPanels.forEach(function (panel) { return panel.removeElement(); }); } if (isCircular) { clones.forEach(function (cloneSet) { cloneSet.splice(index, deleteCount); }); } // Update indexes panels.slice(index).forEach(function (panel) { panel.setIndex(panel.getIndex() - deleteCount); }); // Check last panel is empty var lastIndex = panels.length - 1; if (!panels[lastIndex]) { var reversedPanels = panels.concat().reverse(); var nonEmptyIndexFromLast = findIndex(reversedPanels, function (panel) { return !!panel; }); lastIndex = nonEmptyIndexFromLast < 0 ? -1 // All empty : lastIndex - nonEmptyIndexFromLast; // Remove all empty panels from last panels.splice(lastIndex + 1); if (isCircular) { clones.forEach(function (cloneSet) { cloneSet.splice(lastIndex + 1); }); } } // Update range & length this.range = { min: findIndex(panels, function (panel) { return !!panel; }), max: lastIndex }; this.length -= deletedPanels.length; if (this.length <= 0) { // Reset clones this.clones = []; this.cloneCount = 0; } return deletedPanels; }; __proto.chainAllPanels = function () { var allPanels = this.allPanels().filter(function (panel) { return !!panel; }); var allPanelsCount = allPanels.length; if (allPanelsCount <= 1) { return; } allPanels.slice(1, allPanels.length - 1).forEach(function (panel, idx) { var prevPanel = allPanels[idx]; var nextPanel = allPanels[idx + 2]; panel.prevSibling = prevPanel; panel.nextSibling = nextPanel; }); var firstPanel = allPanels[0]; var lastPanel = allPanels[allPanelsCount - 1]; firstPanel.prevSibling = null; firstPanel.nextSibling = allPanels[1]; lastPanel.prevSibling = allPanels[allPanelsCount - 2]; lastPanel.nextSibling = null; if (this.options.circular) { firstPanel.prevSibling = lastPanel; lastPanel.nextSibling = firstPanel; } }; __proto.insertClones = function (cloneIndex, index, clonedPanels, deleteCount) { if (deleteCount === void 0) { deleteCount = 0; } var clones = this.clones; var lastIndex = this.lastIndex; if (!clones[cloneIndex]) { var newClones_1 = []; clonedPanels.forEach(function (panel, offset) { newClones_1[index + offset] = panel; }); clones[cloneIndex] = newClones_1; } else { var insertTarget_1 = clones[cloneIndex]; if (index >= insertTarget_1.length) { clonedPanels.forEach(function (panel, offset) { insertTarget_1[index + offset] = panel; }); } else { insertTarget_1.splice.apply(insertTarget_1, [index, deleteCount].concat(clonedPanels)); // Remove panels after last index if (clonedPanels.length > lastIndex + 1) { clonedPanels.splice(lastIndex + 1); } } } }; // clones are operating in set __proto.removeClonesAfter = function (cloneIndex) { var panels = this.panels; panels.forEach(function (panel) { panel.removeClonedPanelsAfter(cloneIndex); }); this.clones.splice(cloneIndex); }; __proto.findPanelOf = function (element) { var allPanels = this.allPanels(); for (var _i = 0, allPanels_1 = allPanels; _i < allPanels_1.length; _i++) { var panel = allPanels_1[_i]; if (!panel) { continue; } var panelElement = panel.getElement(); if (panelElement.contains(element)) { return panel; } } }; __proto.findFirstPanelFrom = function (index) { for (var _i = 0, _a = this.panels.slice(index); _i < _a.length; _i++) { var panel = _a[_i]; if (panel && panel.getIndex() >= index && panel.getElement().parentNode) { return panel; } } }; __proto.addNewClones = function (index, originalPanels, deleteCount, nextSibling) { var _this = this; var cameraElement = this.cameraElement; var cloneCount = this.getCloneCount(); var lastPanel = this.lastPanel(); var lastPanelClones = lastPanel ? lastPanel.getClonedPanels() : []; var nextSiblingClones = nextSibling ? nextSibling.getClonedPanels() : []; var _loop_1 = function (cloneIndex) { var cloneNextSibling = nextSiblingClones[cloneIndex]; var lastPanelSibling = lastPanelClones[cloneIndex]; var cloneSiblingElement = cloneNextSibling ? cloneNextSibling.getElement() : lastPanelSibling ? lastPanelSibling.getElement().nextElementSibling : null; var newClones = originalPanels.map(function (panel) { var clone = panel.clone(cloneIndex); if (_this.shouldRender()) { cameraElement.insertBefore(clone.getElement(), cloneSiblingElement); } return clone; }); this_1.insertClones(cloneIndex, index, newClones, deleteCount); }; var this_1 = this; for (var _i = 0, _a = counter(cloneCount); _i < _a.length; _i++) { var cloneIndex = _a[_i]; _loop_1(cloneIndex); } }; __proto.updateIndex = function (insertingIndex) { var panels = this.panels; var range = this.range; var newLastIndex = panels.length - 1; if (newLastIndex > range.max) { range.max = newLastIndex; } if (insertingIndex < range.min || range.min < 0) { range.min = insertingIndex; } }; __proto.insertNewPanels = function (newPanels, siblingElement) { if (this.shouldRender()) { var fragment_1 = document.createDocumentFragment(); newPanels.forEach(function (panel) { return fragment_1.appendChild(panel.getElement()); }); this.cameraElement.insertBefore(fragment_1, siblingElement); } }; __proto.shouldRender = function () { var options = this.options; return !options.renderExternal && !options.renderOnlyVisible; }; return PanelManager; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var State = /*#__PURE__*/ function () { function State() { this.delta = 0; this.direction = null; this.targetPanel = null; this.lastPosition = 0; } var __proto = State.prototype; __proto.onEnter = function (prevState) { this.delta = prevState.delta; this.direction = prevState.direction; this.targetPanel = prevState.targetPanel; this.lastPosition = prevState.lastPosition; }; __proto.onExit = function (nextState) {// DO NOTHING }; __proto.onHold = function (e, context) {// DO NOTHING }; __proto.onChange = function (e, context) {// DO NOTHING }; __proto.onRelease = function (e, context) {// DO NOTHING }; __proto.onAnimationEnd = function (e, context) {// DO NOTHING }; __proto.onFinish = function (e, context) {// DO NOTHING }; return State; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var IdleState = /*#__PURE__*/ function (_super) { __extends(IdleState, _super); function IdleState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.IDLE; _this.holding = false; _this.playing = false; return _this; } var __proto = IdleState.prototype; __proto.onEnter = function () { this.direction = null; this.targetPanel = null; this.delta = 0; this.lastPosition = 0; }; __proto.onHold = function (e, _a) { var flicking = _a.flicking, viewport = _a.viewport, triggerEvent = _a.triggerEvent, transitTo = _a.transitTo; // Shouldn't do any action until any panels on flicking area if (flicking.getPanelCount() <= 0) { if (viewport.options.infinite) { viewport.moveCamera(viewport.getCameraPosition(), e); } transitTo(STATE_TYPE.DISABLED); return; } this.lastPosition = viewport.getCameraPosition(); triggerEvent(EVENTS.HOLD_START, e, true).onSuccess(function () { transitTo(STATE_TYPE.HOLDING); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; // By methods call __proto.onChange = function (e, context) { var triggerEvent = context.triggerEvent, transitTo = context.transitTo; triggerEvent(EVENTS.MOVE_START, e, false).onSuccess(function () { // Trigger AnimatingState's onChange, to trigger "move" event immediately transitTo(STATE_TYPE.ANIMATING).onChange(e, context); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; return IdleState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var HoldingState = /*#__PURE__*/ function (_super) { __extends(HoldingState, _super); function HoldingState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.HOLDING; _this.holding = true; _this.playing = true; _this.releaseEvent = null; return _this; } var __proto = HoldingState.prototype; __proto.onChange = function (e, context) { var flicking = context.flicking, triggerEvent = context.triggerEvent, transitTo = context.transitTo; var offset = flicking.options.horizontal ? e.inputEvent.offsetX : e.inputEvent.offsetY; this.direction = offset < 0 ? DIRECTION.NEXT : DIRECTION.PREV; triggerEvent(EVENTS.MOVE_START, e, true).onSuccess(function () { // Trigger DraggingState's onChange, to trigger "move" event immediately transitTo(STATE_TYPE.DRAGGING).onChange(e, context); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; __proto.onRelease = function (e, context) { var viewport = context.viewport, triggerEvent = context.triggerEvent, transitTo = context.transitTo; triggerEvent(EVENTS.HOLD_END, e, true); if (e.delta.flick !== 0) { // Sometimes "release" event on axes triggered before "change" event // Especially if user flicked panel fast in really short amount of time // if delta is not zero, that means above case happened. // Event flow should be HOLD_START -> MOVE_START -> MOVE -> HOLD_END // At least one move event should be included between holdStart and holdEnd e.setTo({ flick: viewport.getCameraPosition() }, 0); transitTo(STATE_TYPE.IDLE); return; } // Can't handle select event here, // As "finish" axes event happens this.releaseEvent = e; }; __proto.onFinish = function (e, _a) { var viewport = _a.viewport, triggerEvent = _a.triggerEvent, transitTo = _a.transitTo; // Should transite to IDLE state before select event // As user expects hold is already finished transitTo(STATE_TYPE.IDLE); if (!this.releaseEvent) { return; } // Handle release event here // To prevent finish event called twice var releaseEvent = this.releaseEvent; // Static click var srcEvent = releaseEvent.inputEvent.srcEvent; var clickedElement; if (srcEvent.type === "touchend") { var touchEvent = srcEvent; var touch = touchEvent.changedTouches[0]; clickedElement = document.elementFromPoint(touch.clientX, touch.clientY); } else { clickedElement = srcEvent.target; } var clickedPanel = viewport.panelManager.findPanelOf(clickedElement); var cameraPosition = viewport.getCameraPosition(); if (clickedPanel) { var clickedPanelPosition = clickedPanel.getPosition(); var direction = clickedPanelPosition > cameraPosition ? DIRECTION.NEXT : clickedPanelPosition < cameraPosition ? DIRECTION.PREV : null; // Don't provide axes event, to use axes instance instead triggerEvent(EVENTS.SELECT, null, true, { direction: direction, index: clickedPanel.getIndex(), panel: clickedPanel }); } }; return HoldingState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var DraggingState = /*#__PURE__*/ function (_super) { __extends(DraggingState, _super); function DraggingState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.DRAGGING; _this.holding = true; _this.playing = true; return _this; } var __proto = DraggingState.prototype; __proto.onChange = function (e, _a) { var moveCamera = _a.moveCamera, transitTo = _a.transitTo; if (!e.delta.flick) { return; } moveCamera(e).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; __proto.onRelease = function (e, context) { var flicking = context.flicking, viewport = context.viewport, triggerEvent = context.triggerEvent, transitTo = context.transitTo, stopCamera = context.stopCamera; var delta = this.delta; var absDelta = Math.abs(delta); var options = flicking.options; var horizontal = options.horizontal; var moveType = viewport.moveType; var inputEvent = e.inputEvent; var velocity = horizontal ? inputEvent.velocityX : inputEvent.velocityY; var inputDelta = horizontal ? inputEvent.deltaX : inputEvent.deltaY; var isNextDirection = Math.abs(velocity) > 1 ? velocity < 0 : absDelta > 0 ? delta > 0 : inputDelta < 0; var swipeDistance = viewport.options.bound ? Math.max(absDelta, Math.abs(inputDelta)) : absDelta; var swipeAngle = inputEvent.deltaX ? Math.abs(180 * Math.atan(inputEvent.deltaY / inputEvent.deltaX) / Math.PI) : 90; var belowAngleThreshold = horizontal ? swipeAngle <= options.thresholdAngle : swipeAngle > options.thresholdAngle; var overThreshold = swipeDistance >= options.threshold && belowAngleThreshold; var moveTypeContext = { viewport: viewport, axesEvent: e, state: this, swipeDistance: swipeDistance, isNextDirection: isNextDirection }; // Update last position to cope with Axes's animating behavior // Axes uses start position when animation start triggerEvent(EVENTS.HOLD_END, e, true); var targetPanel = this.targetPanel; if (!overThreshold && targetPanel) { // Interrupted while animating var interruptDestInfo = moveType.findPanelWhenInterrupted(moveTypeContext); viewport.moveTo(interruptDestInfo.panel, interruptDestInfo.destPos, interruptDestInfo.eventType, e, interruptDestInfo.duration); transitTo(STATE_TYPE.ANIMATING); return; } var currentPanel = viewport.getCurrentPanel(); var nearestPanel = viewport.getNearestPanel(); if (!currentPanel || !nearestPanel) { // There're no panels e.stop(); transitTo(STATE_TYPE.IDLE); return; } var destInfo = overThreshold ? moveType.findTargetPanel(moveTypeContext) : moveType.findRestorePanel(moveTypeContext); viewport.moveTo(destInfo.panel, destInfo.destPos, destInfo.eventType, e, destInfo.duration).onSuccess(function () { transitTo(STATE_TYPE.ANIMATING); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); stopCamera(e); }); }; return DraggingState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var AnimatingState = /*#__PURE__*/ function (_super) { __extends(AnimatingState, _super); function AnimatingState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.ANIMATING; _this.holding = false; _this.playing = true; return _this; } var __proto = AnimatingState.prototype; __proto.onHold = function (e, _a) { var viewport = _a.viewport, triggerEvent = _a.triggerEvent, transitTo = _a.transitTo; var options = viewport.options; var scrollArea = viewport.getScrollArea(); var scrollAreaSize = viewport.getScrollAreaSize(); var loopCount = Math.floor((this.lastPosition + this.delta - scrollArea.prev) / scrollAreaSize); var targetPanel = this.targetPanel; if (options.circular && loopCount !== 0 && targetPanel) { var cloneCount = viewport.panelManager.getCloneCount(); var originalTargetPosition = targetPanel.getPosition(); // cloneIndex is from -1 to cloneCount - 1 var newCloneIndex = circulate(targetPanel.getCloneIndex() - loopCount, -1, cloneCount - 1, true); var newTargetPosition = originalTargetPosition - loopCount * scrollAreaSize; var newTargetPanel = targetPanel.getIdenticalPanels()[newCloneIndex + 1].clone(newCloneIndex, true); // Set new target panel considering looped count newTargetPanel.setPosition(newTargetPosition); this.targetPanel = newTargetPanel; } // Reset last position and delta this.delta = 0; this.lastPosition = viewport.getCameraPosition(); // Update current panel as current nearest panel viewport.setCurrentPanel(viewport.getNearestPanel()); triggerEvent(EVENTS.HOLD_START, e, true).onSuccess(function () { transitTo(STATE_TYPE.DRAGGING); }).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; __proto.onChange = function (e, _a) { var moveCamera = _a.moveCamera, transitTo = _a.transitTo; if (!e.delta.flick) { return; } moveCamera(e).onStopped(function () { transitTo(STATE_TYPE.DISABLED); }); }; __proto.onFinish = function (e, _a) { var flicking = _a.flicking, viewport = _a.viewport, triggerEvent = _a.triggerEvent, transitTo = _a.transitTo; var isTrusted = e && e.isTrusted; viewport.options.bound ? viewport.setCurrentPanel(this.targetPanel) : viewport.setCurrentPanel(viewport.getNearestPanel()); if (flicking.options.adaptive) { viewport.updateAdaptiveSize(); } transitTo(STATE_TYPE.IDLE); triggerEvent(EVENTS.MOVE_END, e, isTrusted, { direction: this.direction }); }; return AnimatingState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var DisabledState = /*#__PURE__*/ function (_super) { __extends(DisabledState, _super); function DisabledState() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.type = STATE_TYPE.DISABLED; _this.holding = false; _this.playing = true; return _this; } var __proto = DisabledState.prototype; __proto.onAnimationEnd = function (e, _a) { var transitTo = _a.transitTo; transitTo(STATE_TYPE.IDLE); }; __proto.onChange = function (e, _a) { var viewport = _a.viewport, transitTo = _a.transitTo; // Can stop Axes's change event e.stop(); // Should update axes position as it's already changed at this moment viewport.updateAxesPosition(viewport.getCameraPosition()); transitTo(STATE_TYPE.IDLE); }; __proto.onRelease = function (e, _a) { var transitTo = _a.transitTo; // This is needed when stopped hold start event if (e.delta.flick === 0) { transitTo(STATE_TYPE.IDLE); } }; return DisabledState; }(State); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var StateMachine = /*#__PURE__*/ function () { function StateMachine() { var _this = this; this.state = new IdleState(); this.transitTo = function (nextStateType) { var currentState = _this.state; if (currentState.type !== nextStateType) { var nextState = void 0; switch (nextStateType) { case STATE_TYPE.IDLE: nextState = new IdleState(); break; case STATE_TYPE.HOLDING: nextState = new HoldingState(); break; case STATE_TYPE.DRAGGING: nextState = new DraggingState(); break; case STATE_TYPE.ANIMATING: nextState = new AnimatingState(); break; case STATE_TYPE.DISABLED: nextState = new DisabledState(); break; } currentState.onExit(nextState); nextState.onEnter(currentState); _this.state = nextState; } return _this.state; }; } var __proto = StateMachine.prototype; __proto.fire = function (eventType, e, context) { var currentState = this.state; switch (eventType) { case AXES_EVENTS.HOLD: currentState.onHold(e, context); break; case AXES_EVENTS.CHANGE: currentState.onChange(e, context); break; case AXES_EVENTS.RELEASE: currentState.onRelease(e, context); break; case AXES_EVENTS.ANIMATION_END: currentState.onAnimationEnd(e, context); break; case AXES_EVENTS.FINISH: currentState.onFinish(e, context); break; } }; __proto.getState = function () { return this.state; }; return StateMachine; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var MoveType = /*#__PURE__*/ function () { function MoveType() {} var __proto = MoveType.prototype; __proto.is = function (type) { return type === this.type; }; __proto.findRestorePanel = function (ctx) { var viewport = ctx.viewport; var options = viewport.options; var panel = options.circular ? this.findRestorePanelInCircularMode(ctx) : viewport.getCurrentPanel(); return { panel: panel, destPos: viewport.findEstimatedPosition(panel), duration: options.duration, eventType: EVENTS.RESTORE }; }; __proto.findPanelWhenInterrupted = function (ctx) { var state = ctx.state, viewport = ctx.viewport; var targetPanel = state.targetPanel; return { panel: targetPanel, destPos: viewport.findEstimatedPosition(targetPanel), duration: viewport.options.duration, eventType: "" }; }; // Calculate minimum distance to "change" panel __proto.calcBrinkOfChange = function (ctx) { var viewport = ctx.viewport, isNextDirection = ctx.isNextDirection; var options = viewport.options; var currentPanel = viewport.getCurrentPanel(); var halfGap = options.gap / 2; var relativeAnchorPosition = currentPanel.getRelativeAnchorPosition(); // Minimum distance needed to decide prev/next panel as nearest /* * | Prev | Next | * |--------|--------------| * [][ |<-Anchor ][] <- Panel + Half-Gap */ var minimumDistanceToChange = isNextDirection ? currentPanel.getSize() - relativeAnchorPosition + halfGap : relativeAnchorPosition + halfGap; minimumDistanceToChange = Math.max(minimumDistanceToChange, options.threshold); return minimumDistanceToChange; }; __proto.findRestorePanelInCircularMode = function (ctx) { var viewport = ctx.viewport; var originalPanel = viewport.getCurrentPanel().getOriginalPanel(); var hangerPosition = viewport.getHangerPosition(); var firstClonedPanel = originalPanel.getIdenticalPanels()[1]; var lapped = Math.abs(originalPanel.getAnchorPosition() - hangerPosition) > Math.abs(firstClonedPanel.getAnchorPosition() - hangerPosition); return !ctx.isNextDirection && lapped ? firstClonedPanel : originalPanel; }; return MoveType; }(); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var Snap = /*#__PURE__*/ function (_super) { __extends(Snap, _super); function Snap(count) { var _this = _super.call(this) || this; _this.type = MOVE_TYPE.SNAP; _this.count = count; return _this; } var __proto = Snap.prototype; __proto.findTargetPanel = function (ctx) { var viewport = ctx.viewport, axesEvent = ctx.axesEvent, swipeDistance = ctx.swipeDistance; var snapCount = this.count; var eventDelta = Math.abs(axesEvent.delta.flick); var currentPanel = viewport.getCurrentPanel(); var nearestPanel = viewport.getNearestPanel(); var minimumDistanceToChange = this.calcBrinkOfChange(ctx); var nearestIsCurrent = nearestPanel.getIndex() === currentPanel.getIndex(); // This can happen when bounce is 0 var shouldMoveWhenBounceIs0 = viewport.canSetBoundMode() && nearestIsCurrent; var shouldMoveToAdjacent = !viewport.isOutOfBound() && (swipeDistance <= minimumDistanceToChange || shouldMoveWhenBounceIs0); if (snapCount > 1 && eventDelta > minimumDistanceToChange) { return this.findSnappedPanel(ctx); } else if (shouldMoveToAdjacent) { return this.findAdjacentPanel(ctx); } else { return { panel: nearestPanel, duration: viewport.options.duration, destPos: viewport.findEstimatedPosition(nearestPanel), // As swipeDistance holds mouse/touch position change regardless of bounce option value // swipDistance > minimumDistanceToChange can happen in bounce area // Second condition is for handling that. eventType: swipeDistance <= minimumDistanceToChange || viewport.isOutOfBound() && nearestIsCurrent ? EVENTS.RESTORE : EVENTS.CHANGE }; } }; __proto.findSnappedPanel = function (ctx) { var axesEvent = ctx.axesEvent, viewport = ctx.viewport, state = ctx.state, isNextDirection = ctx.isNextDirection; var eventDelta = Math.abs(axesEvent.delta.flick); var minimumDistanceToChange = this.calcBrinkOfChange(ctx); var snapCount = this.count; var options = viewport.options; var scrollAreaSize = viewport.getScrollAreaSize(); var halfGap = options.gap / 2; var estimatedHangerPos = axesEvent.destPos.flick + viewport.getRelativeHangerPosition(); var panelToMove = viewport.getNearestPanel(); var cycleIndex = panelToMove.getCloneIndex() + 1; // 0(original) or 1(clone) var passedPanelCount = 0; while (passedPanelCount < snapCount) { // Since panelToMove holds also cloned panels, we should use original panel's position var originalPanel = panelToMove.getOriginalPanel(); var panelPosition = originalPanel.getPosition() + cycleIndex * scrollAreaSize; var panelSize = originalPanel.getSize(); var panelNextPosition = panelPosition + panelSize + halfGap; var panelPrevPosition = panelPosition - halfGap; // Current panelToMove contains destPos if (isNextDirection && panelNextPosition > estimatedHangerPos || !isNextDirection && panelPrevPosition < estimatedHangerPos) { break; } var siblingPanel = isNextDirection ? panelToMove.nextSibling : panelToMove.prevSibling; if (!siblingPanel) { break; } var panelIndex = panelToMove.getIndex(); var siblingIndex = siblingPanel.getIndex(); if (isNextDirection && siblingIndex <= panelIndex || !isNextDirection && siblingIndex >= panelIndex) { cycleIndex = isNextDirection ? cycleIndex + 1 : cycleIndex - 1; } panelToMove = siblingPanel; passedPanelCount += 1; } var originalPosition = panelToMove.getOriginalPanel().getPosition(); if (cycleIndex !== 0) { panelToMove = panelToMove.clone(panelToMove.getCloneIndex(), true); panelToMove.setPosition(originalPosition + cycleIndex * scrollAreaSize); } var defaultDuration = viewport.options.duration; var duration = clamp(axesEvent.duration, defaultDuration, defaultDuration * passedPanelCount); return { panel: panelToMove, destPos: viewport.findEstimatedPosition(panelToMove), duration: duration, eventType: Math.max(eventDelta, state.delta) > minimumDistanceToChange ? EVENTS.CHANGE : EVENTS.RESTORE }; }; __proto.findAdjacentPanel = function (ctx) { var viewport = ctx.viewport, isNextDirection = ctx.isNextDirection; var options = viewport.options; var currentIndex = viewport.getCurrentIndex(); var currentPanel = viewport.panelManager.get(currentIndex); var hangerPosition = viewport.getHangerPosition(); var scrollArea = viewport.getScrollArea(); var firstClonedPanel = currentPanel.getIdenticalPanels()[1]; var lapped = options.circular && Math.abs(currentPanel.getAnchorPosition() - hangerPosition) > Math.abs(firstClonedPanel.getAnchorPosition() - hangerPosition); // If lapped in circular mode, use first cloned panel as base panel var basePanel = lapped ? firstClonedPanel : currentPanel; var basePosition = basePanel.getPosition(); var adjacentPanel = isNextDirection ? basePanel.nextSibling : basePanel.prevSibling; var eventType = adjacentPanel ? EVENTS.CHANGE : EVENTS.RESTORE; var panelToMove = adjacentPanel ? adjacentPanel : basePanel; var targetRelativeAnchorPosition = panelToMove.getRelativeAnchorPosition(); var estimatedPanelPosition = options.circular ? isNextDirection ? basePosition + basePanel.getSize() + targetRelativeAnchorPosition + options.gap : basePosition - (panelToMove.getSize() - targetRelativeAnchorPosition) - options.gap : panelToMove.getAnchorPosition(); var estimatedPosition = estimatedPanelPosition - viewport.getRelativeHangerPosition(); var destPos = viewport.canSetBoundMode() ? clamp(estimatedPosition, scrollArea.prev, scrollArea.next) : estimatedPosition; return { panel: panelToMove, destPos: destPos, duration: options.duration, eventType: eventType }; }; return Snap; }(MoveType); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var FreeScroll = /*#__PURE__*/ function (_super) { __extends(FreeScroll, _super); function FreeScroll() { var _this = // Set snap count to Infinity _super.call(this, Infinity) || this; _this.type = MOVE_TYPE.FREE_SCROLL; return _this; } var __proto = FreeScroll.prototype; __proto.findTargetPanel = function (ctx) { var axesEvent = ctx.axesEvent, state = ctx.state, viewport = ctx.viewport; var destPos = axesEvent.destPos.flick; var minimumDistanceToChange = this.calcBrinkOfChange(ctx); var scrollArea = viewport.getScrollArea(); var currentPanel = viewport.getCurrentPanel(); var options = viewport.options; var delta = Math.abs(axesEvent.delta.flick + state.delta); if (delta > minimumDistanceToChange) { var destInfo = _super.prototype.findSnappedPanel.call(this, ctx); destInfo.duration = axesEvent.duration; destInfo.destPos = destPos; destInfo.eventType = !options.circular && destInfo.panel === currentPanel ? "" : EVENTS.CHANGE; return destInfo; } else { var estimatedPosition = options.circular ? circulate(destPos, scrollArea.prev, scrollArea.next, false) : destPos; estimatedPosition = clamp(estimatedPosition, scrollArea.prev, scrollArea.next); estimatedPosition += viewport.getRelativeHangerPosition(); var estimatedPanel = viewport.findNearestPanelAt(estimatedPosition); return { panel: estimatedPanel, destPos: destPos, duration: axesEvent.duration, eventType: "" }; } }; __proto.findRestorePanel = function (ctx) { return this.findTargetPanel(ctx); }; __proto.findPanelWhenInterrupted = function (ctx) { var viewport = ctx.viewport; return { panel: viewport.getNearestPanel(), destPos: viewport.getCameraPosition(), duration: 0, eventType: "" }; }; __proto.calcBrinkOfChange = function (ctx) { var viewport = ctx.viewport, isNextDirection = ctx.isNextDirection; var options = viewport.options; var currentPanel = viewport.getCurrentPanel(); var halfGap = options.gap / 2; var lastPosition = viewport.stateMachine.getState().lastPosition; var currentPanelPosition = currentPanel.getPosition(); // As camera can stop anywhere in free scroll mode, // minimumDistanceToChange should be calculated differently. // Ref #191(https://github.com/naver/egjs-flicking/issues/191) var lastHangerPosition = lastPosition + viewport.getRelativeHangerPosition(); var scrollAreaSize = viewport.getScrollAreaSize(); var minimumDistanceToChange = isNextDirection ? currentPanelPosition + currentPanel.getSize() - lastHangerPosition + halfGap : lastHangerPosition - currentPanelPosition + halfGap; minimumDistanceToChange = Math.abs(minimumDistanceToChange % scrollAreaSize); return Math.min(minimumDistanceToChange, scrollAreaSize - minimumDistanceToChange); }; return FreeScroll; }(Snap); /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ var Viewport = /*#__PURE__*/ function () { function Viewport(flicking, options, triggerEvent) { var _this = this; this.plugins = []; this.stopCamera = function (axesEvent) { if (axesEvent && axesEvent.setTo) { axesEvent.setTo({ flick: _this.state.position }, 0); } _this.stateMachine.transitTo(STATE_TYPE.IDLE); }; this.flicking = flicking; this.triggerEvent = triggerEvent; this.state = { size: 0, position: 0, panelMaintainRatio: 0, relativeHangerPosition: 0, positionOffset: 0, scrollArea: { prev: 0, next: 0 }, visibleIndex: { min: NaN, max: NaN }, translate: TRANSFORM, infiniteThreshold: 0, checkedIndexes: [], isAdaptiveCached: false, isViewportGiven: false, isCameraGiven: false, originalViewportStyle: { className: null, style: null }, originalCameraStyle: { className: null, style: null }, cachedBbox: null }; this.options = options; this.stateMachine = new StateMachine(); this.visiblePanels = []; this.panelBboxes = {}; this.build(); } var __proto = Viewport.prototype; __proto.moveTo = function (panel, destPos, eventType, axesEvent, duration) { var _this = this; if (duration === void 0) { duration = this.options.duration; } var state = this.state; var currentState = this.stateMachine.getState(); var currentPosition = state.position; var isTrusted = axesEvent ? axesEvent.isTrusted : false; var direction = destPos === currentPosition ? null : destPos > currentPosition ? DIRECTION.NEXT : DIRECTION.PREV; var eventResult; if (eventType === EVENTS.CHANGE) { eventResult = this.triggerEvent(EVENTS.CHANGE, axesEvent, isTrusted, { index: panel.getIndex(), panel: panel, direction: direction }); } else if (eventType === EVENTS.RESTORE) { eventResult = this.triggerEvent(EVENTS.RESTORE, axesEvent, isTrusted); } else { eventResult = { onSuccess: function (callback) { callback(); return this; }, onStopped: function () { return this; } }; } eventResult.onSuccess(function () { currentState.delta = 0; currentState.lastPosition = _this.getCameraPosition(); currentState.targetPanel = panel; currentState.direction = destPos === currentPosition ? null : destPos > currentPosition ? DIRECTION.NEXT : DIRECTION.PREV; if (destPos === currentPosition) { // no move _this.nearestPanel = panel; _this.currentPanel = panel; } if (axesEvent && axesEvent.setTo) { // freeScroll only occurs in release events axesEvent.setTo({ flick: destPos }, duration); } else { _this.axes.setTo({ flick: destPos }, duration); } }); return eventResult; }; __proto.moveCamera = function (pos, axesEvent) { var state = this.state; var options = this.options; var transform = state.translate.name; var scrollArea = state.scrollArea; // Update position & nearestPanel if (options.circular && !isBetween(pos, scrollArea.prev, scrollArea.next)) { pos = circulate(pos, scrollArea.prev, scrollArea.next, false); } state.position = pos; this.nearestPanel = this.findNearestPanel(); var nearestPanel = this.nearestPanel; var originalNearestPosition = nearestPanel ? nearestPanel.getPosition() : 0; // From 0(panel position) to 1(panel position + panel size) // When it's on gap area value will be (val > 1 || val < 0) if (nearestPanel) { var hangerPosition = this.getHangerPosition(); var panelPosition = nearestPanel.getPosition(); var panelSize = nearestPanel.getSize(); var halfGap = options.gap / 2; // As panel's range is from panel position - half gap ~ panel pos + panel size + half gap state.panelMaintainRatio = (hangerPosition - panelPosition + halfGap) / (panelSize + 2 * halfGap); } else { state.panelMaintainRatio = 0; } this.checkNeedPanel(axesEvent); // Possibly modified after need panel, if it's looped var modifiedNearestPosition = nearestPanel ? nearestPanel.getPosition() : 0; pos += modifiedNearestPosition - originalNearestPosition; state.position = pos; this.updateVisiblePanels(); // Offset is needed to fix camera layer size in visible-only rendering mode var posOffset = options.renderOnlyVisible ? state.positionOffset : 0; var moveVector = options.horizontal ? [-(pos - posOffset), 0] : [0, -(pos - posOffset)]; var moveCoord = moveVector.map(function (coord) { return Math.round(coord) + "px"; }).join(", "); this.cameraElement.style[transform] = state.translate.has3d ? "translate3d(" + moveCoord + ", 0px)" : "translate(" + moveCoord + ")"; }; __proto.unCacheBbox = function () { var state = this.state; var options = this.options; state.cachedBbox = null; state.visibleIndex = { min: NaN, max: NaN }; var viewportElement = this.viewportElement; if (!options.horizontal) { // Don't preserve previous width for adaptive resizing viewportElement.style.width = ""; } else { viewportElement.style.height = ""; } state.isAdaptiveCached = false; this.panelBboxes = {}; }; __proto.resize = function () { this.updateSize(); this.updateOriginalPanelPositions(); this.updateAdaptiveSize(); this.updateScrollArea(); this.updateClonePanels(); this.updateCameraPosition(); this.updatePlugins(); }; // Find nearest anchor from current hanger position __proto.findNearestPanel = function () { var state = this.state; var panelManager = this.panelManager; var hangerPosition = this.getHangerPosition(); if (this.isOutOfBound()) { var position = state.position; return position <= state.scrollArea.prev ? panelManager.firstPanel() : panelManager.lastPanel(); } return this.findNearestPanelAt(hangerPosition); }; __proto.findNearestPanelAt = function (position) { var panelManager = this.panelManager; var allPanels = panelManager.allPanels(); var minimumDistance = Infinity; var nearestPanel; for (var _i = 0, allPanels_1 = allPanels; _i < allPanels_1.length; _i++) { var panel = allPanels_1[_i]; if (!panel) { continue; } var prevPosition = panel.getPosition(); var nextPosition = prevPosition + panel.getSize(); // Use shortest distance from panel's range var distance = isBetween(position, prevPosition, nextPosition) ? 0 : Math.min(Math.abs(prevPosition - position), Math.abs(nextPosition - position)); if (distance > minimumDistance) { break; } else if (distance === minimumDistance) { var minimumAnchorDistance = Math.abs(position - nearestPanel.getAnchorPosition()); var anchorDistance = Math.abs(position - panel.getAnchorPosition()); if (anchorDistance > minimumAnchorDistance) { break; } } minimumDistance = distance; nearestPanel = panel; } return nearestPanel; }; __proto.findNearestIdenticalPanel = function (panel) { var nearest = panel; var shortestDistance = Infinity; var hangerPosition = this.getHangerPosition(); var identicals = panel.getIdenticalPanels(); identicals.forEach(function (identical) { var anchorPosition = identical.getAnchorPosition(); var distance = Math.abs(anchorPosition - hangerPosition); if (distance < shortestDistance) { nearest = identical; shortestDistance = distance; } }); return nearest; }; // Find shortest camera position that distance is minimum __proto.findShortestPositionToPanel = function (panel) { var state = this.state; var options = this.options; var anchorPosition = panel.getAnchorPosition(); var hangerPosition = this.getHangerPosition(); var distance = Math.abs(hangerPosition - anchorPosition); var scrollAreaSize = state.scrollArea.next - state.scrollArea.prev; if (!options.circular) { var position = anchorPosition - state.relativeHangerPosition; return this.canSetBoundMode() ? clamp(position, state.scrollArea.prev, state.scrollArea.next) : position; } else { // If going out of viewport border is more efficient way of moving, choose that position return distance <= scrollAreaSize - distance ? anchorPosition - state.relativeHangerPosition : anchorPosition > hangerPosition // PREV TO NEXT ? anchorPosition - state.relativeHangerPosition - scrollAreaSize // NEXT TO PREV : anchorPosition - state.relativeHangerPosition + scrollAreaSize; } }; __proto.findEstimatedPosition = function (panel) { var scrollArea = this.getScrollArea(); var estimatedPosition = panel.getAnchorPosition() - this.getRelativeHangerPosition(); estimatedPosition = this.canSetBoundMode() ? clamp(estimatedPosition, scrollArea.prev, scrollArea.next) : estimatedPosition; return estimatedPosition; }; __proto.addVisiblePanel = function (panel) { if (this.getVisibleIndexOf(panel) < 0) { this.visiblePanels.push(panel); } }; __proto.enable = function () { this.panInput.enable(); }; __proto.disable = function () { this.panInput.disable(); }; __proto.insert = function (index, element) { var _this = this; var lastIndex = this.panelManager.getLastIndex(); // Index should not below 0 if (index < 0 || index > lastIndex) { return []; } var state = this.state; var options = this.options; var parsedElements = parseElement(element); var panels = parsedElements.map(function (el, idx) { return new Panel(el, index + idx, _this); }).slice(0, lastIndex - index + 1); if (panels.length <= 0) { return []; } var pushedIndex = this.panelManager.insert(index, panels); // ...then calc bbox for all panels this.resizePanels(panels); if (!this.currentPanel) { this.currentPanel = panels[0]; this.nearestPanel = panels[0]; var newCenterPanel = panels[0]; var newPanelPosition = this.findEstimatedPosition(newCenterPanel); state.position = newPanelPosition; this.updateAxesPosition(newPanelPosition); state.panelMaintainRatio = (newCenterPanel.getRelativeAnchorPosition() + options.gap / 2) / (newCenterPanel.getSize() + options.gap); } // Update checked indexes in infinite mode this.updateCheckedIndexes({ min: index, max: index }); state.checkedIndexes.forEach(function (indexes, idx) { var min = indexes[0], max = indexes[1]; if (index < min) { // Push checked index state.checkedIndexes.splice(idx, 1, [min + pushedIndex, max + pushedIndex]); } }); // Uncache visible index to refresh panels state.visibleIndex = { min: NaN, max: NaN }; this.resize(); return panels; }; __proto.replace = function (index, element) { var _this = this; var state = this.state; var options = this.options; var panelManager = this.panelManager; var lastIndex = panelManager.getLastIndex(); // Index should not below 0 if (index < 0 || index > lastIndex) { return []; } var parsedElements = parseElement(element); var panels = parsedElements.map(function (el, idx) { return new Panel(el, index + idx, _this); }).slice(0, lastIndex - index + 1); if (panels.length <= 0) { return []; } var replacedPanels = panelManager.replace(index, panels); replacedPanels.forEach(function (panel) { var visibleIndex = _this.getVisibleIndexOf(panel); if (visibleIndex > -1) { _this.visiblePanels.splice(visibleIndex, 1); } }); // ...then calc bbox for all panels this.resizePanels(panels); var currentPanel = this.currentPanel; var wasEmpty = !currentPanel; if (wasEmpty) { this.currentPanel = panels[0]; this.nearestPanel = panels[0]; var newCenterPanel = panels[0]; var newPanelPosition = this.findEstimatedPosition(newCenterPanel); state.position = newPanelPosition; this.updateAxesPosition(newPanelPosition); state.panelMaintainRatio = (newCenterPanel.getRelativeAnchorPosition() + options.gap / 2) / (newCenterPanel.getSize() + options.gap); } else if (isBetween(currentPanel.getIndex(), index, index + panels.length - 1)) { // Current panel is replaced this.currentPanel = panelManager.get(currentPanel.getIndex()); } // Update checked indexes in infinite mode this.updateCheckedIndexes({ min: index, max: index + panels.length - 1 }); // Uncache visible index to refresh panels state.visibleIndex = { min: NaN, max: NaN }; this.resize(); return panels; }; __proto.remove = function (index, deleteCount) { if (deleteCount === void 0) { deleteCount = 1; } var state = this.state; // Index should not below 0 index = Math.max(index, 0); var panelManager = this.panelManager; var currentIndex = this.getCurrentIndex(); var removedPanels = panelManager.remove(index, deleteCount); if (isBetween(currentIndex, index, index + deleteCount - 1)) { // Current panel is removed // Use panel at removing index - 1 as new current panel if it exists var newCurrentIndex = Math.max(index - 1, panelManager.getRange().min); this.currentPanel = panelManager.get(newCurrentIndex); } // Update checked indexes in infinite mode if (deleteCount > 0) { // Check whether removing index will affect checked indexes // Suppose index 0 is empty and removed index 1, then checked index 0 should be deleted and vice versa. this.updateCheckedIndexes({ min: index - 1, max: index + deleteCount }); // Uncache visible index to refresh panels state.visibleIndex = { min: NaN, max: NaN }; } if (panelManager.getPanelCount() <= 0) { this.currentPanel = undefined; this.nearestPanel = undefined; } this.resize(); var scrollArea = state.scrollArea; if (state.position < scrollArea.prev || state.position > scrollArea.next) { var newPosition = circulate(state.position, scrollArea.prev, scrollArea.next, false); this.moveCamera(newPosition); this.updateAxesPosition(newPosition); } return removedPanels; }; __proto.updateAdaptiveSize = function () { var state = this.state; var options = this.options; var horizontal = options.horizontal; var currentPanel = this.getCurrentPanel(); if (!currentPanel) { return; } var shouldApplyAdaptive = options.adaptive || !state.isAdaptiveCached; var viewportStyle = this.viewportElement.style; if (shouldApplyAdaptive) { var sizeToApply = void 0; if (options.adaptive) { var panelBbox = currentPanel.getBbox(); sizeToApply = horizontal ? panelBbox.height : panelBbox.width; } else { // Find minimum height of panels to maximum panel size var maximumPanelSize = this.panelManager.originalPanels().reduce(function (maximum, panel) { var panelBbox = panel.getBbox(); return Math.max(maximum, horizontal ? panelBbox.height : panelBbox.width); }, 0); sizeToApply = maximumPanelSize; } var viewportBbox = this.updateBbox(); sizeToApply = Math.max(sizeToApply, horizontal ? viewportBbox.height : viewportBbox.width); state.isAdaptiveCached = true; var viewportSize = sizeToApply + "px"; if (horizontal) { viewportStyle.height = viewportSize; } else if (!horizontal) { viewportStyle.width = viewportSize; } } }; __proto.updateBbox = function () { var state = this.state; var options = this.options; var viewportElement = this.viewportElement; if (!state.cachedBbox) { state.cachedBbox = getBbox(viewportElement, options.useOffset); } return state.cachedBbox; }; __proto.updatePlugins = function () { var _this = this; // update for resize this.plugins.forEach(function (plugin) { plugin.update && plugin.update(_this.flicking); }); }; __proto.destroy = function (option) { var state = this.state; var wrapper = this.flicking.getElement(); var viewportElement = this.viewportElement; var cameraElement = this.cameraElement; var originalPanels = this.panelManager.originalPanels(); this.removePlugins(this.plugins); if (!option.preserveUI) { restoreStyle(viewportElement, state.originalViewportStyle); restoreStyle(cameraElement, state.originalCameraStyle); if (!state.isCameraGiven && !this.options.renderExternal) { var topmostElement_1 = state.isViewportGiven ? viewportElement : wrapper; var deletingElement = state.isViewportGiven ? cameraElement : viewportElement; originalPanels.forEach(function (panel) { topmostElement_1.appendChild(panel.getElement()); }); topmostElement_1.removeChild(deletingElement); } } this.axes.destroy(); this.panInput.destroy(); originalPanels.forEach(function (panel) { panel.destroy(option); }); // release resources for (var x in this) { this[x] = null; } }; __proto.restore = function (status) { var panels = status.panels; var defaultIndex = this.options.defaultIndex; var cameraElement = this.cameraElement; var panelManager = this.panelManager; // Restore index cameraElement.innerHTML = panels.map(function (panel) { return panel.html; }).join(""); // Create panels first this.refreshPanels(); var createdPanels = panelManager.originalPanels(); // ...then order it by its index var orderedPanels = []; panels.forEach(function (panel, idx) { var createdPanel = createdPanels[idx]; createdPanel.setIndex(panel.index); orderedPanels[panel.index] = createdPanel; }); panelManager.replacePanels(orderedPanels, []); panelManager.setCloneCount(0); // No clones at this point var panelCount = panelManager.getPanelCount(); if (panelCount > 0) { this.currentPanel = panelManager.get(status.index) || panelManager.get(defaultIndex) || panelManager.firstPanel(); this.nearestPanel = this.currentPanel; } else { this.currentPanel = undefined; this.nearestPanel = undefined; } this.visiblePanels = orderedPanels.filter(function (panel) { return Boolean(panel); }); this.resize(); this.axes.setTo({ flick: status.position }, 0); this.moveCamera(status.position); }; __proto.calcVisiblePanels = function () { var allPanels = this.panelManager.allPanels(); if (this.options.renderOnlyVisible) { var _a = this.state.visibleIndex, min = _a.min, max = _a.max; var visiblePanels = min >= 0 ? allPanels.slice(min, max + 1) : allPanels.slice(0, max + 1).concat(allPanels.slice(min)); return visiblePanels.filter(function (panel) { return panel; }); } else { return allPanels.filter(function (panel) { var outsetProgress = panel.getOutsetProgress(); return outsetProgress > -1 && outsetProgress < 1; }); } }; __proto.getCurrentPanel = function () { return this.currentPanel; }; __proto.getCurrentIndex = function () { var currentPanel = this.currentPanel; return currentPanel ? currentPanel.getIndex() : -1; }; __proto.getNearestPanel = function () { return this.nearestPanel; }; // Get progress from nearest panel __proto.getCurrentProgress = function () { var currentState = this.stateMachine.getState(); var nearestPanel = currentState.playing || currentState.holding ? this.nearestPanel : this.currentPanel; var panelManager = this.panelManager; if (!nearestPanel) { // There're no panels return NaN; } var _a = this.getScrollArea(), prevRange = _a.prev, nextRange = _a.next; var cameraPosition = this.getCameraPosition(); var isOutOfBound = this.isOutOfBound(); var prevPanel = nearestPanel.prevSibling; var nextPanel = nearestPanel.nextSibling; var hangerPosition = this.getHangerPosition(); var nearestAnchorPos = nearestPanel.getAnchorPosition(); if (isOutOfBound && prevPanel && nextPanel && cameraPosition < nextRange // On the basis of anchor, prevPanel is nearestPanel. && hangerPosition - prevPanel.getAnchorPosition() < nearestAnchorPos - hangerPosition) { nearestPanel = prevPanel; nextPanel = nearestPanel.nextSibling; prevPanel = nearestPanel.prevSibling; nearestAnchorPos = nearestPanel.getAnchorPosition(); } var nearestIndex = nearestPanel.getIndex() + (nearestPanel.getCloneIndex() + 1) * panelManager.getPanelCount(); var nearestSize = nearestPanel.getSize(); if (isOutOfBound) { var relativeHangerPosition = this.getRelativeHangerPosition(); if (nearestAnchorPos > nextRange + relativeHangerPosition) { // next bounce area: hangerPosition - relativeHangerPosition - nextRange hangerPosition = nearestAnchorPos + hangerPosition - relativeHangerPosition - nextRange; } else if (nearestAnchorPos < prevRange + relativeHangerPosition) { // prev bounce area: hangerPosition - relativeHangerPosition - prevRange hangerPosition = nearestAnchorPos + hangerPosition - relativeHangerPosition - prevRange; } } var hangerIsNextToNearestPanel = hangerPosition >= nearestAnchorPos; var gap = this.options.gap; var basePosition = nearestAnchorPos; var targetPosition = nearestAnchorPos; if (hangerIsNextToNearestPanel) { targetPosition = nextPanel ? nextPanel.getAnchorPosition() : nearestAnchorPos + nearestSize + gap; } else { basePosition = prevPanel ? prevPanel.getAnchorPosition() : nearestAnchorPos - nearestSize - gap; } var progressBetween = (hangerPosition - basePosition) / (targetPosition - basePosition); var startIndex = hangerIsNextToNearestPanel ? nearestIndex : prevPanel ? prevPanel.getIndex() : nearestIndex - 1; return startIndex + progressBetween; }; // Update axes flick position without triggering event __proto.updateAxesPosition = function (position) { var axes = this.axes; axes.off(); axes.setTo({ flick: position }, 0); axes.on(this.axesHandlers); }; __proto.getSize = function () { return this.state.size; }; __proto.getScrollArea = function () { return this.state.scrollArea; }; __proto.isOutOfBound = function () { var state = this.state; var options = this.options; var scrollArea = state.scrollArea; return !options.circular && options.bound && (state.position <= scrollArea.prev || state.position >= scrollArea.next); }; __proto.canSetBoundMode = function () { var state = this.state; var options = this.options; var lastPanel = this.panelManager.lastPanel(); if (!lastPanel) { return false; } var summedPanelSize = lastPanel.getPosition() + lastPanel.getSize(); return options.bound && !options.circular && summedPanelSize >= state.size; }; __proto.getViewportElement = function () { return this.viewportElement; }; __proto.getCameraElement = function () { return this.cameraElement; }; __proto.getScrollAreaSize = function () { var scrollArea = this.state.scrollArea; return scrollArea.next - scrollArea.prev; }; __proto.getRelativeHangerPosition = function () { return this.state.relativeHangerPosition; }; __proto.getHangerPosition = function () { return this.state.position + this.state.relativeHangerPosition; }; __proto.getCameraPosition = function () { return this.state.position; }; __proto.getPositionOffset = function () { return this.state.positionOffset; }; __proto.getCheckedIndexes = function () { return this.state.checkedIndexes; }; __proto.getVisibleIndex = function () { return this.state.visibleIndex; }; __proto.getVisiblePanels = function () { return this.visiblePanels; }; __proto.setCurrentPanel = function (panel) { this.currentPanel = panel; }; __proto.setLastIndex = function (index) { var currentPanel = this.currentPanel; var panelManager = this.panelManager; panelManager.setLastIndex(index); if (currentPanel && currentPanel.getIndex() > index) { this.currentPanel = panelManager.lastPanel(); } this.resize(); }; __proto.setVisiblePanels = function (panels) { this.visiblePanels = panels; }; __proto.connectAxesHandler = function (handlers) { var axes = this.axes; this.axesHandlers = handlers; axes.on(handlers); }; __proto.addPlugins = function (plugins) { var _this = this; var newPlugins = [].concat(plugins); newPlugins.forEach(function (plugin) { plugin.init(_this.flicking); }); this.plugins = this.plugins.concat(newPlugins); return this; }; __proto.removePlugins = function (plugins) { var _this = this; var currentPlugins = this.plugins; var removedPlugins = [].concat(plugins); removedPlugins.forEach(function (plugin) { var index = currentPlugins.indexOf(plugin); if (index > -1) { currentPlugins.splice(index, 1); } plugin.destroy(_this.flicking); }); return this; }; __proto.updateCheckedIndexes = function (changedRange) { var state = this.state; var removed = 0; state.checkedIndexes.concat().forEach(function (indexes, idx) { var min = indexes[0], max = indexes[1]; // Can fill part of indexes in range if (changedRange.min <= max && changedRange.max >= min) { // Remove checked index from list state.checkedIndexes.splice(idx - removed, 1); removed++; } }); }; __proto.resetVisibleIndex = function () { var visibleIndex = this.state.visibleIndex; visibleIndex.min = NaN; visibleIndex.max = NaN; }; __proto.appendUncachedPanelElements = function (panels) { var _this = this; var options = this.options; var fragment = document.createDocumentFragment(); if (options.isEqualSize) { var prevVisiblePanels = this.visiblePanels; var equalSizeClasses_1 = options.isEqualSize; // for readability var cached_1 = {}; this.visiblePanels = []; Object.keys(this.panelBboxes).forEach(function (className) { cached_1[className] = true; }); panels.forEach(function (panel) { var overlappedClass = panel.getOverlappedClass(equalSizeClasses_1); if (overlappedClass && !cached_1[overlappedClass]) { if (!options.renderExternal) { fragment.appendChild(panel.getElement()); } _this.visiblePanels.push(panel); cached_1[overlappedClass] = true; } else if (!overlappedClass) { if (!options.renderExternal) { fragment.appendChild(panel.getElement()); } _this.visiblePanels.push(panel); } }); prevVisiblePanels.forEach(function (panel) { _this.addVisiblePanel(panel); }); } else { if (!options.renderExternal) { panels.forEach(function (panel) { return fragment.appendChild(panel.getElement()); }); } this.visiblePanels = panels.filter(function (panel) { return Boolean(panel); }); } if (!options.renderExternal) { this.cameraElement.appendChild(fragment); } }; __proto.updateClonePanels = function () { var panelManager = this.panelManager; // Clone panels in circular mode if (this.options.circular && panelManager.getPanelCount() > 0) { this.clonePanels(); this.updateClonedPanelPositions(); } panelManager.chainAllPanels(); }; __proto.getVisibleIndexOf = function (panel) { return findIndex(this.visiblePanels, function (visiblePanel) { return visiblePanel === panel; }); }; __proto.build = function () { this.setElements(); this.applyCSSValue(); this.setMoveType(); this.setAxesInstance(); this.refreshPanels(); this.setDefaultPanel(); this.resize(); this.moveToDefaultPanel(); }; __proto.setElements = function () { var state = this.state; var options = this.options; var wrapper = this.flicking.getElement(); var classPrefix = options.classPrefix; var viewportCandidate = wrapper.children[0]; var hasViewportElement = viewportCandidate && hasClass(viewportCandidate, classPrefix + "-viewport"); var viewportElement = hasViewportElement ? viewportCandidate : document.createElement("div"); var cameraCandidate = hasViewportElement ? viewportElement.children[0] : wrapper.children[0]; var hasCameraElement = cameraCandidate && hasClass(cameraCandidate, classPrefix + "-camera"); var cameraElement = hasCameraElement ? cameraCandidate : document.createElement("div"); if (!hasCameraElement) { cameraElement.className = classPrefix + "-camera"; var panelElements = hasViewportElement ? viewportElement.children : wrapper.children; // Make all panels to be a child of camera element // wrapper <- viewport <- camera <- panels[1...n] toArray(panelElements).forEach(function (child) { cameraElement.appendChild(child); }); } else { state.originalCameraStyle = { className: cameraElement.getAttribute("class"), style: cameraElement.getAttribute("style") }; } if (!hasViewportElement) { viewportElement.className = classPrefix + "-viewport"; // Add viewport element to wrapper wrapper.appendChild(viewportElement); } else { state.originalViewportStyle = { className: viewportElement.getAttribute("class"), style: viewportElement.getAttribute("style") }; } if (!hasCameraElement || !hasViewportElement) { viewportElement.appendChild(cameraElement); } this.viewportElement = viewportElement; this.cameraElement = cameraElement; state.isViewportGiven = hasViewportElement; state.isCameraGiven = hasCameraElement; }; __proto.applyCSSValue = function () { var options = this.options; var viewportElement = this.viewportElement; var cameraElement = this.cameraElement; var viewportStyle = this.viewportElement.style; // Set default css values for each element applyCSS(viewportElement, DEFAULT_VIEWPORT_CSS); applyCSS(cameraElement, DEFAULT_CAMERA_CSS); viewportElement.style.zIndex = "" + options.zIndex; if (options.horizontal) { viewportStyle.minHeight = "100%"; viewportStyle.width = "100%"; } else { viewportStyle.minWidth = "100%"; viewportStyle.height = "100%"; } if (options.overflow) { viewportStyle.overflow = "visible"; } this.panelManager = new PanelManager(this.cameraElement, options); }; __proto.setMoveType = function () { var moveType = this.options.moveType; switch (moveType.type) { case MOVE_TYPE.SNAP: this.moveType = new Snap(moveType.count); break; case MOVE_TYPE.FREE_SCROLL: this.moveType = new FreeScroll(); break; default: throw new Error("moveType is not correct!"); } }; __proto.setAxesInstance = function () { var state = this.state; var options = this.options; var scrollArea = state.scrollArea; var horizontal = options.horizontal; this.axes = new Axes({ flick: { range: [scrollArea.prev, scrollArea.next], circular: options.circular, bounce: [0, 0] } }, { easing: options.panelEffect, deceleration: options.deceleration, interruptable: true }); this.panInput = new Axes.PanInput(this.viewportElement, { inputType: options.inputType, thresholdAngle: options.thresholdAngle, scale: options.horizontal ? [-1, 0] : [0, -1] }); this.axes.connect(horizontal ? ["flick", ""] : ["", "flick"], this.panInput); }; __proto.refreshPanels = function () { var _this = this; var panelManager = this.panelManager; // Panel elements were attached to camera element by Flicking class var panelElements = this.cameraElement.children; // Initialize panels var panels = toArray(panelElements).map(function (el, idx) { return new Panel(el, idx, _this); }); panelManager.replacePanels(panels, []); this.visiblePanels = panels.filter(function (panel) { return Boolean(panel); }); }; __proto.setDefaultPanel = function () { var options = this.options; var panelManager = this.panelManager; var indexRange = this.panelManager.getRange(); var index = clamp(options.defaultIndex, indexRange.min, indexRange.max); this.currentPanel = panelManager.get(index); }; __proto.clonePanels = function () { var state = this.state; var options = this.options; var panelManager = this.panelManager; var gap = options.gap; var viewportSize = state.size; var firstPanel = panelManager.firstPanel(); var lastPanel = panelManager.lastPanel(); // There're no panels exist if (!firstPanel) { return; } // For each panels, clone itself while last panel's position + size is below viewport size var panels = panelManager.originalPanels(); var reversedPanels = panels.concat().reverse(); var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + gap; var relativeAnchorPosition = firstPanel.getRelativeAnchorPosition(); var relativeHangerPosition = this.getRelativeHangerPosition(); var areaPrev = (relativeHangerPosition - relativeAnchorPosition) % sumOriginalPanelSize; var sizeSum = 0; var panelAtLeftBoundary; for (var _i = 0, reversedPanels_1 = reversedPanels; _i < reversedPanels_1.length; _i++) { var panel = reversedPanels_1[_i]; if (!panel) { continue; } sizeSum += panel.getSize() + gap; if (sizeSum >= areaPrev) { panelAtLeftBoundary = panel; break; } } var areaNext = (viewportSize - relativeHangerPosition + relativeAnchorPosition) % sumOriginalPanelSize; sizeSum = 0; var panelAtRightBoundary; for (var _a = 0, panels_1 = panels; _a < panels_1.length; _a++) { var panel = panels_1[_a]; if (!panel) { continue; } sizeSum += panel.getSize() + gap; if (sizeSum >= areaNext) { panelAtRightBoundary = panel; break; } } // Need one more set of clones on prev area of original panel 0 var needCloneOnPrev = panelAtLeftBoundary.getIndex() !== 0 && panelAtLeftBoundary.getIndex() <= panelAtRightBoundary.getIndex(); // Visible count of panel 0 on first screen var panel0OnFirstscreen = Math.ceil((relativeHangerPosition + firstPanel.getSize() - relativeAnchorPosition) / sumOriginalPanelSize) + Math.ceil((viewportSize - relativeHangerPosition + relativeAnchorPosition) / sumOriginalPanelSize) - 1; // duplication var cloneCount = panel0OnFirstscreen + (needCloneOnPrev ? 1 : 0); var prevCloneCount = panelManager.getCloneCount(); panelManager.setCloneCount(cloneCount); if (options.renderExternal) { return; } if (cloneCount > prevCloneCount) { var _loop_1 = function (cloneIndex) { var clones = panels.map(function (origPanel) { return origPanel.clone(cloneIndex); }); var fragment = document.createDocumentFragment(); clones.forEach(function (panel) { return fragment.appendChild(panel.getElement()); }); this_1.cameraElement.appendChild(fragment); (_a = this_1.visiblePanels).push.apply(_a, clones.filter(function (clone) { return Boolean(clone); })); panelManager.insertClones(cloneIndex, 0, clones); var _a; }; var this_1 = this; // should clone more for (var cloneIndex = prevCloneCount; cloneIndex < cloneCount; cloneIndex++) { _loop_1(cloneIndex); } } else if (cloneCount < prevCloneCount) { // should remove some panelManager.removeClonesAfter(cloneCount); } }; __proto.moveToDefaultPanel = function () { var state = this.state; var panelManager = this.panelManager; var options = this.options; var indexRange = this.panelManager.getRange(); var defaultIndex = clamp(options.defaultIndex, indexRange.min, indexRange.max); var defaultPanel = panelManager.get(defaultIndex); var defaultPosition = 0; if (defaultPanel) { defaultPosition = defaultPanel.getAnchorPosition() - state.relativeHangerPosition; defaultPosition = this.canSetBoundMode() ? clamp(defaultPosition, state.scrollArea.prev, state.scrollArea.next) : defaultPosition; } this.moveCamera(defaultPosition); this.axes.setTo({ flick: defaultPosition }, 0); }; __proto.updateSize = function () { var state = this.state; var options = this.options; var panels = this.panelManager.originalPanels().filter(function (panel) { return Boolean(panel); }); var bbox = this.updateBbox(); var prevSize = state.size; // Update size & hanger position state.size = options.horizontal ? bbox.width : bbox.height; if (prevSize !== state.size) { state.relativeHangerPosition = parseArithmeticExpression(options.hanger, state.size); state.infiniteThreshold = parseArithmeticExpression(options.infiniteThreshold, state.size); } if (panels.length <= 0) { return; } this.resizePanels(panels); }; __proto.updateOriginalPanelPositions = function () { var gap = this.options.gap; var panelManager = this.panelManager; var firstPanel = panelManager.firstPanel(); var panels = panelManager.originalPanels(); if (!firstPanel) { return; } var currentPanel = this.currentPanel; var nearestPanel = this.nearestPanel; var currentState = this.stateMachine.getState(); var scrollArea = this.state.scrollArea; // Update panel position && fit to wrapper var nextPanelPos = firstPanel.getPosition(); var maintainingPanel = firstPanel; if (nearestPanel) { // We should maintain nearestPanel's position var looped = !isBetween(currentState.lastPosition + currentState.delta, scrollArea.prev, scrollArea.next); maintainingPanel = looped ? currentPanel : nearestPanel; } else if (firstPanel.getIndex() > 0) { maintainingPanel = currentPanel; } var panelsBeforeMaintainPanel = panels.slice(0, maintainingPanel.getIndex() + (maintainingPanel.getCloneIndex() + 1) * panels.length); var accumulatedSize = panelsBeforeMaintainPanel.reduce(function (total, panel) { return total + panel.getSize() + gap; }, 0); nextPanelPos = maintainingPanel.getPosition() - accumulatedSize; panels.forEach(function (panel) { var newPosition = nextPanelPos; var panelSize = panel.getSize(); panel.setPosition(newPosition); nextPanelPos += panelSize + gap; }); if (!this.options.renderOnlyVisible) { panels.forEach(function (panel) { return panel.setPositionCSS(); }); } }; __proto.updateClonedPanelPositions = function () { var state = this.state; var options = this.options; var panelManager = this.panelManager; var clonedPanels = panelManager.clonedPanels().reduce(function (allClones, clones) { return allClones.concat(clones); }, []).filter(function (panel) { return Boolean(panel); }); var scrollArea = state.scrollArea; var firstPanel = panelManager.firstPanel(); var lastPanel = panelManager.lastPanel(); if (!firstPanel) { return; } var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + options.gap; // Locate all cloned panels linearly first for (var _i = 0, clonedPanels_1 = clonedPanels; _i < clonedPanels_1.length; _i++) { var panel = clonedPanels_1[_i]; var origPanel = panel.getOriginalPanel(); var cloneIndex = panel.getCloneIndex(); var cloneBasePos = sumOriginalPanelSize * (cloneIndex + 1); var clonedPanelPos = cloneBasePos + origPanel.getPosition(); panel.setPosition(clonedPanelPos); } var lastReplacePosition = firstPanel.getPosition(); // reverse() pollutes original array, so copy it with concat() for (var _a = 0, _b = clonedPanels.concat().reverse(); _a < _b.length; _a++) { var panel = _b[_a]; var panelSize = panel.getSize(); var replacePosition = lastReplacePosition - panelSize - options.gap; if (replacePosition + panelSize <= scrollArea.prev) { // Replace is not meaningful, as it won't be seen in current scroll area break; } panel.setPosition(replacePosition); lastReplacePosition = replacePosition; } if (!this.options.renderOnlyVisible) { clonedPanels.forEach(function (panel) { panel.setPositionCSS(); }); } }; __proto.updateScrollArea = function () { var state = this.state; var panelManager = this.panelManager; var options = this.options; var axes = this.axes; // Set viewport scrollable area var firstPanel = panelManager.firstPanel(); var lastPanel = panelManager.lastPanel(); var relativeHangerPosition = state.relativeHangerPosition; if (!firstPanel) { state.scrollArea = { prev: 0, next: 0 }; } else if (this.canSetBoundMode()) { state.scrollArea = { prev: firstPanel.getPosition(), next: lastPanel.getPosition() + lastPanel.getSize() - state.size }; } else if (options.circular) { var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + options.gap; // Maximum scroll extends to first clone sequence's first panel state.scrollArea = { prev: firstPanel.getAnchorPosition() - relativeHangerPosition, next: sumOriginalPanelSize + firstPanel.getAnchorPosition() - relativeHangerPosition }; } else { state.scrollArea = { prev: firstPanel.getAnchorPosition() - relativeHangerPosition, next: lastPanel.getAnchorPosition() - relativeHangerPosition }; } var viewportSize = state.size; var bounce = options.bounce; var parsedBounce; if (isArray(bounce)) { parsedBounce = bounce.map(function (val) { return parseArithmeticExpression(val, viewportSize, DEFAULT_OPTIONS.bounce); }); } else { var parsedVal = parseArithmeticExpression(bounce, viewportSize, DEFAULT_OPTIONS.bounce); parsedBounce = [parsedVal, parsedVal]; } // Update axes range and bounce var flick = axes.axis.flick; flick.range = [state.scrollArea.prev, state.scrollArea.next]; flick.bounce = parsedBounce; }; // Update camera position after resizing __proto.updateCameraPosition = function () { var state = this.state; var currentPanel = this.getCurrentPanel(); var currentState = this.stateMachine.getState(); var isFreeScroll = this.moveType.is(MOVE_TYPE.FREE_SCROLL); var relativeHangerPosition = this.getRelativeHangerPosition(); var halfGap = this.options.gap / 2; if (currentState.holding || currentState.playing) { this.updateVisiblePanels(); return; } var newPosition; if (isFreeScroll) { var nearestPanel = this.getNearestPanel(); newPosition = nearestPanel ? nearestPanel.getPosition() - halfGap + (nearestPanel.getSize() + 2 * halfGap) * state.panelMaintainRatio - relativeHangerPosition : this.getCameraPosition(); } else { newPosition = currentPanel ? currentPanel.getAnchorPosition() - relativeHangerPosition : this.getCameraPosition(); } if (this.canSetBoundMode()) { newPosition = clamp(newPosition, state.scrollArea.prev, state.scrollArea.next); } // Pause & resume axes to prevent axes's "change" event triggered // This should be done before moveCamera, as moveCamera can trigger needPanel this.updateAxesPosition(newPosition); this.moveCamera(newPosition); }; __proto.checkNeedPanel = function (axesEvent) { var state = this.state; var options = this.options; var panelManager = this.panelManager; var currentPanel = this.currentPanel; var nearestPanel = this.nearestPanel; var currentState = this.stateMachine.getState(); if (!options.infinite) { return; } var gap = options.gap; var infiniteThreshold = state.infiniteThreshold; var maxLastIndex = panelManager.getLastIndex(); if (maxLastIndex < 0) { return; } if (!currentPanel || !nearestPanel) { // There're no panels this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: null, direction: null, indexRange: { min: 0, max: maxLastIndex, length: maxLastIndex + 1 } }); return; } var originalNearestPosition = nearestPanel.getPosition(); // Check next direction var checkingPanel = !currentState.holding && !currentState.playing ? currentPanel : nearestPanel; while (checkingPanel) { var currentIndex = checkingPanel.getIndex(); var nextSibling = checkingPanel.nextSibling; var lastPanel = panelManager.lastPanel(); var atLastPanel = currentIndex === lastPanel.getIndex(); var nextIndex = !atLastPanel && nextSibling ? nextSibling.getIndex() : maxLastIndex + 1; var currentNearestPosition = nearestPanel.getPosition(); var panelRight = checkingPanel.getPosition() + checkingPanel.getSize() - (currentNearestPosition - originalNearestPosition); var cameraNext = state.position + state.size; // There're empty panels between var emptyPanelExistsBetween = nextIndex - currentIndex > 1; // Expected prev panel's left position is smaller than camera position var overThreshold = panelRight + gap - infiniteThreshold <= cameraNext; if (emptyPanelExistsBetween && overThreshold) { this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: checkingPanel, direction: DIRECTION.NEXT, indexRange: { min: currentIndex + 1, max: nextIndex - 1, length: nextIndex - currentIndex - 1 } }); } // Trigger needPanel in circular & at max panel index if (options.circular && currentIndex === maxLastIndex && overThreshold) { var firstPanel = panelManager.firstPanel(); var firstIndex = firstPanel ? firstPanel.getIndex() : -1; if (firstIndex > 0) { this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: checkingPanel, direction: DIRECTION.NEXT, indexRange: { min: 0, max: firstIndex - 1, length: firstIndex } }); } } // Check whether panels are changed var lastPanelAfterNeed = panelManager.lastPanel(); var atLastPanelAfterNeed = lastPanelAfterNeed && currentIndex === lastPanelAfterNeed.getIndex(); if (atLastPanelAfterNeed || !overThreshold) { break; } checkingPanel = checkingPanel.nextSibling; } // Check prev direction checkingPanel = nearestPanel; while (checkingPanel) { var cameraPrev = state.position; var checkingIndex = checkingPanel.getIndex(); var prevSibling = checkingPanel.prevSibling; var firstPanel = panelManager.firstPanel(); var atFirstPanel = checkingIndex === firstPanel.getIndex(); var prevIndex = !atFirstPanel && prevSibling ? prevSibling.getIndex() : -1; var currentNearestPosition = nearestPanel.getPosition(); var panelLeft = checkingPanel.getPosition() - (currentNearestPosition - originalNearestPosition); // There're empty panels between var emptyPanelExistsBetween = checkingIndex - prevIndex > 1; // Expected prev panel's right position is smaller than camera position var overThreshold = panelLeft - gap + infiniteThreshold >= cameraPrev; if (emptyPanelExistsBetween && overThreshold) { this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: checkingPanel, direction: DIRECTION.PREV, indexRange: { min: prevIndex + 1, max: checkingIndex - 1, length: checkingIndex - prevIndex - 1 } }); } // Trigger needPanel in circular & at panel 0 if (options.circular && checkingIndex === 0 && overThreshold) { var lastPanel = panelManager.lastPanel(); if (lastPanel && lastPanel.getIndex() < maxLastIndex) { var lastIndex = lastPanel.getIndex(); this.triggerNeedPanel({ axesEvent: axesEvent, siblingPanel: checkingPanel, direction: DIRECTION.PREV, indexRange: { min: lastIndex + 1, max: maxLastIndex, length: maxLastIndex - lastIndex } }); } } // Check whether panels were changed var firstPanelAfterNeed = panelManager.firstPanel(); var atFirstPanelAfterNeed = firstPanelAfterNeed && checkingIndex === firstPanelAfterNeed.getIndex(); // Looped in circular mode if (atFirstPanelAfterNeed || !overThreshold) { break; } checkingPanel = checkingPanel.prevSibling; } }; __proto.triggerNeedPanel = function (params) { var _this = this; var axesEvent = params.axesEvent, siblingPanel = params.siblingPanel, direction = params.direction, indexRange = params.indexRange; var options = this.options; var checkedIndexes = this.state.checkedIndexes; var alreadyTriggered = checkedIndexes.some(function (_a) { var min = _a[0], max = _a[1]; return min === indexRange.min || max === indexRange.max; }); var hasHandler = this.flicking.hasOn(EVENTS.NEED_PANEL); if (alreadyTriggered || !hasHandler) { return; } // Should done before triggering event, as we can directly add panels by event callback checkedIndexes.push([indexRange.min, indexRange.max]); var index = siblingPanel ? siblingPanel.getIndex() : 0; var isTrusted = axesEvent ? axesEvent.isTrusted : false; this.triggerEvent(EVENTS.NEED_PANEL, axesEvent, isTrusted, { index: index, panel: siblingPanel, direction: direction, range: indexRange, fill: function (element) { var panelManager = _this.panelManager; if (!siblingPanel) { return _this.insert(panelManager.getRange().max + 1, element); } var parsedElements = parseElement(element); // Slice elements to fit size equal to empty spaces var elements = direction === DIRECTION.NEXT ? parsedElements.slice(0, indexRange.length) : parsedElements.slice(-indexRange.length); if (direction === DIRECTION.NEXT) { if (options.circular && index === panelManager.getLastIndex()) { // needPanel event is triggered on last index, insert at index 0 return _this.insert(0, elements); } else { return siblingPanel.insertAfter(elements); } } else if (direction === DIRECTION.PREV) { if (options.circular && index === 0) { // needPanel event is triggered on first index(0), insert at the last index return _this.insert(indexRange.max - elements.length + 1, elements); } else { return siblingPanel.insertBefore(elements); } } else { // direction is null when there're no panels exist return _this.insert(0, elements); } } }); }; __proto.updateVisiblePanels = function () { var state = this.state; var options = this.options; var cameraElement = this.cameraElement; var visibleIndex = state.visibleIndex; var renderExternal = options.renderExternal, renderOnlyVisible = options.renderOnlyVisible; if (!renderOnlyVisible) { return; } if (!this.nearestPanel) { this.resetVisibleIndex(); while (cameraElement.firstChild) { cameraElement.removeChild(cameraElement.firstChild); } return; } var newVisibleIndex = this.calcNewVisiblePanelIndex(); if (newVisibleIndex.min !== visibleIndex.min || newVisibleIndex.max !== visibleIndex.max) { state.visibleIndex = newVisibleIndex; if (isNaN(newVisibleIndex.min) || isNaN(newVisibleIndex.max)) { return; } var prevVisiblePanels = this.visiblePanels; var newVisiblePanels = this.calcVisiblePanels(); var _a = this.checkVisiblePanelChange(prevVisiblePanels, newVisiblePanels), addedPanels = _a.addedPanels, removedPanels = _a.removedPanels; if (newVisiblePanels.length > 0) { var firstVisiblePanelPos = newVisiblePanels[0].getPosition(); state.positionOffset = firstVisiblePanelPos; } newVisiblePanels.forEach(function (panel) { panel.setPositionCSS(state.positionOffset); }); if (!renderExternal) { removedPanels.forEach(function (panel) { var panelElement = panel.getElement(); panelElement.parentNode && cameraElement.removeChild(panelElement); }); var fragment_1 = document.createDocumentFragment(); addedPanels.forEach(function (panel) { fragment_1.appendChild(panel.getElement()); }); cameraElement.appendChild(fragment_1); } this.visiblePanels = newVisiblePanels; this.flicking.trigger(EVENTS.VISIBLE_CHANGE, { type: EVENTS.VISIBLE_CHANGE, range: { min: newVisibleIndex.min, max: newVisibleIndex.max } }); } else { this.visiblePanels.forEach(function (panel) { return panel.setPositionCSS(state.positionOffset); }); } }; __proto.calcNewVisiblePanelIndex = function () { var cameraPos = this.getCameraPosition(); var viewportSize = this.getSize(); var basePanel = this.nearestPanel; var panelManager = this.panelManager; var allPanelCount = panelManager.getRange().max + 1; var cloneCount = panelManager.getCloneCount(); var checkLastPanel = function (panel, getNextPanel, isOutOfViewport) { var lastPanel = panel; while (true) { var nextPanel = getNextPanel(lastPanel); if (!nextPanel || isOutOfViewport(nextPanel)) { break; } lastPanel = nextPanel; } return lastPanel; }; var lastPanelOfNextDir = checkLastPanel(basePanel, function (panel) { var nextPanel = panel.nextSibling; if (nextPanel && nextPanel.getPosition() >= panel.getPosition()) { return nextPanel; } else { return null; } }, function (panel) { return panel.getPosition() >= cameraPos + viewportSize; }); var lastPanelOfPrevDir = checkLastPanel(basePanel, function (panel) { var prevPanel = panel.prevSibling; if (prevPanel && prevPanel.getPosition() <= panel.getPosition()) { return prevPanel; } else { return null; } }, function (panel) { return panel.getPosition() + panel.getSize() <= cameraPos; }); var minPanelCloneIndex = lastPanelOfPrevDir.getCloneIndex(); var maxPanelCloneOffset = allPanelCount * (lastPanelOfNextDir.getCloneIndex() + 1); var minPanelCloneOffset = minPanelCloneIndex > -1 ? allPanelCount * (cloneCount - minPanelCloneIndex) : 0; var newVisibleIndex = { // Relative index including clone, can be negative number min: basePanel.getCloneIndex() > -1 ? lastPanelOfPrevDir.getIndex() + minPanelCloneOffset : lastPanelOfPrevDir.getIndex() - minPanelCloneOffset, // Relative index including clone max: lastPanelOfNextDir.getIndex() + maxPanelCloneOffset }; // Stopped on first cloned first panel if (lastPanelOfPrevDir.getIndex() === 0 && lastPanelOfPrevDir.getCloneIndex() === 0) { newVisibleIndex.min = allPanelCount; } return newVisibleIndex; }; __proto.checkVisiblePanelChange = function (prevVisiblePanels, newVisiblePanels) { var prevRefCount = prevVisiblePanels.map(function () { return 0; }); var newRefCount = newVisiblePanels.map(function () { return 0; }); prevVisiblePanels.forEach(function (prevPanel, prevIndex) { newVisiblePanels.forEach(function (newPanel, newIndex) { if (prevPanel === newPanel) { prevRefCount[prevIndex]++; newRefCount[newIndex]++; } }); }); var removedPanels = prevRefCount.reduce(function (removed, count, index) { return count === 0 ? removed.concat([prevVisiblePanels[index]]) : removed; }, []); var addedPanels = newRefCount.reduce(function (added, count, index) { return count === 0 ? added.concat([newVisiblePanels[index]]) : added; }, []); return { removedPanels: removedPanels, addedPanels: addedPanels }; }; __proto.resizePanels = function (panels) { var options = this.options; var panelBboxes = this.panelBboxes; if (options.isEqualSize === true) { if (!panelBboxes.default) { var defaultPanel = panels[0]; panelBboxes.default = defaultPanel.getBbox(); } var defaultBbox_1 = panelBboxes.default; panels.forEach(function (panel) { panel.resize(defaultBbox_1); }); return; } else if (options.isEqualSize) { var equalSizeClasses_2 = options.isEqualSize; panels.forEach(function (panel) { var overlappedClass = panel.getOverlappedClass(equalSizeClasses_2); if (overlappedClass) { panel.resize(panelBboxes[overlappedClass]); panelBboxes[overlappedClass] = panel.getBbox(); } else { panel.resize(); } }); return; } panels.forEach(function (panel) { panel.resize(); }); }; return Viewport; }(); var tid = "UA-70842526-24"; var cid = Math.random() * Math.pow(10, 20) / Math.pow(10, 10); function sendEvent(category, action, label) { if (!isBrowser) { return; } try { var innerWidth = window.innerWidth; var innerHeight = window.innerHeight; var screen = window.screen || { width: innerWidth, height: innerHeight }; var collectInfos = ["v=1", "t=event", "dl=" + location.href, "ul=" + (navigator.language || "en-us").toLowerCase(), "de=" + (document.charset || document.inputEncoding || document.characterSet || "utf-8"), "dr=" + document.referrer, "dt=" + document.title, "sr=" + screen.width + "x" + screen.height, "vp=" + innerWidth + "x" + innerHeight, "ec=" + category, "ea=" + action, "el=" + JSON.stringify(label), "cid=" + cid, "tid=" + tid, "cd1=3.4.3", "z=" + Math.floor(Math.random() * 10000000)]; var req = new XMLHttpRequest(); req.open("GET", "https://www.google-analytics.com/collect?" + collectInfos.join("&")); req.send(); } catch (e) {} } /** * Copyright (c) 2015 NAVER Corp. * egjs projects are licensed under the MIT license */ /** * @memberof eg * @extends eg.Component * @support {"ie": "10+", "ch" : "latest", "ff" : "latest", "sf" : "latest" , "edge" : "latest", "ios" : "7+", "an" : "4.X+"} * @requires {@link https://github.com/naver/egjs-component|eg.Component} * @requires {@link https://github.com/naver/egjs-axes|eg.Axes} * @see Easing Functions Cheat Sheet {@link http://easings.net/} <ko>이징 함수 Cheat Sheet {@link http://easings.net/}</ko> */ var Flicking = /*#__PURE__*/ function (_super) { __extends(Flicking, _super); /** * @param element A base element for the eg.Flicking module. When specifying a value as a `string` type, you must specify a css selector string to select the element.<ko>eg.Flicking 모듈을 사용할 기준 요소. `string`타입으로 값 지정시 요소를 선택하기 위한 css 선택자 문자열을 지정해야 한다.</ko> * @param options An option object of the eg.Flicking module<ko>eg.Flicking 모듈의 옵션 객체</ko> * @param {string} [options.classPrefix="eg-flick"] A prefix of class names will be added for the panels, viewport, and camera.<ko>패널들과 뷰포트, 카메라에 추가될 클래스 이름의 접두사.</ko> * @param {number} [options.deceleration=0.0075] Deceleration value for panel movement animation for animation triggered by manual user input. A higher value means a shorter running time.<ko>사용자의 동작으로 가속도가 적용된 패널 이동 애니메이션의 감속도. 값이 높을수록 애니메이션 실행 시간이 짧아진다.</ko> * @param {boolean} [options.horizontal=true] The direction of panel movement. (true: horizontal, false: vertical)<ko>패널 이동 방향. (true: 가로방향, false: 세로방향)</ko> * @param {boolean} [options.circular=false] Enables circular mode, which connects first/last panel for continuous scrolling.<ko>순환 모드를 활성화한다. 순환 모드에서는 양 끝의 패널이 서로 연결되어 끊김없는 스크롤이 가능하다.</ko> * @param {boolean} [options.infinite=false] Enables infinite mode, which can automatically trigger needPanel until reaching the last panel's index reaches the lastIndex.<ko>무한 모드를 활성화한다. 무한 모드에서는 needPanel 이벤트를 자동으로 트리거한다. 해당 동작은 마지막 패널의 인덱스가 lastIndex와 일치할때까지 일어난다.</ko> * @param {number} [options.infiniteThreshold=0] A Threshold from viewport edge before triggering `needPanel` event in infinite mode.<ko>무한 모드에서 `needPanel`이벤트가 발생하기 위한 뷰포트 끝으로부터의 최대 거리.</ko> * @param {number} [options.lastIndex=Infinity] Maximum panel index that Flicking can set. Flicking won't trigger `needPanel` when the event's panel index is greater than it.<br/>Also, if the last panel's index reached a given index, you can't add more panels.<ko>Flicking이 설정 가능한 패널의 최대 인덱스. `needPanel` 이벤트에 지정된 인덱스가 최대 패널의 개수보다 같거나 커야 하는 경우에 이벤트를 트리거하지 않게 한다.<br>또한, 마지막 패널의 인덱스가 주어진 인덱스와 동일할 경우, 새로운 패널을 더 이상 추가할 수 없다.</ko> * @param {number} [options.threshold=40] Movement threshold to change panel(unit: pixel). It should be dragged above the threshold to change the current panel.<ko>패널 변경을 위한 이동 임계값 (단위: 픽셀). 주어진 값 이상으로 스크롤해야만 패널 변경이 가능하다.</ko> * @param {number} [options.duration=100] Duration of the panel movement animation. (unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko> * @param {function} [options.panelEffect=x => 1 - Math.pow(1 - x, 3)] An easing function applied to the panel movement animation. Default value is `easeOutCubic`.<ko>패널 이동 애니메이션에 적용할 easing함수. 기본값은 `easeOutCubic`이다.</ko> * @param {number} [options.defaultIndex=0] Index of the panel to set as default when initializing. A zero-based integer.<ko>초기화시 지정할 디폴트 패널의 인덱스로, 0부터 시작하는 정수.</ko> * @param {string[]} [options.inputType=["touch,"mouse"]] Types of input devices to enable.({@link https://naver.github.io/egjs-axes/release/latest/doc/global.html#PanInputOption Reference})<ko>활성화할 입력 장치 종류. ({@link https://naver.github.io/egjs-axes/release/latest/doc/global.html#PanInputOption 참고})</ko> * @param {number} [options.thresholdAngle=45] The threshold angle value(0 ~ 90).<br>If the input angle from click/touched position is above or below this value in horizontal and vertical mode each, scrolling won't happen.<ko>스크롤 동작을 막기 위한 임계각(0 ~ 90).<br>클릭/터치한 지점으로부터 계산된 사용자 입력의 각도가 horizontal/vertical 모드에서 각각 크거나 작으면, 스크롤 동작이 이루어지지 않는다.</ko> * @param {number|string|number[]|string[]} [options.bounce=[10,10]] The size value of the bounce area. Only can be enabled when `circular=false`.<br>You can set different bounce value for prev/next direction by using array.<br>`number` for px value, and `string` for px, and % value relative to viewport size.(ex - 0, "10px", "20%")<ko>바운스 영역의 크기값. `circular=false`인 경우에만 사용할 수 있다.<br>배열을 통해 prev/next 방향에 대해 서로 다른 바운스 값을 지정 가능하다.<br>`number`를 통해 px값을, `stirng`을 통해 px 혹은 뷰포트 크기 대비 %값을 사용할 수 있다.(ex - 0, "10px", "20%")</ko> * @param {boolean} [options.autoResize=false] Whether the `resize` method should be called automatically after a window resize event.<ko>window의 `resize` 이벤트 이후 자동으로 resize()메소드를 호출할지의 여부.</ko> * @param {boolean} [options.adaptive=false] Whether the height(horizontal)/width(vertical) of the viewport element reflects the height/width value of the panel after completing the movement.<ko>목적 패널로 이동한 후 그 패널의 높이(horizontal)/너비(vertical)값을 뷰포트 요소의 높이/너비값에 반영할지 여부.</ko> * @param {number|""} [options.zIndex=2000] z-index value for viewport element.<ko>뷰포트 엘리먼트의 z-index 값.</ko> * @param {boolean} [options.bound=false] Prevent the view from going out of the first/last panel. Only can be enabled when `circular=false`.<ko>뷰가 첫번째와 마지막 패널 밖으로 나가는 것을 막아준다. `circular=false`인 경우에만 사용할 수 있다.</ko> * @param {boolean} [options.overflow=false] Disables CSS property `overflow: hidden` in viewport if `true`.<ko>`true`로 설정시 뷰포트에 `overflow: hidden` 속성을 해제한다.</ko> * @param {string} [options.hanger="50%"] The reference position of the hanger in the viewport, which hangs panel anchors should be stopped at.<br>It should be provided in px or % value of viewport size.<br>You can combinate those values with plus/minus sign.<br>ex) "50", "100px", "0%", "25% + 100px"<ko>뷰포트 내부의 행어의 위치. 패널의 앵커들이 뷰포트 내에서 멈추는 지점에 해당한다.<br>px값이나, 뷰포트의 크기 대비 %값을 사용할 수 있고, 이를 + 혹은 - 기호로 연계하여 사용할 수도 있다.<br>예) "50", "100px", "0%", "25% + 100px"</ko> * @param {string} [options.anchor="50%"] The reference position of the anchor in panels, which can be hanged by viewport hanger.<br>It should be provided in px or % value of panel size.<br>You can combinate those values with plus/minus sign.<br>ex) "50", "100px", "0%", "25% + 100px"<ko>패널 내부의 앵커의 위치. 뷰포트의 행어와 연계하여 패널이 화면 내에서 멈추는 지점을 설정할 수 있다.<br>px값이나, 패널의 크기 대비 %값을 사용할 수 있고, 이를 + 혹은 - 기호로 연계하여 사용할 수도 있다.<br>예) "50", "100px", "0%", "25% + 100px"</ko> * @param {number} [options.gap=0] Space value between panels. Should be given in number.(px)<ko>패널간에 부여할 간격의 크기를 나타내는 숫자.(px)</ko> * @param {eg.Flicking.MoveTypeOption} [options.moveType="snap"] Movement style by user input. (ex: snap, freeScroll)<ko>사용자 입력에 의한 이동 방식.(ex: snap, freeScroll)</ko> * @param {boolean} [options.useOffset=false] Whether to use `offsetWidth`/`offsetHeight` instead of `getBoundingClientRect` for panel/viewport size calculation.<br/>You can use this option to calculate the original panel size when CSS transform is applied to viewport or panel.<br/>⚠️ If panel size is not fixed integer value, there can be a 1px gap between panels.<ko>패널과 뷰포트의 크기를 계산할 때 `offsetWidth`/`offsetHeight`를 `getBoundingClientRect` 대신 사용할지 여부.<br/>패널이나 뷰포트에 CSS transform이 설정되어 있을 때 원래 패널 크기를 계산하려면 옵션을 활성화한다.<br/>⚠️ 패널의 크기가 정수로 고정되어있지 않다면 패널 사이에 1px의 공간이 생길 수 있다.</ko> * @param {boolean} [options.renderOnlyVisible] Whether to render visible panels only. This can dramatically increase performance when there're many panels.<ko>보이는 패널만 렌더링할지 여부를 설정한다. 패널이 많을 경우에 퍼포먼스를 크게 향상시킬 수 있다.</ko> * @param {boolean|string[]} [options.isEqualSize] This option indicates whether all panels have the same size(true) of first panel, or it can hold a list of class names that determines panel size.<br/>Enabling this option can increase performance while recalculating panel size.<ko>모든 패널의 크기가 동일한지(true), 혹은 패널 크기를 결정하는 패널 클래스들의 리스트.<br/>이 옵션을 설정하면 패널 크기 재설정시에 성능을 높일 수 있다.</ko> * @param {boolean} [options.isConstantSize] Whether all panels have a constant size that won't be changed after resize. Enabling this option can increase performance while recalculating panel size.<ko>모든 패널의 크기가 불변인지의 여부. 이 옵션을 'true'로 설정하면 패널 크기 재설정시에 성능을 높일 수 있다.</ko> * @param {boolean} [options.renderExternal] Whether to use external rendering. It will delegate DOM manipulation and can synchronize the rendered state by calling `sync()` method. You can use this option to use in frameworks like React, Vue, Angular, which has its states and rendering methods.<ko>외부 렌더링을 사용할 지의 여부. 이 옵션을 사용시 렌더링을 외부에 위임할 수 있고, `sync()`를 호출하여 그 상태를 동기화할 수 있다. 이 옵션을 사용하여, React, Vue, Angular 등 자체적인 상태와 렌더링 방법을 갖는 프레임워크에 대응할 수 있다.</ko> * @param {boolean} [options.collectStatistics=true] Whether to collect statistics on how you are using `Flicking`. These statistical data do not contain any personal information and are used only as a basis for the development of a user-friendly product.<ko>어떻게 `Flicking`을 사용하고 있는지에 대한 통계 수집 여부를 나타낸다. 이 통계자료는 개인정보를 포함하고 있지 않으며 오직 사용자 친화적인 제품으로 발전시키기 위한 근거자료로서 활용한다.</ko> */ function Flicking(element, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; _this.isPanelChangedAtBeforeSync = false; /** * Update panels to current state. * @ko 패널들을 현재 상태에 맞춰 갱신한다. * @method * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ _this.resize = function () { var viewport = _this.viewport; var options = _this.options; var allPanels = viewport.panelManager.allPanels(); if (!options.isConstantSize) { allPanels.forEach(function (panel) { return panel.unCacheBbox(); }); } var shouldResetElements = options.renderOnlyVisible && !options.isConstantSize && options.isEqualSize !== true; viewport.unCacheBbox(); // This should be done before adding panels, to lower performance issue viewport.updateBbox(); if (shouldResetElements) { viewport.appendUncachedPanelElements(allPanels); } viewport.resize(); return _this; }; _this.triggerEvent = function (eventName, axesEvent, isTrusted, params) { if (params === void 0) { params = {}; } var viewport = _this.viewport; var canceled = true; // Ignore events before viewport is initialized if (viewport) { var state = viewport.stateMachine.getState(); var _a = viewport.getScrollArea(), prev = _a.prev, next = _a.next; var pos = viewport.getCameraPosition(); var progress = getProgress(pos, [prev, prev, next]); if (_this.options.circular) { progress %= 1; } canceled = !_super.prototype.trigger.call(_this, eventName, merge({ type: eventName, index: _this.getIndex(), panel: _this.getCurrentPanel(), direction: state.direction, holding: state.holding, progress: progress, axesEvent: axesEvent, isTrusted: isTrusted }, params)); } return { onSuccess: function (callback) { if (!canceled) { callback(); } return this; }, onStopped: function (callback) { if (canceled) { callback(); } return this; } }; }; // Return result of "move" event triggered _this.moveCamera = function (axesEvent) { var viewport = _this.viewport; var state = viewport.stateMachine.getState(); var options = _this.options; var pos = axesEvent.pos.flick; var previousPosition = viewport.getCameraPosition(); if (axesEvent.isTrusted && state.holding) { var inputOffset = options.horizontal ? axesEvent.inputEvent.offsetX : axesEvent.inputEvent.offsetY; var isNextDirection = inputOffset < 0; var cameraChange = pos - previousPosition; var looped = isNextDirection === pos < previousPosition; if (options.circular && looped) { // Reached at max/min range of axes var scrollAreaSize = viewport.getScrollAreaSize(); cameraChange = (cameraChange > 0 ? -1 : 1) * (scrollAreaSize - Math.abs(cameraChange)); } var currentDirection = cameraChange === 0 ? state.direction : cameraChange > 0 ? DIRECTION.NEXT : DIRECTION.PREV; state.direction = currentDirection; } state.delta += axesEvent.delta.flick; viewport.moveCamera(pos, axesEvent); return _this.triggerEvent(EVENTS.MOVE, axesEvent, axesEvent.isTrusted).onStopped(function () { // Undo camera movement viewport.moveCamera(previousPosition, axesEvent); }); }; // Set flicking wrapper user provided var wrapper; if (isString(element)) { wrapper = document.querySelector(element); if (!wrapper) { throw new Error("Base element doesn't exist."); } } else if (element.nodeName && element.nodeType === 1) { wrapper = element; } else { throw new Error("Element should be provided in string or HTMLElement."); } _this.wrapper = wrapper; // Override default options _this.options = merge({}, DEFAULT_OPTIONS, options); // Override moveType option var currentOptions = _this.options; var moveType = currentOptions.moveType; if (moveType in DEFAULT_MOVE_TYPE_OPTIONS) { currentOptions.moveType = DEFAULT_MOVE_TYPE_OPTIONS[moveType]; } // Make viewport instance with panel container element _this.viewport = new Viewport(_this, _this.options, _this.triggerEvent); _this.listenInput(); _this.listenResize(); if (_this.options.collectStatistics) { sendEvent("usage", "options", options); } return _this; } /** * Move to the previous panel if it exists. * @ko 이전 패널이 존재시 해당 패널로 이동한다. * @param [duration=options.duration] Duration of the panel movement animation.(unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ var __proto = Flicking.prototype; __proto.prev = function (duration) { var currentPanel = this.getCurrentPanel(); var currentState = this.viewport.stateMachine.getState(); if (currentPanel && currentState.type === STATE_TYPE.IDLE) { var prevPanel = currentPanel.prev(); if (prevPanel) { prevPanel.focus(duration); } } return this; }; /** * Move to the next panel if it exists. * @ko 다음 패널이 존재시 해당 패널로 이동한다. * @param [duration=options.duration] Duration of the panel movement animation(unit: ms).<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.next = function (duration) { var currentPanel = this.getCurrentPanel(); var currentState = this.viewport.stateMachine.getState(); if (currentPanel && currentState.type === STATE_TYPE.IDLE) { var nextPanel = currentPanel.next(); if (nextPanel) { nextPanel.focus(duration); } } return this; }; /** * Move to the panel of given index. * @ko 주어진 인덱스에 해당하는 패널로 이동한다. * @param index The index number of the panel to move.<ko>이동할 패널의 인덱스 번호.</ko> * @param duration [duration=options.duration] Duration of the panel movement.(unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.moveTo = function (index, duration) { var viewport = this.viewport; var panel = viewport.panelManager.get(index); var state = viewport.stateMachine.getState(); if (!panel || state.type !== STATE_TYPE.IDLE) { return this; } var anchorPosition = panel.getAnchorPosition(); var hangerPosition = viewport.getHangerPosition(); var targetPanel = panel; if (this.options.circular) { var scrollAreaSize = viewport.getScrollAreaSize(); // Check all three possible locations, find the nearest position among them. var possiblePositions = [anchorPosition - scrollAreaSize, anchorPosition, anchorPosition + scrollAreaSize]; var nearestPosition = possiblePositions.reduce(function (nearest, current) { return Math.abs(current - hangerPosition) < Math.abs(nearest - hangerPosition) ? current : nearest; }, Infinity) - panel.getRelativeAnchorPosition(); var identicals = panel.getIdenticalPanels(); var offset = nearestPosition - anchorPosition; if (offset > 0) { // First cloned panel is nearest targetPanel = identicals[1]; } else if (offset < 0) { // Last cloned panel is nearest targetPanel = identicals[identicals.length - 1]; } targetPanel = targetPanel.clone(targetPanel.getCloneIndex(), true); targetPanel.setPosition(nearestPosition); } var currentIndex = this.getIndex(); if (hangerPosition === targetPanel.getAnchorPosition() && currentIndex === index) { return this; } var eventType = panel.getIndex() === viewport.getCurrentIndex() ? "" : EVENTS.CHANGE; viewport.moveTo(targetPanel, viewport.findEstimatedPosition(targetPanel), eventType, null, duration); return this; }; /** * Return index of the current panel. `-1` if no panel exists. * @ko 현재 패널의 인덱스 번호를 반환한다. 패널이 하나도 없을 경우 `-1`을 반환한다. * @return Current panel's index, zero-based integer.<ko>현재 패널의 인덱스 번호. 0부터 시작하는 정수.</ko> */ __proto.getIndex = function () { return this.viewport.getCurrentIndex(); }; /** * Return the wrapper element user provided in constructor. * @ko 사용자가 생성자에서 제공한 래퍼 엘리먼트를 반환한다. * @return Wrapper element user provided.<ko>사용자가 제공한 래퍼 엘리먼트.</ko> */ __proto.getElement = function () { return this.wrapper; }; /** * Return current panel. `null` if no panel exists. * @ko 현재 패널을 반환한다. 패널이 하나도 없을 경우 `null`을 반환한다. * @return Current panel.<ko>현재 패널.</ko> */ __proto.getCurrentPanel = function () { var viewport = this.viewport; var panel = viewport.getCurrentPanel(); return panel ? panel : null; }; /** * Return the panel of given index. `null` if it doesn't exists. * @ko 주어진 인덱스에 해당하는 패널을 반환한다. 해당 패널이 존재하지 않을 시 `null`이다. * @return Panel of given index.<ko>주어진 인덱스에 해당하는 패널.</ko> */ __proto.getPanel = function (index) { var viewport = this.viewport; var panel = viewport.panelManager.get(index); return panel ? panel : null; }; /** * Return all panels. * @ko 모든 패널들을 반환한다. * @param - Should include cloned panels or not.<ko>복사된 패널들을 포함할지의 여부.</ko> * @return All panels.<ko>모든 패널들.</ko> */ __proto.getAllPanels = function (includeClone) { var viewport = this.viewport; var panelManager = viewport.panelManager; var panels = includeClone ? panelManager.allPanels() : panelManager.originalPanels(); return panels.filter(function (panel) { return !!panel; }); }; /** * Return the panels currently shown in viewport area. * @ko 현재 뷰포트 영역에서 보여지고 있는 패널들을 반환한다. * @return Panels currently shown in viewport area.<ko>현재 뷰포트 영역에 보여지는 패널들</ko> */ __proto.getVisiblePanels = function () { return this.viewport.calcVisiblePanels(); }; /** * Return length of original panels. * @ko 원본 패널의 개수를 반환한다. * @return Length of original panels.<ko>원본 패널의 개수</ko> */ __proto.getPanelCount = function () { return this.viewport.panelManager.getPanelCount(); }; /** * Return how many groups of clones are created. * @ko 몇 개의 클론 그룹이 생성되었는지를 반환한다. * @return Length of cloned panel groups.<ko>클론된 패널 그룹의 개수</ko> */ __proto.getCloneCount = function () { return this.viewport.panelManager.getCloneCount(); }; /** * Get maximum panel index for `infinite` mode. * @ko `infinite` 모드에서 적용되는 추가 가능한 패널의 최대 인덱스 값을 반환한다. * @see {@link eg.Flicking.FlickingOptions} * @return Maximum index of panel that can be added.<ko>최대 추가 가능한 패널의 인덱스.</ko> */ __proto.getLastIndex = function () { return this.viewport.panelManager.getLastIndex(); }; /** * Set maximum panel index for `infinite' mode.<br>[needPanel]{@link eg.Flicking#events:needPanel} won't be triggered anymore when last panel's index reaches it.<br>Also, you can't add more panels after it. * @ko `infinite` 모드에서 적용되는 패널의 최대 인덱스를 설정한다.<br>마지막 패널의 인덱스가 설정한 값에 도달할 경우 더 이상 [needPanel]{@link eg.Flicking#events:needPanel} 이벤트가 발생되지 않는다.<br>또한, 설정한 인덱스 이후로 새로운 패널을 추가할 수 없다. * @param - Maximum panel index. * @see {@link eg.Flicking.FlickingOptions} * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.setLastIndex = function (index) { this.viewport.setLastIndex(index); return this; }; /** * Return panel movement animation. * @ko 현재 패널 이동 애니메이션이 진행 중인지를 반환한다. * @return Is animating or not.<ko>애니메이션 진행 여부.</ko> */ __proto.isPlaying = function () { return this.viewport.stateMachine.getState().playing; }; /** * Unblock input devices. * @ko 막았던 입력 장치로부터의 입력을 푼다. * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.enableInput = function () { this.viewport.enable(); return this; }; /** * Block input devices. * @ko 입력 장치로부터의 입력을 막는다. * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.disableInput = function () { this.viewport.disable(); return this; }; /** * Get current flicking status. You can restore current state by giving returned value to [setStatus()]{@link eg.Flicking#setStatus}. * @ko 현재 상태 값을 반환한다. 반환받은 값을 [setStatus()]{@link eg.Flicking#setStatus} 메소드의 인자로 지정하면 현재 상태를 복원할 수 있다. * @return An object with current status value information.<ko>현재 상태값 정보를 가진 객체.</ko> */ __proto.getStatus = function () { var viewport = this.viewport; var panels = viewport.panelManager.originalPanels().filter(function (panel) { return !!panel; }).map(function (panel) { return { html: panel.getElement().outerHTML, index: panel.getIndex() }; }); return { index: viewport.getCurrentIndex(), panels: panels, position: viewport.getCameraPosition() }; }; /** * Restore to the state of the `status`. * @ko `status`의 상태로 복원한다. * @param status Status value to be restored. You can specify the return value of the [getStatus()]{@link eg.Flicking#getStatus} method.<ko>복원할 상태 값. [getStatus()]{@link eg.Flicking#getStatus}메서드의 반환값을 지정하면 된다.</ko> */ __proto.setStatus = function (status) { this.viewport.restore(status); }; /** * Add plugins that can have different effects on Flicking. * @ko 플리킹에 다양한 효과를 부여할 수 있는 플러그인을 추가한다. * @param - The plugin(s) to add.<ko>추가할 플러그인(들).</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.addPlugins = function (plugins) { this.viewport.addPlugins(plugins); return this; }; /** * Remove plugins from Flicking. * @ko 플리킹으로부터 플러그인들을 제거한다. * @param - The plugin(s) to remove.<ko>제거 플러그인(들).</ko> * @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko> */ __proto.removePlugins = function (plugins) { this.viewport.removePlugins(plugins); return this; }; /** * Return the reference element and all its children to the state they were in before the instance was created. Remove all attached event handlers. Specify `null` for all attributes of the instance (including inherited attributes). * @ko 기준 요소와 그 하위 패널들을 인스턴스 생성전의 상태로 되돌린다. 부착된 모든 이벤트 핸들러를 탈거한다. 인스턴스의 모든 속성(상속받은 속성포함)에 `null`을 지정한다. * @example * const flick = new eg.Flicking("#flick"); * flick.destroy(); * console.log(flick.moveTo); // null */ __proto.destroy = function (option) { if (option === void 0) { option = {}; } this.off(); if (this.options.autoResize) { window.removeEventListener("resize", this.resize); } this.viewport.destroy(option); // release resources for (var x in this) { this[x] = null; } }; /** * Add new panels at the beginning of panels. * @ko 제일 앞에 새로운 패널을 추가한다. * @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko> * @return Array of appended panels.<ko>추가된 패널들의 배열</ko> * @example * // Suppose there were no panels at initialization * const flicking = new eg.Flicking("#flick"); * flicking.replace(3, document.createElement("div")); // Add new panel at index 3 * flicking.prepend("\<div\>Panel\</div\>"); // Prepended at index 2 * flicking.prepend(["\<div\>Panel\</div\>", document.createElement("div")]); // Prepended at index 0, 1 * flicking.prepend("\<div\>Panel\</div\>"); // Prepended at index 0, pushing every panels behind it. */ __proto.prepend = function (element) { var viewport = this.viewport; var parsedElements = parseElement(element); var insertingIndex = Math.max(viewport.panelManager.getRange().min - parsedElements.length, 0); return viewport.insert(insertingIndex, parsedElements); }; /** * Add new panels at the end of panels. * @ko 제일 끝에 새로운 패널을 추가한다. * @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko> * @return Array of appended panels.<ko>추가된 패널들의 배열</ko> * @example * // Suppose there were no panels at initialization * const flicking = new eg.Flicking("#flick"); * flicking.append(document.createElement("div")); // Appended at index 0 * flicking.append("\<div\>Panel\</div\>"); // Appended at index 1 * flicking.append(["\<div\>Panel\</div\>", document.createElement("div")]); // Appended at index 2, 3 * // Even this is possible * flicking.append("\<div\>Panel 1\</div\>\<div\>Panel 2\</div\>"); // Appended at index 4, 5 */ __proto.append = function (element) { var viewport = this.viewport; return viewport.insert(viewport.panelManager.getRange().max + 1, element); }; /** * Replace existing panels with new panels from given index. If target index is empty, add new panel at target index. * @ko 주어진 인덱스로부터의 패널들을 새로운 패널들로 교체한다. 인덱스에 해당하는 자리가 비어있다면, 새로운 패널을 해당 자리에 집어넣는다. * @param index - Start index to replace new panels.<ko>새로운 패널들로 교체할 시작 인덱스</ko> * @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko> * @return Array of created panels by replace.<ko>교체되어 새롭게 추가된 패널들의 배열</ko> * @example * // Suppose there were no panels at initialization * const flicking = new eg.Flicking("#flick"); * * // This will add new panel at index 3, * // Index 0, 1, 2 is empty at this moment. * // [empty, empty, empty, PANEL] * flicking.replace(3, document.createElement("div")); * * // As index 2 was empty, this will also add new panel at index 2. * // [empty, empty, PANEL, PANEL] * flicking.replace(2, "\<div\>Panel\</div\>"); * * // Index 3 was not empty, so it will replace previous one. * // It will also add new panels at index 4 and 5. * // before - [empty, empty, PANEL, PANEL] * // after - [empty, empty, PANEL, NEW_PANEL, NEW_PANEL, NEW_PANEL] * flicking.replace(3, ["\<div\>Panel\</div\>", "\<div\>Panel\</div\>", "\<div\>Panel\</div\>"]) */ __proto.replace = function (index, element) { return this.viewport.replace(index, element); }; /** * Remove panel at target index. This will decrease index of panels behind it. * @ko `index`에 해당하는 자리의 패널을 제거한다. 수행시 `index` 이후의 패널들의 인덱스가 감소된다. * @param index - Index of panel to remove.<ko>제거할 패널의 인덱스</ko> * @param {number} [deleteCount=1] - Number of panels to remove from index.<ko>`index` 이후로 제거할 패널의 개수.</ko> * @return Array of removed panels<ko>제거된 패널들의 배열</ko> */ __proto.remove = function (index, deleteCount) { if (deleteCount === void 0) { deleteCount = 1; } return this.viewport.remove(index, deleteCount); }; /** * Get indexes to render. Should be used with `renderOnlyVisible` option. * @private * @ko 렌더링이 필요한 인덱스들을 반환한다. `renderOnlyVisible` 옵션과 함께 사용해야 한다. * @param - Info object of how panel infos are changed.<ko>패널 정보들의 변경 정보를 담는 오브젝트.</ko> * @return Array of indexes to render.<ko>렌더링할 인덱스의 배열</ko> */ __proto.getRenderingIndexes = function (diffResult) { var viewport = this.viewport; var _a = viewport.getVisibleIndex(), min = _a.min, max = _a.max; var maintained = diffResult.maintained.reduce(function (values, _a) { var before = _a[0], after = _a[1]; values[before] = after; return values; }, {}); var prevPanelCount = diffResult.prevList.length; var panelCount = diffResult.list.length; var added = diffResult.added; var list = counter(prevPanelCount * (this.getCloneCount() + 1)); var visibles = min >= 0 ? list.slice(min, max + 1) : list.slice(0, max + 1).concat(list.slice(min)); visibles = visibles.filter(function (val) { return maintained[val % prevPanelCount] != null; }).map(function (val) { var cloneIndex = Math.floor(val / prevPanelCount); var changedIndex = maintained[val % prevPanelCount]; return changedIndex + panelCount * cloneIndex; }); var renderingPanels = visibles.concat(added); var allPanels = viewport.panelManager.allPanels(); viewport.setVisiblePanels(renderingPanels.map(function (index) { return allPanels[index]; })); return renderingPanels; }; /** * Synchronize info of panels instance with info given by external rendering. * @ko 외부 렌더링 방식에 의해 입력받은 패널의 정보와 현재 플리킹이 갖는 패널 정보를 동기화한다. * @private * @param - Info object of how panel infos are changed.<ko>패널 정보들의 변경 정보를 담는 오브젝트.</ko> * @param - Whether called from sync method <ko> sync 메소드로부터 호출됐는지 여부 </ko> */ __proto.beforeSync = function (diffInfo) { var _this = this; var maintained = diffInfo.maintained, added = diffInfo.added, changed = diffInfo.changed, removed = diffInfo.removed; var viewport = this.viewport; var panelManager = viewport.panelManager; var isCircular = this.options.circular; var cloneCount = panelManager.getCloneCount(); var prevClonedPanels = panelManager.clonedPanels(); // Update visible panels var newVisiblePanels = viewport.getVisiblePanels().filter(function (panel) { return findIndex(removed, function (index) { return index === panel.getIndex(); }) < 0; }); viewport.setVisiblePanels(newVisiblePanels); // Did not changed at all if (added.length <= 0 && removed.length <= 0 && changed.length <= 0 && cloneCount === prevClonedPanels.length) { return this; } var prevOriginalPanels = panelManager.originalPanels(); var newPanels = []; var newClones = counter(cloneCount).map(function () { return []; }); maintained.forEach(function (_a) { var beforeIdx = _a[0], afterIdx = _a[1]; newPanels[afterIdx] = prevOriginalPanels[beforeIdx]; newPanels[afterIdx].setIndex(afterIdx); }); added.forEach(function (addIndex) { newPanels[addIndex] = new Panel(null, addIndex, _this.viewport); }); if (isCircular) { counter(cloneCount).forEach(function (groupIndex) { var prevCloneGroup = prevClonedPanels[groupIndex]; var newCloneGroup = newClones[groupIndex]; maintained.forEach(function (_a) { var beforeIdx = _a[0], afterIdx = _a[1]; newCloneGroup[afterIdx] = prevCloneGroup ? prevCloneGroup[beforeIdx] : newPanels[afterIdx].clone(groupIndex, false); newCloneGroup[afterIdx].setIndex(afterIdx); }); added.forEach(function (addIndex) { var newPanel = newPanels[addIndex]; newCloneGroup[addIndex] = newPanel.clone(groupIndex, false); }); }); } added.forEach(function (index) { viewport.updateCheckedIndexes({ min: index, max: index }); }); removed.forEach(function (index) { viewport.updateCheckedIndexes({ min: index - 1, max: index + 1 }); }); var checkedIndexes = viewport.getCheckedIndexes(); checkedIndexes.forEach(function (_a, idx) { var min = _a[0], max = _a[1]; // Push checked indexes backward var pushedIndex = added.filter(function (index) { return index < min && panelManager.has(index); }).length - removed.filter(function (index) { return index < min; }).length; checkedIndexes.splice(idx, 1, [min + pushedIndex, max + pushedIndex]); }); // Only effective only when there are least one panel which have changed its index if (changed.length > 0) { // Removed checked index by changed ones after pushing maintained.forEach(function (_a) { var next = _a[1]; viewport.updateCheckedIndexes({ min: next, max: next }); }); } panelManager.replacePanels(newPanels, newClones); this.isPanelChangedAtBeforeSync = true; }; /** * Synchronize info of panels with DOM info given by external rendering. * @ko 외부 렌더링 방식에 의해 입력받은 DOM의 정보와 현재 플리킹이 갖는 패널 정보를 동기화 한다. * @private * @param - Info object of how panel elements are changed.<ko>패널의 DOM 요소들의 변경 정보를 담는 오브젝트.</ko> */ __proto.sync = function (diffInfo) { var list = diffInfo.list, maintained = diffInfo.maintained, added = diffInfo.added, changed = diffInfo.changed, removed = diffInfo.removed; // Did not changed at all if (added.length <= 0 && removed.length <= 0 && changed.length <= 0) { return this; } var viewport = this.viewport; var _a = this.options, renderOnlyVisible = _a.renderOnlyVisible, circular = _a.circular; var panelManager = viewport.panelManager; if (!renderOnlyVisible) { var indexRange = panelManager.getRange(); var beforeDiffInfo = diffInfo; if (circular) { var prevOriginalPanelCount_1 = indexRange.max; var originalPanelCount_1 = list.length / (panelManager.getCloneCount() + 1) >> 0; var originalAdded = added.filter(function (index) { return index < originalPanelCount_1; }); var originalRemoved = removed.filter(function (index) { return index <= prevOriginalPanelCount_1; }); var originalMaintained = maintained.filter(function (_a) { var beforeIdx = _a[0]; return beforeIdx <= prevOriginalPanelCount_1; }); var originalChanged = changed.filter(function (_a) { var beforeIdx = _a[0]; return beforeIdx <= prevOriginalPanelCount_1; }); beforeDiffInfo = { added: originalAdded, maintained: originalMaintained, removed: originalRemoved, changed: originalChanged }; } this.beforeSync(beforeDiffInfo); } var visiblePanels = renderOnlyVisible ? viewport.getVisiblePanels() : this.getAllPanels(true); added.forEach(function (addedIndex) { var addedElement = list[addedIndex]; var beforePanel = visiblePanels[addedIndex]; beforePanel.setElement(addedElement); // As it can be 0 beforePanel.unCacheBbox(); }); if (this.isPanelChangedAtBeforeSync) { viewport.resetVisibleIndex(); this.isPanelChangedAtBeforeSync = false; } viewport.resize(); return this; }; __proto.listenInput = function () { var flicking = this; var viewport = flicking.viewport; var stateMachine = viewport.stateMachine; // Set event context flicking.eventContext = { flicking: flicking, viewport: flicking.viewport, transitTo: stateMachine.transitTo, triggerEvent: flicking.triggerEvent, moveCamera: flicking.moveCamera, stopCamera: viewport.stopCamera }; var handlers = {}; var _loop_1 = function (key) { var eventType = AXES_EVENTS[key]; handlers[eventType] = function (e) { return stateMachine.fire(eventType, e, flicking.eventContext); }; }; for (var key in AXES_EVENTS) { _loop_1(key); } // Connect Axes instance with PanInput flicking.viewport.connectAxesHandler(handlers); }; __proto.listenResize = function () { if (this.options.autoResize) { window.addEventListener("resize", this.resize); } }; /** * Version info string * @ko 버전정보 문자열 * @example * eg.Flicking.VERSION; // ex) 3.0.0 * @memberof eg.Flicking */ Flicking.VERSION = "3.4.3"; /** * Direction constant - "PREV" or "NEXT" * @ko 방향 상수 - "PREV" 또는 "NEXT" * @type {object} * @property {"PREV"} PREV - Prev direction from current hanger position.<br/>It's `left(←️)` direction when `horizontal: true`.<br/>Or, `up(↑️)` direction when `horizontal: false`.<ko>현재 행어를 기준으로 이전 방향.<br/>`horizontal: true`일 경우 `왼쪽(←️)` 방향.<br/>`horizontal: false`일 경우 `위쪽(↑️)`방향이다.</ko> * @property {"NEXT"} NEXT - Next direction from current hanger position.<br/>It's `right(→)` direction when `horizontal: true`.<br/>Or, `down(↓️)` direction when `horizontal: false`.<ko>현재 행어를 기준으로 다음 방향.<br/>`horizontal: true`일 경우 `오른쪽(→)` 방향.<br/>`horizontal: false`일 경우 `아래쪽(↓️)`방향이다.</ko> * @example * eg.Flicking.DIRECTION.PREV; // "PREV" * eg.Flicking.DIRECTION.NEXT; // "NEXT" */ Flicking.DIRECTION = DIRECTION; /** * Event type object with event name strings. * @ko 이벤트 이름 문자열들을 담은 객체 * @type {object} * @property {"holdStart"} HOLD_START - holdStart event<ko>holdStart 이벤트</ko> * @property {"holdEnd"} HOLD_END - holdEnd event<ko>holdEnd 이벤트</ko> * @property {"moveStart"} MOVE_START - moveStart event<ko>moveStart 이벤트</ko> * @property {"move"} MOVE - move event<ko>move 이벤트</ko> * @property {"moveEnd"} MOVE_END - moveEnd event<ko>moveEnd 이벤트</ko> * @property {"change"} CHANGE - change event<ko>change 이벤트</ko> * @property {"restore"} RESTORE - restore event<ko>restore 이벤트</ko> * @property {"select"} SELECT - select event<ko>select 이벤트</ko> * @property {"needPanel"} NEED_PANEL - needPanel event<ko>needPanel 이벤트</ko> * @example * eg.Flicking.EVENTS.MOVE_START; // "MOVE_START" */ Flicking.EVENTS = EVENTS; return Flicking; }(Component); Flicking.withFlickingMethods = withFlickingMethods; Flicking.DEFAULT_OPTIONS = DEFAULT_OPTIONS; Flicking.MOVE_TYPE = MOVE_TYPE; return Flicking; })); //# sourceMappingURL=flicking.js.map
cdnjs/cdnjs
ajax/libs/egjs-flicking/3.4.3/flicking.js
JavaScript
mit
186,268
'use strict'; class BottomStatus extends HTMLElement{ createdCallback() { this.classList.add('inline-block') this.classList.add('linter-highlight') this.iconSpan = document.createElement('span') this.iconSpan.classList.add('icon') this.appendChild(this.iconSpan) this.count = 0 this.addEventListener('click', function() { atom.commands.dispatch(atom.views.getView(atom.workspace), 'linter:next-error') }) } get count() { return this._count } set count(Value) { this._count = Value if (Value) { this.classList.remove('status-success') this.iconSpan.classList.remove('icon-check') this.classList.add('status-error') this.iconSpan.classList.add('icon-x') this.iconSpan.textContent = Value === 1 ? '1 Issue' : `${Value} Issues` } else { this.classList.remove('status-error') this.iconSpan.classList.remove('icon-x') this.classList.add('status-success') this.iconSpan.classList.add('icon-check') this.iconSpan.textContent = 'No Issues' } } } module.exports = document.registerElement('linter-bottom-status', {prototype: BottomStatus.prototype})
blakeembrey/linter
lib/ui/bottom-status.js
JavaScript
mit
1,183
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { if (n === 1) return 1; return 5; } root.ng.common.locales['vo'] = [ 'vo', [['AM', 'PM'], u, u], u, [['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], u, u], u, [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], ['M01', 'M02', 'M03', 'M04', 'M05', 'M06', 'M07', 'M08', 'M09', 'M10', 'M11', 'M12'], u ], u, [['BCE', 'CE'], u, u], 1, [6, 0], ['y-MM-dd', 'y MMM d', 'y MMMM d', 'y MMMM d, EEEE'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], u, u, {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural, [] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
mhevery/angular
packages/common/locales/global/vo.js
JavaScript
mit
1,456
var DataStore = artifacts.require("./DataStore.sol"); contract('DataStore', function(accounts) { it("should start with no data", function() { return DataStore.deployed().then(function(instance) { return instance.getData.call(accounts[0]); }).then(function(data) { console.log(data); assert.equal(data, "", "incorrect data returned"); }); }); it("should receive and store data", function() { let testData = "Testing"; return DataStore.new(testData).then(function(instance) { return instance.getData.call(); }).then(function(data) { assert.equal(data, testData, "incorrect data returned"); }); }); // MetaCoin.new().then(function(instance) { // // `instance` is a new instance of the abstraction. // // If this callback is called, the deployment was successful. // console.log(instance.address); // }).catch(function(e) { // // There was an error! Handle it. // }); // contract('DataStore', function(accounts) { // it("should receive and store data", function() { // return DataStore.deployed().then(function(instance) { // return instance.getBalance.call(accounts[0]); // }).then(function(balance) { // assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account"); // }); // }); });
corbinpage/ethereum-play
test/datastore.js
JavaScript
mit
1,335
/* Highmaps JS v7.2.2 (2020-08-24) (c) 2009-2019 Torstein Honsi License: www.highcharts.com/license */ (function(c){"object"===typeof module&&module.exports?(c["default"]=c,module.exports=c):"function"===typeof define&&define.amd?define("highcharts/modules/heatmap",["highcharts"],function(n){c(n);c.Highcharts=n;return c}):c("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(c){function n(a,f,c,p){a.hasOwnProperty(f)||(a[f]=p.apply(null,c))}c=c?c._modules:{};n(c,"parts-map/ColorSeriesMixin.js",[c["parts/Globals.js"]],function(a){a.colorPointMixin={setVisible:function(a){var f=this,c=a?"show": "hide";f.visible=!!a;["graphic","dataLabel"].forEach(function(a){if(f[a])f[a][c]()})}};a.colorSeriesMixin={optionalAxis:"colorAxis",colorAxis:0,translateColors:function(){var a=this,c=this.options.nullColor,p=this.colorAxis,t=this.colorKey;(this.data.length?this.data:this.points).forEach(function(f){var m=f[t];if(m=f.options.color||(f.isNull?c:p&&void 0!==m?p.toColor(m,f):f.color||a.color))f.color=m})}}});n(c,"parts-map/ColorAxis.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(a,f){var c= f.erase,p=f.extend,t=f.isNumber,m=f.pick,n=f.splat;f=a.addEvent;var k=a.Axis,u=a.Chart,r=a.Series,l=a.Point,g=a.color,v=a.Legend,A=a.LegendSymbolMixin,B=a.colorPointMixin,x=a.noop,q=a.merge;p(r.prototype,a.colorSeriesMixin);p(l.prototype,B);var w=a.ColorAxis=function(){this.init.apply(this,arguments)};p(w.prototype,k.prototype);p(w.prototype,{defaultColorAxisOptions:{lineWidth:0,minPadding:0,maxPadding:0,gridLineWidth:1,tickPixelInterval:72,startOnTick:!0,endOnTick:!0,offset:0,marker:{animation:{duration:50}, width:.01,color:"#999999"},labels:{overflow:"justify",rotation:0},minColor:"#e6ebf5",maxColor:"#003399",tickLength:5,showInLegend:!0},keepProps:["legendGroup","legendItemHeight","legendItemWidth","legendItem","legendSymbol"].concat(k.prototype.keepProps),init:function(b,d){this.coll="colorAxis";var h=this.buildOptions.call(b,this.defaultColorAxisOptions,d);k.prototype.init.call(this,b,h);d.dataClasses&&this.initDataClasses(d);this.initStops();this.horiz=!h.opposite;this.zoomEnabled=!1;this.defaultLegendLength= 200},initDataClasses:function(b){var d=this.chart,h,e=0,y=d.options.chart.colorCount,a=this.options,f=b.dataClasses.length;this.dataClasses=h=[];this.legendItems=[];b.dataClasses.forEach(function(b,c){b=q(b);h.push(b);if(d.styledMode||!b.color)"category"===a.dataClassColor?(d.styledMode||(c=d.options.colors,y=c.length,b.color=c[e]),b.colorIndex=e,e++,e===y&&(e=0)):b.color=g(a.minColor).tweenTo(g(a.maxColor),2>f?.5:c/(f-1))})},hasData:function(){return!(!this.tickPositions||!this.tickPositions.length)}, setTickPositions:function(){if(!this.dataClasses)return k.prototype.setTickPositions.call(this)},initStops:function(){this.stops=this.options.stops||[[0,this.options.minColor],[1,this.options.maxColor]];this.stops.forEach(function(b){b.color=g(b[1])})},buildOptions:function(b,d){var h=this.options.legend,e=d.layout?"vertical"!==d.layout:"vertical"!==h.layout;return q(b,{side:e?2:1,reversed:!e},d,{opposite:!e,showEmpty:!1,title:null,visible:h.enabled&&(d?!1!==d.visible:!0)})},setOptions:function(b){k.prototype.setOptions.call(this, b);this.options.crosshair=this.options.marker},setAxisSize:function(){var b=this.legendSymbol,d=this.chart,h=d.options.legend||{},e,a;b?(this.left=h=b.attr("x"),this.top=e=b.attr("y"),this.width=a=b.attr("width"),this.height=b=b.attr("height"),this.right=d.chartWidth-h-a,this.bottom=d.chartHeight-e-b,this.len=this.horiz?a:b,this.pos=this.horiz?h:e):this.len=(this.horiz?h.symbolWidth:h.symbolHeight)||this.defaultLegendLength},normalizedValue:function(b){this.isLog&&(b=this.val2lin(b));return 1-(this.max- b)/(this.max-this.min||1)},toColor:function(b,d){var h=this.stops,e=this.dataClasses,a;if(e)for(a=e.length;a--;){var f=e[a];var c=f.from;h=f.to;if((void 0===c||b>=c)&&(void 0===h||b<=h)){var g=f.color;d&&(d.dataClass=a,d.colorIndex=f.colorIndex);break}}else{b=this.normalizedValue(b);for(a=h.length;a--&&!(b>h[a][0]););c=h[a]||h[a+1];h=h[a+1]||c;b=1-(h[0]-b)/(h[0]-c[0]||1);g=c.color.tweenTo(h.color,b)}return g},getOffset:function(){var b=this.legendGroup,d=this.chart.axisOffset[this.side];b&&(this.axisParent= b,k.prototype.getOffset.call(this),this.added||(this.added=!0,this.labelLeft=0,this.labelRight=this.width),this.chart.axisOffset[this.side]=d)},setLegendColor:function(){var b=this.reversed;var d=b?1:0;b=b?0:1;d=this.horiz?[d,0,b,0]:[0,b,0,d];this.legendColor={linearGradient:{x1:d[0],y1:d[1],x2:d[2],y2:d[3]},stops:this.stops}},drawLegendSymbol:function(b,d){var a=b.padding,e=b.options,c=this.horiz,f=m(e.symbolWidth,c?this.defaultLegendLength:12),g=m(e.symbolHeight,c?12:this.defaultLegendLength),l= m(e.labelPadding,c?16:30);e=m(e.itemDistance,10);this.setLegendColor();d.legendSymbol=this.chart.renderer.rect(0,b.baseline-11,f,g).attr({zIndex:1}).add(d.legendGroup);this.legendItemWidth=f+a+(c?e:l);this.legendItemHeight=g+a+(c?l:0)},setState:function(b){this.series.forEach(function(d){d.setState(b)})},visible:!0,setVisible:x,getSeriesExtremes:function(){var b=this.series,d=b.length,a;this.dataMin=Infinity;for(this.dataMax=-Infinity;d--;){var e=b[d];var c=e.colorKey=m(e.options.colorKey,e.colorKey, e.pointValKey,e.zoneAxis,"y");var f=e.pointArrayMap;var g=e[c+"Min"]&&e[c+"Max"];if(e[c+"Data"])var l=e[c+"Data"];else if(f){l=[];f=f.indexOf(c);var q=e.yData;if(0<=f&&q)for(a=0;a<q.length;a++)l.push(m(q[a][f],q[a]))}else l=e.yData;g?(e.minColorValue=e[c+"Min"],e.maxColorValue=e[c+"Max"]):(r.prototype.getExtremes.call(e,l),e.minColorValue=e.dataMin,e.maxColorValue=e.dataMax);void 0!==e.minColorValue&&(this.dataMin=Math.min(this.dataMin,e.minColorValue),this.dataMax=Math.max(this.dataMax,e.maxColorValue)); g||r.prototype.getExtremes.call(e)}},drawCrosshair:function(b,d){var a=d&&d.plotX,e=d&&d.plotY,c=this.pos,f=this.len;if(d){var g=this.toPixels(d[d.series.colorKey]);g<c?g=c-2:g>c+f&&(g=c+f+2);d.plotX=g;d.plotY=this.len-g;k.prototype.drawCrosshair.call(this,b,d);d.plotX=a;d.plotY=e;this.cross&&!this.cross.addedToColorAxis&&this.legendGroup&&(this.cross.addClass("highcharts-coloraxis-marker").add(this.legendGroup),this.cross.addedToColorAxis=!0,this.chart.styledMode||this.cross.attr({fill:this.crosshair.color}))}}, getPlotLinePath:function(b){var d=b.translatedValue;return t(d)?this.horiz?["M",d-4,this.top-6,"L",d+4,this.top-6,d,this.top,"Z"]:["M",this.left,d,"L",this.left-6,d+6,this.left-6,d-6,"Z"]:k.prototype.getPlotLinePath.apply(this,arguments)},update:function(b,d){var a=this.chart,e=a.legend,c=this.buildOptions.call(a,{},b);this.series.forEach(function(b){b.isDirtyData=!0});(b.dataClasses&&e.allItems||this.dataClasses)&&this.destroyItems();a.options[this.coll]=q(this.userOptions,c);k.prototype.update.call(this, c,d);this.legendItem&&(this.setLegendColor(),e.colorizeItem(this,!0))},destroyItems:function(){var b=this.chart;this.legendItem?b.legend.destroyItem(this):this.legendItems&&this.legendItems.forEach(function(d){b.legend.destroyItem(d)});b.isDirtyLegend=!0},remove:function(b){this.destroyItems();k.prototype.remove.call(this,b)},getDataClassLegendSymbols:function(){var b=this,d=this.chart,c=this.legendItems,e=d.options.legend,f=e.valueDecimals,g=e.valueSuffix||"",l;c.length||this.dataClasses.forEach(function(e, h){var q=!0,m=e.from,k=e.to;l="";void 0===m?l="< ":void 0===k&&(l="> ");void 0!==m&&(l+=a.numberFormat(m,f)+g);void 0!==m&&void 0!==k&&(l+=" - ");void 0!==k&&(l+=a.numberFormat(k,f)+g);c.push(p({chart:d,name:l,options:{},drawLegendSymbol:A.drawRectangle,visible:!0,setState:x,isDataClass:!0,setVisible:function(){q=this.visible=!q;b.series.forEach(function(b){b.points.forEach(function(b){b.dataClass===h&&b.setVisible(q)})});d.legend.colorizeItem(this,q)}},e))});return c},beforePadding:!1,name:""}); ["fill","stroke"].forEach(function(b){a.Fx.prototype[b+"Setter"]=function(){this.elem.attr(b,g(this.start).tweenTo(g(this.end),this.pos),null,!0)}});f(u,"afterGetAxes",function(){var b=this,d=b.options;this.colorAxis=[];d.colorAxis&&(d.colorAxis=n(d.colorAxis),d.colorAxis.forEach(function(d,a){d.index=a;new w(b,d)}))});f(r,"bindAxes",function(){var b=this.axisTypes;b?-1===b.indexOf("colorAxis")&&b.push("colorAxis"):this.axisTypes=["colorAxis"]});f(v,"afterGetAllItems",function(b){var d=[],a,e;(this.chart.colorAxis|| []).forEach(function(e){(a=e.options)&&a.showInLegend&&(a.dataClasses&&a.visible?d=d.concat(e.getDataClassLegendSymbols()):a.visible&&d.push(e),e.series.forEach(function(d){if(!d.options.showInLegend||a.dataClasses)"point"===d.options.legendType?d.points.forEach(function(d){c(b.allItems,d)}):c(b.allItems,d)}))});for(e=d.length;e--;)b.allItems.unshift(d[e])});f(v,"afterColorizeItem",function(b){b.visible&&b.item.legendColor&&b.item.legendSymbol.attr({fill:b.item.legendColor})});f(v,"afterUpdate",function(){var b= this.chart.colorAxis;b&&b.forEach(function(b,a,e){b.update({},e)})});f(r,"afterTranslate",function(){(this.chart.colorAxis&&this.chart.colorAxis.length||this.colorAttribs)&&this.translateColors()})});n(c,"parts-map/ColorMapSeriesMixin.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(a,c){var f=c.defined;c=a.noop;var p=a.seriesTypes;a.colorMapPointMixin={dataLabelOnNull:!0,isValid:function(){return null!==this.value&&Infinity!==this.value&&-Infinity!==this.value},setState:function(c){a.Point.prototype.setState.call(this, c);this.graphic&&this.graphic.attr({zIndex:"hover"===c?1:0})}};a.colorMapSeriesMixin={pointArrayMap:["value"],axisTypes:["xAxis","yAxis","colorAxis"],trackerGroups:["group","markerGroup","dataLabelsGroup"],getSymbol:c,parallelArrays:["x","y","value"],colorKey:"value",pointAttribs:p.column.prototype.pointAttribs,colorAttribs:function(a){var c={};f(a.color)&&(c[this.colorProp||"fill"]=a.color);return c}}});n(c,"parts-map/HeatmapSeries.js",[c["parts/Globals.js"],c["parts/Utilities.js"]],function(a,c){var f= c.extend,p=c.pick;c=a.colorMapPointMixin;var n=a.merge,m=a.noop,z=a.fireEvent,k=a.Series,u=a.seriesType,r=a.seriesTypes;u("heatmap","scatter",{animation:!1,borderWidth:0,nullColor:"#f7f7f7",dataLabels:{formatter:function(){return this.point.value},inside:!0,verticalAlign:"middle",crop:!1,overflow:!1,padding:0},marker:null,pointRange:null,tooltip:{pointFormat:"{point.x}, {point.y}: {point.value}<br/>"},states:{hover:{halo:!1,brightness:.2}}},n(a.colorMapSeriesMixin,{pointArrayMap:["y","value"],hasPointSpecificOptions:!0, getExtremesFromAll:!0,directTouch:!0,init:function(){r.scatter.prototype.init.apply(this,arguments);var a=this.options;a.pointRange=p(a.pointRange,a.colsize||1);this.yAxis.axisPointRange=a.rowsize||1},translate:function(){var a=this.options,c=this.xAxis,f=this.yAxis,m=a.pointPadding||0,k=function(a,c,b){return Math.min(Math.max(c,a),b)},n=this.pointPlacementToXValue();this.generatePoints();this.points.forEach(function(g){var l=(a.colsize||1)/2,b=(a.rowsize||1)/2,d=k(Math.round(c.len-c.translate(g.x- l,0,1,0,1,-n)),-c.len,2*c.len);l=k(Math.round(c.len-c.translate(g.x+l,0,1,0,1,-n)),-c.len,2*c.len);var h=k(Math.round(f.translate(g.y-b,0,1,0,1)),-f.len,2*f.len);b=k(Math.round(f.translate(g.y+b,0,1,0,1)),-f.len,2*f.len);var e=p(g.pointPadding,m);g.plotX=g.clientX=(d+l)/2;g.plotY=(h+b)/2;g.shapeType="rect";g.shapeArgs={x:Math.min(d,l)+e,y:Math.min(h,b)+e,width:Math.max(Math.abs(l-d)-2*e,0),height:Math.max(Math.abs(b-h)-2*e,0)}});z(this,"afterTranslate")},drawPoints:function(){var a=this.chart.styledMode? "css":"animate";r.column.prototype.drawPoints.call(this);this.points.forEach(function(c){c.graphic[a](this.colorAttribs(c))},this)},hasData:function(){return!!this.processedXData.length},getValidPoints:function(a,c){return k.prototype.getValidPoints.call(this,a,c,!0)},animate:m,getBox:m,drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,alignDataLabel:r.column.prototype.alignDataLabel,getExtremes:function(){k.prototype.getExtremes.call(this,this.valueData);this.valueMin=this.dataMin;this.valueMax= this.dataMax;k.prototype.getExtremes.call(this)}}),f({haloPath:function(a){if(!a)return[];var c=this.shapeArgs;return["M",c.x-a,c.y-a,"L",c.x-a,c.y+c.height+a,c.x+c.width+a,c.y+c.height+a,c.x+c.width+a,c.y-a,"Z"]}},c));""});n(c,"masters/modules/heatmap.src.js",[],function(){})}); //# sourceMappingURL=heatmap.js.map
cdnjs/cdnjs
ajax/libs/highcharts/7.2.2/modules/heatmap.js
JavaScript
mit
12,235
MathJax.Localization.addTranslation("kn","MathML",{version:"2.7.9",isLoaded:!0,strings:{BadMglyph:"ಕೆಟ್ಟ mglyph: %1",BadMglyphFont:"ಕೆಟ್ಟ ತೈಲದಾನಿ: %1",UnknownNodeType:"ಗೊತ್ತು ಇರಲೇ ಇದ್ದ ನೋಡ್ ಟೈಪ್: %1",UnexpectedTextNode:"ಎದರು ನೋದಲಿಲ್ಲದ್ದ ನೋಡ್ ಟೈಪ್ : %1",ErrorParsingMathML:"ಮಾತ್ ಎಂ ಎಲ್ ಪಾರ್ಸೆ ಮಾಡುವಾಗ ತ್ರುಟಿ",ParsingError:"ಮಾತ್ ಎಂ ಎಲ್ ಪಾರ್ಸೆ ಮಾಡುವಾಗ ತ್ರುಟಿ: %1",MathMLSingleElement:"ಮಾತ್ ಎಂ ಎಲ್ ಒಂದು ಎಲಿಮೆಂಟ್ ಇಂದ ಮಾಡ ಬೆಕು.",MathMLRootElement:"ಮಾತ್ ಎಂ ಎಲ್ ಒಂದು <math> ಟ್ಯಾಗ್ ಇಂದ ಶುರು ಆಗಬೇಕು, %1 ಇಂದ ಅಲ್ಲ"}}),MathJax.Ajax.loadComplete("[MathJax]/localization/kn/MathML.js");
cdnjs/cdnjs
ajax/libs/mathjax/2.7.9/localization/kn/MathML.min.js
JavaScript
mit
967
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _Accordion.default}});var _Accordion=_interopRequireDefault(require("../Accordion"));
cdnjs/cdnjs
ajax/libs/material-ui/5.0.0-alpha.1/ExpansionPanel/index.min.js
JavaScript
mit
313
(function (factory) { typeof define === 'function' && define.amd ? define(factory) : factory(); }((function () { 'use strict'; (function() { var select = HTMLSelectElement.prototype; if (select.hasOwnProperty("selectedOptions")) return Object.defineProperty(select, "selectedOptions", { get: function() { return this.querySelectorAll(":checked") }, enumerable: true, configurable: true, }); })(); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } (function(){function k(){function p(a){return a?"object"===typeof a||"function"===typeof a:!1}var l=null;var n=function(a,c){function g(){}if(!p(a)||!p(c))throw new TypeError("Cannot create proxy with a non-object as target or handler");l=function(){a=null;g=function(b){throw new TypeError("Cannot perform '"+b+"' on a proxy that has been revoked");};};setTimeout(function(){l=null;},0);var f=c;c={get:null,set:null,apply:null,construct:null};for(var h in f){if(!(h in c))throw new TypeError("Proxy polyfill does not support trap '"+ h+"'");c[h]=f[h];}"function"===typeof f&&(c.apply=f.apply.bind(f));var d=this,q=!1,r=!1;"function"===typeof a?(d=function(){var b=this&&this.constructor===d,e=Array.prototype.slice.call(arguments);g(b?"construct":"apply");return b&&c.construct?c.construct.call(this,a,e):!b&&c.apply?c.apply(a,this,e):b?(e.unshift(a),new (a.bind.apply(a,e))):a.apply(this,e)},q=!0):a instanceof Array&&(d=[],r=!0);var t=c.get?function(b){g("get");return c.get(this,b,d)}:function(b){g("get");return this[b]},w=c.set?function(b, e){g("set");c.set(this,b,e,d);}:function(b,e){g("set");this[b]=e;},u={};Object.getOwnPropertyNames(a).forEach(function(b){if(!((q||r)&&b in d)){var e={enumerable:!!Object.getOwnPropertyDescriptor(a,b).enumerable,get:t.bind(a,b),set:w.bind(a,b)};Object.defineProperty(d,b,e);u[b]=!0;}});f=!0;Object.setPrototypeOf?Object.setPrototypeOf(d,Object.getPrototypeOf(a)):d.__proto__?d.__proto__=a.__proto__:f=!1;if(c.get||!f)for(var m in a)u[m]||Object.defineProperty(d,m,{get:t.bind(a,m)});Object.seal(a);Object.seal(d); return d};n.revocable=function(a,c){return {proxy:new n(a,c),revoke:l}};return n}var v="undefined"!==typeof process&&"[object process]"==={}.toString.call(process)||"undefined"!==typeof navigator&&"ReactNative"===navigator.product?commonjsGlobal:self;v.Proxy||(v.Proxy=k(),v.Proxy.revocable=v.Proxy.revocable);})(); !function(e){var t=e.Element.prototype;"function"!=typeof t.matches&&(t.matches=t.msMatchesSelector||t.mozMatchesSelector||t.webkitMatchesSelector||function(e){for(var t=(this.document||this.ownerDocument).querySelectorAll(e),o=0;t[o]&&t[o]!==this;)++o;return Boolean(t[o])}),"function"!=typeof t.closest&&(t.closest=function(e){for(var t=this;t&&1===t.nodeType;){if(t.matches(e))return t;t=t.parentNode;}return null});}(window); (function (arr) { arr.forEach(function (item) { if (item.hasOwnProperty('remove')) { return; } Object.defineProperty(item, 'remove', { configurable: true, enumerable: true, writable: true, value: function remove() { this.parentNode && this.parentNode.removeChild(this); } }); }); })([Element.prototype, CharacterData.prototype, DocumentType.prototype].filter(Boolean)); /* * classList.js: Cross-browser full element.classList implementation. * 1.1.20170427 * * By Eli Grey, http://eligrey.com * License: Dedicated to the public domain. * See https://github.com/eligrey/classList.js/blob/master/LICENSE.md */ /*global self, document, DOMException */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js */ if ("document" in window.self) { // Full polyfill for browsers with no classList support // Including IE < Edge missing SVGElement.classList if (!("classList" in document.createElement("_")) || document.createElementNS && !("classList" in document.createElementNS("http://www.w3.org/2000/svg","g"))) { (function (view) { if (!('Element' in view)) return; var classListProp = "classList" , protoProp = "prototype" , elemCtrProto = view.Element[protoProp] , objCtr = Object , strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); } , arrIndexOf = Array[protoProp].indexOf || function (item) { var i = 0 , len = this.length ; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; } // Vendors: please allow content code to instantiate DOMExceptions , DOMEx = function (type, message) { this.name = type; this.code = DOMException[type]; this.message = message; } , checkTokenAndGetIndex = function (classList, token) { if (token === "") { throw new DOMEx( "SYNTAX_ERR" , "An invalid or illegal string was specified" ); } if (/\s/.test(token)) { throw new DOMEx( "INVALID_CHARACTER_ERR" , "String contains an invalid character" ); } return arrIndexOf.call(classList, token); } , ClassList = function (elem) { var trimmedClasses = strTrim.call(elem.getAttribute("class") || "") , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [] , i = 0 , len = classes.length ; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute("class", this.toString()); }; } , classListProto = ClassList[protoProp] = [] , classListGetter = function () { return new ClassList(this); } ; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false ; do { token = tokens[i] + ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments , i = 0 , l = tokens.length , token , updated = false , index ; do { token = tokens[i] + ""; index = checkTokenAndGetIndex(this, token); while (index !== -1) { this.splice(index, 1); updated = true; index = checkTokenAndGetIndex(this, token); } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, force) { token += ""; var result = this.contains(token) , method = result ? force !== true && "remove" : force !== false && "add" ; if (method) { this[method](token); } if (force === true || force === false) { return force; } else { return !result; } }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter , enumerable: true , configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true // adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36 // modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected if (ex.number === undefined || ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } }(window.self)); } // There is full or partial native classList support, so just check if we need // to normalize the add/remove and toggle APIs. (function () { var testElement = document.createElement("_"); testElement.classList.add("c1", "c2"); // Polyfill for IE 10/11 and Firefox <26, where classList.add and // classList.remove exist but support only one argument at a time. if (!testElement.classList.contains("c2")) { var createMethod = function(method) { var original = DOMTokenList.prototype[method]; DOMTokenList.prototype[method] = function(token) { var i, len = arguments.length; for (i = 0; i < len; i++) { token = arguments[i]; original.call(this, token); } }; }; createMethod('add'); createMethod('remove'); } testElement.classList.toggle("c3", false); // Polyfill for IE 10 and Firefox <24, where classList.toggle does not // support the second argument. if (testElement.classList.contains("c3")) { var _toggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function(token, force) { if (1 in arguments && !this.contains(token) === !force) { return force; } else { return _toggle.call(this, token); } }; } testElement = null; }()); } /** * @license * Copyright (c) 2016 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ // minimal template polyfill (function() { var needsTemplate = (typeof HTMLTemplateElement === 'undefined'); var brokenDocFragment = !(document.createDocumentFragment().cloneNode() instanceof DocumentFragment); var needsDocFrag = false; // NOTE: Replace DocumentFragment to work around IE11 bug that // causes children of a document fragment modified while // there is a mutation observer to not have a parentNode, or // have a broken parentNode (!?!) if (/Trident/.test(navigator.userAgent)) { (function() { needsDocFrag = true; var origCloneNode = Node.prototype.cloneNode; Node.prototype.cloneNode = function cloneNode(deep) { var newDom = origCloneNode.call(this, deep); if (this instanceof DocumentFragment) { newDom.__proto__ = DocumentFragment.prototype; } return newDom; }; // IE's DocumentFragment querySelector code doesn't work when // called on an element instance DocumentFragment.prototype.querySelectorAll = HTMLElement.prototype.querySelectorAll; DocumentFragment.prototype.querySelector = HTMLElement.prototype.querySelector; Object.defineProperties(DocumentFragment.prototype, { 'nodeType': { get: function () { return Node.DOCUMENT_FRAGMENT_NODE; }, configurable: true }, 'localName': { get: function () { return undefined; }, configurable: true }, 'nodeName': { get: function () { return '#document-fragment'; }, configurable: true } }); var origInsertBefore = Node.prototype.insertBefore; function insertBefore(newNode, refNode) { if (newNode instanceof DocumentFragment) { var child; while ((child = newNode.firstChild)) { origInsertBefore.call(this, child, refNode); } } else { origInsertBefore.call(this, newNode, refNode); } return newNode; } Node.prototype.insertBefore = insertBefore; var origAppendChild = Node.prototype.appendChild; Node.prototype.appendChild = function appendChild(child) { if (child instanceof DocumentFragment) { insertBefore.call(this, child, null); } else { origAppendChild.call(this, child); } return child; }; var origRemoveChild = Node.prototype.removeChild; var origReplaceChild = Node.prototype.replaceChild; Node.prototype.replaceChild = function replaceChild(newChild, oldChild) { if (newChild instanceof DocumentFragment) { insertBefore.call(this, newChild, oldChild); origRemoveChild.call(this, oldChild); } else { origReplaceChild.call(this, newChild, oldChild); } return oldChild; }; Document.prototype.createDocumentFragment = function createDocumentFragment() { var frag = this.createElement('df'); frag.__proto__ = DocumentFragment.prototype; return frag; }; var origImportNode = Document.prototype.importNode; Document.prototype.importNode = function importNode(impNode, deep) { deep = deep || false; var newNode = origImportNode.call(this, impNode, deep); if (impNode instanceof DocumentFragment) { newNode.__proto__ = DocumentFragment.prototype; } return newNode; }; })(); } // NOTE: we rely on this cloneNode not causing element upgrade. // This means this polyfill must load before the CE polyfill and // this would need to be re-worked if a browser supports native CE // but not <template>. var capturedCloneNode = Node.prototype.cloneNode; var capturedCreateElement = Document.prototype.createElement; var capturedImportNode = Document.prototype.importNode; var capturedRemoveChild = Node.prototype.removeChild; var capturedAppendChild = Node.prototype.appendChild; var capturedReplaceChild = Node.prototype.replaceChild; var capturedParseFromString = DOMParser.prototype.parseFromString; var capturedHTMLElementInnerHTML = Object.getOwnPropertyDescriptor(window.HTMLElement.prototype, 'innerHTML') || { /** * @this {!HTMLElement} * @return {string} */ get: function() { return this.innerHTML; }, /** * @this {!HTMLElement} * @param {string} */ set: function(text) { this.innerHTML = text; } }; var capturedChildNodes = Object.getOwnPropertyDescriptor(window.Node.prototype, 'childNodes') || { /** * @this {!Node} * @return {!NodeList} */ get: function() { return this.childNodes; } }; var elementQuerySelectorAll = Element.prototype.querySelectorAll; var docQuerySelectorAll = Document.prototype.querySelectorAll; var fragQuerySelectorAll = DocumentFragment.prototype.querySelectorAll; var scriptSelector = 'script:not([type]),script[type="application/javascript"],script[type="text/javascript"]'; function QSA(node, selector) { // IE 11 throws a SyntaxError with `scriptSelector` if the node has no children due to the `:not([type])` syntax if (!node.childNodes.length) { return []; } switch (node.nodeType) { case Node.DOCUMENT_NODE: return docQuerySelectorAll.call(node, selector); case Node.DOCUMENT_FRAGMENT_NODE: return fragQuerySelectorAll.call(node, selector); default: return elementQuerySelectorAll.call(node, selector); } } // returns true if nested templates cannot be cloned (they cannot be on // some impl's like Safari 8 and Edge) // OR if cloning a document fragment does not result in a document fragment var needsCloning = (function() { if (!needsTemplate) { var t = document.createElement('template'); var t2 = document.createElement('template'); t2.content.appendChild(document.createElement('div')); t.content.appendChild(t2); var clone = t.cloneNode(true); return (clone.content.childNodes.length === 0 || clone.content.firstChild.content.childNodes.length === 0 || brokenDocFragment); } })(); var TEMPLATE_TAG = 'template'; var PolyfilledHTMLTemplateElement = function() {}; if (needsTemplate) { var contentDoc = document.implementation.createHTMLDocument('template'); var canDecorate = true; var templateStyle = document.createElement('style'); templateStyle.textContent = TEMPLATE_TAG + '{display:none;}'; var head = document.head; head.insertBefore(templateStyle, head.firstElementChild); /** Provides a minimal shim for the <template> element. */ PolyfilledHTMLTemplateElement.prototype = Object.create(HTMLElement.prototype); // if elements do not have `innerHTML` on instances, then // templates can be patched by swizzling their prototypes. var canProtoPatch = !(document.createElement('div').hasOwnProperty('innerHTML')); /** The `decorate` method moves element children to the template's `content`. NOTE: there is no support for dynamically adding elements to templates. */ PolyfilledHTMLTemplateElement.decorate = function(template) { // if the template is decorated or not in HTML namespace, return fast if (template.content || template.namespaceURI !== document.documentElement.namespaceURI) { return; } template.content = contentDoc.createDocumentFragment(); var child; while ((child = template.firstChild)) { capturedAppendChild.call(template.content, child); } // NOTE: prefer prototype patching for performance and // because on some browsers (IE11), re-defining `innerHTML` // can result in intermittent errors. if (canProtoPatch) { template.__proto__ = PolyfilledHTMLTemplateElement.prototype; } else { template.cloneNode = function(deep) { return PolyfilledHTMLTemplateElement._cloneNode(this, deep); }; // add innerHTML to template, if possible // Note: this throws on Safari 7 if (canDecorate) { try { defineInnerHTML(template); defineOuterHTML(template); } catch (err) { canDecorate = false; } } } // bootstrap recursively PolyfilledHTMLTemplateElement.bootstrap(template.content); }; // Taken from https://github.com/jquery/jquery/blob/73d7e6259c63ac45f42c6593da8c2796c6ce9281/src/manipulation/wrapMap.js var topLevelWrappingMap = { 'option': ['select'], 'thead': ['table'], 'col': ['colgroup', 'table'], 'tr': ['tbody', 'table'], 'th': ['tr', 'tbody', 'table'], 'td': ['tr', 'tbody', 'table'] }; var getTagName = function(text) { // Taken from https://github.com/jquery/jquery/blob/73d7e6259c63ac45f42c6593da8c2796c6ce9281/src/manipulation/var/rtagName.js return ( /<([a-z][^/\0>\x20\t\r\n\f]+)/i.exec(text) || ['', ''])[1].toLowerCase(); }; var defineInnerHTML = function defineInnerHTML(obj) { Object.defineProperty(obj, 'innerHTML', { get: function() { return getInnerHTML(this); }, set: function(text) { // For IE11, wrap the text in the correct (table) context var wrap = topLevelWrappingMap[getTagName(text)]; if (wrap) { for (var i = 0; i < wrap.length; i++) { text = '<' + wrap[i] + '>' + text + '</' + wrap[i] + '>'; } } contentDoc.body.innerHTML = text; PolyfilledHTMLTemplateElement.bootstrap(contentDoc); while (this.content.firstChild) { capturedRemoveChild.call(this.content, this.content.firstChild); } var body = contentDoc.body; // If we had wrapped, get back to the original node if (wrap) { for (var j = 0; j < wrap.length; j++) { body = body.lastChild; } } while (body.firstChild) { capturedAppendChild.call(this.content, body.firstChild); } }, configurable: true }); }; var defineOuterHTML = function defineOuterHTML(obj) { Object.defineProperty(obj, 'outerHTML', { get: function() { return '<' + TEMPLATE_TAG + '>' + this.innerHTML + '</' + TEMPLATE_TAG + '>'; }, set: function(innerHTML) { if (this.parentNode) { contentDoc.body.innerHTML = innerHTML; var docFrag = this.ownerDocument.createDocumentFragment(); while (contentDoc.body.firstChild) { capturedAppendChild.call(docFrag, contentDoc.body.firstChild); } capturedReplaceChild.call(this.parentNode, docFrag, this); } else { throw new Error("Failed to set the 'outerHTML' property on 'Element': This element has no parent node."); } }, configurable: true }); }; defineInnerHTML(PolyfilledHTMLTemplateElement.prototype); defineOuterHTML(PolyfilledHTMLTemplateElement.prototype); /** The `bootstrap` method is called automatically and "fixes" all <template> elements in the document referenced by the `doc` argument. */ PolyfilledHTMLTemplateElement.bootstrap = function bootstrap(doc) { var templates = QSA(doc, TEMPLATE_TAG); for (var i=0, l=templates.length, t; (i<l) && (t=templates[i]); i++) { PolyfilledHTMLTemplateElement.decorate(t); } }; // auto-bootstrapping for main document document.addEventListener('DOMContentLoaded', function() { PolyfilledHTMLTemplateElement.bootstrap(document); }); // Patch document.createElement to ensure newly created templates have content Document.prototype.createElement = function createElement() { var el = capturedCreateElement.apply(this, arguments); if (el.localName === 'template') { PolyfilledHTMLTemplateElement.decorate(el); } return el; }; DOMParser.prototype.parseFromString = function() { var el = capturedParseFromString.apply(this, arguments); PolyfilledHTMLTemplateElement.bootstrap(el); return el; }; Object.defineProperty(HTMLElement.prototype, 'innerHTML', { get: function() { return getInnerHTML(this); }, set: function(text) { capturedHTMLElementInnerHTML.set.call(this, text); PolyfilledHTMLTemplateElement.bootstrap(this); }, configurable: true, enumerable: true }); // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#escapingString var escapeAttrRegExp = /[&\u00A0"]/g; var escapeDataRegExp = /[&\u00A0<>]/g; var escapeReplace = function(c) { switch (c) { case '&': return '&amp;'; case '<': return '&lt;'; case '>': return '&gt;'; case '"': return '&quot;'; case '\u00A0': return '&nbsp;'; } }; var escapeAttr = function(s) { return s.replace(escapeAttrRegExp, escapeReplace); }; var escapeData = function(s) { return s.replace(escapeDataRegExp, escapeReplace); }; var makeSet = function(arr) { var set = {}; for (var i = 0; i < arr.length; i++) { set[arr[i]] = true; } return set; }; // http://www.whatwg.org/specs/web-apps/current-work/#void-elements var voidElements = makeSet([ 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr' ]); var plaintextParents = makeSet([ 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'plaintext', 'noscript' ]); /** * @param {Node} node * @param {Node} parentNode * @param {Function=} callback */ var getOuterHTML = function(node, parentNode, callback) { switch (node.nodeType) { case Node.ELEMENT_NODE: { var tagName = node.localName; var s = '<' + tagName; var attrs = node.attributes; for (var i = 0, attr; (attr = attrs[i]); i++) { s += ' ' + attr.name + '="' + escapeAttr(attr.value) + '"'; } s += '>'; if (voidElements[tagName]) { return s; } return s + getInnerHTML(node, callback) + '</' + tagName + '>'; } case Node.TEXT_NODE: { var data = /** @type {Text} */ (node).data; if (parentNode && plaintextParents[parentNode.localName]) { return data; } return escapeData(data); } case Node.COMMENT_NODE: { return '<!--' + /** @type {Comment} */ (node).data + '-->'; } default: { window.console.error(node); throw new Error('not implemented'); } } }; /** * @param {Node} node * @param {Function=} callback */ var getInnerHTML = function(node, callback) { if (node.localName === 'template') { node = /** @type {HTMLTemplateElement} */ (node).content; } var s = ''; var c$ = callback ? callback(node) : capturedChildNodes.get.call(node); for (var i=0, l=c$.length, child; (i<l) && (child=c$[i]); i++) { s += getOuterHTML(child, node, callback); } return s; }; } // make cloning/importing work! if (needsTemplate || needsCloning) { PolyfilledHTMLTemplateElement._cloneNode = function _cloneNode(template, deep) { var clone = capturedCloneNode.call(template, false); // NOTE: decorate doesn't auto-fix children because they are already // decorated so they need special clone fixup. if (this.decorate) { this.decorate(clone); } if (deep) { // NOTE: use native clone node to make sure CE's wrapped // cloneNode does not cause elements to upgrade. capturedAppendChild.call(clone.content, capturedCloneNode.call(template.content, true)); // now ensure nested templates are cloned correctly. fixClonedDom(clone.content, template.content); } return clone; }; // Given a source and cloned subtree, find <template>'s in the cloned // subtree and replace them with cloned <template>'s from source. // We must do this because only the source templates have proper .content. var fixClonedDom = function fixClonedDom(clone, source) { // do nothing if cloned node is not an element if (!source.querySelectorAll) return; // these two lists should be coincident var s$ = QSA(source, TEMPLATE_TAG); if (s$.length === 0) { return; } var t$ = QSA(clone, TEMPLATE_TAG); for (var i=0, l=t$.length, t, s; i<l; i++) { s = s$[i]; t = t$[i]; if (PolyfilledHTMLTemplateElement && PolyfilledHTMLTemplateElement.decorate) { PolyfilledHTMLTemplateElement.decorate(s); } capturedReplaceChild.call(t.parentNode, cloneNode.call(s, true), t); } }; // make sure scripts inside of a cloned template are executable var fixClonedScripts = function fixClonedScripts(fragment) { var scripts = QSA(fragment, scriptSelector); for (var ns, s, i = 0; i < scripts.length; i++) { s = scripts[i]; ns = capturedCreateElement.call(document, 'script'); ns.textContent = s.textContent; var attrs = s.attributes; for (var ai = 0, a; ai < attrs.length; ai++) { a = attrs[ai]; ns.setAttribute(a.name, a.value); } capturedReplaceChild.call(s.parentNode, ns, s); } }; // override all cloning to fix the cloned subtree to contain properly // cloned templates. var cloneNode = Node.prototype.cloneNode = function cloneNode(deep) { var dom; // workaround for Edge bug cloning documentFragments // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8619646/ if (!needsDocFrag && brokenDocFragment && this instanceof DocumentFragment) { if (!deep) { return this.ownerDocument.createDocumentFragment(); } else { dom = importNode.call(this.ownerDocument, this, true); } } else if (this.nodeType === Node.ELEMENT_NODE && this.localName === TEMPLATE_TAG && this.namespaceURI == document.documentElement.namespaceURI) { dom = PolyfilledHTMLTemplateElement._cloneNode(this, deep); } else { dom = capturedCloneNode.call(this, deep); } // template.content is cloned iff `deep`. if (deep) { fixClonedDom(dom, this); } return dom; }; // NOTE: we are cloning instead of importing <template>'s. // However, the ownerDocument of the cloned template will be correct! // This is because the native import node creates the right document owned // subtree and `fixClonedDom` inserts cloned templates into this subtree, // thus updating the owner doc. var importNode = Document.prototype.importNode = function importNode(element, deep) { deep = deep || false; if (element.localName === TEMPLATE_TAG) { return PolyfilledHTMLTemplateElement._cloneNode(element, deep); } else { var dom = capturedImportNode.call(this, element, deep); if (deep) { fixClonedDom(dom, element); fixClonedScripts(dom); } return dom; } }; } if (needsTemplate) { window.HTMLTemplateElement = PolyfilledHTMLTemplateElement; } })(); // Polyfill for creating CustomEvents on IE9/10/11 // code pulled from: // https://github.com/d4tocchini/customevent-polyfill // https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill (function() { if (typeof window === 'undefined') { return; } try { var ce = new window.CustomEvent('test', { cancelable: true }); ce.preventDefault(); if (ce.defaultPrevented !== true) { // IE has problems with .preventDefault() on custom events // http://stackoverflow.com/questions/23349191 throw new Error('Could not prevent default'); } } catch (e) { var CustomEvent = function(event, params) { var evt, origPrevent; params = params || {}; params.bubbles = !!params.bubbles; params.cancelable = !!params.cancelable; evt = document.createEvent('CustomEvent'); evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail ); origPrevent = evt.preventDefault; evt.preventDefault = function() { origPrevent.call(this); try { Object.defineProperty(this, 'defaultPrevented', { get: function() { return true; } }); } catch (e) { this.defaultPrevented = true; } }; return evt; }; CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; // expose definition to window } })(); var check = function (it) { return it && it.Math == Math && it; }; // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global_1 = // eslint-disable-next-line no-undef check(typeof globalThis == 'object' && globalThis) || check(typeof window == 'object' && window) || check(typeof self == 'object' && self) || check(typeof commonjsGlobal == 'object' && commonjsGlobal) || // eslint-disable-next-line no-new-func Function('return this')(); var fails = function (exec) { try { return !!exec(); } catch (error) { return true; } }; // Thank's IE8 for his funny defineProperty var descriptors = !fails(function () { return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7; }); var nativePropertyIsEnumerable = {}.propertyIsEnumerable; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // Nashorn ~ JDK8 bug var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); // `Object.prototype.propertyIsEnumerable` method implementation // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable var f = NASHORN_BUG ? function propertyIsEnumerable(V) { var descriptor = getOwnPropertyDescriptor(this, V); return !!descriptor && descriptor.enumerable; } : nativePropertyIsEnumerable; var objectPropertyIsEnumerable = { f: f }; var createPropertyDescriptor = function (bitmap, value) { return { enumerable: !(bitmap & 1), configurable: !(bitmap & 2), writable: !(bitmap & 4), value: value }; }; var toString = {}.toString; var classofRaw = function (it) { return toString.call(it).slice(8, -1); }; var split = ''.split; // fallback for non-array-like ES3 and non-enumerable old V8 strings var indexedObject = fails(function () { // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 // eslint-disable-next-line no-prototype-builtins return !Object('z').propertyIsEnumerable(0); }) ? function (it) { return classofRaw(it) == 'String' ? split.call(it, '') : Object(it); } : Object; // `RequireObjectCoercible` abstract operation // https://tc39.github.io/ecma262/#sec-requireobjectcoercible var requireObjectCoercible = function (it) { if (it == undefined) throw TypeError("Can't call method on " + it); return it; }; // toObject with fallback for non-array-like ES3 strings var toIndexedObject = function (it) { return indexedObject(requireObjectCoercible(it)); }; var isObject = function (it) { return typeof it === 'object' ? it !== null : typeof it === 'function'; }; // `ToPrimitive` abstract operation // https://tc39.github.io/ecma262/#sec-toprimitive // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string var toPrimitive = function (input, PREFERRED_STRING) { if (!isObject(input)) return input; var fn, val; if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; throw TypeError("Can't convert object to primitive value"); }; var hasOwnProperty = {}.hasOwnProperty; var has = function (it, key) { return hasOwnProperty.call(it, key); }; var document$1 = global_1.document; // typeof document.createElement is 'object' in old IE var EXISTS = isObject(document$1) && isObject(document$1.createElement); var documentCreateElement = function (it) { return EXISTS ? document$1.createElement(it) : {}; }; // Thank's IE8 for his funny defineProperty var ie8DomDefine = !descriptors && !fails(function () { return Object.defineProperty(documentCreateElement('div'), 'a', { get: function () { return 7; } }).a != 7; }); var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; // `Object.getOwnPropertyDescriptor` method // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { O = toIndexedObject(O); P = toPrimitive(P, true); if (ie8DomDefine) try { return nativeGetOwnPropertyDescriptor(O, P); } catch (error) { /* empty */ } if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]); }; var objectGetOwnPropertyDescriptor = { f: f$1 }; var anObject = function (it) { if (!isObject(it)) { throw TypeError(String(it) + ' is not an object'); } return it; }; var nativeDefineProperty = Object.defineProperty; // `Object.defineProperty` method // https://tc39.github.io/ecma262/#sec-object.defineproperty var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) { anObject(O); P = toPrimitive(P, true); anObject(Attributes); if (ie8DomDefine) try { return nativeDefineProperty(O, P, Attributes); } catch (error) { /* empty */ } if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); if ('value' in Attributes) O[P] = Attributes.value; return O; }; var objectDefineProperty = { f: f$2 }; var createNonEnumerableProperty = descriptors ? function (object, key, value) { return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value)); } : function (object, key, value) { object[key] = value; return object; }; var setGlobal = function (key, value) { try { createNonEnumerableProperty(global_1, key, value); } catch (error) { global_1[key] = value; } return value; }; var SHARED = '__core-js_shared__'; var store = global_1[SHARED] || setGlobal(SHARED, {}); var sharedStore = store; var functionToString = Function.toString; // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper if (typeof sharedStore.inspectSource != 'function') { sharedStore.inspectSource = function (it) { return functionToString.call(it); }; } var inspectSource = sharedStore.inspectSource; var WeakMap = global_1.WeakMap; var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap)); var shared = createCommonjsModule(function (module) { (module.exports = function (key, value) { return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {}); })('versions', []).push({ version: '3.6.4', mode: 'global', copyright: '© 2020 Denis Pushkarev (zloirock.ru)' }); }); var id = 0; var postfix = Math.random(); var uid = function (key) { return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); }; var keys = shared('keys'); var sharedKey = function (key) { return keys[key] || (keys[key] = uid(key)); }; var hiddenKeys = {}; var WeakMap$1 = global_1.WeakMap; var set, get, has$1; var enforce = function (it) { return has$1(it) ? get(it) : set(it, {}); }; var getterFor = function (TYPE) { return function (it) { var state; if (!isObject(it) || (state = get(it)).type !== TYPE) { throw TypeError('Incompatible receiver, ' + TYPE + ' required'); } return state; }; }; if (nativeWeakMap) { var store$1 = new WeakMap$1(); var wmget = store$1.get; var wmhas = store$1.has; var wmset = store$1.set; set = function (it, metadata) { wmset.call(store$1, it, metadata); return metadata; }; get = function (it) { return wmget.call(store$1, it) || {}; }; has$1 = function (it) { return wmhas.call(store$1, it); }; } else { var STATE = sharedKey('state'); hiddenKeys[STATE] = true; set = function (it, metadata) { createNonEnumerableProperty(it, STATE, metadata); return metadata; }; get = function (it) { return has(it, STATE) ? it[STATE] : {}; }; has$1 = function (it) { return has(it, STATE); }; } var internalState = { set: set, get: get, has: has$1, enforce: enforce, getterFor: getterFor }; var redefine = createCommonjsModule(function (module) { var getInternalState = internalState.get; var enforceInternalState = internalState.enforce; var TEMPLATE = String(String).split('String'); (module.exports = function (O, key, value, options) { var unsafe = options ? !!options.unsafe : false; var simple = options ? !!options.enumerable : false; var noTargetGet = options ? !!options.noTargetGet : false; if (typeof value == 'function') { if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key); enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : ''); } if (O === global_1) { if (simple) O[key] = value; else setGlobal(key, value); return; } else if (!unsafe) { delete O[key]; } else if (!noTargetGet && O[key]) { simple = true; } if (simple) O[key] = value; else createNonEnumerableProperty(O, key, value); // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, 'toString', function toString() { return typeof this == 'function' && getInternalState(this).source || inspectSource(this); }); }); var path = global_1; var aFunction = function (variable) { return typeof variable == 'function' ? variable : undefined; }; var getBuiltIn = function (namespace, method) { return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace]) : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method]; }; var ceil = Math.ceil; var floor = Math.floor; // `ToInteger` abstract operation // https://tc39.github.io/ecma262/#sec-tointeger var toInteger = function (argument) { return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); }; var min = Math.min; // `ToLength` abstract operation // https://tc39.github.io/ecma262/#sec-tolength var toLength = function (argument) { return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 }; var max = Math.max; var min$1 = Math.min; // Helper for a popular repeating case of the spec: // Let integer be ? ToInteger(index). // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). var toAbsoluteIndex = function (index, length) { var integer = toInteger(index); return integer < 0 ? max(integer + length, 0) : min$1(integer, length); }; // `Array.prototype.{ indexOf, includes }` methods implementation var createMethod = function (IS_INCLUDES) { return function ($this, el, fromIndex) { var O = toIndexedObject($this); var length = toLength(O.length); var index = toAbsoluteIndex(fromIndex, length); var value; // Array#includes uses SameValueZero equality algorithm // eslint-disable-next-line no-self-compare if (IS_INCLUDES && el != el) while (length > index) { value = O[index++]; // eslint-disable-next-line no-self-compare if (value != value) return true; // Array#indexOf ignores holes, Array#includes - not } else for (;length > index; index++) { if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; var arrayIncludes = { // `Array.prototype.includes` method // https://tc39.github.io/ecma262/#sec-array.prototype.includes includes: createMethod(true), // `Array.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.indexof indexOf: createMethod(false) }; var indexOf = arrayIncludes.indexOf; var objectKeysInternal = function (object, names) { var O = toIndexedObject(object); var i = 0; var result = []; var key; for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); // Don't enum bug & hidden keys while (names.length > i) if (has(O, key = names[i++])) { ~indexOf(result, key) || result.push(key); } return result; }; // IE8- don't enum bug keys var enumBugKeys = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype'); // `Object.getOwnPropertyNames` method // https://tc39.github.io/ecma262/#sec-object.getownpropertynames var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { return objectKeysInternal(O, hiddenKeys$1); }; var objectGetOwnPropertyNames = { f: f$3 }; var f$4 = Object.getOwnPropertySymbols; var objectGetOwnPropertySymbols = { f: f$4 }; // all object keys, includes non-enumerable and symbols var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { var keys = objectGetOwnPropertyNames.f(anObject(it)); var getOwnPropertySymbols = objectGetOwnPropertySymbols.f; return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; }; var copyConstructorProperties = function (target, source) { var keys = ownKeys(source); var defineProperty = objectDefineProperty.f; var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); } }; var replacement = /#|\.prototype\./; var isForced = function (feature, detection) { var value = data[normalize(feature)]; return value == POLYFILL ? true : value == NATIVE ? false : typeof detection == 'function' ? fails(detection) : !!detection; }; var normalize = isForced.normalize = function (string) { return String(string).replace(replacement, '.').toLowerCase(); }; var data = isForced.data = {}; var NATIVE = isForced.NATIVE = 'N'; var POLYFILL = isForced.POLYFILL = 'P'; var isForced_1 = isForced; var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f; /* options.target - name of the target object options.global - target is the global object options.stat - export as static methods of target options.proto - export as prototype methods of target options.real - real prototype method for the `pure` version options.forced - export even if the native feature is available options.bind - bind methods to the target, required for the `pure` version options.wrap - wrap constructors to preventing global pollution, required for the `pure` version options.unsafe - use the simple assignment of property instead of delete + defineProperty options.sham - add a flag to not completely full polyfills options.enumerable - export as enumerable property options.noTargetGet - prevent calling a getter on target */ var _export = function (options, source) { var TARGET = options.target; var GLOBAL = options.global; var STATIC = options.stat; var FORCED, target, key, targetProperty, sourceProperty, descriptor; if (GLOBAL) { target = global_1; } else if (STATIC) { target = global_1[TARGET] || setGlobal(TARGET, {}); } else { target = (global_1[TARGET] || {}).prototype; } if (target) for (key in source) { sourceProperty = source[key]; if (options.noTargetGet) { descriptor = getOwnPropertyDescriptor$1(target, key); targetProperty = descriptor && descriptor.value; } else targetProperty = target[key]; FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); // contained in target if (!FORCED && targetProperty !== undefined) { if (typeof sourceProperty === typeof targetProperty) continue; copyConstructorProperties(sourceProperty, targetProperty); } // add a flag to not completely full polyfills if (options.sham || (targetProperty && targetProperty.sham)) { createNonEnumerableProperty(sourceProperty, 'sham', true); } // extend global redefine(target, key, sourceProperty, options); } }; var aFunction$1 = function (it) { if (typeof it != 'function') { throw TypeError(String(it) + ' is not a function'); } return it; }; // optional / simple context binding var functionBindContext = function (fn, that, length) { aFunction$1(fn); if (that === undefined) return fn; switch (length) { case 0: return function () { return fn.call(that); }; 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); }; }; // `ToObject` abstract operation // https://tc39.github.io/ecma262/#sec-toobject var toObject = function (argument) { return Object(requireObjectCoercible(argument)); }; // `IsArray` abstract operation // https://tc39.github.io/ecma262/#sec-isarray var isArray = Array.isArray || function isArray(arg) { return classofRaw(arg) == 'Array'; }; var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () { // Chrome 38 Symbol has incorrect toString conversion // eslint-disable-next-line no-undef return !String(Symbol()); }); var useSymbolAsUid = nativeSymbol // eslint-disable-next-line no-undef && !Symbol.sham // eslint-disable-next-line no-undef && typeof Symbol.iterator == 'symbol'; var WellKnownSymbolsStore = shared('wks'); var Symbol$1 = global_1.Symbol; var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid; var wellKnownSymbol = function (name) { if (!has(WellKnownSymbolsStore, name)) { if (nativeSymbol && has(Symbol$1, name)) WellKnownSymbolsStore[name] = Symbol$1[name]; else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name); } return WellKnownSymbolsStore[name]; }; var SPECIES = wellKnownSymbol('species'); // `ArraySpeciesCreate` abstract operation // https://tc39.github.io/ecma262/#sec-arrayspeciescreate var arraySpeciesCreate = function (originalArray, length) { var C; if (isArray(originalArray)) { C = originalArray.constructor; // cross-realm fallback if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; else if (isObject(C)) { C = C[SPECIES]; if (C === null) C = undefined; } } return new (C === undefined ? Array : C)(length === 0 ? 0 : length); }; var push = [].push; // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation var createMethod$1 = function (TYPE) { var IS_MAP = TYPE == 1; var IS_FILTER = TYPE == 2; var IS_SOME = TYPE == 3; var IS_EVERY = TYPE == 4; var IS_FIND_INDEX = TYPE == 6; var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; return function ($this, callbackfn, that, specificCreate) { var O = toObject($this); var self = indexedObject(O); var boundFunction = functionBindContext(callbackfn, that, 3); var length = toLength(self.length); var index = 0; var create = specificCreate || arraySpeciesCreate; var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined; var value, result; for (;length > index; index++) if (NO_HOLES || index in self) { value = self[index]; result = boundFunction(value, index, O); if (TYPE) { if (IS_MAP) target[index] = result; // map else if (result) switch (TYPE) { case 3: return true; // some case 5: return value; // find case 6: return index; // findIndex case 2: push.call(target, value); // filter } else if (IS_EVERY) return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target; }; }; var arrayIteration = { // `Array.prototype.forEach` method // https://tc39.github.io/ecma262/#sec-array.prototype.foreach forEach: createMethod$1(0), // `Array.prototype.map` method // https://tc39.github.io/ecma262/#sec-array.prototype.map map: createMethod$1(1), // `Array.prototype.filter` method // https://tc39.github.io/ecma262/#sec-array.prototype.filter filter: createMethod$1(2), // `Array.prototype.some` method // https://tc39.github.io/ecma262/#sec-array.prototype.some some: createMethod$1(3), // `Array.prototype.every` method // https://tc39.github.io/ecma262/#sec-array.prototype.every every: createMethod$1(4), // `Array.prototype.find` method // https://tc39.github.io/ecma262/#sec-array.prototype.find find: createMethod$1(5), // `Array.prototype.findIndex` method // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex findIndex: createMethod$1(6) }; var engineUserAgent = getBuiltIn('navigator', 'userAgent') || ''; var process$1 = global_1.process; var versions = process$1 && process$1.versions; var v8 = versions && versions.v8; var match, version; if (v8) { match = v8.split('.'); version = match[0] + match[1]; } else if (engineUserAgent) { match = engineUserAgent.match(/Edge\/(\d+)/); if (!match || match[1] >= 74) { match = engineUserAgent.match(/Chrome\/(\d+)/); if (match) version = match[1]; } } var engineV8Version = version && +version; var SPECIES$1 = wellKnownSymbol('species'); var arrayMethodHasSpeciesSupport = function (METHOD_NAME) { // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/677 return engineV8Version >= 51 || !fails(function () { var array = []; var constructor = array.constructor = {}; constructor[SPECIES$1] = function () { return { foo: 1 }; }; return array[METHOD_NAME](Boolean).foo !== 1; }); }; var defineProperty = Object.defineProperty; var cache = {}; var thrower = function (it) { throw it; }; var arrayMethodUsesToLength = function (METHOD_NAME, options) { if (has(cache, METHOD_NAME)) return cache[METHOD_NAME]; if (!options) options = {}; var method = [][METHOD_NAME]; var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false; var argument0 = has(options, 0) ? options[0] : thrower; var argument1 = has(options, 1) ? options[1] : undefined; return cache[METHOD_NAME] = !!method && !fails(function () { if (ACCESSORS && !descriptors) return true; var O = { length: -1 }; if (ACCESSORS) defineProperty(O, 1, { enumerable: true, get: thrower }); else O[1] = 1; method.call(O, argument0, argument1); }); }; var $filter = arrayIteration.filter; var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); // Edge 14- issue var USES_TO_LENGTH = arrayMethodUsesToLength('filter'); // `Array.prototype.filter` method // https://tc39.github.io/ecma262/#sec-array.prototype.filter // with adding support of @@species _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, { filter: function filter(callbackfn /* , thisArg */) { return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); var arrayMethodIsStrict = function (METHOD_NAME, argument) { var method = [][METHOD_NAME]; return !!method && fails(function () { // eslint-disable-next-line no-useless-call,no-throw-literal method.call(null, argument || function () { throw 1; }, 1); }); }; var $forEach = arrayIteration.forEach; var STRICT_METHOD = arrayMethodIsStrict('forEach'); var USES_TO_LENGTH$1 = arrayMethodUsesToLength('forEach'); // `Array.prototype.forEach` method implementation // https://tc39.github.io/ecma262/#sec-array.prototype.foreach var arrayForEach = (!STRICT_METHOD || !USES_TO_LENGTH$1) ? function forEach(callbackfn /* , thisArg */) { return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } : [].forEach; // `Array.prototype.forEach` method // https://tc39.github.io/ecma262/#sec-array.prototype.foreach _export({ target: 'Array', proto: true, forced: [].forEach != arrayForEach }, { forEach: arrayForEach }); // call something on iterator step with safe closing on error var callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) { try { return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch (error) { var returnMethod = iterator['return']; if (returnMethod !== undefined) anObject(returnMethod.call(iterator)); throw error; } }; var iterators = {}; var ITERATOR = wellKnownSymbol('iterator'); var ArrayPrototype = Array.prototype; // check on default Array iterator var isArrayIteratorMethod = function (it) { return it !== undefined && (iterators.Array === it || ArrayPrototype[ITERATOR] === it); }; var createProperty = function (object, key, value) { var propertyKey = toPrimitive(key); if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value)); else object[propertyKey] = value; }; var TO_STRING_TAG = wellKnownSymbol('toStringTag'); var test = {}; test[TO_STRING_TAG] = 'z'; var toStringTagSupport = String(test) === '[object z]'; var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag'); // ES3 wrong here var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function (it, key) { try { return it[key]; } catch (error) { /* empty */ } }; // getting tag from ES6+ `Object.prototype.toString` var classof = toStringTagSupport ? classofRaw : function (it) { var O, tag, result; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$1)) == 'string' ? tag // builtinTag case : CORRECT_ARGUMENTS ? classofRaw(O) // ES3 arguments fallback : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result; }; var ITERATOR$1 = wellKnownSymbol('iterator'); var getIteratorMethod = function (it) { if (it != undefined) return it[ITERATOR$1] || it['@@iterator'] || iterators[classof(it)]; }; // `Array.from` method implementation // https://tc39.github.io/ecma262/#sec-array.from var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { var O = toObject(arrayLike); var C = typeof this == 'function' ? this : Array; var argumentsLength = arguments.length; var mapfn = argumentsLength > 1 ? arguments[1] : undefined; var mapping = mapfn !== undefined; var iteratorMethod = getIteratorMethod(O); var index = 0; var length, result, step, iterator, next, value; if (mapping) mapfn = functionBindContext(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); // if the target is not iterable or it's an array with the default iterator - use a simple case if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { iterator = iteratorMethod.call(O); next = iterator.next; result = new C(); for (;!(step = next.call(iterator)).done; index++) { value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value; createProperty(result, index, value); } } else { length = toLength(O.length); result = new C(length); for (;length > index; index++) { value = mapping ? mapfn(O[index], index) : O[index]; createProperty(result, index, value); } } result.length = index; return result; }; var ITERATOR$2 = wellKnownSymbol('iterator'); var SAFE_CLOSING = false; try { var called = 0; var iteratorWithReturn = { next: function () { return { done: !!called++ }; }, 'return': function () { SAFE_CLOSING = true; } }; iteratorWithReturn[ITERATOR$2] = function () { return this; }; // eslint-disable-next-line no-throw-literal Array.from(iteratorWithReturn, function () { throw 2; }); } catch (error) { /* empty */ } var checkCorrectnessOfIteration = function (exec, SKIP_CLOSING) { if (!SKIP_CLOSING && !SAFE_CLOSING) return false; var ITERATION_SUPPORT = false; try { var object = {}; object[ITERATOR$2] = function () { return { next: function () { return { done: ITERATION_SUPPORT = true }; } }; }; exec(object); } catch (error) { /* empty */ } return ITERATION_SUPPORT; }; var INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) { Array.from(iterable); }); // `Array.from` method // https://tc39.github.io/ecma262/#sec-array.from _export({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, { from: arrayFrom }); // `String.prototype.{ codePointAt, at }` methods implementation var createMethod$2 = function (CONVERT_TO_STRING) { return function ($this, pos) { var S = String(requireObjectCoercible($this)); var position = toInteger(pos); var size = S.length; var first, second; if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; first = S.charCodeAt(position); return first < 0xD800 || first > 0xDBFF || position + 1 === size || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF ? CONVERT_TO_STRING ? S.charAt(position) : first : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; }; }; var stringMultibyte = { // `String.prototype.codePointAt` method // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat codeAt: createMethod$2(false), // `String.prototype.at` method // https://github.com/mathiasbynens/String.prototype.at charAt: createMethod$2(true) }; var correctPrototypeGetter = !fails(function () { function F() { /* empty */ } F.prototype.constructor = null; return Object.getPrototypeOf(new F()) !== F.prototype; }); var IE_PROTO = sharedKey('IE_PROTO'); var ObjectPrototype = Object.prototype; // `Object.getPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.getprototypeof var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) { O = toObject(O); if (has(O, IE_PROTO)) return O[IE_PROTO]; if (typeof O.constructor == 'function' && O instanceof O.constructor) { return O.constructor.prototype; } return O instanceof Object ? ObjectPrototype : null; }; var ITERATOR$3 = wellKnownSymbol('iterator'); var BUGGY_SAFARI_ITERATORS = false; var returnThis = function () { return this; }; // `%IteratorPrototype%` object // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; if ([].keys) { arrayIterator = [].keys(); // Safari 8 has buggy iterators w/o `next` if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; else { PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator)); if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; } } if (IteratorPrototype == undefined) IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() if ( !has(IteratorPrototype, ITERATOR$3)) { createNonEnumerableProperty(IteratorPrototype, ITERATOR$3, returnThis); } var iteratorsCore = { IteratorPrototype: IteratorPrototype, BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS }; // `Object.keys` method // https://tc39.github.io/ecma262/#sec-object.keys var objectKeys = Object.keys || function keys(O) { return objectKeysInternal(O, enumBugKeys); }; // `Object.defineProperties` method // https://tc39.github.io/ecma262/#sec-object.defineproperties var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) { anObject(O); var keys = objectKeys(Properties); var length = keys.length; var index = 0; var key; while (length > index) objectDefineProperty.f(O, key = keys[index++], Properties[key]); return O; }; var html = getBuiltIn('document', 'documentElement'); var GT = '>'; var LT = '<'; var PROTOTYPE = 'prototype'; var SCRIPT = 'script'; var IE_PROTO$1 = sharedKey('IE_PROTO'); var EmptyConstructor = function () { /* empty */ }; var scriptTag = function (content) { return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; }; // Create object with fake `null` prototype: use ActiveX Object with cleared prototype var NullProtoObjectViaActiveX = function (activeXDocument) { activeXDocument.write(scriptTag('')); activeXDocument.close(); var temp = activeXDocument.parentWindow.Object; activeXDocument = null; // avoid memory leak return temp; }; // Create object with fake `null` prototype: use iframe Object with cleared prototype var NullProtoObjectViaIFrame = function () { // Thrash, waste and sodomy: IE GC bug var iframe = documentCreateElement('iframe'); var JS = 'java' + SCRIPT + ':'; var iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); // https://github.com/zloirock/core-js/issues/475 iframe.src = String(JS); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write(scriptTag('document.F=Object')); iframeDocument.close(); return iframeDocument.F; }; // Check for document.domain and active x support // No need to use active x approach when document.domain is not set // see https://github.com/es-shims/es5-shim/issues/150 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 // avoid IE GC bug var activeXDocument; var NullProtoObject = function () { try { /* global ActiveXObject */ activeXDocument = document.domain && new ActiveXObject('htmlfile'); } catch (error) { /* ignore */ } NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame(); var length = enumBugKeys.length; while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; return NullProtoObject(); }; hiddenKeys[IE_PROTO$1] = true; // `Object.create` method // https://tc39.github.io/ecma262/#sec-object.create var objectCreate = Object.create || function create(O, Properties) { var result; if (O !== null) { EmptyConstructor[PROTOTYPE] = anObject(O); result = new EmptyConstructor(); EmptyConstructor[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO$1] = O; } else result = NullProtoObject(); return Properties === undefined ? result : objectDefineProperties(result, Properties); }; var defineProperty$1 = objectDefineProperty.f; var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag'); var setToStringTag = function (it, TAG, STATIC) { if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG$2)) { defineProperty$1(it, TO_STRING_TAG$2, { configurable: true, value: TAG }); } }; var IteratorPrototype$1 = iteratorsCore.IteratorPrototype; var returnThis$1 = function () { return this; }; var createIteratorConstructor = function (IteratorConstructor, NAME, next) { var TO_STRING_TAG = NAME + ' Iterator'; IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(1, next) }); setToStringTag(IteratorConstructor, TO_STRING_TAG, false); iterators[TO_STRING_TAG] = returnThis$1; return IteratorConstructor; }; var aPossiblePrototype = function (it) { if (!isObject(it) && it !== null) { throw TypeError("Can't set " + String(it) + ' as a prototype'); } return it; }; // `Object.setPrototypeOf` method // https://tc39.github.io/ecma262/#sec-object.setprototypeof // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () { var CORRECT_SETTER = false; var test = {}; var setter; try { setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set; setter.call(test, []); CORRECT_SETTER = test instanceof Array; } catch (error) { /* empty */ } return function setPrototypeOf(O, proto) { anObject(O); aPossiblePrototype(proto); if (CORRECT_SETTER) setter.call(O, proto); else O.__proto__ = proto; return O; }; }() : undefined); var IteratorPrototype$2 = iteratorsCore.IteratorPrototype; var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS; var ITERATOR$4 = wellKnownSymbol('iterator'); var KEYS = 'keys'; var VALUES = 'values'; var ENTRIES = 'entries'; var returnThis$2 = function () { return this; }; var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { createIteratorConstructor(IteratorConstructor, NAME, next); var getIterationMethod = function (KIND) { if (KIND === DEFAULT && defaultIterator) return defaultIterator; if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) return IterablePrototype[KIND]; switch (KIND) { case KEYS: return function keys() { return new IteratorConstructor(this, KIND); }; case VALUES: return function values() { return new IteratorConstructor(this, KIND); }; case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); }; } return function () { return new IteratorConstructor(this); }; }; var TO_STRING_TAG = NAME + ' Iterator'; var INCORRECT_VALUES_NAME = false; var IterablePrototype = Iterable.prototype; var nativeIterator = IterablePrototype[ITERATOR$4] || IterablePrototype['@@iterator'] || DEFAULT && IterablePrototype[DEFAULT]; var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT); var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; var CurrentIteratorPrototype, methods, KEY; // fix native if (anyNativeIterator) { CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable())); if (IteratorPrototype$2 !== Object.prototype && CurrentIteratorPrototype.next) { if ( objectGetPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype$2) { if (objectSetPrototypeOf) { objectSetPrototypeOf(CurrentIteratorPrototype, IteratorPrototype$2); } else if (typeof CurrentIteratorPrototype[ITERATOR$4] != 'function') { createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR$4, returnThis$2); } } // Set @@toStringTag to native iterators setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true); } } // fix Array#{values, @@iterator}.name in V8 / FF if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { INCORRECT_VALUES_NAME = true; defaultIterator = function values() { return nativeIterator.call(this); }; } // define iterator if ( IterablePrototype[ITERATOR$4] !== defaultIterator) { createNonEnumerableProperty(IterablePrototype, ITERATOR$4, defaultIterator); } iterators[NAME] = defaultIterator; // export additional methods if (DEFAULT) { methods = { values: getIterationMethod(VALUES), keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), entries: getIterationMethod(ENTRIES) }; if (FORCED) for (KEY in methods) { if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { redefine(IterablePrototype, KEY, methods[KEY]); } } else _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME }, methods); } return methods; }; var charAt = stringMultibyte.charAt; var STRING_ITERATOR = 'String Iterator'; var setInternalState = internalState.set; var getInternalState = internalState.getterFor(STRING_ITERATOR); // `String.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator defineIterator(String, 'String', function (iterated) { setInternalState(this, { type: STRING_ITERATOR, string: String(iterated), index: 0 }); // `%StringIteratorPrototype%.next` method // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next }, function next() { var state = getInternalState(this); var string = state.string; var index = state.index; var point; if (index >= string.length) return { value: undefined, done: true }; point = charAt(string, index); state.index += point.length; return { value: point, done: false }; }); // iterable DOM collections // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods var domIterables = { CSSRuleList: 0, CSSStyleDeclaration: 0, CSSValueList: 0, ClientRectList: 0, DOMRectList: 0, DOMStringList: 0, DOMTokenList: 1, DataTransferItemList: 0, FileList: 0, HTMLAllCollection: 0, HTMLCollection: 0, HTMLFormElement: 0, HTMLSelectElement: 0, MediaList: 0, MimeTypeArray: 0, NamedNodeMap: 0, NodeList: 1, PaintRequestList: 0, Plugin: 0, PluginArray: 0, SVGLengthList: 0, SVGNumberList: 0, SVGPathSegList: 0, SVGPointList: 0, SVGStringList: 0, SVGTransformList: 0, SourceBufferList: 0, StyleSheetList: 0, TextTrackCueList: 0, TextTrackList: 0, TouchList: 0 }; for (var COLLECTION_NAME in domIterables) { var Collection = global_1[COLLECTION_NAME]; var CollectionPrototype = Collection && Collection.prototype; // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype && CollectionPrototype.forEach !== arrayForEach) try { createNonEnumerableProperty(CollectionPrototype, 'forEach', arrayForEach); } catch (error) { CollectionPrototype.forEach = arrayForEach; } } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } 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 ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } var runtime_1 = createCommonjsModule(function (module) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var runtime = (function (exports) { var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined$1; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { prototype[method] = function(arg) { return this._invoke(method, arg); }; }); } exports.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; exports.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; if (!(toStringTagSymbol in genFun)) { genFun[toStringTagSymbol] = "GeneratorFunction"; } } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. exports.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. result.value = unwrapped; resolve(result); }, function(error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl ); return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined$1) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { // Note: ["return"] must be used for ES3 parsing compatibility. if (delegate.iterator["return"]) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined$1; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined$1; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined$1; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } exports.values = values; function doneResult() { return { value: undefined$1, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined$1; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined$1; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined$1; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined$1; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined$1; } return ContinueSentinel; } }; // Regardless of whether this script is executing as a CommonJS module // or not, return the runtime object so that we can declare the variable // regeneratorRuntime in the outer scope, which allows this module to be // injected easily by `bin/regenerator --include-runtime script.js`. return exports; }( // If this script is executing as a CommonJS module, use module.exports // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. module.exports )); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { // This module should not be running in strict mode, so the above // assignment should always work unless something is misconfigured. Just // in case runtime.js accidentally runs in strict mode, we can escape // strict mode using a global Function call. This could conceivably fail // if a Content Security Policy forbids using Function, but in that case // the proper solution is to fix the accidental strict mode problem. If // you've misconfigured your bundler to force strict mode and applied a // CSP to forbid Function, and you're not willing to fix either of those // problems, please detail your unique predicament in a GitHub issue. Function("r", "regeneratorRuntime = r")(runtime); } }); var UNSCOPABLES = wellKnownSymbol('unscopables'); var ArrayPrototype$1 = Array.prototype; // Array.prototype[@@unscopables] // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables if (ArrayPrototype$1[UNSCOPABLES] == undefined) { objectDefineProperty.f(ArrayPrototype$1, UNSCOPABLES, { configurable: true, value: objectCreate(null) }); } // add a key to Array.prototype[@@unscopables] var addToUnscopables = function (key) { ArrayPrototype$1[UNSCOPABLES][key] = true; }; var $findIndex = arrayIteration.findIndex; var FIND_INDEX = 'findIndex'; var SKIPS_HOLES = true; var USES_TO_LENGTH$2 = arrayMethodUsesToLength(FIND_INDEX); // Shouldn't skip holes if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES = false; }); // `Array.prototype.findIndex` method // https://tc39.github.io/ecma262/#sec-array.prototype.findindex _export({ target: 'Array', proto: true, forced: SKIPS_HOLES || !USES_TO_LENGTH$2 }, { findIndex: function findIndex(callbackfn /* , that = undefined */) { return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables(FIND_INDEX); var $includes = arrayIncludes.includes; var USES_TO_LENGTH$3 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 }); // `Array.prototype.includes` method // https://tc39.github.io/ecma262/#sec-array.prototype.includes _export({ target: 'Array', proto: true, forced: !USES_TO_LENGTH$3 }, { includes: function includes(el /* , fromIndex = 0 */) { return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('includes'); var $map = arrayIteration.map; var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport('map'); // FF49- issue var USES_TO_LENGTH$4 = arrayMethodUsesToLength('map'); // `Array.prototype.map` method // https://tc39.github.io/ecma262/#sec-array.prototype.map // with adding support of @@species _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 || !USES_TO_LENGTH$4 }, { map: function map(callbackfn /* , thisArg */) { return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // `Array.prototype.{ reduce, reduceRight }` methods implementation var createMethod$3 = function (IS_RIGHT) { return function (that, callbackfn, argumentsLength, memo) { aFunction$1(callbackfn); var O = toObject(that); var self = indexedObject(O); var length = toLength(O.length); var index = IS_RIGHT ? length - 1 : 0; var i = IS_RIGHT ? -1 : 1; if (argumentsLength < 2) while (true) { if (index in self) { memo = self[index]; index += i; break; } index += i; if (IS_RIGHT ? index < 0 : length <= index) { throw TypeError('Reduce of empty array with no initial value'); } } for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) { memo = callbackfn(memo, self[index], index, O); } return memo; }; }; var arrayReduce = { // `Array.prototype.reduce` method // https://tc39.github.io/ecma262/#sec-array.prototype.reduce left: createMethod$3(false), // `Array.prototype.reduceRight` method // https://tc39.github.io/ecma262/#sec-array.prototype.reduceright right: createMethod$3(true) }; var $reduce = arrayReduce.left; var STRICT_METHOD$1 = arrayMethodIsStrict('reduce'); var USES_TO_LENGTH$5 = arrayMethodUsesToLength('reduce', { 1: 0 }); // `Array.prototype.reduce` method // https://tc39.github.io/ecma262/#sec-array.prototype.reduce _export({ target: 'Array', proto: true, forced: !STRICT_METHOD$1 || !USES_TO_LENGTH$5 }, { reduce: function reduce(callbackfn /* , initialValue */) { return $reduce(this, callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); } }); var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport('splice'); var USES_TO_LENGTH$6 = arrayMethodUsesToLength('splice', { ACCESSORS: true, 0: 0, 1: 2 }); var max$1 = Math.max; var min$2 = Math.min; var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; // `Array.prototype.splice` method // https://tc39.github.io/ecma262/#sec-array.prototype.splice // with adding support of @@species _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 || !USES_TO_LENGTH$6 }, { splice: function splice(start, deleteCount /* , ...items */) { var O = toObject(this); var len = toLength(O.length); var actualStart = toAbsoluteIndex(start, len); var argumentsLength = arguments.length; var insertCount, actualDeleteCount, A, k, from, to; if (argumentsLength === 0) { insertCount = actualDeleteCount = 0; } else if (argumentsLength === 1) { insertCount = 0; actualDeleteCount = len - actualStart; } else { insertCount = argumentsLength - 2; actualDeleteCount = min$2(max$1(toInteger(deleteCount), 0), len - actualStart); } if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) { throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED); } A = arraySpeciesCreate(O, actualDeleteCount); for (k = 0; k < actualDeleteCount; k++) { from = actualStart + k; if (from in O) createProperty(A, k, O[from]); } A.length = actualDeleteCount; if (insertCount < actualDeleteCount) { for (k = actualStart; k < len - actualDeleteCount; k++) { from = k + actualDeleteCount; to = k + insertCount; if (from in O) O[to] = O[from]; else delete O[to]; } for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1]; } else if (insertCount > actualDeleteCount) { for (k = len - actualDeleteCount; k > actualStart; k--) { from = k + actualDeleteCount - 1; to = k + insertCount - 1; if (from in O) O[to] = O[from]; else delete O[to]; } } for (k = 0; k < insertCount; k++) { O[k + actualStart] = arguments[k + 2]; } O.length = len - actualDeleteCount + insertCount; return A; } }); // `SameValue` abstract operation // https://tc39.github.io/ecma262/#sec-samevalue var sameValue = Object.is || function is(x, y) { // eslint-disable-next-line no-self-compare return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; // `Object.is` method // https://tc39.github.io/ecma262/#sec-object.is _export({ target: 'Object', stat: true }, { is: sameValue }); var FAILS_ON_PRIMITIVES = fails(function () { objectKeys(1); }); // `Object.keys` method // https://tc39.github.io/ecma262/#sec-object.keys _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { keys: function keys(it) { return objectKeys(toObject(it)); } }); // `Object.prototype.toString` method implementation // https://tc39.github.io/ecma262/#sec-object.prototype.tostring var objectToString = toStringTagSupport ? {}.toString : function toString() { return '[object ' + classof(this) + ']'; }; // `Object.prototype.toString` method // https://tc39.github.io/ecma262/#sec-object.prototype.tostring if (!toStringTagSupport) { redefine(Object.prototype, 'toString', objectToString, { unsafe: true }); } var nativePromiseConstructor = global_1.Promise; var redefineAll = function (target, src, options) { for (var key in src) redefine(target, key, src[key], options); return target; }; var SPECIES$2 = wellKnownSymbol('species'); var setSpecies = function (CONSTRUCTOR_NAME) { var Constructor = getBuiltIn(CONSTRUCTOR_NAME); var defineProperty = objectDefineProperty.f; if (descriptors && Constructor && !Constructor[SPECIES$2]) { defineProperty(Constructor, SPECIES$2, { configurable: true, get: function () { return this; } }); } }; var anInstance = function (it, Constructor, name) { if (!(it instanceof Constructor)) { throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation'); } return it; }; var iterate_1 = createCommonjsModule(function (module) { var Result = function (stopped, result) { this.stopped = stopped; this.result = result; }; var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) { var boundFunction = functionBindContext(fn, that, AS_ENTRIES ? 2 : 1); var iterator, iterFn, index, length, result, next, step; if (IS_ITERATOR) { iterator = iterable; } else { iterFn = getIteratorMethod(iterable); if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); // optimisation for array iterators if (isArrayIteratorMethod(iterFn)) { for (index = 0, length = toLength(iterable.length); length > index; index++) { result = AS_ENTRIES ? boundFunction(anObject(step = iterable[index])[0], step[1]) : boundFunction(iterable[index]); if (result && result instanceof Result) return result; } return new Result(false); } iterator = iterFn.call(iterable); } next = iterator.next; while (!(step = next.call(iterator)).done) { result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES); if (typeof result == 'object' && result && result instanceof Result) return result; } return new Result(false); }; iterate.stop = function (result) { return new Result(true, result); }; }); var SPECIES$3 = wellKnownSymbol('species'); // `SpeciesConstructor` abstract operation // https://tc39.github.io/ecma262/#sec-speciesconstructor var speciesConstructor = function (O, defaultConstructor) { var C = anObject(O).constructor; var S; return C === undefined || (S = anObject(C)[SPECIES$3]) == undefined ? defaultConstructor : aFunction$1(S); }; var engineIsIos = /(iphone|ipod|ipad).*applewebkit/i.test(engineUserAgent); var location = global_1.location; var set$1 = global_1.setImmediate; var clear = global_1.clearImmediate; var process$2 = global_1.process; var MessageChannel = global_1.MessageChannel; var Dispatch = global_1.Dispatch; var counter = 0; var queue = {}; var ONREADYSTATECHANGE = 'onreadystatechange'; var defer, channel, port; var run = function (id) { // eslint-disable-next-line no-prototype-builtins if (queue.hasOwnProperty(id)) { var fn = queue[id]; delete queue[id]; fn(); } }; var runner = function (id) { return function () { run(id); }; }; var listener = function (event) { run(event.data); }; var post = function (id) { // old engines have not location.origin global_1.postMessage(id + '', location.protocol + '//' + location.host); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if (!set$1 || !clear) { set$1 = function setImmediate(fn) { var args = []; var i = 1; while (arguments.length > i) args.push(arguments[i++]); queue[++counter] = function () { // eslint-disable-next-line no-new-func (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args); }; defer(counter); return counter; }; clear = function clearImmediate(id) { delete queue[id]; }; // Node.js 0.8- if (classofRaw(process$2) == 'process') { defer = function (id) { process$2.nextTick(runner(id)); }; // Sphere (JS game engine) Dispatch API } else if (Dispatch && Dispatch.now) { defer = function (id) { Dispatch.now(runner(id)); }; // Browsers with MessageChannel, includes WebWorkers // except iOS - https://github.com/zloirock/core-js/issues/624 } else if (MessageChannel && !engineIsIos) { channel = new MessageChannel(); port = channel.port2; channel.port1.onmessage = listener; defer = functionBindContext(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if (global_1.addEventListener && typeof postMessage == 'function' && !global_1.importScripts && !fails(post)) { defer = post; global_1.addEventListener('message', listener, false); // IE8- } else if (ONREADYSTATECHANGE in documentCreateElement('script')) { defer = function (id) { html.appendChild(documentCreateElement('script'))[ONREADYSTATECHANGE] = function () { html.removeChild(this); run(id); }; }; // Rest old browsers } else { defer = function (id) { setTimeout(runner(id), 0); }; } } var task = { set: set$1, clear: clear }; var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f; var macrotask = task.set; var MutationObserver$1 = global_1.MutationObserver || global_1.WebKitMutationObserver; var process$3 = global_1.process; var Promise$1 = global_1.Promise; var IS_NODE = classofRaw(process$3) == 'process'; // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask` var queueMicrotaskDescriptor = getOwnPropertyDescriptor$2(global_1, 'queueMicrotask'); var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value; var flush, head, last, notify, toggle, node, promise, then; // modern engines have queueMicrotask method if (!queueMicrotask) { flush = function () { var parent, fn; if (IS_NODE && (parent = process$3.domain)) parent.exit(); while (head) { fn = head.fn; head = head.next; try { fn(); } catch (error) { if (head) notify(); else last = undefined; throw error; } } last = undefined; if (parent) parent.enter(); }; // Node.js if (IS_NODE) { notify = function () { process$3.nextTick(flush); }; // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 } else if (MutationObserver$1 && !engineIsIos) { toggle = true; node = document.createTextNode(''); new MutationObserver$1(flush).observe(node, { characterData: true }); notify = function () { node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if (Promise$1 && Promise$1.resolve) { // Promise.resolve without an argument throws an error in LG WebOS 2 promise = Promise$1.resolve(undefined); then = promise.then; notify = function () { then.call(promise, flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function () { // strange IE + webpack dev server bug - use .call(global) macrotask.call(global_1, flush); }; } } var microtask = queueMicrotask || function (fn) { var task = { fn: fn, next: undefined }; if (last) last.next = task; if (!head) { head = task; notify(); } last = task; }; var PromiseCapability = function (C) { var resolve, reject; this.promise = new C(function ($$resolve, $$reject) { if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction$1(resolve); this.reject = aFunction$1(reject); }; // 25.4.1.5 NewPromiseCapability(C) var f$5 = function (C) { return new PromiseCapability(C); }; var newPromiseCapability = { f: f$5 }; var promiseResolve = function (C, x) { anObject(C); if (isObject(x) && x.constructor === C) return x; var promiseCapability = newPromiseCapability.f(C); var resolve = promiseCapability.resolve; resolve(x); return promiseCapability.promise; }; var hostReportErrors = function (a, b) { var console = global_1.console; if (console && console.error) { arguments.length === 1 ? console.error(a) : console.error(a, b); } }; var perform = function (exec) { try { return { error: false, value: exec() }; } catch (error) { return { error: true, value: error }; } }; var task$1 = task.set; var SPECIES$4 = wellKnownSymbol('species'); var PROMISE = 'Promise'; var getInternalState$1 = internalState.get; var setInternalState$1 = internalState.set; var getInternalPromiseState = internalState.getterFor(PROMISE); var PromiseConstructor = nativePromiseConstructor; var TypeError$1 = global_1.TypeError; var document$2 = global_1.document; var process$4 = global_1.process; var $fetch = getBuiltIn('fetch'); var newPromiseCapability$1 = newPromiseCapability.f; var newGenericPromiseCapability = newPromiseCapability$1; var IS_NODE$1 = classofRaw(process$4) == 'process'; var DISPATCH_EVENT = !!(document$2 && document$2.createEvent && global_1.dispatchEvent); var UNHANDLED_REJECTION = 'unhandledrejection'; var REJECTION_HANDLED = 'rejectionhandled'; var PENDING = 0; var FULFILLED = 1; var REJECTED = 2; var HANDLED = 1; var UNHANDLED = 2; var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen; var FORCED = isForced_1(PROMISE, function () { var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor); if (!GLOBAL_CORE_JS_PROMISE) { // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 // We can't detect it synchronously, so just check versions if (engineV8Version === 66) return true; // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test if (!IS_NODE$1 && typeof PromiseRejectionEvent != 'function') return true; } // We can't use @@species feature detection in V8 since it causes // deoptimization and performance degradation // https://github.com/zloirock/core-js/issues/679 if (engineV8Version >= 51 && /native code/.test(PromiseConstructor)) return false; // Detect correctness of subclassing with @@species support var promise = PromiseConstructor.resolve(1); var FakePromise = function (exec) { exec(function () { /* empty */ }, function () { /* empty */ }); }; var constructor = promise.constructor = {}; constructor[SPECIES$4] = FakePromise; return !(promise.then(function () { /* empty */ }) instanceof FakePromise); }); var INCORRECT_ITERATION$1 = FORCED || !checkCorrectnessOfIteration(function (iterable) { PromiseConstructor.all(iterable)['catch'](function () { /* empty */ }); }); // helpers var isThenable = function (it) { var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var notify$1 = function (promise, state, isReject) { if (state.notified) return; state.notified = true; var chain = state.reactions; microtask(function () { var value = state.value; var ok = state.state == FULFILLED; var index = 0; // variable length - can't use forEach while (chain.length > index) { var reaction = chain[index++]; var handler = ok ? reaction.ok : reaction.fail; var resolve = reaction.resolve; var reject = reaction.reject; var domain = reaction.domain; var result, then, exited; try { if (handler) { if (!ok) { if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state); state.rejection = HANDLED; } if (handler === true) result = value; else { if (domain) domain.enter(); result = handler(value); // can throw if (domain) { domain.exit(); exited = true; } } if (result === reaction.promise) { reject(TypeError$1('Promise-chain cycle')); } else if (then = isThenable(result)) { then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch (error) { if (domain && !exited) domain.exit(); reject(error); } } state.reactions = []; state.notified = false; if (isReject && !state.rejection) onUnhandled(promise, state); }); }; var dispatchEvent = function (name, promise, reason) { var event, handler; if (DISPATCH_EVENT) { event = document$2.createEvent('Event'); event.promise = promise; event.reason = reason; event.initEvent(name, false, true); global_1.dispatchEvent(event); } else event = { promise: promise, reason: reason }; if (handler = global_1['on' + name]) handler(event); else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason); }; var onUnhandled = function (promise, state) { task$1.call(global_1, function () { var value = state.value; var IS_UNHANDLED = isUnhandled(state); var result; if (IS_UNHANDLED) { result = perform(function () { if (IS_NODE$1) { process$4.emit('unhandledRejection', value, promise); } else dispatchEvent(UNHANDLED_REJECTION, promise, value); }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should state.rejection = IS_NODE$1 || isUnhandled(state) ? UNHANDLED : HANDLED; if (result.error) throw result.value; } }); }; var isUnhandled = function (state) { return state.rejection !== HANDLED && !state.parent; }; var onHandleUnhandled = function (promise, state) { task$1.call(global_1, function () { if (IS_NODE$1) { process$4.emit('rejectionHandled', promise); } else dispatchEvent(REJECTION_HANDLED, promise, state.value); }); }; var bind = function (fn, promise, state, unwrap) { return function (value) { fn(promise, state, value, unwrap); }; }; var internalReject = function (promise, state, value, unwrap) { if (state.done) return; state.done = true; if (unwrap) state = unwrap; state.value = value; state.state = REJECTED; notify$1(promise, state, true); }; var internalResolve = function (promise, state, value, unwrap) { if (state.done) return; state.done = true; if (unwrap) state = unwrap; try { if (promise === value) throw TypeError$1("Promise can't be resolved itself"); var then = isThenable(value); if (then) { microtask(function () { var wrapper = { done: false }; try { then.call(value, bind(internalResolve, promise, wrapper, state), bind(internalReject, promise, wrapper, state) ); } catch (error) { internalReject(promise, wrapper, error, state); } }); } else { state.value = value; state.state = FULFILLED; notify$1(promise, state, false); } } catch (error) { internalReject(promise, { done: false }, error, state); } }; // constructor polyfill if (FORCED) { // 25.4.3.1 Promise(executor) PromiseConstructor = function Promise(executor) { anInstance(this, PromiseConstructor, PROMISE); aFunction$1(executor); Internal.call(this); var state = getInternalState$1(this); try { executor(bind(internalResolve, this, state), bind(internalReject, this, state)); } catch (error) { internalReject(this, state, error); } }; // eslint-disable-next-line no-unused-vars Internal = function Promise(executor) { setInternalState$1(this, { type: PROMISE, done: false, notified: false, parent: false, reactions: [], rejection: false, state: PENDING, value: undefined }); }; Internal.prototype = redefineAll(PromiseConstructor.prototype, { // `Promise.prototype.then` method // https://tc39.github.io/ecma262/#sec-promise.prototype.then then: function then(onFulfilled, onRejected) { var state = getInternalPromiseState(this); var reaction = newPromiseCapability$1(speciesConstructor(this, PromiseConstructor)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = IS_NODE$1 ? process$4.domain : undefined; state.parent = true; state.reactions.push(reaction); if (state.state != PENDING) notify$1(this, state, false); return reaction.promise; }, // `Promise.prototype.catch` method // https://tc39.github.io/ecma262/#sec-promise.prototype.catch 'catch': function (onRejected) { return this.then(undefined, onRejected); } }); OwnPromiseCapability = function () { var promise = new Internal(); var state = getInternalState$1(promise); this.promise = promise; this.resolve = bind(internalResolve, promise, state); this.reject = bind(internalReject, promise, state); }; newPromiseCapability.f = newPromiseCapability$1 = function (C) { return C === PromiseConstructor || C === PromiseWrapper ? new OwnPromiseCapability(C) : newGenericPromiseCapability(C); }; if ( typeof nativePromiseConstructor == 'function') { nativeThen = nativePromiseConstructor.prototype.then; // wrap native Promise#then for native async functions redefine(nativePromiseConstructor.prototype, 'then', function then(onFulfilled, onRejected) { var that = this; return new PromiseConstructor(function (resolve, reject) { nativeThen.call(that, resolve, reject); }).then(onFulfilled, onRejected); // https://github.com/zloirock/core-js/issues/640 }, { unsafe: true }); // wrap fetch result if (typeof $fetch == 'function') _export({ global: true, enumerable: true, forced: true }, { // eslint-disable-next-line no-unused-vars fetch: function fetch(input /* , init */) { return promiseResolve(PromiseConstructor, $fetch.apply(global_1, arguments)); } }); } } _export({ global: true, wrap: true, forced: FORCED }, { Promise: PromiseConstructor }); setToStringTag(PromiseConstructor, PROMISE, false); setSpecies(PROMISE); PromiseWrapper = getBuiltIn(PROMISE); // statics _export({ target: PROMISE, stat: true, forced: FORCED }, { // `Promise.reject` method // https://tc39.github.io/ecma262/#sec-promise.reject reject: function reject(r) { var capability = newPromiseCapability$1(this); capability.reject.call(undefined, r); return capability.promise; } }); _export({ target: PROMISE, stat: true, forced: FORCED }, { // `Promise.resolve` method // https://tc39.github.io/ecma262/#sec-promise.resolve resolve: function resolve(x) { return promiseResolve( this, x); } }); _export({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION$1 }, { // `Promise.all` method // https://tc39.github.io/ecma262/#sec-promise.all all: function all(iterable) { var C = this; var capability = newPromiseCapability$1(C); var resolve = capability.resolve; var reject = capability.reject; var result = perform(function () { var $promiseResolve = aFunction$1(C.resolve); var values = []; var counter = 0; var remaining = 1; iterate_1(iterable, function (promise) { var index = counter++; var alreadyCalled = false; values.push(undefined); remaining++; $promiseResolve.call(C, promise).then(function (value) { if (alreadyCalled) return; alreadyCalled = true; values[index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if (result.error) reject(result.value); return capability.promise; }, // `Promise.race` method // https://tc39.github.io/ecma262/#sec-promise.race race: function race(iterable) { var C = this; var capability = newPromiseCapability$1(C); var reject = capability.reject; var result = perform(function () { var $promiseResolve = aFunction$1(C.resolve); iterate_1(iterable, function (promise) { $promiseResolve.call(C, promise).then(capability.resolve, reject); }); }); if (result.error) reject(result.value); return capability.promise; } }); // `RegExp.prototype.flags` getter implementation // https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags var regexpFlags = function () { var that = anObject(this); var result = ''; if (that.global) result += 'g'; if (that.ignoreCase) result += 'i'; if (that.multiline) result += 'm'; if (that.dotAll) result += 's'; if (that.unicode) result += 'u'; if (that.sticky) result += 'y'; return result; }; // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError, // so we use an intermediate function. function RE(s, f) { return RegExp(s, f); } var UNSUPPORTED_Y = fails(function () { // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError var re = RE('a', 'y'); re.lastIndex = 2; return re.exec('abcd') != null; }); var BROKEN_CARET = fails(function () { // https://bugzilla.mozilla.org/show_bug.cgi?id=773687 var re = RE('^r', 'gy'); re.lastIndex = 2; return re.exec('str') != null; }); var regexpStickyHelpers = { UNSUPPORTED_Y: UNSUPPORTED_Y, BROKEN_CARET: BROKEN_CARET }; var nativeExec = RegExp.prototype.exec; // This always refers to the native implementation, because the // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js, // which loads this file before patching the method. var nativeReplace = String.prototype.replace; var patchedExec = nativeExec; var UPDATES_LAST_INDEX_WRONG = (function () { var re1 = /a/; var re2 = /b*/g; nativeExec.call(re1, 'a'); nativeExec.call(re2, 'a'); return re1.lastIndex !== 0 || re2.lastIndex !== 0; })(); var UNSUPPORTED_Y$1 = regexpStickyHelpers.UNSUPPORTED_Y || regexpStickyHelpers.BROKEN_CARET; // nonparticipating capturing group, copied from es5-shim's String#split patch. var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y$1; if (PATCH) { patchedExec = function exec(str) { var re = this; var lastIndex, reCopy, match, i; var sticky = UNSUPPORTED_Y$1 && re.sticky; var flags = regexpFlags.call(re); var source = re.source; var charsAdded = 0; var strCopy = str; if (sticky) { flags = flags.replace('y', ''); if (flags.indexOf('g') === -1) { flags += 'g'; } strCopy = String(str).slice(re.lastIndex); // Support anchored sticky behavior. if (re.lastIndex > 0 && (!re.multiline || re.multiline && str[re.lastIndex - 1] !== '\n')) { source = '(?: ' + source + ')'; strCopy = ' ' + strCopy; charsAdded++; } // ^(? + rx + ) is needed, in combination with some str slicing, to // simulate the 'y' flag. reCopy = new RegExp('^(?:' + source + ')', flags); } if (NPCG_INCLUDED) { reCopy = new RegExp('^' + source + '$(?!\\s)', flags); } if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex; match = nativeExec.call(sticky ? reCopy : re, strCopy); if (sticky) { if (match) { match.input = match.input.slice(charsAdded); match[0] = match[0].slice(charsAdded); match.index = re.lastIndex; re.lastIndex += match[0].length; } else re.lastIndex = 0; } else if (UPDATES_LAST_INDEX_WRONG && match) { re.lastIndex = re.global ? match.index + match[0].length : lastIndex; } if (NPCG_INCLUDED && match && match.length > 1) { // Fix browsers whose `exec` methods don't consistently return `undefined` // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/ nativeReplace.call(match[0], reCopy, function () { for (i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undefined) match[i] = undefined; } }); } return match; }; } var regexpExec = patchedExec; _export({ target: 'RegExp', proto: true, forced: /./.exec !== regexpExec }, { exec: regexpExec }); var MATCH = wellKnownSymbol('match'); // `IsRegExp` abstract operation // https://tc39.github.io/ecma262/#sec-isregexp var isRegexp = function (it) { var isRegExp; return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp'); }; var notARegexp = function (it) { if (isRegexp(it)) { throw TypeError("The method doesn't accept regular expressions"); } return it; }; var MATCH$1 = wellKnownSymbol('match'); var correctIsRegexpLogic = function (METHOD_NAME) { var regexp = /./; try { '/./'[METHOD_NAME](regexp); } catch (e) { try { regexp[MATCH$1] = false; return '/./'[METHOD_NAME](regexp); } catch (f) { /* empty */ } } return false; }; // `String.prototype.includes` method // https://tc39.github.io/ecma262/#sec-string.prototype.includes _export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, { includes: function includes(searchString /* , position = 0 */) { return !!~String(requireObjectCoercible(this)) .indexOf(notARegexp(searchString), arguments.length > 1 ? arguments[1] : undefined); } }); // TODO: Remove from `core-js@4` since it's moved to entry points var SPECIES$5 = wellKnownSymbol('species'); var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () { // #replace needs built-in support for named groups. // #match works fine because it just return the exec results, even if it has // a "grops" property. var re = /./; re.exec = function () { var result = []; result.groups = { a: '7' }; return result; }; return ''.replace(re, '$<a>') !== '7'; }); // IE <= 11 replaces $0 with the whole match, as if it was $& // https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0 var REPLACE_KEEPS_$0 = (function () { return 'a'.replace(/./, '$0') === '$0'; })(); var REPLACE = wellKnownSymbol('replace'); // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = (function () { if (/./[REPLACE]) { return /./[REPLACE]('a', '$0') === ''; } return false; })(); // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec // Weex JS has frozen built-in prototypes, so use try / catch wrapper var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () { var re = /(?:)/; var originalExec = re.exec; re.exec = function () { return originalExec.apply(this, arguments); }; var result = 'ab'.split(re); return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b'; }); var fixRegexpWellKnownSymbolLogic = function (KEY, length, exec, sham) { var SYMBOL = wellKnownSymbol(KEY); var DELEGATES_TO_SYMBOL = !fails(function () { // String methods call symbol-named RegEp methods var O = {}; O[SYMBOL] = function () { return 7; }; return ''[KEY](O) != 7; }); var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () { // Symbol-named RegExp methods call .exec var execCalled = false; var re = /a/; if (KEY === 'split') { // We can't use real regex here since it causes deoptimization // and serious performance degradation in V8 // https://github.com/zloirock/core-js/issues/306 re = {}; // RegExp[@@split] doesn't call the regex's exec method, but first creates // a new one. We need to return the patched regex when creating the new one. re.constructor = {}; re.constructor[SPECIES$5] = function () { return re; }; re.flags = ''; re[SYMBOL] = /./[SYMBOL]; } re.exec = function () { execCalled = true; return null; }; re[SYMBOL](''); return !execCalled; }); if ( !DELEGATES_TO_SYMBOL || !DELEGATES_TO_EXEC || (KEY === 'replace' && !( REPLACE_SUPPORTS_NAMED_GROUPS && REPLACE_KEEPS_$0 && !REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE )) || (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC) ) { var nativeRegExpMethod = /./[SYMBOL]; var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) { if (regexp.exec === regexpExec) { if (DELEGATES_TO_SYMBOL && !forceStringMethod) { // The native String method already delegates to @@method (this // polyfilled function), leasing to infinite recursion. // We avoid it by directly calling the native @@method method. return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) }; } return { done: true, value: nativeMethod.call(str, regexp, arg2) }; } return { done: false }; }, { REPLACE_KEEPS_$0: REPLACE_KEEPS_$0, REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE: REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE }); var stringMethod = methods[0]; var regexMethod = methods[1]; redefine(String.prototype, KEY, stringMethod); redefine(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) // 21.2.5.11 RegExp.prototype[@@split](string, limit) ? function (string, arg) { return regexMethod.call(string, this, arg); } // 21.2.5.6 RegExp.prototype[@@match](string) // 21.2.5.9 RegExp.prototype[@@search](string) : function (string) { return regexMethod.call(string, this); } ); } if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true); }; var charAt$1 = stringMultibyte.charAt; // `AdvanceStringIndex` abstract operation // https://tc39.github.io/ecma262/#sec-advancestringindex var advanceStringIndex = function (S, index, unicode) { return index + (unicode ? charAt$1(S, index).length : 1); }; // `RegExpExec` abstract operation // https://tc39.github.io/ecma262/#sec-regexpexec var regexpExecAbstract = function (R, S) { var exec = R.exec; if (typeof exec === 'function') { var result = exec.call(R, S); if (typeof result !== 'object') { throw TypeError('RegExp exec method returned something other than an Object or null'); } return result; } if (classofRaw(R) !== 'RegExp') { throw TypeError('RegExp#exec called on incompatible receiver'); } return regexpExec.call(R, S); }; var arrayPush = [].push; var min$3 = Math.min; var MAX_UINT32 = 0xFFFFFFFF; // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); }); // @@split logic fixRegexpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) { var internalSplit; if ( 'abbc'.split(/(b)*/)[1] == 'c' || 'test'.split(/(?:)/, -1).length != 4 || 'ab'.split(/(?:ab)*/).length != 2 || '.'.split(/(.?)(.?)/).length != 4 || '.'.split(/()()/).length > 1 || ''.split(/.?/).length ) { // based on es5-shim implementation, need to rework it internalSplit = function (separator, limit) { var string = String(requireObjectCoercible(this)); var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; if (lim === 0) return []; if (separator === undefined) return [string]; // If `separator` is not a regex, use native split if (!isRegexp(separator)) { return nativeSplit.call(string, separator, lim); } var output = []; var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); var lastLastIndex = 0; // Make `global` and avoid `lastIndex` issues by working with a copy var separatorCopy = new RegExp(separator.source, flags + 'g'); var match, lastIndex, lastLength; while (match = regexpExec.call(separatorCopy, string)) { lastIndex = separatorCopy.lastIndex; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1)); lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= lim) break; } if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop } if (lastLastIndex === string.length) { if (lastLength || !separatorCopy.test('')) output.push(''); } else output.push(string.slice(lastLastIndex)); return output.length > lim ? output.slice(0, lim) : output; }; // Chakra, V8 } else if ('0'.split(undefined, 0).length) { internalSplit = function (separator, limit) { return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit); }; } else internalSplit = nativeSplit; return [ // `String.prototype.split` method // https://tc39.github.io/ecma262/#sec-string.prototype.split function split(separator, limit) { var O = requireObjectCoercible(this); var splitter = separator == undefined ? undefined : separator[SPLIT]; return splitter !== undefined ? splitter.call(separator, O, limit) : internalSplit.call(String(O), separator, limit); }, // `RegExp.prototype[@@split]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split // // NOTE: This cannot be properly polyfilled in engines that don't support // the 'y' flag. function (regexp, limit) { var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit); if (res.done) return res.value; var rx = anObject(regexp); var S = String(this); var C = speciesConstructor(rx, RegExp); var unicodeMatching = rx.unicode; var flags = (rx.ignoreCase ? 'i' : '') + (rx.multiline ? 'm' : '') + (rx.unicode ? 'u' : '') + (SUPPORTS_Y ? 'y' : 'g'); // ^(? + rx + ) is needed, in combination with some S slicing, to // simulate the 'y' flag. var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; if (lim === 0) return []; if (S.length === 0) return regexpExecAbstract(splitter, S) === null ? [S] : []; var p = 0; var q = 0; var A = []; while (q < S.length) { splitter.lastIndex = SUPPORTS_Y ? q : 0; var z = regexpExecAbstract(splitter, SUPPORTS_Y ? S : S.slice(q)); var e; if ( z === null || (e = min$3(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p ) { q = advanceStringIndex(S, q, unicodeMatching); } else { A.push(S.slice(p, q)); if (A.length === lim) return A; for (var i = 1; i <= z.length - 1; i++) { A.push(z[i]); if (A.length === lim) return A; } q = p = e; } } A.push(S.slice(p)); return A; } ]; }, !SUPPORTS_Y); var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); var MAX_SAFE_INTEGER$1 = 0x1FFFFFFFFFFFFF; var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; // We can't use this feature detection in V8 since it causes // deoptimization and serious performance degradation // https://github.com/zloirock/core-js/issues/679 var IS_CONCAT_SPREADABLE_SUPPORT = engineV8Version >= 51 || !fails(function () { var array = []; array[IS_CONCAT_SPREADABLE] = false; return array.concat()[0] !== array; }); var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); var isConcatSpreadable = function (O) { if (!isObject(O)) return false; var spreadable = O[IS_CONCAT_SPREADABLE]; return spreadable !== undefined ? !!spreadable : isArray(O); }; var FORCED$1 = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; // `Array.prototype.concat` method // https://tc39.github.io/ecma262/#sec-array.prototype.concat // with adding support of @@isConcatSpreadable and @@species _export({ target: 'Array', proto: true, forced: FORCED$1 }, { concat: function concat(arg) { // eslint-disable-line no-unused-vars var O = toObject(this); var A = arraySpeciesCreate(O, 0); var n = 0; var i, k, length, len, E; for (i = -1, length = arguments.length; i < length; i++) { E = i === -1 ? O : arguments[i]; if (isConcatSpreadable(E)) { len = toLength(E.length); if (n + len > MAX_SAFE_INTEGER$1) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); } else { if (n >= MAX_SAFE_INTEGER$1) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); createProperty(A, n++, E); } } A.length = n; return A; } }); var $find = arrayIteration.find; var FIND = 'find'; var SKIPS_HOLES$1 = true; var USES_TO_LENGTH$7 = arrayMethodUsesToLength(FIND); // Shouldn't skip holes if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES$1 = false; }); // `Array.prototype.find` method // https://tc39.github.io/ecma262/#sec-array.prototype.find _export({ target: 'Array', proto: true, forced: SKIPS_HOLES$1 || !USES_TO_LENGTH$7 }, { find: function find(callbackfn /* , that = undefined */) { return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables(FIND); var $indexOf = arrayIncludes.indexOf; var nativeIndexOf = [].indexOf; var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0; var STRICT_METHOD$2 = arrayMethodIsStrict('indexOf'); var USES_TO_LENGTH$8 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 }); // `Array.prototype.indexOf` method // https://tc39.github.io/ecma262/#sec-array.prototype.indexof _export({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || !STRICT_METHOD$2 || !USES_TO_LENGTH$8 }, { indexOf: function indexOf(searchElement /* , fromIndex = 0 */) { return NEGATIVE_ZERO // convert -0 to +0 ? nativeIndexOf.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined); } }); var ARRAY_ITERATOR = 'Array Iterator'; var setInternalState$2 = internalState.set; var getInternalState$2 = internalState.getterFor(ARRAY_ITERATOR); // `Array.prototype.entries` method // https://tc39.github.io/ecma262/#sec-array.prototype.entries // `Array.prototype.keys` method // https://tc39.github.io/ecma262/#sec-array.prototype.keys // `Array.prototype.values` method // https://tc39.github.io/ecma262/#sec-array.prototype.values // `Array.prototype[@@iterator]` method // https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator // `CreateArrayIterator` internal method // https://tc39.github.io/ecma262/#sec-createarrayiterator var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) { setInternalState$2(this, { type: ARRAY_ITERATOR, target: toIndexedObject(iterated), // target index: 0, // next index kind: kind // kind }); // `%ArrayIteratorPrototype%.next` method // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next }, function () { var state = getInternalState$2(this); var target = state.target; var kind = state.kind; var index = state.index++; if (!target || index >= target.length) { state.target = undefined; return { value: undefined, done: true }; } if (kind == 'keys') return { value: index, done: false }; if (kind == 'values') return { value: target[index], done: false }; return { value: [index, target[index]], done: false }; }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% // https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject // https://tc39.github.io/ecma262/#sec-createmappedargumentsobject iterators.Arguments = iterators.Array; // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); var nativeJoin = [].join; var ES3_STRINGS = indexedObject != Object; var STRICT_METHOD$3 = arrayMethodIsStrict('join', ','); // `Array.prototype.join` method // https://tc39.github.io/ecma262/#sec-array.prototype.join _export({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD$3 }, { join: function join(separator) { return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator); } }); var defineProperty$2 = objectDefineProperty.f; var FunctionPrototype = Function.prototype; var FunctionPrototypeToString = FunctionPrototype.toString; var nameRE = /^\s*function ([^ (]*)/; var NAME = 'name'; // Function instances `.name` property // https://tc39.github.io/ecma262/#sec-function-instances-name if (descriptors && !(NAME in FunctionPrototype)) { defineProperty$2(FunctionPrototype, NAME, { configurable: true, get: function () { try { return FunctionPrototypeToString.call(this).match(nameRE)[1]; } catch (error) { return ''; } } }); } // makes subclassing work correct for wrapped built-ins var inheritIfRequired = function ($this, dummy, Wrapper) { var NewTarget, NewTargetPrototype; if ( // it can work only with native `setPrototypeOf` objectSetPrototypeOf && // we haven't completely correct pre-ES6 way for getting `new.target`, so use this typeof (NewTarget = dummy.constructor) == 'function' && NewTarget !== Wrapper && isObject(NewTargetPrototype = NewTarget.prototype) && NewTargetPrototype !== Wrapper.prototype ) objectSetPrototypeOf($this, NewTargetPrototype); return $this; }; // a string of all valid unicode whitespaces // eslint-disable-next-line max-len var whitespaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; var whitespace = '[' + whitespaces + ']'; var ltrim = RegExp('^' + whitespace + whitespace + '*'); var rtrim = RegExp(whitespace + whitespace + '*$'); // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation var createMethod$4 = function (TYPE) { return function ($this) { var string = String(requireObjectCoercible($this)); if (TYPE & 1) string = string.replace(ltrim, ''); if (TYPE & 2) string = string.replace(rtrim, ''); return string; }; }; var stringTrim = { // `String.prototype.{ trimLeft, trimStart }` methods // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart start: createMethod$4(1), // `String.prototype.{ trimRight, trimEnd }` methods // https://tc39.github.io/ecma262/#sec-string.prototype.trimend end: createMethod$4(2), // `String.prototype.trim` method // https://tc39.github.io/ecma262/#sec-string.prototype.trim trim: createMethod$4(3) }; var getOwnPropertyNames = objectGetOwnPropertyNames.f; var getOwnPropertyDescriptor$3 = objectGetOwnPropertyDescriptor.f; var defineProperty$3 = objectDefineProperty.f; var trim = stringTrim.trim; var NUMBER = 'Number'; var NativeNumber = global_1[NUMBER]; var NumberPrototype = NativeNumber.prototype; // Opera ~12 has broken Object#toString var BROKEN_CLASSOF = classofRaw(objectCreate(NumberPrototype)) == NUMBER; // `ToNumber` abstract operation // https://tc39.github.io/ecma262/#sec-tonumber var toNumber = function (argument) { var it = toPrimitive(argument, false); var first, third, radix, maxCode, digits, length, index, code; if (typeof it == 'string' && it.length > 2) { it = trim(it); first = it.charCodeAt(0); if (first === 43 || first === 45) { third = it.charCodeAt(2); if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix } else if (first === 48) { switch (it.charCodeAt(1)) { case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i default: return +it; } digits = it.slice(2); length = digits.length; for (index = 0; index < length; index++) { code = digits.charCodeAt(index); // parseInt parses a string to a first unavailable symbol // but ToNumber should return NaN if a string contains unavailable symbols if (code < 48 || code > maxCode) return NaN; } return parseInt(digits, radix); } } return +it; }; // `Number` constructor // https://tc39.github.io/ecma262/#sec-number-constructor if (isForced_1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) { var NumberWrapper = function Number(value) { var it = arguments.length < 1 ? 0 : value; var dummy = this; return dummy instanceof NumberWrapper // check on 1..constructor(foo) case && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classofRaw(dummy) != NUMBER) ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it); }; for (var keys$1 = descriptors ? getOwnPropertyNames(NativeNumber) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES2015 (in case, if modules with ES2015 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' ).split(','), j = 0, key; keys$1.length > j; j++) { if (has(NativeNumber, key = keys$1[j]) && !has(NumberWrapper, key)) { defineProperty$3(NumberWrapper, key, getOwnPropertyDescriptor$3(NativeNumber, key)); } } NumberWrapper.prototype = NumberPrototype; NumberPrototype.constructor = NumberWrapper; redefine(global_1, NUMBER, NumberWrapper); } var propertyIsEnumerable = objectPropertyIsEnumerable.f; // `Object.{ entries, values }` methods implementation var createMethod$5 = function (TO_ENTRIES) { return function (it) { var O = toIndexedObject(it); var keys = objectKeys(O); var length = keys.length; var i = 0; var result = []; var key; while (length > i) { key = keys[i++]; if (!descriptors || propertyIsEnumerable.call(O, key)) { result.push(TO_ENTRIES ? [key, O[key]] : O[key]); } } return result; }; }; var objectToArray = { // `Object.entries` method // https://tc39.github.io/ecma262/#sec-object.entries entries: createMethod$5(true), // `Object.values` method // https://tc39.github.io/ecma262/#sec-object.values values: createMethod$5(false) }; var $values = objectToArray.values; // `Object.values` method // https://tc39.github.io/ecma262/#sec-object.values _export({ target: 'Object', stat: true }, { values: function values(O) { return $values(O); } }); var freezing = !fails(function () { return Object.isExtensible(Object.preventExtensions({})); }); var internalMetadata = createCommonjsModule(function (module) { var defineProperty = objectDefineProperty.f; var METADATA = uid('meta'); var id = 0; var isExtensible = Object.isExtensible || function () { return true; }; var setMetadata = function (it) { defineProperty(it, METADATA, { value: { objectID: 'O' + ++id, // object ID weakData: {} // weak collections IDs } }); }; var fastKey = function (it, create) { // return a primitive with prefix if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if (!has(it, METADATA)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return 'F'; // not necessary to add metadata if (!create) return 'E'; // add missing metadata setMetadata(it); // return object ID } return it[METADATA].objectID; }; var getWeakData = function (it, create) { if (!has(it, METADATA)) { // can't set metadata to uncaught frozen object if (!isExtensible(it)) return true; // not necessary to add metadata if (!create) return false; // add missing metadata setMetadata(it); // return the store of weak collections IDs } return it[METADATA].weakData; }; // add metadata on freeze-family methods calling var onFreeze = function (it) { if (freezing && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it); return it; }; var meta = module.exports = { REQUIRED: false, fastKey: fastKey, getWeakData: getWeakData, onFreeze: onFreeze }; hiddenKeys[METADATA] = true; }); var internalMetadata_1 = internalMetadata.REQUIRED; var internalMetadata_2 = internalMetadata.fastKey; var internalMetadata_3 = internalMetadata.getWeakData; var internalMetadata_4 = internalMetadata.onFreeze; var collection = function (CONSTRUCTOR_NAME, wrapper, common) { var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1; var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1; var ADDER = IS_MAP ? 'set' : 'add'; var NativeConstructor = global_1[CONSTRUCTOR_NAME]; var NativePrototype = NativeConstructor && NativeConstructor.prototype; var Constructor = NativeConstructor; var exported = {}; var fixMethod = function (KEY) { var nativeMethod = NativePrototype[KEY]; redefine(NativePrototype, KEY, KEY == 'add' ? function add(value) { nativeMethod.call(this, value === 0 ? 0 : value); return this; } : KEY == 'delete' ? function (key) { return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); } : KEY == 'get' ? function get(key) { return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key); } : KEY == 'has' ? function has(key) { return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); } : function set(key, value) { nativeMethod.call(this, key === 0 ? 0 : key, value); return this; } ); }; // eslint-disable-next-line max-len if (isForced_1(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () { new NativeConstructor().entries().next(); })))) { // create collection constructor Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); internalMetadata.REQUIRED = true; } else if (isForced_1(CONSTRUCTOR_NAME, true)) { var instance = new Constructor(); // early implementations not supports chaining var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); // most early implementations doesn't supports iterables, most modern - not close it correctly // eslint-disable-next-line no-new var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); }); // for early implementations -0 and +0 not the same var BUGGY_ZERO = !IS_WEAK && fails(function () { // V8 ~ Chromium 42- fails only with 5+ elements var $instance = new NativeConstructor(); var index = 5; while (index--) $instance[ADDER](index, index); return !$instance.has(-0); }); if (!ACCEPT_ITERABLES) { Constructor = wrapper(function (dummy, iterable) { anInstance(dummy, Constructor, CONSTRUCTOR_NAME); var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor); if (iterable != undefined) iterate_1(iterable, that[ADDER], that, IS_MAP); return that; }); Constructor.prototype = NativePrototype; NativePrototype.constructor = Constructor; } if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); // weak collections should not contains .clear method if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; } exported[CONSTRUCTOR_NAME] = Constructor; _export({ global: true, forced: Constructor != NativeConstructor }, exported); setToStringTag(Constructor, CONSTRUCTOR_NAME); if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP); return Constructor; }; var defineProperty$4 = objectDefineProperty.f; var fastKey = internalMetadata.fastKey; var setInternalState$3 = internalState.set; var internalStateGetterFor = internalState.getterFor; var collectionStrong = { getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { var C = wrapper(function (that, iterable) { anInstance(that, C, CONSTRUCTOR_NAME); setInternalState$3(that, { type: CONSTRUCTOR_NAME, index: objectCreate(null), first: undefined, last: undefined, size: 0 }); if (!descriptors) that.size = 0; if (iterable != undefined) iterate_1(iterable, that[ADDER], that, IS_MAP); }); var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); var define = function (that, key, value) { var state = getInternalState(that); var entry = getEntry(that, key); var previous, index; // change existing entry if (entry) { entry.value = value; // create new entry } else { state.last = entry = { index: index = fastKey(key, true), key: key, value: value, previous: previous = state.last, next: undefined, removed: false }; if (!state.first) state.first = entry; if (previous) previous.next = entry; if (descriptors) state.size++; else that.size++; // add to index if (index !== 'F') state.index[index] = entry; } return that; }; var getEntry = function (that, key) { var state = getInternalState(that); // fast case var index = fastKey(key); var entry; if (index !== 'F') return state.index[index]; // frozen object case for (entry = state.first; entry; entry = entry.next) { if (entry.key == key) return entry; } }; redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear() { var that = this; var state = getInternalState(that); var data = state.index; var entry = state.first; while (entry) { entry.removed = true; if (entry.previous) entry.previous = entry.previous.next = undefined; delete data[entry.index]; entry = entry.next; } state.first = state.last = undefined; if (descriptors) state.size = 0; else that.size = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function (key) { var that = this; var state = getInternalState(that); var entry = getEntry(that, key); if (entry) { var next = entry.next; var prev = entry.previous; delete state.index[entry.index]; entry.removed = true; if (prev) prev.next = next; if (next) next.previous = prev; if (state.first == entry) state.first = next; if (state.last == entry) state.last = prev; if (descriptors) state.size--; else that.size--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /* , that = undefined */) { var state = getInternalState(this); var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); var entry; while (entry = entry ? entry.next : state.first) { boundFunction(entry.value, entry.key, this); // revert to the last existing entry while (entry && entry.removed) entry = entry.previous; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key) { return !!getEntry(this, key); } }); redefineAll(C.prototype, IS_MAP ? { // 23.1.3.6 Map.prototype.get(key) get: function get(key) { var entry = getEntry(this, key); return entry && entry.value; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value) { return define(this, key === 0 ? 0 : key, value); } } : { // 23.2.3.1 Set.prototype.add(value) add: function add(value) { return define(this, value = value === 0 ? 0 : value, value); } }); if (descriptors) defineProperty$4(C.prototype, 'size', { get: function () { return getInternalState(this).size; } }); return C; }, setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) { var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) { setInternalState$3(this, { type: ITERATOR_NAME, target: iterated, state: getInternalCollectionState(iterated), kind: kind, last: undefined }); }, function () { var state = getInternalIteratorState(this); var kind = state.kind; var entry = state.last; // revert to the last existing entry while (entry && entry.removed) entry = entry.previous; // get next entry if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { // or finish the iteration state.target = undefined; return { value: undefined, done: true }; } // return step by kind if (kind == 'keys') return { value: entry.key, done: false }; if (kind == 'values') return { value: entry.value, done: false }; return { value: [entry.key, entry.value], done: false }; }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(CONSTRUCTOR_NAME); } }; // `Set` constructor // https://tc39.github.io/ecma262/#sec-set-objects var es_set = collection('Set', function (init) { return function Set() { return init(this, arguments.length ? arguments[0] : undefined); }; }, collectionStrong); // @@match logic fixRegexpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) { return [ // `String.prototype.match` method // https://tc39.github.io/ecma262/#sec-string.prototype.match function match(regexp) { var O = requireObjectCoercible(this); var matcher = regexp == undefined ? undefined : regexp[MATCH]; return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); }, // `RegExp.prototype[@@match]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match function (regexp) { var res = maybeCallNative(nativeMatch, regexp, this); if (res.done) return res.value; var rx = anObject(regexp); var S = String(this); if (!rx.global) return regexpExecAbstract(rx, S); var fullUnicode = rx.unicode; rx.lastIndex = 0; var A = []; var n = 0; var result; while ((result = regexpExecAbstract(rx, S)) !== null) { var matchStr = String(result[0]); A[n] = matchStr; if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); n++; } return n === 0 ? null : A; } ]; }); var max$2 = Math.max; var min$4 = Math.min; var floor$1 = Math.floor; var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g; var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g; var maybeToString = function (it) { return it === undefined ? it : String(it); }; // @@replace logic fixRegexpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) { var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE; var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0; var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0'; return [ // `String.prototype.replace` method // https://tc39.github.io/ecma262/#sec-string.prototype.replace function replace(searchValue, replaceValue) { var O = requireObjectCoercible(this); var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; return replacer !== undefined ? replacer.call(searchValue, O, replaceValue) : nativeReplace.call(String(O), searchValue, replaceValue); }, // `RegExp.prototype[@@replace]` method // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace function (regexp, replaceValue) { if ( (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0) || (typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1) ) { var res = maybeCallNative(nativeReplace, regexp, this, replaceValue); if (res.done) return res.value; } var rx = anObject(regexp); var S = String(this); var functionalReplace = typeof replaceValue === 'function'; if (!functionalReplace) replaceValue = String(replaceValue); var global = rx.global; if (global) { var fullUnicode = rx.unicode; rx.lastIndex = 0; } var results = []; while (true) { var result = regexpExecAbstract(rx, S); if (result === null) break; results.push(result); if (!global) break; var matchStr = String(result[0]); if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); } var accumulatedResult = ''; var nextSourcePosition = 0; for (var i = 0; i < results.length; i++) { result = results[i]; var matched = String(result[0]); var position = max$2(min$4(toInteger(result.index), S.length), 0); var captures = []; // NOTE: This is equivalent to // captures = result.slice(1).map(maybeToString) // but for some reason `nativeSlice.call(result, 1, result.length)` (called in // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); var namedCaptures = result.groups; if (functionalReplace) { var replacerArgs = [matched].concat(captures, position, S); if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); var replacement = String(replaceValue.apply(undefined, replacerArgs)); } else { replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); } if (position >= nextSourcePosition) { accumulatedResult += S.slice(nextSourcePosition, position) + replacement; nextSourcePosition = position + matched.length; } } return accumulatedResult + S.slice(nextSourcePosition); } ]; // https://tc39.github.io/ecma262/#sec-getsubstitution function getSubstitution(matched, str, position, captures, namedCaptures, replacement) { var tailPos = position + matched.length; var m = captures.length; var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; if (namedCaptures !== undefined) { namedCaptures = toObject(namedCaptures); symbols = SUBSTITUTION_SYMBOLS; } return nativeReplace.call(replacement, symbols, function (match, ch) { var capture; switch (ch.charAt(0)) { case '$': return '$'; case '&': return matched; case '`': return str.slice(0, position); case "'": return str.slice(tailPos); case '<': capture = namedCaptures[ch.slice(1, -1)]; break; default: // \d\d? var n = +ch; if (n === 0) return match; if (n > m) { var f = floor$1(n / 10); if (f === 0) return match; if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); return match; } capture = captures[n - 1]; } return capture === undefined ? '' : capture; }); } }); var getOwnPropertyDescriptor$4 = objectGetOwnPropertyDescriptor.f; var nativeStartsWith = ''.startsWith; var min$5 = Math.min; var CORRECT_IS_REGEXP_LOGIC = correctIsRegexpLogic('startsWith'); // https://github.com/zloirock/core-js/pull/702 var MDN_POLYFILL_BUG = !CORRECT_IS_REGEXP_LOGIC && !!function () { var descriptor = getOwnPropertyDescriptor$4(String.prototype, 'startsWith'); return descriptor && !descriptor.writable; }(); // `String.prototype.startsWith` method // https://tc39.github.io/ecma262/#sec-string.prototype.startswith _export({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, { startsWith: function startsWith(searchString /* , position = 0 */) { var that = String(requireObjectCoercible(this)); notARegexp(searchString); var index = toLength(min$5(arguments.length > 1 ? arguments[1] : undefined, that.length)); var search = String(searchString); return nativeStartsWith ? nativeStartsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); var non = '\u200B\u0085\u180E'; // check that a method works with the correct list // of whitespaces and has a correct name var stringTrimForced = function (METHOD_NAME) { return fails(function () { return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME; }); }; var $trim = stringTrim.trim; // `String.prototype.trim` method // https://tc39.github.io/ecma262/#sec-string.prototype.trim _export({ target: 'String', proto: true, forced: stringTrimForced('trim') }, { trim: function trim() { return $trim(this); } }); var ITERATOR$5 = wellKnownSymbol('iterator'); var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag'); var ArrayValues = es_array_iterator.values; for (var COLLECTION_NAME$1 in domIterables) { var Collection$1 = global_1[COLLECTION_NAME$1]; var CollectionPrototype$1 = Collection$1 && Collection$1.prototype; if (CollectionPrototype$1) { // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype$1[ITERATOR$5] !== ArrayValues) try { createNonEnumerableProperty(CollectionPrototype$1, ITERATOR$5, ArrayValues); } catch (error) { CollectionPrototype$1[ITERATOR$5] = ArrayValues; } if (!CollectionPrototype$1[TO_STRING_TAG$3]) { createNonEnumerableProperty(CollectionPrototype$1, TO_STRING_TAG$3, COLLECTION_NAME$1); } if (domIterables[COLLECTION_NAME$1]) for (var METHOD_NAME in es_array_iterator) { // some Chrome versions have non-configurable methods on DOMTokenList if (CollectionPrototype$1[METHOD_NAME] !== es_array_iterator[METHOD_NAME]) try { createNonEnumerableProperty(CollectionPrototype$1, METHOD_NAME, es_array_iterator[METHOD_NAME]); } catch (error) { CollectionPrototype$1[METHOD_NAME] = es_array_iterator[METHOD_NAME]; } } } } // Thanks @stimulus: // https://github.com/stimulusjs/stimulus/blob/master/packages/%40stimulus/core/src/application.ts function domReady() { var _this = this; return new Promise(function (resolve) { _newArrowCheck(this, _this); if (document.readyState == "loading") { document.addEventListener("DOMContentLoaded", resolve); } else { resolve(); } }.bind(this)); } function arrayUnique(array) { return Array.from(new Set(array)); } function isTesting() { return navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom"); } function kebabCase(subject) { return subject.replace(/([a-z])([A-Z])/g, '$1-$2').replace(/[_\s]/, '-').toLowerCase(); } function walk(el, callback) { if (callback(el) === false) return; var node = el.firstElementChild; while (node) { walk(node, callback); node = node.nextElementSibling; } } function debounce(func, wait) { var timeout; return function () { var context = this, args = arguments; var later = function later() { timeout = null; func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } function saferEval(expression, dataContext) { var additionalHelperVariables = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return new Function(['$data'].concat(_toConsumableArray(Object.keys(additionalHelperVariables))), "var result; with($data) { result = ".concat(expression, " }; return result")).apply(void 0, [dataContext].concat(_toConsumableArray(Object.values(additionalHelperVariables)))); } function saferEvalNoReturn(expression, dataContext) { var additionalHelperVariables = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; // For the cases when users pass only a function reference to the caller: `x-on:click="foo"` // Where "foo" is a function. Also, we'll pass the function the event instance when we call it. if (Object.keys(dataContext).includes(expression)) { var methodReference = new Function(['dataContext'].concat(_toConsumableArray(Object.keys(additionalHelperVariables))), "with(dataContext) { return ".concat(expression, " }")).apply(void 0, [dataContext].concat(_toConsumableArray(Object.values(additionalHelperVariables)))); if (typeof methodReference === 'function') { return methodReference.call(dataContext, additionalHelperVariables['$event']); } } return new Function(['dataContext'].concat(_toConsumableArray(Object.keys(additionalHelperVariables))), "with(dataContext) { ".concat(expression, " }")).apply(void 0, [dataContext].concat(_toConsumableArray(Object.values(additionalHelperVariables)))); } var xAttrRE = /^x-(on|bind|data|text|html|model|if|for|show|cloak|transition|ref)\b/; function isXAttr(attr) { var name = replaceAtAndColonWithStandardSyntax(attr.name); return xAttrRE.test(name); } function getXAttrs(el, type) { var _this2 = this; return Array.from(el.attributes).filter(isXAttr).map(function (attr) { var _this3 = this; _newArrowCheck(this, _this2); var name = replaceAtAndColonWithStandardSyntax(attr.name); var typeMatch = name.match(xAttrRE); var valueMatch = name.match(/:([a-zA-Z\-:]+)/); var modifiers = name.match(/\.[^.\]]+(?=[^\]]*$)/g) || []; return { type: typeMatch ? typeMatch[1] : null, value: valueMatch ? valueMatch[1] : null, modifiers: modifiers.map(function (i) { _newArrowCheck(this, _this3); return i.replace('.', ''); }.bind(this)), expression: attr.value }; }.bind(this)).filter(function (i) { _newArrowCheck(this, _this2); // If no type is passed in for filtering, bypass filter if (!type) return true; return i.type === type; }.bind(this)); } function isBooleanAttr(attrName) { // As per HTML spec table https://html.spec.whatwg.org/multipage/indices.html#attributes-3:boolean-attribute // Array roughly ordered by estimated usage var booleanAttributes = ['disabled', 'checked', 'required', 'readonly', 'hidden', 'open', 'selected', 'autofocus', 'itemscope', 'multiple', 'novalidate', 'allowfullscreen', 'allowpaymentrequest', 'formnovalidate', 'autoplay', 'controls', 'loop', 'muted', 'playsinline', 'default', 'ismap', 'reversed', 'async', 'defer', 'nomodule']; return booleanAttributes.includes(attrName); } function replaceAtAndColonWithStandardSyntax(name) { if (name.startsWith('@')) { return name.replace('@', 'x-on:'); } else if (name.startsWith(':')) { return name.replace(':', 'x-bind:'); } return name; } function transitionIn(el, show) { var _this4 = this; var forceSkip = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; // We don't want to transition on the initial page load. if (forceSkip) return show(); var attrs = getXAttrs(el, 'transition'); var showAttr = getXAttrs(el, 'show')[0]; // If this is triggered by a x-show.transition. if (showAttr && showAttr.modifiers.includes('transition')) { var modifiers = showAttr.modifiers; // If x-show.transition.out, we'll skip the "in" transition. if (modifiers.includes('out') && !modifiers.includes('in')) return show(); var settingBothSidesOfTransition = modifiers.includes('in') && modifiers.includes('out'); // If x-show.transition.in...out... only use "in" related modifiers for this transition. modifiers = settingBothSidesOfTransition ? modifiers.filter(function (i, index) { _newArrowCheck(this, _this4); return index < modifiers.indexOf('out'); }.bind(this)) : modifiers; transitionHelperIn(el, modifiers, show); // Otherwise, we can assume x-transition:enter. } else if (attrs.length > 0) { transitionClassesIn(el, attrs, show); } else { // If neither, just show that damn thing. show(); } } function transitionOut(el, hide) { var _this5 = this; var forceSkip = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (forceSkip) return hide(); var attrs = getXAttrs(el, 'transition'); var showAttr = getXAttrs(el, 'show')[0]; if (showAttr && showAttr.modifiers.includes('transition')) { var modifiers = showAttr.modifiers; if (modifiers.includes('in') && !modifiers.includes('out')) return hide(); var settingBothSidesOfTransition = modifiers.includes('in') && modifiers.includes('out'); modifiers = settingBothSidesOfTransition ? modifiers.filter(function (i, index) { _newArrowCheck(this, _this5); return index > modifiers.indexOf('out'); }.bind(this)) : modifiers; transitionHelperOut(el, modifiers, settingBothSidesOfTransition, hide); } else if (attrs.length > 0) { transitionClassesOut(el, attrs, hide); } else { hide(); } } function transitionHelperIn(el, modifiers, showCallback) { var _this6 = this; // Default values inspired by: https://material.io/design/motion/speed.html#duration var styleValues = { duration: modifierValue(modifiers, 'duration', 150), origin: modifierValue(modifiers, 'origin', 'center'), first: { opacity: 0, scale: modifierValue(modifiers, 'scale', 95) }, second: { opacity: 1, scale: 100 } }; transitionHelper(el, modifiers, showCallback, function () { _newArrowCheck(this, _this6); }.bind(this), styleValues); } function transitionHelperOut(el, modifiers, settingBothSidesOfTransition, hideCallback) { var _this7 = this; // Make the "out" transition .5x slower than the "in". (Visually better) // HOWEVER, if they explicitly set a duration for the "out" transition, // use that. var duration = settingBothSidesOfTransition ? modifierValue(modifiers, 'duration', 150) : modifierValue(modifiers, 'duration', 150) / 2; var styleValues = { duration: duration, origin: modifierValue(modifiers, 'origin', 'center'), first: { opacity: 1, scale: 100 }, second: { opacity: 0, scale: modifierValue(modifiers, 'scale', 95) } }; transitionHelper(el, modifiers, function () { _newArrowCheck(this, _this7); }.bind(this), hideCallback, styleValues); } function modifierValue(modifiers, key, fallback) { // If the modifier isn't present, use the default. if (modifiers.indexOf(key) === -1) return fallback; // If it IS present, grab the value after it: x-show.transition.duration.500ms var rawValue = modifiers[modifiers.indexOf(key) + 1]; if (!rawValue) return fallback; if (key === 'scale') { // Check if the very next value is NOT a number and return the fallback. // If x-show.transition.scale, we'll use the default scale value. // That is how a user opts out of the opacity transition. if (!isNumeric(rawValue)) return fallback; } if (key === 'duration') { // Support x-show.transition.duration.500ms && duration.500 var match = rawValue.match(/([0-9]+)ms/); if (match) return match[1]; } if (key === 'origin') { // Support chaining origin directions: x-show.transition.top.right if (['top', 'right', 'left', 'center', 'bottom'].includes(modifiers[modifiers.indexOf(key) + 2])) { return [rawValue, modifiers[modifiers.indexOf(key) + 2]].join(' '); } } return rawValue; } function transitionHelper(el, modifiers, hook1, hook2, styleValues) { // If the user set these style values, we'll put them back when we're done with them. var opacityCache = el.style.opacity; var transformCache = el.style.transform; var transformOriginCache = el.style.transformOrigin; // If no modifiers are present: x-show.transition, we'll default to both opacity and scale. var noModifiers = !modifiers.includes('opacity') && !modifiers.includes('scale'); var transitionOpacity = noModifiers || modifiers.includes('opacity'); var transitionScale = noModifiers || modifiers.includes('scale'); // These are the explicit stages of a transition (same stages for in and for out). // This way you can get a birds eye view of the hooks, and the differences // between them. var stages = { start: function start() { if (transitionOpacity) el.style.opacity = styleValues.first.opacity; if (transitionScale) el.style.transform = "scale(".concat(styleValues.first.scale / 100, ")"); }, during: function during() { if (transitionScale) el.style.transformOrigin = styleValues.origin; el.style.transitionProperty = [transitionOpacity ? "opacity" : "", transitionScale ? "transform" : ""].join(' ').trim(); el.style.transitionDuration = "".concat(styleValues.duration / 1000, "s"); el.style.transitionTimingFunction = "cubic-bezier(0.4, 0.0, 0.2, 1)"; }, show: function show() { hook1(); }, end: function end() { if (transitionOpacity) el.style.opacity = styleValues.second.opacity; if (transitionScale) el.style.transform = "scale(".concat(styleValues.second.scale / 100, ")"); }, hide: function hide() { hook2(); }, cleanup: function cleanup() { if (transitionOpacity) el.style.opacity = opacityCache; if (transitionScale) el.style.transform = transformCache; if (transitionScale) el.style.transformOrigin = transformOriginCache; el.style.transitionProperty = null; el.style.transitionDuration = null; el.style.transitionTimingFunction = null; } }; transition(el, stages); } function transitionClassesIn(el, directives, showCallback) { var _this8 = this; var enter = (directives.find(function (i) { _newArrowCheck(this, _this8); return i.value === 'enter'; }.bind(this)) || { expression: '' }).expression.split(' ').filter(function (i) { _newArrowCheck(this, _this8); return i !== ''; }.bind(this)); var enterStart = (directives.find(function (i) { _newArrowCheck(this, _this8); return i.value === 'enter-start'; }.bind(this)) || { expression: '' }).expression.split(' ').filter(function (i) { _newArrowCheck(this, _this8); return i !== ''; }.bind(this)); var enterEnd = (directives.find(function (i) { _newArrowCheck(this, _this8); return i.value === 'enter-end'; }.bind(this)) || { expression: '' }).expression.split(' ').filter(function (i) { _newArrowCheck(this, _this8); return i !== ''; }.bind(this)); transitionClasses(el, enter, enterStart, enterEnd, showCallback, function () { _newArrowCheck(this, _this8); }.bind(this)); } function transitionClassesOut(el, directives, hideCallback) { var _this9 = this; var leave = (directives.find(function (i) { _newArrowCheck(this, _this9); return i.value === 'leave'; }.bind(this)) || { expression: '' }).expression.split(' ').filter(function (i) { _newArrowCheck(this, _this9); return i !== ''; }.bind(this)); var leaveStart = (directives.find(function (i) { _newArrowCheck(this, _this9); return i.value === 'leave-start'; }.bind(this)) || { expression: '' }).expression.split(' ').filter(function (i) { _newArrowCheck(this, _this9); return i !== ''; }.bind(this)); var leaveEnd = (directives.find(function (i) { _newArrowCheck(this, _this9); return i.value === 'leave-end'; }.bind(this)) || { expression: '' }).expression.split(' ').filter(function (i) { _newArrowCheck(this, _this9); return i !== ''; }.bind(this)); transitionClasses(el, leave, leaveStart, leaveEnd, function () { _newArrowCheck(this, _this9); }.bind(this), hideCallback); } function transitionClasses(el, classesDuring, classesStart, classesEnd, hook1, hook2) { var originalClasses = el.__x_original_classes || []; var stages = { start: function start() { var _el$classList; (_el$classList = el.classList).add.apply(_el$classList, _toConsumableArray(classesStart)); }, during: function during() { var _el$classList2; (_el$classList2 = el.classList).add.apply(_el$classList2, _toConsumableArray(classesDuring)); }, show: function show() { hook1(); }, end: function end() { var _el$classList3, _this10 = this, _el$classList4; // Don't remove classes that were in the original class attribute. (_el$classList3 = el.classList).remove.apply(_el$classList3, _toConsumableArray(classesStart.filter(function (i) { _newArrowCheck(this, _this10); return !originalClasses.includes(i); }.bind(this)))); (_el$classList4 = el.classList).add.apply(_el$classList4, _toConsumableArray(classesEnd)); }, hide: function hide() { hook2(); }, cleanup: function cleanup() { var _el$classList5, _this11 = this, _el$classList6; (_el$classList5 = el.classList).remove.apply(_el$classList5, _toConsumableArray(classesDuring.filter(function (i) { _newArrowCheck(this, _this11); return !originalClasses.includes(i); }.bind(this)))); (_el$classList6 = el.classList).remove.apply(_el$classList6, _toConsumableArray(classesEnd.filter(function (i) { _newArrowCheck(this, _this11); return !originalClasses.includes(i); }.bind(this)))); } }; transition(el, stages); } function transition(el, stages) { var _this12 = this; stages.start(); stages.during(); requestAnimationFrame(function () { var _this13 = this; _newArrowCheck(this, _this12); // Note: Safari's transitionDuration property will list out comma separated transition durations // for every single transition property. Let's grab the first one and call it a day. var duration = Number(getComputedStyle(el).transitionDuration.replace(/,.*/, '').replace('s', '')) * 1000; stages.show(); requestAnimationFrame(function () { var _this14 = this; _newArrowCheck(this, _this13); stages.end(); setTimeout(function () { _newArrowCheck(this, _this14); stages.hide(); // Adding an "isConnected" check, in case the callback // removed the element from the DOM. if (el.isConnected) { stages.cleanup(); } }.bind(this), duration); }.bind(this)); }.bind(this)); } function isNumeric(subject) { return !isNaN(subject); } function handleForDirective(component, templateEl, expression, initialUpdate, extraVars) { var _this = this; warnIfNotTemplateTag(templateEl); var iteratorNames = parseForExpression(expression); var items = evaluateItemsAndReturnEmptyIfXIfIsPresentAndFalseOnElement(component, templateEl, iteratorNames, extraVars); // As we walk the array, we'll also walk the DOM (updating/creating as we go). var currentEl = templateEl; items.forEach(function (item, index) { var _this2 = this; _newArrowCheck(this, _this); var iterationScopeVariables = getIterationScopeVariables(iteratorNames, item, index, items, extraVars()); var currentKey = generateKeyForIteration(component, templateEl, index, iterationScopeVariables); var nextEl = currentEl.nextElementSibling; // If there's no previously x-for processed element ahead, add one. if (!nextEl || nextEl.__x_for_key === undefined) { nextEl = addElementInLoopAfterCurrentEl(templateEl, currentEl); // And transition it in if it's not the first page load. transitionIn(nextEl, function () { _newArrowCheck(this, _this2); }.bind(this), initialUpdate); nextEl.__x_for = iterationScopeVariables; component.initializeElements(nextEl, function () { _newArrowCheck(this, _this2); return nextEl.__x_for; }.bind(this)); } else { nextEl = lookAheadForMatchingKeyedElementAndMoveItIfFound(nextEl, currentKey); // If we haven't found a matching key, just insert the element at the current position if (!nextEl) { nextEl = addElementInLoopAfterCurrentEl(templateEl, currentEl); } // Temporarily remove the key indicator to allow the normal "updateElements" to work delete nextEl.__x_for_key; nextEl.__x_for = iterationScopeVariables; component.updateElements(nextEl, function () { _newArrowCheck(this, _this2); return nextEl.__x_for; }.bind(this)); } currentEl = nextEl; currentEl.__x_for_key = currentKey; }.bind(this)); removeAnyLeftOverElementsFromPreviousUpdate(currentEl); } // This was taken from VueJS 2.* core. Thanks Vue! function parseForExpression(expression) { var forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; var stripParensRE = /^\(|\)$/g; var forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; var inMatch = expression.match(forAliasRE); if (!inMatch) return; var res = {}; res.items = inMatch[2].trim(); var item = inMatch[1].trim().replace(stripParensRE, ''); var iteratorMatch = item.match(forIteratorRE); if (iteratorMatch) { res.item = item.replace(forIteratorRE, '').trim(); res.index = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.collection = iteratorMatch[2].trim(); } } else { res.item = item; } return res; } function getIterationScopeVariables(iteratorNames, item, index, items, extraVars) { // We must create a new object, so each iteration has a new scope var scopeVariables = extraVars ? _objectSpread2({}, extraVars) : {}; scopeVariables[iteratorNames.item] = item; if (iteratorNames.index) scopeVariables[iteratorNames.index] = index; if (iteratorNames.collection) scopeVariables[iteratorNames.collection] = items; return scopeVariables; } function generateKeyForIteration(component, el, index, iterationScopeVariables) { var _this3 = this; var bindKeyAttribute = getXAttrs(el, 'bind').filter(function (attr) { _newArrowCheck(this, _this3); return attr.value === 'key'; }.bind(this))[0]; // If the dev hasn't specified a key, just return the index of the iteration. if (!bindKeyAttribute) return index; return component.evaluateReturnExpression(el, bindKeyAttribute.expression, function () { _newArrowCheck(this, _this3); return iterationScopeVariables; }.bind(this)); } function warnIfNotTemplateTag(el) { if (el.tagName.toLowerCase() !== 'template') console.warn('Alpine: [x-for] directive should only be added to <template> tags.'); } function evaluateItemsAndReturnEmptyIfXIfIsPresentAndFalseOnElement(component, el, iteratorNames, extraVars) { var ifAttribute = getXAttrs(el, 'if')[0]; if (ifAttribute && !component.evaluateReturnExpression(el, ifAttribute.expression)) { return []; } return component.evaluateReturnExpression(el, iteratorNames.items, extraVars); } function addElementInLoopAfterCurrentEl(templateEl, currentEl) { var clone = document.importNode(templateEl.content, true); if (clone.childElementCount !== 1) console.warn('Alpine: <template> tag with [x-for] encountered with multiple element roots. Make sure <template> only has a single child node.'); currentEl.parentElement.insertBefore(clone, currentEl.nextElementSibling); return currentEl.nextElementSibling; } function lookAheadForMatchingKeyedElementAndMoveItIfFound(nextEl, currentKey) { // If the the key's DO match, no need to look ahead. if (nextEl.__x_for_key === currentKey) return nextEl; // If they don't, we'll look ahead for a match. // If we find it, we'll move it to the current position in the loop. var tmpNextEl = nextEl; while (tmpNextEl) { if (tmpNextEl.__x_for_key === currentKey) { return tmpNextEl.parentElement.insertBefore(tmpNextEl, nextEl); } tmpNextEl = tmpNextEl.nextElementSibling && tmpNextEl.nextElementSibling.__x_for_key !== undefined ? tmpNextEl.nextElementSibling : false; } } function removeAnyLeftOverElementsFromPreviousUpdate(currentEl) { var nextElementFromOldLoop = currentEl.nextElementSibling && currentEl.nextElementSibling.__x_for_key !== undefined ? currentEl.nextElementSibling : false; var _loop = function _loop() { var _this4 = this; var nextElementFromOldLoopImmutable = nextElementFromOldLoop; var nextSibling = nextElementFromOldLoop.nextElementSibling; transitionOut(nextElementFromOldLoop, function () { _newArrowCheck(this, _this4); nextElementFromOldLoopImmutable.remove(); }.bind(this)); nextElementFromOldLoop = nextSibling && nextSibling.__x_for_key !== undefined ? nextSibling : false; }; while (nextElementFromOldLoop) { _loop(); } } function handleAttributeBindingDirective(component, el, attrName, expression, extraVars, attrType) { var _this = this; var value = component.evaluateReturnExpression(el, expression, extraVars); if (attrName === 'value') { // If nested model key is undefined, set the default value to empty string. if (value === undefined && expression.match(/\./).length) { value = ''; } if (el.type === 'radio') { // Set radio value from x-bind:value, if no "value" attribute exists. // If there are any initial state values, radio will have a correct // "checked" value since x-bind:value is processed before x-model. if (el.attributes.value === undefined && attrType === 'bind') { el.value = value; } else if (attrType !== 'bind') { el.checked = el.value == value; } } else if (el.type === 'checkbox') { if (Array.isArray(value)) { // I'm purposely not using Array.includes here because it's // strict, and because of Numeric/String mis-casting, I // want the "includes" to be "fuzzy". var valueFound = false; value.forEach(function (val) { _newArrowCheck(this, _this); if (val == el.value) { valueFound = true; } }.bind(this)); el.checked = valueFound; } else { el.checked = !!value; } // If we are explicitly binding a string to the :value, set the string, // If the value is a boolean, leave it alone, it will be set to "on" // automatically. if (typeof value === 'string') { el.value = value; } } else if (el.tagName === 'SELECT') { updateSelect(el, value); } else if (el.type === 'text') { // Cursor position should be restored back to origin due to a safari bug var selectionStart = el.selectionStart; var selectionEnd = el.selectionEnd; var selectionDirection = el.selectionDirection; el.value = value; if (el === document.activeElement && selectionStart !== null) { el.setSelectionRange(selectionStart, selectionEnd, selectionDirection); } } else { el.value = value; } } else if (attrName === 'class') { if (Array.isArray(value)) { var originalClasses = el.__x_original_classes || []; el.setAttribute('class', arrayUnique(originalClasses.concat(value)).join(' ')); } else if (_typeof(value) === 'object') { // Sorting the keys / class names by their boolean value will ensure that // anything that evaluates to `false` and needs to remove classes is run first. var keysSortedByBooleanValue = Object.keys(value).sort(function (a, b) { _newArrowCheck(this, _this); return value[a] - value[b]; }.bind(this)); keysSortedByBooleanValue.forEach(function (classNames) { var _this2 = this; _newArrowCheck(this, _this); if (value[classNames]) { classNames.split(' ').forEach(function (className) { _newArrowCheck(this, _this2); return el.classList.add(className); }.bind(this)); } else { classNames.split(' ').forEach(function (className) { _newArrowCheck(this, _this2); return el.classList.remove(className); }.bind(this)); } }.bind(this)); } else { var _originalClasses = el.__x_original_classes || []; var newClasses = value.split(' '); el.setAttribute('class', arrayUnique(_originalClasses.concat(newClasses)).join(' ')); } } else if (isBooleanAttr(attrName)) { // Boolean attributes have to be explicitly added and removed, not just set. if (!!value) { el.setAttribute(attrName, ''); } else { el.removeAttribute(attrName); } } else { el.setAttribute(attrName, value); } } function updateSelect(el, value) { var _this3 = this; var arrayWrappedValue = [].concat(value).map(function (value) { _newArrowCheck(this, _this3); return value + ''; }.bind(this)); Array.from(el.options).forEach(function (option) { _newArrowCheck(this, _this3); option.selected = arrayWrappedValue.includes(option.value || option.text); }.bind(this)); } function handleTextDirective(el, output, expression) { // If nested model key is undefined, set the default value to empty string. if (output === undefined && expression.match(/\./).length) { output = ''; } el.innerText = output; } function handleHtmlDirective(component, el, expression, extraVars) { el.innerHTML = component.evaluateReturnExpression(el, expression, extraVars); } function handleShowDirective(component, el, value, modifiers) { var _this = this; var initialUpdate = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var hide = function hide() { _newArrowCheck(this, _this); el.style.display = 'none'; }.bind(this); var show = function show() { _newArrowCheck(this, _this); if (el.style.length === 1 && el.style.display === 'none') { el.removeAttribute('style'); } else { el.style.removeProperty('display'); } }.bind(this); if (initialUpdate === true) { if (value) { show(); } else { hide(); } return; } var handle = function handle(resolve) { var _this2 = this; _newArrowCheck(this, _this); if (!value) { if (el.style.display !== 'none') { transitionOut(el, function () { var _this3 = this; _newArrowCheck(this, _this2); resolve(function () { _newArrowCheck(this, _this3); hide(); }.bind(this)); }.bind(this)); } else { resolve(function () { _newArrowCheck(this, _this2); }.bind(this)); } } else { if (el.style.display !== '') { transitionIn(el, function () { _newArrowCheck(this, _this2); show(); }.bind(this)); } // Resolve immediately, only hold up parent `x-show`s for hidin. resolve(function () { _newArrowCheck(this, _this2); }.bind(this)); } }.bind(this); // The working of x-show is a bit complex because we need to // wait for any child transitions to finish before hiding // some element. Also, this has to be done recursively. // If x-show.immediate, foregoe the waiting. if (modifiers.includes('immediate')) { handle(function (finish) { _newArrowCheck(this, _this); return finish(); }.bind(this)); return; } // x-show is encountered during a DOM tree walk. If an element // we encounter is NOT a child of another x-show element we // can execute the previous x-show stack (if one exists). if (component.showDirectiveLastElement && !component.showDirectiveLastElement.contains(el)) { component.executeAndClearRemainingShowDirectiveStack(); } // We'll push the handler onto a stack to be handled later. component.showDirectiveStack.push(handle); component.showDirectiveLastElement = el; } function handleIfDirective(component, el, expressionResult, initialUpdate, extraVars) { var _this = this; if (el.nodeName.toLowerCase() !== 'template') console.warn("Alpine: [x-if] directive should only be added to <template> tags. See https://github.com/alpinejs/alpine#x-if"); var elementHasAlreadyBeenAdded = el.nextElementSibling && el.nextElementSibling.__x_inserted_me === true; if (expressionResult && !elementHasAlreadyBeenAdded) { var clone = document.importNode(el.content, true); el.parentElement.insertBefore(clone, el.nextElementSibling); transitionIn(el.nextElementSibling, function () { _newArrowCheck(this, _this); }.bind(this), initialUpdate); component.initializeElements(el.nextElementSibling, extraVars); el.nextElementSibling.__x_inserted_me = true; } else if (!expressionResult && elementHasAlreadyBeenAdded) { transitionOut(el.nextElementSibling, function () { _newArrowCheck(this, _this); el.nextElementSibling.remove(); }.bind(this), initialUpdate); } } function registerListener(component, el, event, modifiers, expression) { var _this = this; var extraVars = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : {}; if (modifiers.includes('away')) { var _handler = function handler(e) { _newArrowCheck(this, _this); // Don't do anything if the click came form the element or within it. if (el.contains(e.target)) return; // Don't do anything if this element isn't currently visible. if (el.offsetWidth < 1 && el.offsetHeight < 1) return; // Now that we are sure the element is visible, AND the click // is from outside it, let's run the expression. runListenerHandler(component, expression, e, extraVars); if (modifiers.includes('once')) { document.removeEventListener(event, _handler); } }.bind(this); // Listen for this event at the root level. document.addEventListener(event, _handler); } else { var listenerTarget = modifiers.includes('window') ? window : modifiers.includes('document') ? document : el; var _handler2 = function handler(e) { _newArrowCheck(this, _this); // Remove this global event handler if the element that declared it // has been removed. It's now stale. if (listenerTarget === window || listenerTarget === document) { if (!document.body.contains(el)) { listenerTarget.removeEventListener(event, _handler2); return; } } if (isKeyEvent(event)) { if (isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers)) { return; } } if (modifiers.includes('prevent')) e.preventDefault(); if (modifiers.includes('stop')) e.stopPropagation(); // If the .self modifier isn't present, or if it is present and // the target element matches the element we are registering the // event on, run the handler if (!modifiers.includes('self') || e.target === el) { var returnValue = runListenerHandler(component, expression, e, extraVars); if (returnValue === false) { e.preventDefault(); } else { if (modifiers.includes('once')) { listenerTarget.removeEventListener(event, _handler2); } } } }.bind(this); if (modifiers.includes('debounce')) { var nextModifier = modifiers[modifiers.indexOf('debounce') + 1] || 'invalid-wait'; var wait = isNumeric(nextModifier.split('ms')[0]) ? Number(nextModifier.split('ms')[0]) : 250; _handler2 = debounce(_handler2, wait); } listenerTarget.addEventListener(event, _handler2); } } function runListenerHandler(component, expression, e, extraVars) { var _this2 = this; return component.evaluateCommandExpression(e.target, expression, function () { _newArrowCheck(this, _this2); return _objectSpread2({}, extraVars(), { '$event': e }); }.bind(this)); } function isKeyEvent(event) { return ['keydown', 'keyup'].includes(event); } function isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers) { var _this3 = this; var keyModifiers = modifiers.filter(function (i) { _newArrowCheck(this, _this3); return !['window', 'document', 'prevent', 'stop'].includes(i); }.bind(this)); if (keyModifiers.includes('debounce')) { var debounceIndex = keyModifiers.indexOf('debounce'); keyModifiers.splice(debounceIndex, isNumeric((keyModifiers[debounceIndex + 1] || 'invalid-wait').split('ms')[0]) ? 2 : 1); } // If no modifier is specified, we'll call it a press. if (keyModifiers.length === 0) return false; // If one is passed, AND it matches the key pressed, we'll call it a press. if (keyModifiers.length === 1 && keyModifiers[0] === keyToModifier(e.key)) return false; // The user is listening for key combinations. var systemKeyModifiers = ['ctrl', 'shift', 'alt', 'meta', 'cmd', 'super']; var selectedSystemKeyModifiers = systemKeyModifiers.filter(function (modifier) { _newArrowCheck(this, _this3); return keyModifiers.includes(modifier); }.bind(this)); keyModifiers = keyModifiers.filter(function (i) { _newArrowCheck(this, _this3); return !selectedSystemKeyModifiers.includes(i); }.bind(this)); if (selectedSystemKeyModifiers.length > 0) { var activelyPressedKeyModifiers = selectedSystemKeyModifiers.filter(function (modifier) { _newArrowCheck(this, _this3); // Alias "cmd" and "super" to "meta" if (modifier === 'cmd' || modifier === 'super') modifier = 'meta'; return e["".concat(modifier, "Key")]; }.bind(this)); // If all the modifiers selected are pressed, ... if (activelyPressedKeyModifiers.length === selectedSystemKeyModifiers.length) { // AND the remaining key is pressed as well. It's a press. if (keyModifiers[0] === keyToModifier(e.key)) return false; } } // We'll call it NOT a valid keypress. return true; } function keyToModifier(key) { switch (key) { case '/': return 'slash'; case ' ': case 'Spacebar': return 'space'; default: return key && kebabCase(key); } } function registerModelListener(component, el, modifiers, expression, extraVars) { var _this = this; // If the element we are binding to is a select, a radio, or checkbox // we'll listen for the change event instead of the "input" event. var event = el.tagName.toLowerCase() === 'select' || ['checkbox', 'radio'].includes(el.type) || modifiers.includes('lazy') ? 'change' : 'input'; var listenerExpression = "".concat(expression, " = rightSideOfExpression($event, ").concat(expression, ")"); registerListener(component, el, event, modifiers, listenerExpression, function () { _newArrowCheck(this, _this); return _objectSpread2({}, extraVars(), { rightSideOfExpression: generateModelAssignmentFunction(el, modifiers, expression) }); }.bind(this)); } function generateModelAssignmentFunction(el, modifiers, expression) { var _this2 = this; if (el.type === 'radio') { // Radio buttons only work properly when they share a name attribute. // People might assume we take care of that for them, because // they already set a shared "x-model" attribute. if (!el.hasAttribute('name')) el.setAttribute('name', expression); } return function (event, currentValue) { var _this3 = this; _newArrowCheck(this, _this2); // Check for event.detail due to an issue where IE11 handles other events as a CustomEvent. if (event instanceof CustomEvent && event.detail) { return event.detail; } else if (el.type === 'checkbox') { // If the data we are binding to is an array, toggle it's value inside the array. if (Array.isArray(currentValue)) { return event.target.checked ? currentValue.concat([event.target.value]) : currentValue.filter(function (i) { _newArrowCheck(this, _this3); return i !== event.target.value; }.bind(this)); } else { return event.target.checked; } } else if (el.tagName.toLowerCase() === 'select' && el.multiple) { return modifiers.includes('number') ? Array.from(event.target.selectedOptions).map(function (option) { _newArrowCheck(this, _this3); var rawValue = option.value || option.text; var number = rawValue ? parseFloat(rawValue) : null; return isNaN(number) ? rawValue : number; }.bind(this)) : Array.from(event.target.selectedOptions).map(function (option) { _newArrowCheck(this, _this3); return option.value || option.text; }.bind(this)); } else { var rawValue = event.target.value; var number = rawValue ? parseFloat(rawValue) : null; return modifiers.includes('number') ? isNaN(number) ? rawValue : number : modifiers.includes('trim') ? rawValue.trim() : rawValue; } }.bind(this); } // `Reflect.set` method // https://tc39.github.io/ecma262/#sec-reflect.set function set$2(target, propertyKey, V /* , receiver */) { var receiver = arguments.length < 4 ? target : arguments[3]; var ownDescriptor = objectGetOwnPropertyDescriptor.f(anObject(target), propertyKey); var existingDescriptor, prototype; if (!ownDescriptor) { if (isObject(prototype = objectGetPrototypeOf(target))) { return set$2(prototype, propertyKey, V, receiver); } ownDescriptor = createPropertyDescriptor(0); } if (has(ownDescriptor, 'value')) { if (ownDescriptor.writable === false || !isObject(receiver)) return false; if (existingDescriptor = objectGetOwnPropertyDescriptor.f(receiver, propertyKey)) { if (existingDescriptor.get || existingDescriptor.set || existingDescriptor.writable === false) return false; existingDescriptor.value = V; objectDefineProperty.f(receiver, propertyKey, existingDescriptor); } else objectDefineProperty.f(receiver, propertyKey, createPropertyDescriptor(0, V)); return true; } return ownDescriptor.set === undefined ? false : (ownDescriptor.set.call(receiver, V), true); } // MS Edge 17-18 Reflect.set allows setting the property to object // with non-writable property on the prototype var MS_EDGE_BUG = fails(function () { var object = objectDefineProperty.f({}, 'a', { configurable: true }); // eslint-disable-next-line no-undef return Reflect.set(objectGetPrototypeOf(object), 'a', 1, object) !== false; }); _export({ target: 'Reflect', stat: true, forced: MS_EDGE_BUG }, { set: set$2 }); function wrap(data, mutationCallback) { /* IE11-ONLY:START */ return wrapForIe11(data, mutationCallback); } function unwrap(membrane, observable) { var _this = this; var unwrappedData = membrane.unwrapProxy(observable); var copy = {}; Object.keys(unwrappedData).forEach(function (key) { _newArrowCheck(this, _this); if (['$el', '$refs', '$nextTick', '$watch'].includes(key)) return; copy[key] = unwrappedData[key]; }.bind(this)); return copy; } function wrapForIe11(data, mutationCallback) { var proxyHandler = { set: function set(target, key, value) { // Set the value converting it to a "Deep Proxy" when required // Note that if a project is not a valid object, it won't be converted to a proxy var setWasSuccessful = Reflect.set(target, key, deepProxy(value, proxyHandler)); mutationCallback(target, key); return setWasSuccessful; }, get: function get(target, key) { // Provide a way to determine if this object is an Alpine proxy or not. if (key === "$isAlpineProxy") return true; // Just return the flippin' value. Gawsh. return target[key]; } }; return { data: deepProxy(data, proxyHandler), membrane: { unwrapProxy: function unwrapProxy(proxy) { return proxy; } } }; } function deepProxy(target, proxyHandler) { // If target is null, return it. if (target === null) return target; // If target is not an object, return it. if (_typeof(target) !== 'object') return target; // If target is a DOM node (like in the case of this.$el), return it. if (target instanceof Node) return target; // If target is already an Alpine proxy, return it. if (target['$isAlpineProxy']) return target; // Otherwise proxy the properties recursively. // This enables reactivity on setting nested data. // Note that if a project is not a valid object, it won't be converted to a proxy for (var property in target) { target[property] = deepProxy(target[property], proxyHandler); } return new Proxy(target, proxyHandler); } var Component = /*#__PURE__*/function () { function Component(el) { var _this = this; var seedDataForCloning = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; _classCallCheck(this, Component); this.$el = el; var dataAttr = this.$el.getAttribute('x-data'); var dataExpression = dataAttr === '' ? '{}' : dataAttr; var initExpression = this.$el.getAttribute('x-init'); this.unobservedData = seedDataForCloning ? seedDataForCloning : saferEval(dataExpression, {}); /* IE11-ONLY:START */ // For IE11, add our magic properties to the original data for access. // The Proxy polyfill does not allow properties to be added after creation. this.unobservedData.$el = null; this.unobservedData.$refs = null; this.unobservedData.$nextTick = null; this.unobservedData.$watch = null; /* IE11-ONLY:END */ // Construct a Proxy-based observable. This will be used to handle reactivity. var _this$wrapDataInObser = this.wrapDataInObservable(this.unobservedData), membrane = _this$wrapDataInObser.membrane, data = _this$wrapDataInObser.data; this.$data = data; this.membrane = membrane; // After making user-supplied data methods reactive, we can now add // our magic properties to the original data for access. this.unobservedData.$el = this.$el; this.unobservedData.$refs = this.getRefsProxy(); this.nextTickStack = []; this.unobservedData.$nextTick = function (callback) { _newArrowCheck(this, _this); this.nextTickStack.push(callback); }.bind(this); this.watchers = {}; this.unobservedData.$watch = function (property, callback) { _newArrowCheck(this, _this); if (!this.watchers[property]) this.watchers[property] = []; this.watchers[property].push(callback); }.bind(this); this.showDirectiveStack = []; this.showDirectiveLastElement; var initReturnedCallback; // If x-init is present AND we aren't cloning (skip x-init on clone) if (initExpression && !seedDataForCloning) { // We want to allow data manipulation, but not trigger DOM updates just yet. // We haven't even initialized the elements with their Alpine bindings. I mean c'mon. this.pauseReactivity = true; initReturnedCallback = this.evaluateReturnExpression(this.$el, initExpression); this.pauseReactivity = false; } // Register all our listeners and set all our attribute bindings. this.initializeElements(this.$el); // Use mutation observer to detect new elements being added within this component at run-time. // Alpine's just so darn flexible amirite? this.listenForNewElementsToInitialize(); if (typeof initReturnedCallback === 'function') { // Run the callback returned from the "x-init" hook to allow the user to do stuff after // Alpine's got it's grubby little paws all over everything. initReturnedCallback.call(this.$data); } } _createClass(Component, [{ key: "getUnobservedData", value: function getUnobservedData() { return unwrap(this.membrane, this.$data); } }, { key: "wrapDataInObservable", value: function wrapDataInObservable(data) { var _this2 = this; var self = this; var updateDom = debounce(function () { self.updateElements(self.$el); }, 0); return wrap(data, function (target, key) { var _this3 = this; _newArrowCheck(this, _this2); if (self.watchers[key]) { // If there's a watcher for this specific key, run it. self.watchers[key].forEach(function (callback) { _newArrowCheck(this, _this3); return callback(target[key]); }.bind(this)); } else { // Let's walk through the watchers with "dot-notation" (foo.bar) and see // if this mutation fits any of them. Object.keys(self.watchers).filter(function (i) { _newArrowCheck(this, _this3); return i.includes('.'); }.bind(this)).forEach(function (fullDotNotationKey) { var _this4 = this; _newArrowCheck(this, _this3); var dotNotationParts = fullDotNotationKey.split('.'); // If this dot-notation watcher's last "part" doesn't match the current // key, then skip it early for performance reasons. if (key !== dotNotationParts[dotNotationParts.length - 1]) return; // Now, walk through the dot-notation "parts" recursively to find // a match, and call the watcher if one's found. dotNotationParts.reduce(function (comparisonData, part) { var _this5 = this; _newArrowCheck(this, _this4); if (Object.is(target, comparisonData)) { // Run the watchers. self.watchers[fullDotNotationKey].forEach(function (callback) { _newArrowCheck(this, _this5); return callback(target[key]); }.bind(this)); } return comparisonData[part]; }.bind(this), self.getUnobservedData()); }.bind(this)); } // Don't react to data changes for cases like the `x-created` hook. if (self.pauseReactivity) return; updateDom(); }.bind(this)); } }, { key: "walkAndSkipNestedComponents", value: function walkAndSkipNestedComponents(el, callback) { var _this6 = this; var initializeComponentCallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () { _newArrowCheck(this, _this6); }.bind(this); walk(el, function (el) { _newArrowCheck(this, _this6); // We've hit a component. if (el.hasAttribute('x-data')) { // If it's not the current one. if (!el.isSameNode(this.$el)) { // Initialize it if it's not. if (!el.__x) initializeComponentCallback(el); // Now we'll let that sub-component deal with itself. return false; } } return callback(el); }.bind(this)); } }, { key: "initializeElements", value: function initializeElements(rootEl) { var _this7 = this; var extraVars = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () { _newArrowCheck(this, _this7); }.bind(this); this.walkAndSkipNestedComponents(rootEl, function (el) { _newArrowCheck(this, _this7); // Don't touch spawns from for loop if (el.__x_for_key !== undefined) return false; // Don't touch spawns from if directives if (el.__x_inserted_me !== undefined) return false; this.initializeElement(el, extraVars); }.bind(this), function (el) { _newArrowCheck(this, _this7); el.__x = new Component(el); }.bind(this)); this.executeAndClearRemainingShowDirectiveStack(); this.executeAndClearNextTickStack(rootEl); } }, { key: "initializeElement", value: function initializeElement(el, extraVars) { // To support class attribute merging, we have to know what the element's // original class attribute looked like for reference. if (el.hasAttribute('class') && getXAttrs(el).length > 0) { el.__x_original_classes = el.getAttribute('class').split(' '); } this.registerListeners(el, extraVars); this.resolveBoundAttributes(el, true, extraVars); } }, { key: "updateElements", value: function updateElements(rootEl) { var _this8 = this; var extraVars = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () { _newArrowCheck(this, _this8); }.bind(this); this.walkAndSkipNestedComponents(rootEl, function (el) { _newArrowCheck(this, _this8); // Don't touch spawns from for loop (and check if the root is actually a for loop in a parent, don't skip it.) if (el.__x_for_key !== undefined && !el.isSameNode(this.$el)) return false; this.updateElement(el, extraVars); }.bind(this), function (el) { _newArrowCheck(this, _this8); el.__x = new Component(el); }.bind(this)); this.executeAndClearRemainingShowDirectiveStack(); this.executeAndClearNextTickStack(rootEl); } }, { key: "executeAndClearNextTickStack", value: function executeAndClearNextTickStack(el) { // Skip spawns from alpine directives if (el === this.$el) { // Walk through the $nextTick stack and clear it as we go. while (this.nextTickStack.length > 0) { this.nextTickStack.shift()(); } } } }, { key: "executeAndClearRemainingShowDirectiveStack", value: function executeAndClearRemainingShowDirectiveStack() { var _this9 = this; // The goal here is to start all the x-show transitions // and build a nested promise chain so that elements // only hide when the children are finished hiding. this.showDirectiveStack.reverse().map(function (thing) { var _this10 = this; _newArrowCheck(this, _this9); return new Promise(function (resolve) { var _this11 = this; _newArrowCheck(this, _this10); thing(function (finish) { _newArrowCheck(this, _this11); resolve(finish); }.bind(this)); }.bind(this)); }.bind(this)).reduce(function (nestedPromise, promise) { var _this12 = this; _newArrowCheck(this, _this9); return nestedPromise.then(function () { var _this13 = this; _newArrowCheck(this, _this12); return promise.then(function (finish) { _newArrowCheck(this, _this13); return finish(); }.bind(this)); }.bind(this)); }.bind(this), Promise.resolve(function () { _newArrowCheck(this, _this9); }.bind(this))); // We've processed the handler stack. let's clear it. this.showDirectiveStack = []; this.showDirectiveLastElement = undefined; } }, { key: "updateElement", value: function updateElement(el, extraVars) { this.resolveBoundAttributes(el, false, extraVars); } }, { key: "registerListeners", value: function registerListeners(el, extraVars) { var _this14 = this; getXAttrs(el).forEach(function (_ref) { var type = _ref.type, value = _ref.value, modifiers = _ref.modifiers, expression = _ref.expression; _newArrowCheck(this, _this14); switch (type) { case 'on': registerListener(this, el, value, modifiers, expression, extraVars); break; case 'model': registerModelListener(this, el, modifiers, expression, extraVars); break; } }.bind(this)); } }, { key: "resolveBoundAttributes", value: function resolveBoundAttributes(el) { var _this15 = this; var initialUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var extraVars = arguments.length > 2 ? arguments[2] : undefined; var attrs = getXAttrs(el); if (el.type !== undefined && el.type === 'radio') { // If there's an x-model on a radio input, move it to end of attribute list // to ensure that x-bind:value (if present) is processed first. var modelIdx = attrs.findIndex(function (attr) { _newArrowCheck(this, _this15); return attr.type === 'model'; }.bind(this)); if (modelIdx > -1) { attrs.push(attrs.splice(modelIdx, 1)[0]); } } attrs.forEach(function (_ref2) { var _this16 = this; var type = _ref2.type, value = _ref2.value, modifiers = _ref2.modifiers, expression = _ref2.expression; _newArrowCheck(this, _this15); switch (type) { case 'model': handleAttributeBindingDirective(this, el, 'value', expression, extraVars, type); break; case 'bind': // The :key binding on an x-for is special, ignore it. if (el.tagName.toLowerCase() === 'template' && value === 'key') return; handleAttributeBindingDirective(this, el, value, expression, extraVars, type); break; case 'text': var output = this.evaluateReturnExpression(el, expression, extraVars); handleTextDirective(el, output, expression); break; case 'html': handleHtmlDirective(this, el, expression, extraVars); break; case 'show': var output = this.evaluateReturnExpression(el, expression, extraVars); handleShowDirective(this, el, output, modifiers, initialUpdate); break; case 'if': // If this element also has x-for on it, don't process x-if. // We will let the "x-for" directive handle the "if"ing. if (attrs.filter(function (i) { _newArrowCheck(this, _this16); return i.type === 'for'; }.bind(this)).length > 0) return; var output = this.evaluateReturnExpression(el, expression, extraVars); handleIfDirective(this, el, output, initialUpdate, extraVars); break; case 'for': handleForDirective(this, el, expression, initialUpdate, extraVars); break; case 'cloak': el.removeAttribute('x-cloak'); break; } }.bind(this)); } }, { key: "evaluateReturnExpression", value: function evaluateReturnExpression(el, expression) { var _this17 = this; var extraVars = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () { _newArrowCheck(this, _this17); }.bind(this); return saferEval(expression, this.$data, _objectSpread2({}, extraVars(), { $dispatch: this.getDispatchFunction(el) })); } }, { key: "evaluateCommandExpression", value: function evaluateCommandExpression(el, expression) { var _this18 = this; var extraVars = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () { _newArrowCheck(this, _this18); }.bind(this); return saferEvalNoReturn(expression, this.$data, _objectSpread2({}, extraVars(), { $dispatch: this.getDispatchFunction(el) })); } }, { key: "getDispatchFunction", value: function getDispatchFunction(el) { var _this19 = this; return function (event) { var detail = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; _newArrowCheck(this, _this19); el.dispatchEvent(new CustomEvent(event, { detail: detail, bubbles: true })); }.bind(this); } }, { key: "listenForNewElementsToInitialize", value: function listenForNewElementsToInitialize() { var _this20 = this; var targetNode = this.$el; var observerOptions = { childList: true, attributes: true, subtree: true }; var observer = new MutationObserver(function (mutations) { var _this21 = this; _newArrowCheck(this, _this20); for (var i = 0; i < mutations.length; i++) { // Filter out mutations triggered from child components. var closestParentComponent = mutations[i].target.closest('[x-data]'); if (!(closestParentComponent && closestParentComponent.isSameNode(this.$el))) continue; if (mutations[i].type === 'attributes' && mutations[i].attributeName === 'x-data') { (function () { var _this22 = this; var rawData = saferEval(mutations[i].target.getAttribute('x-data'), {}); Object.keys(rawData).forEach(function (key) { _newArrowCheck(this, _this22); if (_this21.$data[key] !== rawData[key]) { _this21.$data[key] = rawData[key]; } }.bind(this)); })(); } if (mutations[i].addedNodes.length > 0) { mutations[i].addedNodes.forEach(function (node) { _newArrowCheck(this, _this21); if (node.nodeType !== 1 || node.__x_inserted_me) return; if (node.matches('[x-data]')) { node.__x = new Component(node); return; } this.initializeElements(node); }.bind(this)); } } }.bind(this)); observer.observe(targetNode, observerOptions); } }, { key: "getRefsProxy", value: function getRefsProxy() { var _this23 = this; var self = this; var refObj = {}; /* IE11-ONLY:START */ // Add any properties up-front that might be necessary for the Proxy polyfill. refObj.$isRefsProxy = false; refObj.$isAlpineProxy = false; // If we are in IE, since the polyfill needs all properties to be defined before building the proxy, // we just loop on the element, look for any x-ref and create a tmp property on a fake object. this.walkAndSkipNestedComponents(self.$el, function (el) { _newArrowCheck(this, _this23); if (el.hasAttribute('x-ref')) { refObj[el.getAttribute('x-ref')] = true; } }.bind(this)); /* IE11-ONLY:END */ // One of the goals of this is to not hold elements in memory, but rather re-evaluate // the DOM when the system needs something from it. This way, the framework is flexible and // friendly to outside DOM changes from libraries like Vue/Livewire. // For this reason, I'm using an "on-demand" proxy to fake a "$refs" object. return new Proxy(refObj, { get: function get(object, property) { var _this24 = this; if (property === '$isAlpineProxy') return true; var ref; // We can't just query the DOM because it's hard to filter out refs in // nested components. self.walkAndSkipNestedComponents(self.$el, function (el) { _newArrowCheck(this, _this24); if (el.hasAttribute('x-ref') && el.getAttribute('x-ref') === property) { ref = el; } }.bind(this)); return ref; } }); } }]); return Component; }(); var Alpine = { version: "2.3.3", start: function () { var _start = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { var _this = this; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (isTesting()) { _context.next = 3; break; } _context.next = 3; return domReady(); case 3: this.discoverComponents(function (el) { _newArrowCheck(this, _this); this.initializeComponent(el); }.bind(this)); // It's easier and more performant to just support Turbolinks than listen // to MutationObserver mutations at the document level. document.addEventListener("turbolinks:load", function () { var _this2 = this; _newArrowCheck(this, _this); this.discoverUninitializedComponents(function (el) { _newArrowCheck(this, _this2); this.initializeComponent(el); }.bind(this)); }.bind(this)); this.listenForNewUninitializedComponentsAtRunTime(function (el) { _newArrowCheck(this, _this); this.initializeComponent(el); }.bind(this)); case 6: case "end": return _context.stop(); } } }, _callee, this); })); function start() { return _start.apply(this, arguments); } return start; }(), discoverComponents: function discoverComponents(callback) { var _this3 = this; var rootEls = document.querySelectorAll('[x-data]'); rootEls.forEach(function (rootEl) { _newArrowCheck(this, _this3); callback(rootEl); }.bind(this)); }, discoverUninitializedComponents: function discoverUninitializedComponents(callback) { var _this4 = this; var el = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var rootEls = (el || document).querySelectorAll('[x-data]'); Array.from(rootEls).filter(function (el) { _newArrowCheck(this, _this4); return el.__x === undefined; }.bind(this)).forEach(function (rootEl) { _newArrowCheck(this, _this4); callback(rootEl); }.bind(this)); }, listenForNewUninitializedComponentsAtRunTime: function listenForNewUninitializedComponentsAtRunTime(callback) { var _this5 = this; var targetNode = document.querySelector('body'); var observerOptions = { childList: true, attributes: true, subtree: true }; var observer = new MutationObserver(function (mutations) { var _this6 = this; _newArrowCheck(this, _this5); for (var i = 0; i < mutations.length; i++) { if (mutations[i].addedNodes.length > 0) { mutations[i].addedNodes.forEach(function (node) { var _this7 = this; _newArrowCheck(this, _this6); // Discard non-element nodes (like line-breaks) if (node.nodeType !== 1) return; // Discard any changes happening within an existing component. // They will take care of themselves. if (node.parentElement && node.parentElement.closest('[x-data]')) return; this.discoverUninitializedComponents(function (el) { _newArrowCheck(this, _this7); this.initializeComponent(el); }.bind(this), node.parentElement); }.bind(this)); } } }.bind(this)); observer.observe(targetNode, observerOptions); }, initializeComponent: function initializeComponent(el) { if (!el.__x) { el.__x = new Component(el); } }, clone: function clone(component, newEl) { if (!newEl.__x) { newEl.__x = new Component(newEl, component.getUnobservedData()); } } }; if (!isTesting()) { window.Alpine = Alpine; if (window.deferLoadingAlpine) { window.deferLoadingAlpine(function () { window.Alpine.start(); }); } else { window.Alpine.start(); } } })));
cdnjs/cdnjs
ajax/libs/alpinejs/2.3.3/alpine-ie11.js
JavaScript
mit
254,038
/** * @license Highstock JS v8.0.1 (2020-03-02) * @module highcharts/indicators/mfi * @requires highcharts * @requires highcharts/modules/stock * * Money Flow Index indicator for Highstock * * (c) 2010-2019 Grzegorz Blachliński * * License: www.highcharts.com/license */ 'use strict'; import '../../indicators/mfi.src.js';
cdnjs/cdnjs
ajax/libs/highcharts/8.0.1/es-modules/masters/indicators/mfi.src.js
JavaScript
mit
335
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.MathJax_Typewriter,{768:[611,-485,0,-409,-195],769:[611,-485,0,-331,-117],770:[611,-460,0,-429,-97],771:[611,-466,0,-438,-88],772:[577,-500,0,-452,-74],774:[611,-504,0,-446,-79],776:[612,-519,0,-421,-104],778:[619,-499,0,-344,-182],780:[577,-449,0,-427,-99]}),MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/Typewriter/Regular/CombDiacritMarks.js");
cdnjs/cdnjs
ajax/libs/mathjax/2.7.9/jax/output/HTML-CSS/fonts/TeX/Typewriter/Regular/CombDiacritMarks.min.js
JavaScript
mit
431
jsonp({"cep":"72821110","logradouro":"Quadra Quadra 249","bairro":"Parque Estrela Dalva IV","cidade":"Luzi\u00e2nia","uf":"GO","estado":"Goi\u00e1s"});
lfreneda/cepdb
api/v1/72821110.jsonp.js
JavaScript
cc0-1.0
152
jsonp({"cep":"71570501","logradouro":"Quadra Quadra 5 Conjunto A","bairro":"Parano\u00e1","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
lfreneda/cepdb
api/v1/71570501.jsonp.js
JavaScript
cc0-1.0
156
jsonp({"cep":"76908158","logradouro":"Rua Calama","bairro":"S\u00e3o Francisco","cidade":"Ji-Paran\u00e1","uf":"RO","estado":"Rond\u00f4nia"});
lfreneda/cepdb
api/v1/76908158.jsonp.js
JavaScript
cc0-1.0
144
jsonp({"cep":"70767120","logradouro":"Quadra SQN 314 Bloco L","bairro":"Asa Norte","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
lfreneda/cepdb
api/v1/70767120.jsonp.js
JavaScript
cc0-1.0
149
jsonp({"cep":"15091440","logradouro":"Rua Jos\u00e9 Pinho Monteiro","bairro":"Jardim Tarraf","cidade":"S\u00e3o Jos\u00e9 do Rio Preto","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/15091440.jsonp.js
JavaScript
cc0-1.0
175
jsonp({"cep":"20780260","logradouro":"Rua Engenheiro Gast\u00e3o Lob\u00e3o","bairro":"Cachambi","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/20780260.jsonp.js
JavaScript
cc0-1.0
162
jsonp({"cep":"77824808","logradouro":"Rua dos Guatambus","bairro":"Bairro da Cimba","cidade":"Aragua\u00edna","uf":"TO","estado":"Tocantins"});
lfreneda/cepdb
api/v1/77824808.jsonp.js
JavaScript
cc0-1.0
144
jsonp({"cep":"31749005","logradouro":"Rua Luanda","bairro":"Cana\u00e3","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/31749005.jsonp.js
JavaScript
cc0-1.0
135
jsonp({"cep":"71510080","logradouro":"Quadra SHIN QI 2 Conjunto 8","bairro":"Setor de Habita\u00e7\u00f5es Individuais Norte","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
lfreneda/cepdb
api/v1/71510080.jsonp.js
JavaScript
cc0-1.0
192
jsonp({"cep":"04857320","logradouro":"Rua Genciana","bairro":"Jardim Novo Horizonte","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/04857320.jsonp.js
JavaScript
cc0-1.0
150
jsonp({"cep":"29031715","logradouro":"Rua Zulmira da Silva Constantino","bairro":"Inhanguet\u00e1","cidade":"Vit\u00f3ria","uf":"ES","estado":"Esp\u00edrito Santo"});
lfreneda/cepdb
api/v1/29031715.jsonp.js
JavaScript
cc0-1.0
167
jsonp({"cep":"95059460","logradouro":"Rua Verginio Zago","bairro":"Jardim Eldorado","cidade":"Caxias do Sul","uf":"RS","estado":"Rio Grande do Sul"});
lfreneda/cepdb
api/v1/95059460.jsonp.js
JavaScript
cc0-1.0
151
jsonp({"cep":"69915226","logradouro":"Rua 15 de Dezembro","bairro":"Nova Esperan\u00e7a","cidade":"Rio Branco","uf":"AC","estado":"Acre"});
lfreneda/cepdb
api/v1/69915226.jsonp.js
JavaScript
cc0-1.0
140
jsonp({"cep":"66820095","logradouro":"Rua Q","bairro":"Tenon\u00e9","cidade":"Bel\u00e9m","uf":"PA","estado":"Par\u00e1"});
lfreneda/cepdb
api/v1/66820095.jsonp.js
JavaScript
cc0-1.0
124
jsonp({"cep":"15053305","logradouro":"Rua Em\u00edlio Trigo Alves","bairro":"Bosque da Felicidade","cidade":"S\u00e3o Jos\u00e9 do Rio Preto","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/15053305.jsonp.js
JavaScript
cc0-1.0
181
jsonp({"cep":"29948540","logradouro":"Rua Ocalixto Loubach","bairro":"Nova Lima (Itauninhas)","cidade":"S\u00e3o Mateus","uf":"ES","estado":"Esp\u00edrito Santo"});
lfreneda/cepdb
api/v1/29948540.jsonp.js
JavaScript
cc0-1.0
165
jsonp({"cep":"09971220","logradouro":"Rua Cambeva","bairro":"Eldorado","cidade":"Diadema","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/09971220.jsonp.js
JavaScript
cc0-1.0
129
jsonp({"cep":"09615050","logradouro":"Rua Ipiranga","bairro":"Rudge Ramos","cidade":"S\u00e3o Bernardo do Campo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/09615050.jsonp.js
JavaScript
cc0-1.0
152
jsonp({"cep":"24320270","logradouro":"Rua Doutor Fernando Lib\u00f3rio Filho","bairro":"Pendotiba","cidade":"Niter\u00f3i","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/24320270.jsonp.js
JavaScript
cc0-1.0
162
jsonp({"cep":"16201192","logradouro":"Rua Roberto Babolim","bairro":"Recanto Verde","cidade":"Birig\u00fci","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/16201192.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"58414085","logradouro":"Rua Pernambuco","bairro":"Liberdade","cidade":"Campina Grande","uf":"PB","estado":"Para\u00edba"});
lfreneda/cepdb
api/v1/58414085.jsonp.js
JavaScript
cc0-1.0
138
jsonp({"cep":"78043640","logradouro":"Rua S\u00e3o Lucas","bairro":"Jardim Santa Marta","cidade":"Cuiab\u00e1","uf":"MT","estado":"Mato Grosso"});
lfreneda/cepdb
api/v1/78043640.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"58033110","logradouro":"Rua Telegrafista Jos\u00e9 Neves Pacote","bairro":"Brisamar","cidade":"Jo\u00e3o Pessoa","uf":"PB","estado":"Para\u00edba"});
lfreneda/cepdb
api/v1/58033110.jsonp.js
JavaScript
cc0-1.0
164
jsonp({"cep":"75710364","logradouro":"Rua 96","bairro":"Loteamento Bela Vista","cidade":"Catal\u00e3o","uf":"GO","estado":"Goi\u00e1s"});
lfreneda/cepdb
api/v1/75710364.jsonp.js
JavaScript
cc0-1.0
138
jsonp({"cep":"85022020","logradouro":"Rua dos Coleiros","bairro":"Boqueir\u00e3o","cidade":"Guarapuava","uf":"PR","estado":"Paran\u00e1"});
lfreneda/cepdb
api/v1/85022020.jsonp.js
JavaScript
cc0-1.0
140
jsonp({"cep":"18022205","logradouro":"Viela Nilza de Oliveira Altomare","bairro":"Vila Zacarias","cidade":"Sorocaba","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/18022205.jsonp.js
JavaScript
cc0-1.0
156
jsonp({"cep":"09404050","logradouro":"Rua das Espat\u00f3deas","bairro":"Alian\u00e7a","cidade":"Ribeir\u00e3o Pires","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/09404050.jsonp.js
JavaScript
cc0-1.0
157
jsonp({"cep":"76822591","logradouro":"Avenida Rio Madeira","bairro":"Nova Esperan\u00e7a","cidade":"Porto Velho","uf":"RO","estado":"Rond\u00f4nia"});
lfreneda/cepdb
api/v1/76822591.jsonp.js
JavaScript
cc0-1.0
151
jsonp({"cep":"07716265","logradouro":"Rua dos Pinheirais","bairro":"Serpa","cidade":"Caieiras","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/07716265.jsonp.js
JavaScript
cc0-1.0
134
jsonp({"cep":"03892070","logradouro":"Rua Deniz Pinto de Matos","bairro":"Jardim Ponte Rasa","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/03892070.jsonp.js
JavaScript
cc0-1.0
158
jsonp({"cep":"03962000","logradouro":"Avenida Maria Cursi","bairro":"Cidade S\u00e3o Mateus","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/03962000.jsonp.js
JavaScript
cc0-1.0
158
jsonp({"cep":"29172905","logradouro":"Rua S\u00e3o Pedro","bairro":"Castel\u00e2ndia","cidade":"Serra","uf":"ES","estado":"Esp\u00edrito Santo"});
lfreneda/cepdb
api/v1/29172905.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"64202196","logradouro":"Avenida Deputado Pinheiro Machado - L Impar","bairro":"Nossa Senhora de F\u00e1tima","cidade":"Parna\u00edba","uf":"PI","estado":"Piau\u00ed"});
lfreneda/cepdb
api/v1/64202196.jsonp.js
JavaScript
cc0-1.0
183
jsonp({"cep":"60130600","logradouro":"Rua Evaristo Reis","bairro":"S\u00e3o Jo\u00e3o do Tauape","cidade":"Fortaleza","uf":"CE","estado":"Cear\u00e1"});
lfreneda/cepdb
api/v1/60130600.jsonp.js
JavaScript
cc0-1.0
153
jsonp({"cep":"22743340","logradouro":"Rua Jornalista Jos\u00e9 Morais","bairro":"Pechincha","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/22743340.jsonp.js
JavaScript
cc0-1.0
157
jsonp({"cep":"38400448","logradouro":"Avenida Vasconcelos Costa","bairro":"Martins","cidade":"Uberl\u00e2ndia","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/38400448.jsonp.js
JavaScript
cc0-1.0
148
jsonp({"cep":"26062194","logradouro":"Rua Neide","bairro":"Bar\u00e3o de Guandu","cidade":"Nova Igua\u00e7u","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/26062194.jsonp.js
JavaScript
cc0-1.0
148
jsonp({"cep":"31742072","logradouro":"Rua Te\u00f3filo Otoni","bairro":"Floramar","cidade":"Belo Horizonte","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/31742072.jsonp.js
JavaScript
cc0-1.0
145
jsonp({"cep":"03721000","logradouro":"Rua Doutor Arnaldo de Morais","bairro":"Canga\u00edba","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/03721000.jsonp.js
JavaScript
cc0-1.0
158
jsonp({"cep":"88812402","logradouro":"Rua 800","bairro":"Quarta Linha","cidade":"Crici\u00fama","uf":"SC","estado":"Santa Catarina"});
lfreneda/cepdb
api/v1/88812402.jsonp.js
JavaScript
cc0-1.0
135
jsonp({"cep":"38405164","logradouro":"Rua Amarela","bairro":"Tibery","cidade":"Uberl\u00e2ndia","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/38405164.jsonp.js
JavaScript
cc0-1.0
133
jsonp({"cep":"83210138","logradouro":"Acesso Constantino Bauraquiades Filho","bairro":"Jardim Igua\u00e7u","cidade":"Paranagu\u00e1","uf":"PR","estado":"Paran\u00e1"});
lfreneda/cepdb
api/v1/83210138.jsonp.js
JavaScript
cc0-1.0
169
jsonp({"cep":"87300110","logradouro":"Rua Francisco Ferreira Albuquerque","bairro":"Jardim Laura","cidade":"Campo Mour\u00e3o","uf":"PR","estado":"Paran\u00e1"});
lfreneda/cepdb
api/v1/87300110.jsonp.js
JavaScript
cc0-1.0
163
jsonp({"cep":"07223181","logradouro":"Viela Nepal","bairro":"Cidade Industrial Sat\u00e9lite de S\u00e3o Paulo","cidade":"Guarulhos","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/07223181.jsonp.js
JavaScript
cc0-1.0
172
jsonp({"cep":"39401843","logradouro":"Rua Hermenegildo Soares Malaquias","bairro":"Alcides Rabelo","cidade":"Montes Claros","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/39401843.jsonp.js
JavaScript
cc0-1.0
161
jsonp({"cep":"75050150","logradouro":"Rua 2","bairro":"Itamaraty II","cidade":"An\u00e1polis","uf":"GO","estado":"Goi\u00e1s"});
lfreneda/cepdb
api/v1/75050150.jsonp.js
JavaScript
cc0-1.0
129
jsonp({"cep":"61900025","logradouro":"Rua Capit\u00e3o Valdemar de Lima","bairro":"Centro","cidade":"Maracana\u00fa","uf":"CE","estado":"Cear\u00e1"});
lfreneda/cepdb
api/v1/61900025.jsonp.js
JavaScript
cc0-1.0
152
jsonp({"cep":"23050465","logradouro":"Rua Alu\u00edsio Palhano","bairro":"Campo Grande","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
lfreneda/cepdb
api/v1/23050465.jsonp.js
JavaScript
cc0-1.0
153
jsonp({"cep":"35502303","logradouro":"Rua Ilh\u00e9us","bairro":"Floramar","cidade":"Divin\u00f3polis","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/35502303.jsonp.js
JavaScript
cc0-1.0
140
jsonp({"cep":"35171125","logradouro":"Rua Maucia","bairro":"Aparecida do Norte","cidade":"Coronel Fabriciano","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/35171125.jsonp.js
JavaScript
cc0-1.0
147
jsonp({"cep":"52280505","logradouro":"Rua Mirandela","bairro":"Vasco da Gama","cidade":"Recife","uf":"PE","estado":"Pernambuco"});
lfreneda/cepdb
api/v1/52280505.jsonp.js
JavaScript
cc0-1.0
131
jsonp({"cep":"75910342","logradouro":"Rua PV 38","bairro":"Parque Dom Miguel","cidade":"Rio Verde","uf":"GO","estado":"Goi\u00e1s"});
lfreneda/cepdb
api/v1/75910342.jsonp.js
JavaScript
cc0-1.0
134
jsonp({"cep":"81900710","logradouro":"Rua Paulo Alves de Bastos","bairro":"S\u00edtio Cercado","cidade":"Curitiba","uf":"PR","estado":"Paran\u00e1"});
lfreneda/cepdb
api/v1/81900710.jsonp.js
JavaScript
cc0-1.0
151
jsonp({"cep":"35930491","logradouro":"Pra\u00e7a Maur\u00edcio P Vasconcelos","bairro":"Lourdes","cidade":"Jo\u00e3o Monlevade","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/35930491.jsonp.js
JavaScript
cc0-1.0
165
jsonp({"cep":"07183502","logradouro":"Viela Oliveira","bairro":"Jardim das Na\u00e7\u00f5es","cidade":"Guarulhos","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/07183502.jsonp.js
JavaScript
cc0-1.0
153
jsonp({"cep":"37701419","logradouro":"Rua Major Luiz Jos\u00e9 Dias","bairro":"Jardim Gama Cruz","cidade":"Po\u00e7os de Caldas","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/37701419.jsonp.js
JavaScript
cc0-1.0
166
jsonp({"cep":"99025420","logradouro":"Rua Tupinamb\u00e1s","bairro":"Boqueir\u00e3o","cidade":"Passo Fundo","uf":"RS","estado":"Rio Grande do Sul"});
lfreneda/cepdb
api/v1/99025420.jsonp.js
JavaScript
cc0-1.0
150
jsonp({"cep":"88341191","logradouro":"Rua Daniel Silv\u00e9rio","bairro":"L\u00eddia Duarte","cidade":"Cambori\u00fa","uf":"SC","estado":"Santa Catarina"});
lfreneda/cepdb
api/v1/88341191.jsonp.js
JavaScript
cc0-1.0
157
jsonp({"cep":"35182328","logradouro":"Pra\u00e7a S\u00e3o Jo\u00e3o","bairro":"Ana Rita","cidade":"Tim\u00f3teo","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/35182328.jsonp.js
JavaScript
cc0-1.0
150