code
stringlengths
2
1.05M
module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/svg-icons/maps/directions-run": require('material-ui/svg-icons/maps/directions-run') } }, name: "MapsDirectionsRun", ports: { input: {}, output: { component: { title: "MapsDirectionsRun", type: "Component" } } } }
/** * Created by Thomas on 05/07/2015. */ (function () { 'use strict'; angular.module('tg.docs') .provider('settingsService', [settingsProvider]); /** * @ngdoc provider * @name settingsServiceProvider * @module tg.docs * @description A Provider to register app availaible in the application */ function settingsProvider() { var provider = this; var settings = {language: 'en', apps: {}}; var apps = []; var appId; /** * @ngdoc method * @name settingsProvider#setHandlerFunctions * @description Add an application to docs * @param {Object} appObject A new application {} * @return {Object} settingsProvider instance */ provider.addApp = function (appObject) { appObject.children = []; apps.push(appObject); return provider; }; provider.$get = ['$translate', 'gclient', settingsService]; /** * @ngdoc service * @name settingsService * @module tg.docs * @description Setting service to manage the application properties * @requires $translate * @requires gclient */ function settingsService($translate, gclient) { var languages = [ {key:'en', name: 'English'}, {key:'fr', name: 'Français'} ]; return { /** * @ngdoc property * @name settingsService#settings * @description The app setting object * @type {Object} */ datas: settings, /** * @ngdoc property * @name settingsService#apps * @description The available apps * @type {Array} */ apps: apps, /** * @ngdoc property * @name settingsService#languages * @description The available app language * @type {Array} */ languages: languages, load: load, update: update }; /** * @ngdoc method * @name settingsService#load * @description Load the app parameters from Google drive * @return {Object} Promise */ function load() { return gclient.request( 'drive.files.list', {'q': 'properties has { key="docs" and value="docs" and visibility="PRIVATE" }'} ) .then(function (res) { if (res.result.items.length > 0) { appId = res.result.items[0].id; return gclient.request('drive.files.get', {'fileId': appId, 'alt': 'media'}); } else { var metadata = { title: 'docs.json', mimeType: 'application/json', parents: [{id: 'appfolder'}], properties: [{'key': 'docs', 'value': 'docs', 'visibility': 'PRIVATE'}] }; angular.forEach(apps, function (app) { settings.apps[app.name] = true; }); return gclient.drive.insert(metadata, settings).then(function(res){ appId = res.result.id; return {result: settings}; }); } }) .then(function (res) { settings = res.result; angular.forEach(apps, function (app) { app.enabled = settings.apps[app.id]; }); return $translate.use(settings.language); }); } /** * @ngdoc method * @name settingsService#update * @description Save the app parameters in Google drive * @return {Object} Promise */ function update() { angular.forEach(apps, function (app) { settings.apps[app.id] = app.enabled; }); return gclient.drive.update(appId, settings); } } } })();
import assert from 'assert'; import tddTest from '../lib'; describe('tdd-test', function () { it('2nd test', function () { assert(true, 1===1); }); it('2nd test', function () { assert(true, 1===1); }); });
let exercise = require('workshopper-exercise')(), filecheck = require('workshopper-exercise/filecheck'), execute = require('workshopper-exercise/execute'), comparestdout = require('workshopper-exercise/comparestdout'), babelProcessor = require('../babel-processor'); // checks that the submission file actually exists exercise = filecheck(exercise); //Do babelProcessor exercise = babelProcessor(exercise); // execute the solution and submission in parallel with spawn() exercise = execute(exercise); // compare stdout of solution and submission exercise = comparestdout(exercise); module.exports = exercise;
/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */ dbm.registerClass("dbm.constants.status.ReadyStateTypes", null, function(objectFunctions, staticFunctions) { //console.log("dbm.constants.status.ReadyStateTypes"); var ReadyStateTypes = dbm.importClass("dbm.constants.status.ReadyStateTypes"); staticFunctions.UNINIZIALIZED = 0; staticFunctions.SET_UP = 1; staticFunctions.SENT = 2; staticFunctions.PARTLY_DONE = 3; staticFunctions.DONE = 4; });
var jayson = require(__dirname + '/../..'); var format = require('util').format; var methods = { add: function(a, b, callback) { callback(null, a + b); } }; var server = jayson.server(methods, { router: function(method) { // regular by-name routing first if(typeof(this._methods[method]) === 'function') return this._methods[method]; if(method === 'add_2') { var fn = server.getMethod('add').getHandler(); return fn[0].bind(null, 2); } } }); server.http().listen(3000);
export class BinaryWriter { constructor (byteLength, isLittleEndian) { this.arrayBuffer = new ArrayBuffer (byteLength); this.dataView = new DataView (this.arrayBuffer); this.isLittleEndian = isLittleEndian; this.position = 0; } GetPosition () { return this.position; } SetPosition (position) { this.position = position; } End () { return this.position >= this.arrayBuffer.byteLength; } GetBuffer () { return this.arrayBuffer; } WriteArrayBuffer (arrayBuffer) { let bufferView = new Uint8Array (arrayBuffer); let thisBufferView = new Uint8Array (this.arrayBuffer); thisBufferView.set (bufferView, this.position); this.position += arrayBuffer.byteLength; } WriteBoolean8 (val) { this.dataView.setInt8 (this.position, val ? 1 : 0); this.position = this.position + 1; } WriteCharacter8 (val) { this.dataView.setInt8 (this.position, val); this.position = this.position + 1; } WriteUnsignedCharacter8 (val) { this.dataView.setUint8 (this.position, val); this.position = this.position + 1; } WriteInteger16 (val) { this.dataView.setInt16 (this.position, val, this.isLittleEndian); this.position = this.position + 2; } WriteUnsignedInteger16 (val) { this.dataView.setUint16 (this.position, val, this.isLittleEndian); this.position = this.position + 2; } WriteInteger32 (val) { this.dataView.setInt32 (this.position, val, this.isLittleEndian); this.position = this.position + 4; } WriteUnsignedInteger32 (val) { this.dataView.setUint32 (this.position, val, this.isLittleEndian); this.position = this.position + 4; } WriteFloat32 (val) { this.dataView.setFloat32 (this.position, val, this.isLittleEndian); this.position = this.position + 4; } WriteDouble64 (val) { this.dataView.setFloat64 (this.position, val, this.isLittleEndian); this.position = this.position + 8; } }
var commands = { LL: function(){ if(app.pointerA <= 1){ app.pointerA = 1 } else{ app.pointerA-- } }, LR: function(){ if(app.pointerA >= app.registryLength){ app.pointerA = app.registryLength; } else{ if(app.pointerA == app.pointerB){ app.pointerB++ } app.pointerA++ } }, RL: function(){ if(app.pointerB <= 1){ app.pointerB = 1; } else{ if(app.pointerA == app.pointerB){ app.pointerA-- } app.pointerB-- } }, RR: function(){ if(app.pointerB >= app.registryLength){ app.pointerB = app.registryLength } else{ app.pointerB++ } }, OP: function(){ var matchingClose = app.openClosePairs.open[app.currentCommandIndex]; var jumpTo = matchingClose if(app.pointersAreEqual){ app.currentCommandIndex = jumpTo } else if(app.pointerAValue == app.pointerBValue){ app.currentCommandIndex = jumpTo } }, CL: function(){ var matchingOpen = app.openClosePairs.close[app.currentCommandIndex]; var jumpTo = matchingOpen - 1 if(app.pointerAValue != app.pointerBValue){ app.currentCommandIndex = jumpTo } }, GV: function(){ if(app.pointersAreEqual){ app.output.push(app.pointerBValue); app.output.push(" "); } else{ var index = (app.pointerA - 1); var newValue = app.pointerAValue + app.pointerBValue; if(newValue <= app.min){ app.updateRegister(index, app.min); } else if(newValue >= app.max){ app.updateRegister(index, app.max) } else{ app.updateRegister(index, newValue); } } }, TK: function(){ if(app.pointersAreEqual){ app.getInput(); } else{ var index = (app.pointerA - 1); var newValue = app.pointerAValue - app.pointerBValue; if(newValue <= app.min){ app.updateRegister(index, app.min); } else if(newValue >= app.max){ app.updateRegister(index, app.max) } else{ app.updateRegister(index, newValue); } } } }
'use strict'; import optimist from 'optimist'; import fs from 'fs'; import { resolve } from 'path'; // import { renderPath } from '../dist/server-bundle'; // nginx will look for $uri with the .html extension const prerenderRoutes = [ { path: '/', filename: 'index.html' }, { path: '/counters', filename: 'counters.html' }, { path: '/todos', filename: 'todos.html' } ]; let argv = optimist .alias('o', 'out') .default('o', 'site/') .argv; /* prerenderRoutes.forEach((route) => { fs.writeFile( resolve(__dirname, argv.out + route.filename), resolvePath(route.path), (err) => { if(err) { return console.log(err); // eslint-disable-line } console.log(`${route.filename} saved...`); //eslint-disable-line }); }); */
module.exports = function (sequelize, DataTypes) { return sequelize.define('inventarios', { inventarioId: {type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4}, descripcion: {type: DataTypes.STRING, allowNull: false, unique: true}, cuentaContable: {type: DataTypes.STRING}, estado: {type: DataTypes.ENUM('A', 'E'), allowNull: false, defaultValue: 'A'} }) }
define(['knockout', 'app/dataservice', 'app/config'], function (ko, dataservice, config) { return function (params) { var question = ko.observable(); var url = ko.observable(params.url); var userComponent = ko.observable(config.userComponent); var tagsComponent = ko.observable(config.tagsComponent); var commentsComponent = ko.observable(config.commentsComponent); var answersComponent = ko.observable(config.answersComponent); var annotationUrl = ko.observable(); var searchUserId = ko.observable(params.searchUserId); var body = ko.observable(); var prevComponent = ko.observable(params.prevComponent); var annotations = ko.observableArray(); var markings = ko.observableArray(); var annotationBody = ko.observable(); var isNewAnnotation = ko.observable(false); var getSelectionText = function () { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } isNewAnnotation(true); } document.onmouseup = getSelectionText; dataservice.getQuestion(url(), function (data) { question(data); body(data.body); url(data.url); if (searchUserId !== undefined || searchUserId !== null) { dataservice.getQuestionAnnotations(data.id, searchUserId(), function (annotationData) { annotations(annotationData.data); for (var i = 0; i < annotations().length; i++) { //body().substring(annotations()[i].markingStart, annotations()[i].markingEnd); markings.push(body().substring(annotations()[i].markingStart, annotations()[i].markingEnd)); console.log(markings()); } for (var i = 0; i < annotations().length; i++) { body(body().replace(markings()[i], '<em onClick = \"ns.postbox.notify({annotationUrl: \'' + annotations()[i].url + '\'}, \'annotationUrl\');\">' + markings()[i] + '</em>')); } }); } }); /*$parents(1).showAnnotation(' + 'annotations()[i].url' + ')"*/ /*onClick = "$root.showAnnotation(\"blablba\")"*/ var goback = function () { ns.postbox.notify({ component: prevComponent() }, "currentComponent"); var searchBarContent = params.searchBarContent; ns.postbox.notify(searchBarContent, "searchBarContent"); } var getAnnotationBody = function (content, annotationUrl) { dataservice.getAnnotation(annotationUrl().annotationUrl, function (data) { isNewAnnotation(false); annotationBody(data.body); }); }; var saveAnnotation = function () { console.log("URL: " + annotationUrl().annotationUrl + " Body: " + annotationBody()); dataservice.getAnnotation(annotationUrl().annotationUrl, function (data) { var newAnnotation = ko.toJS({ Body: annotationBody(), MarkingStart: data.markingStart, MarkingEnd: data.markingEnd, PostId: data.postId, CommentId: data.commentId, SearchUserId: data.searchUserId }); dataservice.updateData(annotationUrl().annotationUrl, newAnnotation); }); } var createAnnotation = function () { console.log("Body: " + annotationBody() + " questionId: " + question().id); var newAnnotation = ko.toJS({ Body: annotationBody(), MarkingStart: null, MarkingEnd: null, PostId: question().id, CommentId: null, SearchUserId: 1 }); dataservice.postData(config.annotationsUrl, newAnnotation); isNewAnnotation(false); } ns.postbox.subscribe(function (data) { annotationUrl(data); }, "annotationUrl"); return { question: question, body: body, userComponent: userComponent, tagsComponent: tagsComponent, commentsComponent: commentsComponent, answersComponent: answersComponent, url: url, goback: goback, annotationUrl: annotationUrl, getAnnotationBody: getAnnotationBody, annotationBody: annotationBody, saveAnnotation: saveAnnotation, isNewAnnotation: isNewAnnotation, createAnnotation: createAnnotation } }; });
#!/usr/bin/env node require('babel/polyfill'); var commander = require('commander'); var fs = require("fs"); var each = require("lodash/collection/each"); var keys = require("lodash/object/keys"); var pkg = require("../package.json"); var glob = require("glob"); var path = require("path"); var colors = require('colors'); var program = new commander.Command('harmonika'); program.option("-s, --source <file/folder>", "Source to convert from ES5 to ES6 i.e. harmonika -s src"); program.option("-o, --out-folder [out]", "output folder (ouput file will be the same name)"); program.option("--no-classes", "Don't convert function/prototypes into classes"); program.description(pkg.description); program.version(pkg.version); program.usage("[options] <file>"); program.parse(process.argv); var sources = program.source; var outFolder = program.outFolder; var noClass = program.classes; if (!sources) { return program.help(); } var folderSearch = path.join(process.cwd(), sources, "/**/*.js"); var testFileName = path.join(process.cwd(), sources); var files = []; if (testFileName.match(/\.js/g)) { files.push(testFileName); }else{ console.log("File pattern to search: " + folderSearch); files = glob.sync(folderSearch); } if (!files) { console.log("Error globbing files.".red); return program.help(); } if (!files.length) { console.log("No files to convert.".yellow); return program.help(); } if (!outFolder || outFolder === true) outFolder = process.cwd()+'/output_files'; var outFolderName = outFolder; if(!fs.existsSync(outFolderName)){ fs.mkdirSync(outFolderName); } console.log(("File will be saved on "+outFolderName).green); var options = { files : files, outFolder : outFolderName, noClass : noClass || false }; var fn = require('./file'); fn(options);
export default function generateEmailMarkdown({to, beginning, url, title, content}) { const titleMakrdown = title ? `# ${title}\n` : ''; return ` Hi ${to}, ${beginning} You can read it [here](${url}) --- ${titleMakrdown} ${content} --- Thanks,<br />KB `; }
export const ic_brightness_auto_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M11 7l-3.2 9h1.9l.7-2h3.2l.7 2h1.9L13 7h-2zm-.15 5.65L12 9l1.15 3.65h-2.3zM20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zm-2 5.79V18h-3.52L12 20.48 9.52 18H6v-3.52L3.52 12 6 9.52V6h3.52L12 3.52 14.48 6H18v3.52L20.48 12 18 14.48z"},"children":[]}]};
fs = require('fs'); function ControllerObject(command, mediaName){ this.command = command; this.mediaName = mediaName; }; var Search = require('./apiSearch.js') var newSearch = new Search(); ControllerObject.prototype.getTweets = function(){ newSearch.tweets(this.command, this.mediaName, this.display2Console, this.write2File); }; ControllerObject.prototype.getSong = function(){ if(this.mediaName == ''){this.mediaName = 'the sign ace of base'}; newSearch.song(this.command, this.mediaName, this.display2Console, this.write2File); }; ControllerObject.prototype.getMovie = function(){ if(this.mediaName == ''){this.mediaName = 'mr nobody'}; newSearch.movie(this.command, this.mediaName, this.display2Console, this.write2File); }; ControllerObject.prototype.getHelp = function(){ helpText = 'Available commands:\n' tweetHelp = 'my-tweets will display last 20 tweets \n' movieHelp = 'movie-this will display movie information \n' songHelp = 'spotify-this-song get song information \n' doWhatHelp = 'do-what-it-says: not quite sure what this does'; console.log(helpText, tweetHelp, movieHelp, songHelp, doWhatHelp); }; //write2File writes command, mediaName and the results returned from search on a file named log.txt. this method takes command, mediaName, and an object as parameters. ControllerObject.prototype.write2File = function(command, mediaName, obj){ //logText will be used to log the command, mediaName, timeStamp and results. we begin by defining it with timestamp, command, and mediaName. var logText = 'timestamp: ' + Math.floor(Date.now() / 1000) + ',' + 'command: ' + command + ',' + 'mediaName: ' + mediaName + ','; //objText will be used to collect the search response obj. this object can be made up of information about tweets, songs, or movies. some strings inside obj can contain new lines so we write a regex string to find new lines. var objText = ''; var newLineRegex = /\r?\n|\r/g; for(firstKey in obj){ objText += firstKey + ': ' for(secondKey in obj[firstKey]){ objText += secondKey + ': ' + obj[firstKey][secondKey] + ',' }; }; objText = objText.replace(newLineRegex, ''); //replace new lines with an empty space. logText += objText + '\n'; //add objText and a new line to logText //write to log.txt fs.appendFile('log.txt', logText, function(error){ if(error) throw error; }); }; ControllerObject.prototype.display2Console = function(obj){ for(firstKey in obj){ for(secondKey in obj[firstKey]){ console.log(secondKey + ': ' + obj[firstKey][secondKey]); }; console.log('\n') }; }; ControllerObject.prototype.readRandom = function(){ var that = this; fs.readFile('random.txt', 'utf8', function(error, data){ if(error) throw error; var newLineRegex = /\r?\n|\r/g; data = data.split('\n'); var dataArray = data.map(function(elem,index){ return elem.replace(newLineRegex,'').split(','); }); var randomElem = Math.floor(Math.random()*dataArray.length); that.command = dataArray[randomElem][0]; that.mediaName = dataArray[randomElem][1]; switch(that.command){ case 'my-tweets': that.getTweets(); break; case 'spotify-this-song': that.getSong(); break; case 'movie-this': that.getMovie(); break; default: 'try again?'; }; }); }; module.exports = ControllerObject;
import { getWikiHtml } from './helpers.js' import execAll from 'execall' // Get the current claim ticket offers export default async function blackLionStatuette () { let page = await getWikiHtml('Black_Lion_Statuette') // Find all items sold for Black Lion Statuette with their costs let regex = /<tr[\s\S]*?<a href="[^"]*" title="([^"]*)">[\s\S]*?class="inline-icon">(\d*)(&nbsp;|&#160;)*<a [^>]* title="Black Lion Statuette"[\s\S]*?<\/tr>/gi let matches = execAll(regex, page).map(x => x.sub) let map = {} matches.map(x => { const name = x[0].replace(/&#39;/g, `'`) map[name] = parseInt(x[1], 10) }) return map }
import React from 'react'; import { Link } from 'react-router-dom'; import { sparqlConnect } from 'sparql-connect'; import Spinner from 'components/shared/spinner'; import { simsLink } from '../routes'; import D, { getLang } from 'i18n'; /** * Builds the query that retrieves the products issued of a given series. */ const queryBuilder = simsURI => ` PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> SELECT ?simsLabel FROM <http://rdf.insee.fr/graphes/qualite/rapport/${simsURI.slice( simsURI.lastIndexOf('/') + 1 )}> WHERE { ?simsURI rdfs:label ?simsLabel . FILTER (lang(?simsLabel) = '${getLang()}') } ORDER BY ?simsLabel `; const connector = sparqlConnect(queryBuilder, { queryName: 'simsLabelBySeries', params: ['simsURI'], singleResult: true, }); function SimsLabelBySeries({ simsURI, simsLabel }) { return <Link to={simsLink(simsURI)}>{simsLabel}</Link>; } export default connector(SimsLabelBySeries, { loading: () => <Spinner text={D.loadingSims} />, });
// TBD: create templateBase (like @sss) // +++ use templateBase HERE and in server/frontend/render.js export default function getStaticIndexHtml({js, css}) { return `<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="./${css}"> </head> <body> <div id="app"></div> <script type="text/javascript" src="./${js}"></script> </body> </html> ` }
const fs = require('fs'); const jsesc = require('jsesc'); const template = require('lodash.template'); function format(object) { return jsesc(object, { json: true, compact: false, }) + '\n'; } function parse(source) { const indexByCodePoint = {}; const indexByPointer = {}; let decoded = ''; const encoded = []; var lines = source.split('\n'); for (const line of lines) { const data = line.trim().split('\t'); if (data.length != 3) { continue; } const pointer = Number(data[0]); const codePoint = Number(data[1]); const symbol = String.fromCodePoint(codePoint); decoded += symbol; encoded.push(pointer + 0x80); indexByCodePoint[codePoint] = pointer; indexByPointer[pointer] = symbol; } return { decoded: decoded, encoded: encoded, indexByCodePoint: indexByCodePoint, indexByPointer: indexByPointer }; } const source = fs.readFileSync('./data/index.txt', 'utf-8'); const result = parse(source); fs.writeFileSync( './data/index-by-code-point.json', format(result.indexByCodePoint) ); fs.writeFileSync( './data/index-by-pointer.json', format(result.indexByPointer) ); fs.writeFileSync( './data/decoded.json', format(result.decoded) ); fs.writeFileSync( './data/encoded.json', format(result.encoded) ); const TEMPLATE_OPTIONS = { interpolate: /<\%=([\s\S]+?)%\>/g, }; // tests/tests.src.js → tests/tests.js const TEST_TEMPLATE = fs.readFileSync('./tests/tests.src.mjs', 'utf8'); const createTest = template(TEST_TEMPLATE, TEMPLATE_OPTIONS); const testCode = createTest(require('./export-data.js')); fs.writeFileSync('./tests/tests.mjs', testCode); // src/koi8-r.src.mjs → koi8-r.mjs const LIB_TEMPLATE = fs.readFileSync('./src/koi8-r.src.mjs', 'utf8'); const createLib = template(LIB_TEMPLATE, TEMPLATE_OPTIONS); const libCode = createLib(require('./export-data.js')); fs.writeFileSync('./koi8-r.mjs', libCode); // src/koi8-r.d.ts → koi8-r.d.ts const TYPES_TEMPLATE = fs.readFileSync('./src/koi8-r.d.ts', 'utf8'); const createTypes = template(TYPES_TEMPLATE, TEMPLATE_OPTIONS); const typesCode = createTypes(require('./export-data.js')); fs.writeFileSync('./koi8-r.d.ts', typesCode);
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Config; exports.exportForWebpack = exportForWebpack; var _debug = __webpack_require__(1); var _debug2 = _interopRequireDefault(_debug); var _immutable = __webpack_require__(2); var _fp = __webpack_require__(3); var _fp2 = _interopRequireDefault(_fp); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var error = (0, _debug2.default)('webpack-config-builder:error'); var debug = (0, _debug2.default)('webpack-config-builder:debug'); var HOOKS_KEY = '_hooks'; var defaultReducers = [function (c) { return c; }]; /** * @type Config * @param {Object|Immutable.Map} state * @param {Function[]} reducers */ function Config(state) { var reducers = arguments.length <= 1 || arguments[1] === undefined ? defaultReducers : arguments[1]; state = _immutable.Map.isMap(state) ? state : (0, _immutable.fromJS)(state || {}); return { use: use, useIf: useIf, toJs: toJs, compose: compose, getReducers: function getReducers() { return reducers; }, getState: function getState() { return state; }, plugin: plugin, hook: useHook, emit: useEmit }; /** * Plugin * @param {Function} pluginFn * @returns {Config} */ function plugin(pluginFn) { return pluginFn.apply(this, [this]); } /** * @param {Config} config */ function compose(config) { return Config(config.getState().mergeDeep(state), reducers.concat(config.getReducers())); } /** * toJs * @returns {Object|Boolean} */ function toJs() { try { return _fp2.default.flow(reducers)(state).remove(HOOKS_KEY).toJS(); } catch (err) { error(err); return false; } } /** * Use * @param {Function} reducer - function that receives the state object * @returns {Config} */ function use(reducer) { debug('Added reducer: \'' + (reducer.name || 'Anonymous') + '\''); return Config(state, reducers.concat(reducer)); } /** * Run reducer only if condition in config is met * @param {String[]} getInPath - Path in configurator to value * @param {Function} reducer - state 'changer' * @returns {Config} */ function useIf(getInPath, reducer) { return this.use(function (c) { if (c.getIn(getInPath)) { return reducer(c); } return c; }); } } /** * exportForWebpack * @note exportForWebpack doesn't cover all webpack settings that require mapping from object to array. */ function exportForWebpack(c) { return c.withMutations(function (c) { return c.updateIn(['module', 'loaders'], objectToArray).updateIn(['plugins'], objectToArray).updateIn(['resolve', 'modulesDirectories'], objectToArray).updateIn(['externals'], objectToArray); }); } function objectToArray(obj) { return obj ? obj.toArray() : void 0; } function useHook(hook, reducer) { return this.use(function (c) { return c.updateIn([HOOKS_KEY, hook], function (reducers) { reducers = !reducers ? [] : reducers; reducers.push(reducer); return reducers; }); }); } function useEmit(hook) { return this.use(function (c) { var reducers = c.getIn([HOOKS_KEY, hook], false); if (reducers) { c = _fp2.default.flow(reducers)(c); } return c; }); } /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = require("debug"); /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = require("immutable"); /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = require("lodash/fp"); /***/ } /******/ ]);
const command = () => ({ method: 'GET', endpoint: '/session/:sessionId/element', body: {using: 'css selector', value: 'img'}, result: {value: {x: 75, y: 11, width: 160, height: 160}}, cid: '0-0', sessionId: '4d1707ae-820f-1645-8485-5a820b2a40da', capabilities: {} }) const screenShotCommand = () => ({ method: 'GET', body: {using: 'css selector', value: 'img'}, endpoint: '/session/:sessionId/screenshot', result: {value: 'base64'}, cid: '0-0', sessionId: '4d1707ae-820f-1645-8485-5a820b2a40da', capabilities: {} }) export function commandStart() { return command() } export function commandEnd() { return command() } export function commandStartScreenShot() { return screenShotCommand() } export function commandEndScreenShot() { return screenShotCommand() }
/*jslint browser: true, sloppy: true */ /*global UNIVERSE, THREE */ /** A set of default objects to add to the Universe Object Library @constructor @param {UNIVERSE.Universe} universe - A Universe instance to use the default objects in */ UNIVERSE.DefaultObjects = function (universe) { universe.setObjectInLibrary("default_ground_object_geometry", new THREE.SphereGeometry(200, 20, 10)); universe.setObjectInLibrary("default_ground_object_material", new THREE.MeshBasicMaterial({ color : 0xCC0000 })); universe.setObjectInLibrary("default_ground_track_material", new THREE.MeshBasicMaterial({ color: 0xCC0000, transparent: true, opacity: 0.4, blending: THREE.AdditiveBlending })); universe.setObjectInLibrary("default_orbit_line_material", new THREE.LineBasicMaterial({ color : 0x990000, opacity : 1 })); universe.setObjectInLibrary("default_ground_object_tracing_line_material", new THREE.LineBasicMaterial({ color : 0x009900, opacity : 1 })); this.sensorColors = { colorList: [ "0xff0000", "0x00cc00", "0x0066ff", "0x9900cc", "0xffff00", "0xff6666", "0xebebeb", "0xffaa00" ], iterator: -1, // Grab the next color on the list and iterate to the next color nextColor: function () { this.iterator = (this.iterator + 1) % this.colorList.length; return this.colorList[this.iterator]; } }; };
import Component from '@ember/component'; import { run } from "@ember/runloop"; export default Component.extend({ classNames: ['ember-content-editable'], classNameBindings: ['clearPlaceholderOnFocus:clear-on-focus'], attributeBindings: [ 'contenteditable', 'placeholder', 'spellcheck', 'tabindex', 'disabled' ], disabled: false, spellcheck: null, allowNewlines: true, autofocus: false, clearPlaceholderOnFocus: false, init() { this._super(...arguments); this.set('keyWhitelist', [ 8, // backspace 27, // escape 37, // left arrow 38, // up arrow 39, // right arrow 40 // down arrow ]); this._pasteHandler = run.bind(this, this.pasteHandler); }, didInsertElement() { this._super(...arguments); this.updateDom(); this._mutationObserver = new MutationObserver(run.bind(this, this.domChanged)); this._mutationObserver.observe(this.element, {attributes: false, childList: true, characterData: true, subtree: true}); if (this.get('autofocus')) { this.element.focus(); } this.element.addEventListener('paste', this._pasteHandler); }, willDestroyElement() { this._super(...arguments); this.element.removeEventListener('paste', this._pasteHandler); this._mutationObserver.disconnect(); }, domChanged() { const text = this.element.innerText; this.setProperties({ value: text, _internalValue: text }); }, didReceiveAttrs() { this._super(...arguments); this.set('contenteditable', !this.get('disabled')); }, didUpdateAttrs() { this._super(...arguments); // if update has been initiated by a change of the dom (user entered something) we don't do anything because // - value has already been updated by domChanged // - the rendered text already shows the current value if (this.get('value') != this.get('_internalValue')) { this.updateDom(); } }, updateDom() { const value = this.get('value'); if (value === undefined || value === null) { this.element.innerText = ''; } else { this.element.innerText = value; } }, keyUp(event) { this.get('key-up')(event); }, keyPress(event) { // Firefox seems to call this method on backspace and cursor keyboard events, whereas chrome does not. // Therefore we keep a whitelist of keyCodes that we allow in case it is necessary. const newLength = this.element.innerText.length - this.getSelectionLength(); if (this.get('maxlength') && newLength >= this.get('maxlength') && !this.get('keyWhitelist').includes(event.keyCode)) { event.preventDefault(); this.get('length-exceeded')(this.element.innerText.length + 1); return false; } this.get('key-press')(event); }, keyDown(event) { if (event.keyCode === 27) { this.get('escape-press')(event); } else if (event.keyCode === 13) { this.get('enter')(event); if (this.get('allowNewlines')) { this.get('insert-newline')(event); } else { event.preventDefault(); return false; } } this.get('key-down')(event); }, getSelectionLength() { const selection = window.getSelection(); if (selection && selection.rangeCount > 0) { const range = selection.getRangeAt(0); return range.endOffset - range.startOffset; } return 0; }, pasteHandler(event) { event.preventDefault(); // replace any html formatted text with its plain text equivalent let text = ''; if (event.clipboardData) { text = event.clipboardData.getData('text/plain'); } else if (window.clipboardData) { text = window.clipboardData.getData('Text'); } // check max length if (this.get('maxlength')) { // a selection will be replaced. substract the length of the selection from the total length const selectionLength = this.getSelectionLength(); const afterPasteLength = text.length + this.element.innerText.length - selectionLength; if (afterPasteLength > this.get('maxlength')) { this.get('length-exceeded')(afterPasteLength); return false; } } crossSupportInsertText(text); this.get('paste')(text); }, enter() { }, 'escape-press'() { }, 'key-up'() { }, 'key-press'() { }, 'key-down'() { }, 'length-exceeded'() { }, 'insert-newline'() { }, paste() { } }).reopenClass({ positionalParams: ['value'] }); function crossSupportInsertText(text) { if (document.queryCommandSupported('insertText')) { document.execCommand('insertText', false, text); } else { const range = document.getSelection().getRangeAt(0); range.deleteContents(); const textNode = document.createTextNode(text); range.insertNode(textNode); range.selectNodeContents(textNode); range.collapse(false); const selection = document.getSelection(); selection.removeAllRanges(); selection.addRange(range); } }
//this controller simply tells the dialogs service to open a mediaPicker window //with a specified callback, this callback will receive an object with a selection on it angular.module('umbraco').controller("Umbraco.PropertyEditors.MediaPickerController", function ($scope, entityResource, mediaHelper, $timeout, userService, localizationService, editorService, angularHelper) { var vm = { labels: { mediaPicker_deletedItem: "" } } //check the pre-values for multi-picker var multiPicker = $scope.model.config.multiPicker && $scope.model.config.multiPicker !== '0' ? true : false; var onlyImages = $scope.model.config.onlyImages && $scope.model.config.onlyImages !== '0' ? true : false; var disableFolderSelect = $scope.model.config.disableFolderSelect && $scope.model.config.disableFolderSelect !== '0' ? true : false; $scope.allowEditMedia = false; $scope.allowAddMedia = false; function setupViewModel() { $scope.mediaItems = []; $scope.ids = []; $scope.isMultiPicker = multiPicker; if ($scope.model.value) { var ids = $scope.model.value.split(','); //NOTE: We need to use the entityResource NOT the mediaResource here because // the mediaResource has server side auth configured for which the user must have // access to the media section, if they don't they'll get auth errors. The entityResource // acts differently in that it allows access if the user has access to any of the apps that // might require it's use. Therefore we need to use the metaData property to get at the thumbnail // value. entityResource.getByIds(ids, "Media").then(function (medias) { // The service only returns item results for ids that exist (deleted items are silently ignored). // This results in the picked items value to be set to contain only ids of picked items that could actually be found. // Since a referenced item could potentially be restored later on, instead of changing the selected values here based // on whether the items exist during a save event - we should keep "placeholder" items for picked items that currently // could not be fetched. This will preserve references and ensure that the state of an item does not differ depending // on whether it is simply resaved or not. // This is done by remapping the int/guid ids into a new array of items, where we create "Deleted item" placeholders // when there is no match for a selected id. This will ensure that the values being set on save, are the same as before. medias = _.map(ids, function (id) { var found = _.find(medias, function (m) { // We could use coercion (two ='s) here .. but not sure if this works equally well in all browsers and // it's prone to someone "fixing" it at some point without knowing the effects. Rather use toString() // compares and be completely sure it works. return m.udi.toString() === id.toString() || m.id.toString() === id.toString(); }); if (found) { return found; } else { return { name: vm.labels.mediaPicker_deletedItem, id: $scope.model.config.idType !== "udi" ? id : null, udi: $scope.model.config.idType === "udi" ? id : null, icon: "icon-picture", thumbnail: null, trashed: true }; } }); _.each(medias, function (media, i) { // if there is no thumbnail, try getting one if the media is not a placeholder item if (!media.thumbnail && media.id && media.metaData) { media.thumbnail = mediaHelper.resolveFileFromEntity(media, true); } $scope.mediaItems.push(media); if ($scope.model.config.idType === "udi") { $scope.ids.push(media.udi); } else { $scope.ids.push(media.id); } }); sync(); }); } } function sync() { $scope.model.value = $scope.ids.join(); }; function setDirty() { angularHelper.getCurrentForm($scope).$setDirty(); } function reloadUpdatedMediaItems(updatedMediaNodes) { // because the images can be edited through the media picker we need to // reload. We only reload the images that is already picked but has been updated. // We have to get the entities from the server because the media // can be edited without being selected _.each($scope.images, function (image, i) { if (updatedMediaNodes.indexOf(image.udi) !== -1) { image.loading = true; entityResource.getById(image.udi, "media") .then(function (mediaEntity) { angular.extend(image, mediaEntity); image.thumbnail = mediaHelper.resolveFileFromEntity(image, true); image.loading = false; }); } }); } function init() { localizationService.localizeMany(["mediaPicker_deletedItem"]) .then(function(data) { vm.labels.mediaPicker_deletedItem = data[0]; userService.getCurrentUser().then(function (userData) { if (!$scope.model.config.startNodeId) { if ($scope.model.config.ignoreUserStartNodes === true) { $scope.model.config.startNodeId = -1; $scope.model.config.startNodeIsVirtual = true; } else { $scope.model.config.startNodeId = userData.startMediaIds.length !== 1 ? -1 : userData.startMediaIds[0]; $scope.model.config.startNodeIsVirtual = userData.startMediaIds.length !== 1; } } // only allow users to add and edit media if they have access to the media section var hasAccessToMedia = userData.allowedSections.indexOf("media") !== -1; $scope.allowEditMedia = hasAccessToMedia; $scope.allowAddMedia = hasAccessToMedia; setupViewModel(); //When the model value changes sync the view model $scope.$watch("model.value", function (newVal, oldVal) { if (newVal !== oldVal) { setupViewModel(); } }); }); }); } $scope.remove = function (index) { $scope.mediaItems.splice(index, 1); $scope.ids.splice(index, 1); sync(); setDirty(); }; $scope.editItem = function (item) { var mediaEditor = { id: item.id, submit: function (model) { editorService.close(); // update the selected media item to match the saved media item // the media picker is using media entities so we get the // entity so we easily can format it for use in the media grid if (model && model.mediaNode) { entityResource.getById(model.mediaNode.id, "media") .then(function (mediaEntity) { // if an image is selecting more than once // we need to update all the media items angular.forEach($scope.images, function (image) { if (image.id === model.mediaNode.id) { angular.extend(image, mediaEntity); image.thumbnail = mediaHelper.resolveFileFromEntity(image, true); } }); }); } }, close: function (model) { editorService.close(); } }; editorService.mediaEditor(mediaEditor); }; $scope.add = function () { var mediaPicker = { startNodeId: $scope.model.config.startNodeId, startNodeIsVirtual: $scope.model.config.startNodeIsVirtual, dataTypeKey: $scope.model.dataTypeKey, multiPicker: multiPicker, onlyImages: onlyImages, disableFolderSelect: disableFolderSelect, allowMediaEdit: true, submit: function (model) { editorService.close(); _.each(model.selection, function (media, i) { // if there is no thumbnail, try getting one if the media is not a placeholder item if (!media.thumbnail && media.id && media.metaData) { media.thumbnail = mediaHelper.resolveFileFromEntity(media, true); } $scope.mediaItems.push(media); if ($scope.model.config.idType === "udi") { $scope.ids.push(media.udi); } else { $scope.ids.push(media.id); } }); sync(); reloadUpdatedMediaItems(model.updatedMediaNodes); setDirty(); }, close: function (model) { editorService.close(); reloadUpdatedMediaItems(model.updatedMediaNodes); } } editorService.mediaPicker(mediaPicker); }; $scope.sortableOptions = { disabled: !multiPicker, items: "li:not(.add-wrapper)", cancel: ".unsortable", update: function (e, ui) { setDirty(); var r = []; // TODO: Instead of doing this with a half second delay would be better to use a watch like we do in the // content picker. Then we don't have to worry about setting ids, render models, models, we just set one and let the // watch do all the rest. $timeout(function () { angular.forEach($scope.mediaItems, function (value, key) { r.push($scope.model.config.idType === "udi" ? value.udi : value.id); }); $scope.ids = r; sync(); }, 500, false); } }; $scope.showAdd = function () { if (!multiPicker) { if ($scope.model.value && $scope.model.value !== "") { return false; } } return true; }; init(); });
let nextTodoId = 0; export const addTodo = (text) => ({ type: 'ADD_TODO', id: nextTodoId++, text: text, }); export const toggleTodo = (id) => { debugger; return ({ type: 'TOGGLE_TODO', id }); }; export const setVisibilityFilter = (filter) => ({ type: 'SET_VISIBILITY_FILTER', filter: filter });
var webpack = require('webpack'); var path = require('path'); var nib = require('nib'); var fs = require('fs'); var options = { devtool: "inline-source-map", debug: true, cache: true, module: { loaders: [ { test: /\.ts$/, loader: 'ts' }, { test: /\.html$/, loader: 'raw' }, { test: /\.css$/, loaders: ['style','css'] }, { test: /\.scss$/, loaders: ['style', 'css', 'sass'] } ] }, transforms: [ function(file) { return fs.createReadStream(file); } ], stylus: { use: [nib()] }, wrap: { strict: { before: [ //'"use strict";' ] } }, plugins: [ ], resolve: { extensions: ['', '.webpack.js', '.web.js', '.ts', '.js'], alias: { }, modulesDirectories: ['.', 'app', 'node_modules'] }, output: { path: '/', filename: 'main.js' } }; module.exports = options;
'use strict'; var React = require('React'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var View = require('View'); var DummyProgressViewIOS = function (_React$Component) { babelHelpers.inherits(DummyProgressViewIOS, _React$Component); function DummyProgressViewIOS() { babelHelpers.classCallCheck(this, DummyProgressViewIOS); return babelHelpers.possibleConstructorReturn(this, (DummyProgressViewIOS.__proto__ || Object.getPrototypeOf(DummyProgressViewIOS)).apply(this, arguments)); } babelHelpers.createClass(DummyProgressViewIOS, [{ key: 'render', value: function render() { return React.createElement( View, { style: [styles.dummy, this.props.style] }, React.createElement( Text, { style: styles.text }, 'ProgressViewIOS is not supported on this platform!' ) ); } }]); return DummyProgressViewIOS; }(React.Component); var styles = StyleSheet.create({ dummy: { width: 120, height: 20, backgroundColor: '#ffbcbc', borderWidth: 1, borderColor: 'red', alignItems: 'center', justifyContent: 'center' }, text: { color: '#333333', margin: 5, fontSize: 10 } }); module.exports = DummyProgressViewIOS;
var card = { rank: 3, suit: "spades" }; console.log( JSON.stringify(card));
/** * @license Copyright (c) 2014, Viet Trinh All Rights Reserved. * Available via MIT license. */ /** * A collection hs index request/response. */ define([ 'framework/request/base_request' ], function(BaseRequest) { return BaseRequest.create([], [ 'sets' ]); });
import React from 'react'; import { connect } from 'react-redux'; import {Router, Route, IndexRedirect, browserHistory} from 'react-router'; import { updatePlayersArray, updateLastNumberRolled, updateNextPlayerIndexTurn, setFirstPlayerTurn, startGame, buy, receivingMoney, receiveMoney } from '../reducers/gameReducer'; import {purchaseEstablishment, allPlayers} from '../basestuff'; import Login from './Login'; import WhoAmI from './WhoAmI'; import Board from './Board'; const App = connect( ({ auth }) => ({ user: auth }) )( ({ user, children }) => <div id="parent"> <nav> {user ? <WhoAmI /> : <Login />} </nav> {children} </div> ); const Routes = ({initialListen}) => { return ( <Router history={browserHistory}> <Route path="/" component={App} onEnter={initialListen}> <IndexRedirect to="/board" /> <Route path="/board" component={Board} /> </Route> </Router> ); }; const mapDispatch = dispatch => ({ initialListen: function(){ socket.on('addPlayer', (players)=> { dispatch(updatePlayersArray(players)) }); socket.on('playerRoll', (dice)=> { dispatch(updateLastNumberRolled(dice.roll)) }); socket.on('endTurn', (indices) => { dispatch(updateNextPlayerIndexTurn(indices.nextPlayerIndex, indices.lastPlayerIndex)) }); socket.on('startingPlayer', (player) => { alert(`The starting player will be Player ${player.index + 1}`) dispatch(setFirstPlayerTurn(player.index)) dispatch(startGame()) }); socket.on('playerBuy', ({game, playerId, establishmentId}) => { let newState = purchaseEstablishment(game, playerId, establishmentId); dispatch(buy(newState)) }); socket.on('playerReceiveMoney', ({playerAmountsToChange}) => { playerAmountsToChange.forEach(changeObject => { dispatch(receiveMoney(changeObject.playerIndex, changeObject.amount)) }); }); } }); export default connect(null, mapDispatch)(Routes);
module.exports = class RedirectionException extends Error { constructor(redirectionUrl, queryParams = {}, ...params) { super(...params); Error.captureStackTrace(this, RedirectionException); this.redirectionUrl = redirectionUrl; this.queryParams = queryParams; this.message = `Redirection due to ${this.queryParams.error}`; } };
function get_tour_dates(songkick) { $.ajax({ url: songkick, type: "GET", dataType: 'json', success: function (data) { var gigs = data.resultsPage.results.event; if ( gigs == undefined ) { var no_dates = '<div class="timeline-left"><a href="#timeline" class="timeline-icon icon-lg tooltip" data-tooltip="No dates available"></a></div>' + '<div class="timeline-content"><div class="tile"><div class="tile-content"><p class="tile-title"> No Current Tour Dates Available.' + '</p></div></div></div>'; $("#tour-date-timeline").append(no_dates); } else { for (var x = 0; x < gigs.length; x++) { var start_date = new Date( gigs[x].start.datetime.toString('dd-MM-yy') ).toLocaleDateString("en-GB"); var tour_date = '<div class="timeline-item" id="timeline"><div class="timeline-left"><a href="#timeline" class="timeline-icon icon-lg tooltip" data-tooltip="' + start_date + '"></a></div><div class="timeline-content"><div class="tile"><div class="tile-content">' + '<p class="tile-subtitle">' + start_date + '</p><p class="tile-title">' + gigs[x].displayName + '</p><p class="tile-title">' + gigs[x].type + '</p><p class="tile-title"><a href="' + gigs[x].venue.uri + '">' + gigs[x].venue.displayName + '</a> | ' + gigs[x].location.city + '</p></div><div class="tile-action"><a href="' + gigs[x].uri + '" class="btn">Book Tickets</a></div></div></div></div>'; $("#tour-date-timeline").append(tour_date); } } } }); }
/** * @ngdoc overview * @name Angularjs::routes Configuration * @description * @property $urlRouterProvider * # AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. * # @link https://github.com/angular-ui/ui-router * @property $locationProvider Use the $locationProvider to configure how the application deep linking paths are stored. * @property $httpProvider Use $httpProvider to change the default behavior of the $http service. * @property $stateProvider $state service is responsible for representing states as well as transitioning between them. It also provides interfaces to ask for current state or even states you're coming from. */ function Configuration($urlRouterProvider, $locationProvider, $httpProvider, $stateProvider, $sceDelegateProvider) { const defaultPage = 'firebase.helloworld'; // Use $urlRouterProvider to configure any redirects (when) and invalid urls (otherwise). $urlRouterProvider // If the url is ever invalid, e.g. '/asdf', then redirect to '/' aka the home state .otherwise(defaultPage); // Use $stateProvider to configure your states. $stateProvider .state('firebase', { // With abstract set to true, that means this state can not be explicitly activated // It can only be implicitly activated by activating one of its children. abstract: true, template: '<section ui-view class="widgets"></section>' }); // use the HTML5 History API $locationProvider.html5Mode(true); }; Configuration.$inject = ['$urlRouterProvider', '$locationProvider', '$httpProvider', '$stateProvider', '$sceDelegateProvider']; export default Configuration;
/** * @popperjs/core v2.7.0 - MIT License */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function getBoundingClientRect(element) { var rect = element.getBoundingClientRect(); return { width: rect.width, height: rect.height, top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, x: rect.left, y: rect.top }; } /*:: import type { Window } from '../types'; */ /*:: declare function getWindow(node: Node | Window): Window; */ function getWindow(node) { if (node.toString() !== '[object Window]') { var ownerDocument = node.ownerDocument; return ownerDocument ? ownerDocument.defaultView || window : window; } return node; } function getWindowScroll(node) { var win = getWindow(node); var scrollLeft = win.pageXOffset; var scrollTop = win.pageYOffset; return { scrollLeft: scrollLeft, scrollTop: scrollTop }; } /*:: declare function isElement(node: mixed): boolean %checks(node instanceof Element); */ function isElement(node) { var OwnElement = getWindow(node).Element; return node instanceof OwnElement || node instanceof Element; } /*:: declare function isHTMLElement(node: mixed): boolean %checks(node instanceof HTMLElement); */ function isHTMLElement(node) { var OwnElement = getWindow(node).HTMLElement; return node instanceof OwnElement || node instanceof HTMLElement; } /*:: declare function isShadowRoot(node: mixed): boolean %checks(node instanceof ShadowRoot); */ function isShadowRoot(node) { var OwnElement = getWindow(node).ShadowRoot; return node instanceof OwnElement || node instanceof ShadowRoot; } function getHTMLElementScroll(element) { return { scrollLeft: element.scrollLeft, scrollTop: element.scrollTop }; } function getNodeScroll(node) { if (node === getWindow(node) || !isHTMLElement(node)) { return getWindowScroll(node); } else { return getHTMLElementScroll(node); } } function getNodeName(element) { return element ? (element.nodeName || '').toLowerCase() : null; } function getDocumentElement(element) { // $FlowFixMe[incompatible-return]: assume body is always available return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing] element.document) || window.document).documentElement; } function getWindowScrollBarX(element) { // If <html> has a CSS width greater than the viewport, then this will be // incorrect for RTL. // Popper 1 is broken in this case and never had a bug report so let's assume // it's not an issue. I don't think anyone ever specifies width on <html> // anyway. // Browsers where the left scrollbar doesn't cause an issue report `0` for // this (e.g. Edge 2019, IE11, Safari) return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; } function getComputedStyle(element) { return getWindow(element).getComputedStyle(element); } function isScrollParent(element) { // Firefox wants us to check `-x` and `-y` variations as well var _getComputedStyle = getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY; return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); } // Composite means it takes into account transforms as well as layout. function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { if (isFixed === void 0) { isFixed = false; } var documentElement = getDocumentElement(offsetParent); var rect = getBoundingClientRect(elementOrVirtualElement); var isOffsetParentAnElement = isHTMLElement(offsetParent); var scroll = { scrollLeft: 0, scrollTop: 0 }; var offsets = { x: 0, y: 0 }; if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078 isScrollParent(documentElement)) { scroll = getNodeScroll(offsetParent); } if (isHTMLElement(offsetParent)) { offsets = getBoundingClientRect(offsetParent); offsets.x += offsetParent.clientLeft; offsets.y += offsetParent.clientTop; } else if (documentElement) { offsets.x = getWindowScrollBarX(documentElement); } } return { x: rect.left + scroll.scrollLeft - offsets.x, y: rect.top + scroll.scrollTop - offsets.y, width: rect.width, height: rect.height }; } // Returns the layout rect of an element relative to its offsetParent. Layout // means it doesn't take into account transforms. function getLayoutRect(element) { return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } function getParentNode(element) { if (getNodeName(element) === 'html') { return element; } return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle // $FlowFixMe[incompatible-return] // $FlowFixMe[prop-missing] element.assignedSlot || // step into the shadow DOM of the parent of a slotted node element.parentNode || // DOM Element detected // $FlowFixMe[incompatible-return]: need a better way to handle this... element.host || // ShadowRoot detected // $FlowFixMe[incompatible-call]: HTMLElement is a Node getDocumentElement(element) // fallback ); } function getScrollParent(node) { if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) { // $FlowFixMe[incompatible-return]: assume body is always available return node.ownerDocument.body; } if (isHTMLElement(node) && isScrollParent(node)) { return node; } return getScrollParent(getParentNode(node)); } /* given a DOM element, return the list of all scroll parents, up the list of ancesors until we get to the top window object. This list is what we attach scroll listeners to, because if any of these parent elements scroll, we'll need to re-calculate the reference element's position. */ function listScrollParents(element, list) { if (list === void 0) { list = []; } var scrollParent = getScrollParent(element); var isBody = scrollParent === element.ownerDocument.body; var win = getWindow(scrollParent); var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; var updatedList = list.concat(target); return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here updatedList.concat(listScrollParents(getParentNode(target))); } function isTableElement(element) { return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0; } function getTrueOffsetParent(element) { if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837 getComputedStyle(element).position === 'fixed') { return null; } var offsetParent = element.offsetParent; if (offsetParent) { var html = getDocumentElement(offsetParent); if (getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static' && getComputedStyle(html).position !== 'static') { return html; } } return offsetParent; } // `.offsetParent` reports `null` for fixed elements, while absolute elements // return the containing block function getContainingBlock(element) { var currentNode = getParentNode(element); while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) { var css = getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that // create a containing block. if (css.transform !== 'none' || css.perspective !== 'none' || css.willChange && css.willChange !== 'auto') { return currentNode; } else { currentNode = currentNode.parentNode; } } return null; } // Gets the closest ancestor positioned element. Handles some edge cases, // such as table ancestors and cross browser bugs. function getOffsetParent(element) { var window = getWindow(element); var offsetParent = getTrueOffsetParent(element); while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === 'static') { offsetParent = getTrueOffsetParent(offsetParent); } if (offsetParent && getNodeName(offsetParent) === 'body' && getComputedStyle(offsetParent).position === 'static') { return window; } return offsetParent || getContainingBlock(element) || window; } var top = 'top'; var bottom = 'bottom'; var right = 'right'; var left = 'left'; var auto = 'auto'; var basePlacements = [top, bottom, right, left]; var start = 'start'; var end = 'end'; var clippingParents = 'clippingParents'; var viewport = 'viewport'; var popper = 'popper'; var reference = 'reference'; var beforeRead = 'beforeRead'; var read = 'read'; var afterRead = 'afterRead'; // pure-logic modifiers var beforeMain = 'beforeMain'; var main = 'main'; var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state) var beforeWrite = 'beforeWrite'; var write = 'write'; var afterWrite = 'afterWrite'; var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; function order(modifiers) { var map = new Map(); var visited = new Set(); var result = []; modifiers.forEach(function (modifier) { map.set(modifier.name, modifier); }); // On visiting object, check for its dependencies and visit them recursively function sort(modifier) { visited.add(modifier.name); var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); requires.forEach(function (dep) { if (!visited.has(dep)) { var depModifier = map.get(dep); if (depModifier) { sort(depModifier); } } }); result.push(modifier); } modifiers.forEach(function (modifier) { if (!visited.has(modifier.name)) { // check for visited object sort(modifier); } }); return result; } function orderModifiers(modifiers) { // order based on dependencies var orderedModifiers = order(modifiers); // order based on phase return modifierPhases.reduce(function (acc, phase) { return acc.concat(orderedModifiers.filter(function (modifier) { return modifier.phase === phase; })); }, []); } function debounce(fn) { var pending; return function () { if (!pending) { pending = new Promise(function (resolve) { Promise.resolve().then(function () { pending = undefined; resolve(fn()); }); }); } return pending; }; } function format(str) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return [].concat(args).reduce(function (p, c) { return p.replace(/%s/, c); }, str); } var INVALID_MODIFIER_ERROR = 'Popper: modifier "%s" provided an invalid %s property, expected %s but got %s'; var MISSING_DEPENDENCY_ERROR = 'Popper: modifier "%s" requires "%s", but "%s" modifier is not available'; var VALID_PROPERTIES = ['name', 'enabled', 'phase', 'fn', 'effect', 'requires', 'options']; function validateModifiers(modifiers) { modifiers.forEach(function (modifier) { Object.keys(modifier).forEach(function (key) { switch (key) { case 'name': if (typeof modifier.name !== 'string') { console.error(format(INVALID_MODIFIER_ERROR, String(modifier.name), '"name"', '"string"', "\"" + String(modifier.name) + "\"")); } break; case 'enabled': if (typeof modifier.enabled !== 'boolean') { console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"enabled"', '"boolean"', "\"" + String(modifier.enabled) + "\"")); } case 'phase': if (modifierPhases.indexOf(modifier.phase) < 0) { console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"phase"', "either " + modifierPhases.join(', '), "\"" + String(modifier.phase) + "\"")); } break; case 'fn': if (typeof modifier.fn !== 'function') { console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"fn"', '"function"', "\"" + String(modifier.fn) + "\"")); } break; case 'effect': if (typeof modifier.effect !== 'function') { console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"effect"', '"function"', "\"" + String(modifier.fn) + "\"")); } break; case 'requires': if (!Array.isArray(modifier.requires)) { console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requires"', '"array"', "\"" + String(modifier.requires) + "\"")); } break; case 'requiresIfExists': if (!Array.isArray(modifier.requiresIfExists)) { console.error(format(INVALID_MODIFIER_ERROR, modifier.name, '"requiresIfExists"', '"array"', "\"" + String(modifier.requiresIfExists) + "\"")); } break; case 'options': case 'data': break; default: console.error("PopperJS: an invalid property has been provided to the \"" + modifier.name + "\" modifier, valid properties are " + VALID_PROPERTIES.map(function (s) { return "\"" + s + "\""; }).join(', ') + "; but \"" + key + "\" was provided."); } modifier.requires && modifier.requires.forEach(function (requirement) { if (modifiers.find(function (mod) { return mod.name === requirement; }) == null) { console.error(format(MISSING_DEPENDENCY_ERROR, String(modifier.name), requirement, requirement)); } }); }); }); } function uniqueBy(arr, fn) { var identifiers = new Set(); return arr.filter(function (item) { var identifier = fn(item); if (!identifiers.has(identifier)) { identifiers.add(identifier); return true; } }); } function getBasePlacement(placement) { return placement.split('-')[0]; } function mergeByName(modifiers) { var merged = modifiers.reduce(function (merged, current) { var existing = merged[current.name]; merged[current.name] = existing ? Object.assign(Object.assign(Object.assign({}, existing), current), {}, { options: Object.assign(Object.assign({}, existing.options), current.options), data: Object.assign(Object.assign({}, existing.data), current.data) }) : current; return merged; }, {}); // IE11 does not support Object.values return Object.keys(merged).map(function (key) { return merged[key]; }); } function getViewportRect(element) { var win = getWindow(element); var html = getDocumentElement(element); var visualViewport = win.visualViewport; var width = html.clientWidth; var height = html.clientHeight; var x = 0; var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper // can be obscured underneath it. // Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even // if it isn't open, so if this isn't available, the popper will be detected // to overflow the bottom of the screen too early. if (visualViewport) { width = visualViewport.width; height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently) // In Chrome, it returns a value very close to 0 (+/-) but contains rounding // errors due to floating point numbers, so we need to check precision. // Safari returns a number <= 0, usually < -1 when pinch-zoomed // Feature detection fails in mobile emulation mode in Chrome. // Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) < // 0.001 // Fallback here: "Not Safari" userAgent if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { x = visualViewport.offsetLeft; y = visualViewport.offsetTop; } } return { width: width, height: height, x: x + getWindowScrollBarX(element), y: y }; } // of the `<html>` and `<body>` rect bounds if horizontally scrollable function getDocumentRect(element) { var html = getDocumentElement(element); var winScroll = getWindowScroll(element); var body = element.ownerDocument.body; var width = Math.max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); var height = Math.max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); var x = -winScroll.scrollLeft + getWindowScrollBarX(element); var y = -winScroll.scrollTop; if (getComputedStyle(body || html).direction === 'rtl') { x += Math.max(html.clientWidth, body ? body.clientWidth : 0) - width; } return { width: width, height: height, x: x, y: y }; } function contains(parent, child) { var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method if (parent.contains(child)) { return true; } // then fallback to custom implementation with Shadow DOM support else if (rootNode && isShadowRoot(rootNode)) { var next = child; do { if (next && parent.isSameNode(next)) { return true; } // $FlowFixMe[prop-missing]: need a better way to handle this... next = next.parentNode || next.host; } while (next); } // Give up, the result is false return false; } function rectToClientRect(rect) { return Object.assign(Object.assign({}, rect), {}, { left: rect.x, top: rect.y, right: rect.x + rect.width, bottom: rect.y + rect.height }); } function getInnerBoundingClientRect(element) { var rect = getBoundingClientRect(element); rect.top = rect.top + element.clientTop; rect.left = rect.left + element.clientLeft; rect.bottom = rect.top + element.clientHeight; rect.right = rect.left + element.clientWidth; rect.width = element.clientWidth; rect.height = element.clientHeight; rect.x = rect.left; rect.y = rect.top; return rect; } function getClientRectFromMixedType(element, clippingParent) { return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element))); } // A "clipping parent" is an overflowable container with the characteristic of // clipping (or hiding) overflowing elements with a position different from // `initial` function getClippingParents(element) { var clippingParents = listScrollParents(getParentNode(element)); var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle(element).position) >= 0; var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; if (!isElement(clipperElement)) { return []; } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414 return clippingParents.filter(function (clippingParent) { return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body'; }); } // Gets the maximum area that the element is visible in due to any number of // clipping parents function getClippingRect(element, boundary, rootBoundary) { var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary); var clippingParents = [].concat(mainClippingParents, [rootBoundary]); var firstClippingParent = clippingParents[0]; var clippingRect = clippingParents.reduce(function (accRect, clippingParent) { var rect = getClientRectFromMixedType(element, clippingParent); accRect.top = Math.max(rect.top, accRect.top); accRect.right = Math.min(rect.right, accRect.right); accRect.bottom = Math.min(rect.bottom, accRect.bottom); accRect.left = Math.max(rect.left, accRect.left); return accRect; }, getClientRectFromMixedType(element, firstClippingParent)); clippingRect.width = clippingRect.right - clippingRect.left; clippingRect.height = clippingRect.bottom - clippingRect.top; clippingRect.x = clippingRect.left; clippingRect.y = clippingRect.top; return clippingRect; } function getVariation(placement) { return placement.split('-')[1]; } function getMainAxisFromPlacement(placement) { return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y'; } function computeOffsets(_ref) { var reference = _ref.reference, element = _ref.element, placement = _ref.placement; var basePlacement = placement ? getBasePlacement(placement) : null; var variation = placement ? getVariation(placement) : null; var commonX = reference.x + reference.width / 2 - element.width / 2; var commonY = reference.y + reference.height / 2 - element.height / 2; var offsets; switch (basePlacement) { case top: offsets = { x: commonX, y: reference.y - element.height }; break; case bottom: offsets = { x: commonX, y: reference.y + reference.height }; break; case right: offsets = { x: reference.x + reference.width, y: commonY }; break; case left: offsets = { x: reference.x - element.width, y: commonY }; break; default: offsets = { x: reference.x, y: reference.y }; } var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; if (mainAxis != null) { var len = mainAxis === 'y' ? 'height' : 'width'; switch (variation) { case start: offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2); break; case end: offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2); break; } } return offsets; } function getFreshSideObject() { return { top: 0, right: 0, bottom: 0, left: 0 }; } function mergePaddingObject(paddingObject) { return Object.assign(Object.assign({}, getFreshSideObject()), paddingObject); } function expandToHashMap(value, keys) { return keys.reduce(function (hashMap, key) { hashMap[key] = value; return hashMap; }, {}); } function detectOverflow(state, options) { if (options === void 0) { options = {}; } var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding; var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); var altContext = elementContext === popper ? reference : popper; var referenceElement = state.elements.reference; var popperRect = state.rects.popper; var element = state.elements[altBoundary ? altContext : elementContext]; var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary); var referenceClientRect = getBoundingClientRect(referenceElement); var popperOffsets = computeOffsets({ reference: referenceClientRect, element: popperRect, strategy: 'absolute', placement: placement }); var popperClientRect = rectToClientRect(Object.assign(Object.assign({}, popperRect), popperOffsets)); var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect // 0 or negative = within the clipping rect var overflowOffsets = { top: clippingClientRect.top - elementClientRect.top + paddingObject.top, bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, left: clippingClientRect.left - elementClientRect.left + paddingObject.left, right: elementClientRect.right - clippingClientRect.right + paddingObject.right }; var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element if (elementContext === popper && offsetData) { var offset = offsetData[placement]; Object.keys(overflowOffsets).forEach(function (key) { var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x'; overflowOffsets[key] += offset[axis] * multiply; }); } return overflowOffsets; } var INVALID_ELEMENT_ERROR = 'Popper: Invalid reference or popper argument provided. They must be either a DOM element or virtual element.'; var INFINITE_LOOP_ERROR = 'Popper: An infinite loop in the modifiers cycle has been detected! The cycle has been interrupted to prevent a browser crash.'; var DEFAULT_OPTIONS = { placement: 'bottom', modifiers: [], strategy: 'absolute' }; function areValidElements() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return !args.some(function (element) { return !(element && typeof element.getBoundingClientRect === 'function'); }); } function popperGenerator(generatorOptions) { if (generatorOptions === void 0) { generatorOptions = {}; } var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; return function createPopper(reference, popper, options) { if (options === void 0) { options = defaultOptions; } var state = { placement: 'bottom', orderedModifiers: [], options: Object.assign(Object.assign({}, DEFAULT_OPTIONS), defaultOptions), modifiersData: {}, elements: { reference: reference, popper: popper }, attributes: {}, styles: {} }; var effectCleanupFns = []; var isDestroyed = false; var instance = { state: state, setOptions: function setOptions(options) { cleanupModifierEffects(); state.options = Object.assign(Object.assign(Object.assign({}, defaultOptions), state.options), options); state.scrollParents = { reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [], popper: listScrollParents(popper) }; // Orders the modifiers based on their dependencies and `phase` // properties var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers state.orderedModifiers = orderedModifiers.filter(function (m) { return m.enabled; }); // Validate the provided modifiers so that the consumer will get warned // if one of the modifiers is invalid for any reason if (process.env.NODE_ENV !== "production") { var modifiers = uniqueBy([].concat(orderedModifiers, state.options.modifiers), function (_ref) { var name = _ref.name; return name; }); validateModifiers(modifiers); if (getBasePlacement(state.options.placement) === auto) { var flipModifier = state.orderedModifiers.find(function (_ref2) { var name = _ref2.name; return name === 'flip'; }); if (!flipModifier) { console.error(['Popper: "auto" placements require the "flip" modifier be', 'present and enabled to work.'].join(' ')); } } var _getComputedStyle = getComputedStyle(popper), marginTop = _getComputedStyle.marginTop, marginRight = _getComputedStyle.marginRight, marginBottom = _getComputedStyle.marginBottom, marginLeft = _getComputedStyle.marginLeft; // We no longer take into account `margins` on the popper, and it can // cause bugs with positioning, so we'll warn the consumer if ([marginTop, marginRight, marginBottom, marginLeft].some(function (margin) { return parseFloat(margin); })) { console.warn(['Popper: CSS "margin" styles cannot be used to apply padding', 'between the popper and its reference element or boundary.', 'To replicate margin, use the `offset` modifier, as well as', 'the `padding` option in the `preventOverflow` and `flip`', 'modifiers.'].join(' ')); } } runModifierEffects(); return instance.update(); }, // Sync update – it will always be executed, even if not necessary. This // is useful for low frequency updates where sync behavior simplifies the // logic. // For high frequency updates (e.g. `resize` and `scroll` events), always // prefer the async Popper#update method forceUpdate: function forceUpdate() { if (isDestroyed) { return; } var _state$elements = state.elements, reference = _state$elements.reference, popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements // anymore if (!areValidElements(reference, popper)) { if (process.env.NODE_ENV !== "production") { console.error(INVALID_ELEMENT_ERROR); } return; } // Store the reference and popper rects to be read by modifiers state.rects = { reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'), popper: getLayoutRect(popper) }; // Modifiers have the ability to reset the current update cycle. The // most common use case for this is the `flip` modifier changing the // placement, which then needs to re-run all the modifiers, because the // logic was previously ran for the previous placement and is therefore // stale/incorrect state.reset = false; state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier // is filled with the initial data specified by the modifier. This means // it doesn't persist and is fresh on each update. // To ensure persistent data, use `${name}#persistent` state.orderedModifiers.forEach(function (modifier) { return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); }); var __debug_loops__ = 0; for (var index = 0; index < state.orderedModifiers.length; index++) { if (process.env.NODE_ENV !== "production") { __debug_loops__ += 1; if (__debug_loops__ > 100) { console.error(INFINITE_LOOP_ERROR); break; } } if (state.reset === true) { state.reset = false; index = -1; continue; } var _state$orderedModifie = state.orderedModifiers[index], fn = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name; if (typeof fn === 'function') { state = fn({ state: state, options: _options, name: name, instance: instance }) || state; } } }, // Async and optimistically optimized update – it will not be executed if // not necessary (debounced to run at most once-per-tick) update: debounce(function () { return new Promise(function (resolve) { instance.forceUpdate(); resolve(state); }); }), destroy: function destroy() { cleanupModifierEffects(); isDestroyed = true; } }; if (!areValidElements(reference, popper)) { if (process.env.NODE_ENV !== "production") { console.error(INVALID_ELEMENT_ERROR); } return instance; } instance.setOptions(options).then(function (state) { if (!isDestroyed && options.onFirstUpdate) { options.onFirstUpdate(state); } }); // Modifiers have the ability to execute arbitrary code before the first // update cycle runs. They will be executed in the same order as the update // cycle. This is useful when a modifier adds some persistent data that // other modifiers need to use, but the modifier is run after the dependent // one. function runModifierEffects() { state.orderedModifiers.forEach(function (_ref3) { var name = _ref3.name, _ref3$options = _ref3.options, options = _ref3$options === void 0 ? {} : _ref3$options, effect = _ref3.effect; if (typeof effect === 'function') { var cleanupFn = effect({ state: state, name: name, instance: instance, options: options }); var noopFn = function noopFn() {}; effectCleanupFns.push(cleanupFn || noopFn); } }); } function cleanupModifierEffects() { effectCleanupFns.forEach(function (fn) { return fn(); }); effectCleanupFns = []; } return instance; }; } var passive = { passive: true }; function effect(_ref) { var state = _ref.state, instance = _ref.instance, options = _ref.options; var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize; var window = getWindow(state.elements.popper); var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); if (scroll) { scrollParents.forEach(function (scrollParent) { scrollParent.addEventListener('scroll', instance.update, passive); }); } if (resize) { window.addEventListener('resize', instance.update, passive); } return function () { if (scroll) { scrollParents.forEach(function (scrollParent) { scrollParent.removeEventListener('scroll', instance.update, passive); }); } if (resize) { window.removeEventListener('resize', instance.update, passive); } }; } // eslint-disable-next-line import/no-unused-modules var eventListeners = { name: 'eventListeners', enabled: true, phase: 'write', fn: function fn() {}, effect: effect, data: {} }; function popperOffsets(_ref) { var state = _ref.state, name = _ref.name; // Offsets are the actual position the popper needs to have to be // properly positioned near its reference element // This is the most basic placement, and will be adjusted by // the modifiers in the next step state.modifiersData[name] = computeOffsets({ reference: state.rects.reference, element: state.rects.popper, strategy: 'absolute', placement: state.placement }); } // eslint-disable-next-line import/no-unused-modules var popperOffsets$1 = { name: 'popperOffsets', enabled: true, phase: 'read', fn: popperOffsets, data: {} }; var round = Math.round; var unsetSides = { top: 'auto', right: 'auto', bottom: 'auto', left: 'auto' }; // Round the offsets to the nearest suitable subpixel based on the DPR. // Zooming can change the DPR, but it seems to report a value that will // cleanly divide the values into the appropriate subpixels. function roundOffsetsByDPR(_ref) { var x = _ref.x, y = _ref.y; var win = window; var dpr = win.devicePixelRatio || 1; return { x: round(round(x * dpr) / dpr) || 0, y: round(round(y * dpr) / dpr) || 0 }; } function mapToStyles(_ref2) { var _Object$assign2; var popper = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets; var _ref3 = roundOffsets === true ? roundOffsetsByDPR(offsets) : typeof roundOffsets === 'function' ? roundOffsets(offsets) : offsets, _ref3$x = _ref3.x, x = _ref3$x === void 0 ? 0 : _ref3$x, _ref3$y = _ref3.y, y = _ref3$y === void 0 ? 0 : _ref3$y; var hasX = offsets.hasOwnProperty('x'); var hasY = offsets.hasOwnProperty('y'); var sideX = left; var sideY = top; var win = window; if (adaptive) { var offsetParent = getOffsetParent(popper); if (offsetParent === getWindow(popper)) { offsetParent = getDocumentElement(popper); } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it /*:: offsetParent = (offsetParent: Element); */ if (placement === top) { sideY = bottom; y -= offsetParent.clientHeight - popperRect.height; y *= gpuAcceleration ? 1 : -1; } if (placement === left) { sideX = right; x -= offsetParent.clientWidth - popperRect.width; x *= gpuAcceleration ? 1 : -1; } } var commonStyles = Object.assign({ position: position }, adaptive && unsetSides); if (gpuAcceleration) { var _Object$assign; return Object.assign(Object.assign({}, commonStyles), {}, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) < 2 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); } return Object.assign(Object.assign({}, commonStyles), {}, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2)); } function computeStyles(_ref4) { var state = _ref4.state, options = _ref4.options; var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; if (process.env.NODE_ENV !== "production") { var transitionProperty = getComputedStyle(state.elements.popper).transitionProperty || ''; if (adaptive && ['transform', 'top', 'right', 'bottom', 'left'].some(function (property) { return transitionProperty.indexOf(property) >= 0; })) { console.warn(['Popper: Detected CSS transitions on at least one of the following', 'CSS properties: "transform", "top", "right", "bottom", "left".', '\n\n', 'Disable the "computeStyles" modifier\'s `adaptive` option to allow', 'for smooth transitions, or remove these properties from the CSS', 'transition declaration on the popper element if only transitioning', 'opacity or background-color for example.', '\n\n', 'We recommend using the popper element as a wrapper around an inner', 'element that can have any CSS property transitioned for animations.'].join(' ')); } } var commonStyles = { placement: getBasePlacement(state.placement), popper: state.elements.popper, popperRect: state.rects.popper, gpuAcceleration: gpuAcceleration }; if (state.modifiersData.popperOffsets != null) { state.styles.popper = Object.assign(Object.assign({}, state.styles.popper), mapToStyles(Object.assign(Object.assign({}, commonStyles), {}, { offsets: state.modifiersData.popperOffsets, position: state.options.strategy, adaptive: adaptive, roundOffsets: roundOffsets }))); } if (state.modifiersData.arrow != null) { state.styles.arrow = Object.assign(Object.assign({}, state.styles.arrow), mapToStyles(Object.assign(Object.assign({}, commonStyles), {}, { offsets: state.modifiersData.arrow, position: 'absolute', adaptive: false, roundOffsets: roundOffsets }))); } state.attributes.popper = Object.assign(Object.assign({}, state.attributes.popper), {}, { 'data-popper-placement': state.placement }); } // eslint-disable-next-line import/no-unused-modules var computeStyles$1 = { name: 'computeStyles', enabled: true, phase: 'beforeWrite', fn: computeStyles, data: {} }; // and applies them to the HTMLElements such as popper and arrow function applyStyles(_ref) { var state = _ref.state; Object.keys(state.elements).forEach(function (name) { var style = state.styles[name] || {}; var attributes = state.attributes[name] || {}; var element = state.elements[name]; // arrow is optional + virtual elements if (!isHTMLElement(element) || !getNodeName(element)) { return; } // Flow doesn't support to extend this property, but it's the most // effective way to apply styles to an HTMLElement // $FlowFixMe[cannot-write] Object.assign(element.style, style); Object.keys(attributes).forEach(function (name) { var value = attributes[name]; if (value === false) { element.removeAttribute(name); } else { element.setAttribute(name, value === true ? '' : value); } }); }); } function effect$1(_ref2) { var state = _ref2.state; var initialStyles = { popper: { position: state.options.strategy, left: '0', top: '0', margin: '0' }, arrow: { position: 'absolute' }, reference: {} }; Object.assign(state.elements.popper.style, initialStyles.popper); if (state.elements.arrow) { Object.assign(state.elements.arrow.style, initialStyles.arrow); } return function () { Object.keys(state.elements).forEach(function (name) { var element = state.elements[name]; var attributes = state.attributes[name] || {}; var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them var style = styleProperties.reduce(function (style, property) { style[property] = ''; return style; }, {}); // arrow is optional + virtual elements if (!isHTMLElement(element) || !getNodeName(element)) { return; } Object.assign(element.style, style); Object.keys(attributes).forEach(function (attribute) { element.removeAttribute(attribute); }); }); }; } // eslint-disable-next-line import/no-unused-modules var applyStyles$1 = { name: 'applyStyles', enabled: true, phase: 'write', fn: applyStyles, effect: effect$1, requires: ['computeStyles'] }; var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1]; var createPopper = /*#__PURE__*/popperGenerator({ defaultModifiers: defaultModifiers }); // eslint-disable-next-line import/no-unused-modules exports.createPopper = createPopper; exports.defaultModifiers = defaultModifiers; exports.detectOverflow = detectOverflow; exports.popperGenerator = popperGenerator; //# sourceMappingURL=popper-lite.js.map
import React from 'react'; import PropTypes from 'prop-types'; import { values, pickBy, has, omit, map, startCase, pick, remove } from '../../../utils/lodash'; import moment from 'moment'; import PieGraph from './PieGraph'; import { PieColors } from '../GraphColors'; import config from '../../../config'; import { compare } from '../sort'; function buildTitle(query, ytd_end_month, time_period) { const units = query.flow_type === 'QTY' ? 'Metric Tons' : 'U.S. Dollars'; const flow = query.trade_flow === 'EXP' ? ' Exports to ' : ' Imports from '; const ytd_label = 'YTD ' + ytd_end_month + ' '; const chart_title = 'Share of ' + query.reporter_countries + flow + 'Top 5 Partner Countries of ' + query.product_groups + ' in ' + units + ' - ' + time_period.replace('sum_', '').replace('ytd_', ytd_label); return chart_title; } const Footnote = ({query, total, last_updated}) => { const units = query.flow_type === 'QTY' ? ' metric tons' : ' U.S. dollars'; const last_updated_date = moment(last_updated).utc().format('MM-DD-YYYY'); return ( <p className="explorer__graph-footnote"> {config.footnote + ' Updated on ' + last_updated_date + '. Trade covered in the table is ' + parseFloat(total.toFixed(2)).toLocaleString() + units + '.'} </p> ); }; const ProductGroupPie = ({ data, query, last_updated, time_period }) => { const chartTitle = buildTitle(query, data[0].ytd_end_month, time_period); const sorted_data = data.sort(compare(time_period)).slice(); remove(sorted_data, function(n) { return n.partner_country === 'Other Countries'; }); const data_entries = sorted_data.slice(1, 6); const total = sorted_data[0][time_period]; const labels = map(data_entries, (entry) => { return entry.partner_country; }); labels.push('Rest of the World'); let percentage_subtotal = 0; const data_values = map(data_entries, (entry) => { let percentage = (entry[time_period]/total)*100; percentage_subtotal += percentage; return percentage.toFixed(2); }); data_values.push((100 - percentage_subtotal).toFixed(2)); return ( <div> <h3 className="explorer__chart-title">{chartTitle}</h3> <PieGraph data_values={data_values} labels={labels} time_period={time_period} /> <Footnote query={query} total={total} last_updated={last_updated}/> </div> ); }; export default ProductGroupPie;
const mongoose = require('mongoose'); const bcrypt = require('bcrypt-nodejs'); const Schema = mongoose.Schema; const UserSchema = new Schema({ username: { type: String, lowercase: true, unique: true, required: true, }, password: { type: String, required: true, }, }, { timestamps: true, }); // add pre-hook to salt+hash password on save // DO NOT USE ARROW FNS HERE UserSchema.pre('save', function (next) { const user = this; const SALT_FACTOR = 5; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(SALT_FACTOR, (err, salt) => { if (err) { return next(err); } bcrypt.hash(user.password, salt, null, (err, hash) => { if (err) { return next(err); } user.password = hash; next(); }); }); }); // add method to check password // DO NOT USE ARROW FNS HERE UserSchema.methods.comparePassword = function (candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { if (err) { return cb(err); } cb(null, isMatch); }); }; module.exports = mongoose.model('user', UserSchema);
/** * Module dependencies. */ var fs = require('fs') , package = JSON.parse(fs.readFileSync(__dirname+ '/../package.json')) , uglify = require('uglify-js'); /** * License headers. * * @api private */ var template = '/*! sink.%ext% build:' + package.version + ', %type%. Copyright(c) 2013 Eric Zhang, Michelle Bu, Rolland Wu MIT Licensed */' , prefix = '\n(function(exports){\n' , development = template.replace('%type%', 'development').replace('%ext%', 'js') , production = template.replace('%type%', 'production').replace('%ext%', 'min.js') , suffix = '\n})(this);\n'; /** * If statements, these allows you to create serveride & client side compatible * code using specially designed `if` statements that remove serverside * designed code from the source files * * @api private */ var starttagIF = '// if node' , endtagIF = '// end node'; var base = [ 'util.js' , 'syncedproxy.js' , 'sink.js' ]; /** * Builds a custom sinkJS client distribution based on the transports that you * need. You can configure the build to create development build or production * build (minified). * * @param {Array} transports The transports that needs to be bundled. * @param {Object} [options] Options to configure the building process. * @param {Function} callback Last argument should always be the callback * @callback {String|Boolean} err An optional argument, if it exists than an error * occurred during the build process. * @callback {String} result The result of the build process. * @api public */ var builder = module.exports = function () { var options, callback, error = null , args = Array.prototype.slice.call(arguments, 0) , settings = { minify: true , node: false , custom: [] }; // Fancy pancy argument support this makes any pattern possible mainly // because we require only one of each type args.forEach(function (arg) { var type = Object.prototype.toString.call(arg) .replace(/\[object\s(\w+)\]/gi , '$1' ).toLowerCase(); switch (type) { case 'object': return options = arg; case 'function': return callback = arg; } }); // Add defaults options = options || {}; // Merge the data for(var option in options) { settings[option] = options[option]; } // Start creating a dependencies chain with all the required files for the // custom sinkJS client bundle. var files = []; base.forEach(function (file) { files.push(__dirname + '/../lib/' + file); }); var results = {}; files.forEach(function (file) { fs.readFile(file, function (err, content) { if (err) error = err; results[file] = content; // check if we are done yet, or not.. Just by checking the size of the result // object. if (Object.keys(results).length !== files.length) return; // concatinate the file contents in order var code = development , ignore = 0; code += prefix; files.forEach(function (file) { code += results[file]; }); // check if we need to add custom code if (settings.custom.length) { settings.custom.forEach(function (content) { code += content; }); } // Search for conditional code blocks that need to be removed as they // where designed for a server side env. but only if we don't want to // make this build node compatible. if (!settings.node) { code = code.split('\n').filter(function (line) { // check if there are tags in here var start = line.indexOf(starttagIF) >= 0 , end = line.indexOf(endtagIF) >= 0 , ret = ignore; // ignore the current line if (start) { ignore++; ret = ignore; } // stop ignoring the next line if (end) { ignore--; } return ret == 0; }).join('\n'); } code += suffix; // check if we need to process it any further if (settings.minify) { var ast = uglify.parser.parse(code); ast = uglify.uglify.ast_mangle(ast); ast = uglify.uglify.ast_squeeze(ast); code = production + uglify.uglify.gen_code(ast, { ascii_only: true }); } callback(error, code); }) }) }; /** * Builder version is also the current client version * this way we don't have to do another include for the * clients version number and we can just include the builder. * * @type {String} * @api public */ builder.version = package.version; /** * Command line support, this allows us to generate builds without having * to load it as module. */ if (!module.parent){ // the first 2 are `node` and the path to this file, we don't need them var args = process.argv.slice(2); // build a development build builder(args.length ? args : false, { minify:false }, function (err, content) { if (err) return console.error(err); console.log(__dirname); fs.write( fs.openSync(__dirname + '/../dist/sink.js', 'w') , content , 0 , 'utf8' ); console.log('Successfully generated the development build: sink.js'); }); // and build a production build builder(args.length ? args : false, function (err, content) { if (err) return console.error(err); fs.write( fs.openSync(__dirname + '/../dist/sink.min.js', 'w') , content , 0 , 'utf8' ); console.log('Successfully generated the production build: sink.min.js'); }); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ Ext.define('sisprod.view.WorkRequestSource.AddWorkRequestSource', { extend: 'sisprod.view.base.BaseDataWindow', alias: 'widget.addWorkRequestSource', require: [ 'sisprod.view.base.BaseDataWindow' ], title: 'Agregar Origenes de Pedido', messages: { labels: { workRequestSourceName: 'Nombre de Origen', workRequestSourceAcronym: 'Acrónimo' } }, modal: true, width: 400, singleAddition: false, // height: 150, initComponent: function(){ var me = this; me.formOptions = { bodyPadding: 2, items: [ { xtype: 'textfield', grow: true, name: 'workRequestSourceName', fieldLabel: me.messages.labels.workRequestSourceName, anchor: '100%', allowBlank: false, maxLength: 100, fieldStyle: {textTransform: 'uppercase'} }, { xtype: 'textfield', grow: true, name: 'workRequestSourceAcronym', fieldLabel: me.messages.labels.workRequestSourceAcronym, anchor: '40%', maxLength: 6, fieldStyle: {textTransform: 'uppercase'} } ] }; me.callParent(arguments); } });
import { PRINTABLE_ASCII } from '../const'; import v from '../voca'; describe('isUpperCase', function() { it('should return true for an upper case string', function() { expect(v.isUpperCase('A')).toBe(true); expect(v.isUpperCase('HELLOWORLD')).toBe(true); expect(v.isUpperCase('WELCOMETOEARTH')).toBe(true); expect(v.isUpperCase('ÁÉÈÊËÍÎÏÓÔÚÛÝÀÒÜÇÄÖÂÙŸÃÕÑ')).toBe(true); }); it('should return true for a lower case string representation of an object', function() { expect(v.isUpperCase(['ROBOCOP'])).toBe(true); expect( v.isUpperCase({ toString: function() { return 'BATMAN'; }, }) ).toBe(true); }); it('should return false for a string containing lower case characters', function() { expect(v.isUpperCase('Helloworld')).toBe(false); expect(v.isUpperCase('WeLCOMETOEARTH')).toBe(false); }); it('should return false for a boolean', function() { expect(v.isUpperCase(true)).toBe(false); expect(v.isUpperCase(false)).toBe(false); }); it('should return false for a string containing characters different than upper case', function() { expect(v.isUpperCase('hello world!')).toBe(false); expect(v.isUpperCase('No one cared who I was until I put on the mask.')).toBe(false); expect(v.isUpperCase('\n')).toBe(false); expect(v.isUpperCase('\t')).toBe(false); expect(v.isUpperCase(' ')).toBe(false); expect(v.isUpperCase('')).toBe(false); expect(v.isUpperCase(PRINTABLE_ASCII)).toBe(false); }); it('should return false for a non upper case string representation of an object', function() { expect(v.isUpperCase(['RoboCop'])).toBe(false); expect( v.isUpperCase({ toString: function() { return 'Batman'; }, }) ).toBe(false); }); it('should return false for a number or numeric string', function() { expect(v.isUpperCase(0)).toBe(false); expect(v.isUpperCase(-1500)).toBe(false); expect(v.isUpperCase(2017)).toBe(false); expect(v.isUpperCase('0')).toBe(false); expect(v.isUpperCase('1998')).toBe(false); }); it('should return false for a null', function() { expect(v.isUpperCase(null)).toBe(false); }); it('should return false for an undefined', function() { expect(v.isUpperCase(undefined)).toBe(false); expect(v.isUpperCase()).toBe(false); }); });
/*! UIkit 3.6.18 | https://www.getuikit.com | (c) 2014 - 2021 YOOtheme | MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikitparallax', ['uikit-util'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.UIkitParallax = factory(global.UIkit.util)); }(this, (function (uikitUtil) { 'use strict'; var Media = { props: { media: Boolean }, data: { media: false }, computed: { matchMedia: function() { var media = toMedia(this.media); return !media || window.matchMedia(media).matches; } } }; function toMedia(value) { if (uikitUtil.isString(value)) { if (value[0] === '@') { var name = "breakpoint-" + (value.substr(1)); value = uikitUtil.toFloat(uikitUtil.getCssVar(name)); } else if (isNaN(value)) { return value; } } return value && !isNaN(value) ? ("(min-width: " + value + "px)") : false; } uikitUtil.memoize(function (src) { return new uikitUtil.Promise(function (resolve, reject) { if (!src) { reject(); return; } if (uikitUtil.startsWith(src, 'data:')) { resolve(decodeURIComponent(src.split(',')[1])); } else { uikitUtil.ajax(src).then( function (xhr) { return resolve(xhr.response); }, function () { return reject('SVG not found.'); } ); } }); } ); function getMaxPathLength(el) { return Math.ceil(Math.max.apply(Math, [ 0 ].concat( uikitUtil.$$('[stroke]', el).map(function (stroke) { try { return stroke.getTotalLength(); } catch (e) { return 0; } }) ))); } var props = ['x', 'y', 'bgx', 'bgy', 'rotate', 'scale', 'color', 'backgroundColor', 'borderColor', 'opacity', 'blur', 'hue', 'grayscale', 'invert', 'saturate', 'sepia', 'fopacity', 'stroke']; var Parallax = { mixins: [Media], props: props.reduce(function (props, prop) { props[prop] = 'list'; return props; }, {}), data: props.reduce(function (data, prop) { data[prop] = undefined; return data; }, {}), computed: { props: function(properties, $el) { var this$1 = this; return props.reduce(function (props, prop) { if (uikitUtil.isUndefined(properties[prop])) { return props; } var isColor = prop.match(/color/i); var isCssProp = isColor || prop === 'opacity'; var pos, bgPos, diff; var steps = properties[prop].slice(); if (isCssProp) { uikitUtil.css($el, prop, ''); } if (steps.length < 2) { steps.unshift((prop === 'scale' ? 1 : isCssProp ? uikitUtil.css($el, prop) : 0) || 0); } var unit = getUnit(steps); if (isColor) { var ref = $el.style; var color = ref.color; steps = steps.map(function (step) { return parseColor($el, step); }); $el.style.color = color; } else if (uikitUtil.startsWith(prop, 'bg')) { var attr = prop === 'bgy' ? 'height' : 'width'; steps = steps.map(function (step) { return uikitUtil.toPx(step, attr, this$1.$el); }); uikitUtil.css($el, ("background-position-" + (prop[2])), ''); bgPos = uikitUtil.css($el, 'backgroundPosition').split(' ')[prop[2] === 'x' ? 0 : 1]; // IE 11 can't read background-position-[x|y] if (this$1.covers) { var min = Math.min.apply(Math, steps); var max = Math.max.apply(Math, steps); var down = steps.indexOf(min) < steps.indexOf(max); diff = max - min; steps = steps.map(function (step) { return step - (down ? min : max); }); pos = (down ? -diff : 0) + "px"; } else { pos = bgPos; } } else { steps = steps.map(uikitUtil.toFloat); } if (prop === 'stroke') { if (!steps.some(function (step) { return step; })) { return props; } var length = getMaxPathLength(this$1.$el); uikitUtil.css($el, 'strokeDasharray', length); if (unit === '%') { steps = steps.map(function (step) { return step * length / 100; }); } steps = steps.reverse(); prop = 'strokeDashoffset'; } props[prop] = {steps: steps, unit: unit, pos: pos, bgPos: bgPos, diff: diff}; return props; }, {}); }, bgProps: function() { var this$1 = this; return ['bgx', 'bgy'].filter(function (bg) { return bg in this$1.props; }); }, covers: function(_, $el) { return covers($el); } }, disconnected: function() { delete this._image; }, update: { read: function(data) { var this$1 = this; if (!this.matchMedia) { return; } if (!data.image && this.covers && this.bgProps.length) { var src = uikitUtil.css(this.$el, 'backgroundImage').replace(/^none|url\(["']?(.+?)["']?\)$/, '$1'); if (src) { var img = new Image(); img.src = src; data.image = img; if (!img.naturalWidth) { img.onload = function () { return this$1.$update(); }; } } } var image = data.image; if (!image || !image.naturalWidth) { return; } var dimEl = { width: this.$el.offsetWidth, height: this.$el.offsetHeight }; var dimImage = { width: image.naturalWidth, height: image.naturalHeight }; var dim = uikitUtil.Dimensions.cover(dimImage, dimEl); this.bgProps.forEach(function (prop) { var ref = this$1.props[prop]; var diff = ref.diff; var bgPos = ref.bgPos; var steps = ref.steps; var attr = prop === 'bgy' ? 'height' : 'width'; var span = dim[attr] - dimEl[attr]; if (span < diff) { dimEl[attr] = dim[attr] + diff - span; } else if (span > diff) { var posPercentage = dimEl[attr] / uikitUtil.toPx(bgPos, attr, this$1.$el); if (posPercentage) { this$1.props[prop].steps = steps.map(function (step) { return step - (span - diff) / posPercentage; }); } } dim = uikitUtil.Dimensions.cover(dimImage, dimEl); }); data.dim = dim; }, write: function(ref) { var dim = ref.dim; if (!this.matchMedia) { uikitUtil.css(this.$el, {backgroundSize: '', backgroundRepeat: ''}); return; } dim && uikitUtil.css(this.$el, { backgroundSize: ((dim.width) + "px " + (dim.height) + "px"), backgroundRepeat: 'no-repeat' }); }, events: ['resize'] }, methods: { reset: function() { var this$1 = this; uikitUtil.each(this.getCss(0), function (_, prop) { return uikitUtil.css(this$1.$el, prop, ''); }); }, getCss: function(percent) { var ref = this; var props = ref.props; return Object.keys(props).reduce(function (css, prop) { var ref = props[prop]; var steps = ref.steps; var unit = ref.unit; var pos = ref.pos; var value = getValue(steps, percent); switch (prop) { // transforms case 'x': case 'y': { unit = unit || 'px'; css.transform += " translate" + (uikitUtil.ucfirst(prop)) + "(" + (uikitUtil.toFloat(value).toFixed(unit === 'px' ? 0 : 2)) + unit + ")"; break; } case 'rotate': unit = unit || 'deg'; css.transform += " rotate(" + (value + unit) + ")"; break; case 'scale': css.transform += " scale(" + value + ")"; break; // bg image case 'bgy': case 'bgx': css[("background-position-" + (prop[2]))] = "calc(" + pos + " + " + value + "px)"; break; // color case 'color': case 'backgroundColor': case 'borderColor': { var ref$1 = getStep(steps, percent); var start = ref$1[0]; var end = ref$1[1]; var p = ref$1[2]; css[prop] = "rgba(" + (start.map(function (value, i) { value = value + p * (end[i] - value); return i === 3 ? uikitUtil.toFloat(value) : parseInt(value, 10); }).join(',')) + ")"; break; } // CSS Filter case 'blur': unit = unit || 'px'; css.filter += " blur(" + (value + unit) + ")"; break; case 'hue': unit = unit || 'deg'; css.filter += " hue-rotate(" + (value + unit) + ")"; break; case 'fopacity': unit = unit || '%'; css.filter += " opacity(" + (value + unit) + ")"; break; case 'grayscale': case 'invert': case 'saturate': case 'sepia': unit = unit || '%'; css.filter += " " + prop + "(" + (value + unit) + ")"; break; default: css[prop] = value; } return css; }, {transform: '', filter: ''}); } } }; function parseColor(el, color) { return uikitUtil.css(uikitUtil.css(el, 'color', color), 'color') .split(/[(),]/g) .slice(1, -1) .concat(1) .slice(0, 4) .map(uikitUtil.toFloat); } function getStep(steps, percent) { var count = steps.length - 1; var index = Math.min(Math.floor(count * percent), count - 1); var step = steps.slice(index, index + 2); step.push(percent === 1 ? 1 : percent % (1 / count) * count); return step; } function getValue(steps, percent, digits) { if ( digits === void 0 ) digits = 2; var ref = getStep(steps, percent); var start = ref[0]; var end = ref[1]; var p = ref[2]; return (uikitUtil.isNumber(start) ? start + Math.abs(start - end) * p * (start < end ? 1 : -1) : +end ).toFixed(digits); } function getUnit(steps) { return steps.reduce(function (unit, step) { return uikitUtil.isString(step) && step.replace(/-|\d/g, '').trim() || unit; }, ''); } function covers(el) { var ref = el.style; var backgroundSize = ref.backgroundSize; var covers = uikitUtil.css(uikitUtil.css(el, 'backgroundSize', ''), 'backgroundSize') === 'cover'; el.style.backgroundSize = backgroundSize; return covers; } var Component = { mixins: [Parallax], props: { target: String, viewport: Number, easing: Number }, data: { target: false, viewport: 1, easing: 1 }, computed: { target: function(ref, $el) { var target = ref.target; return getOffsetElement(target && uikitUtil.query(target, $el) || $el); } }, update: { read: function(ref, types) { var percent = ref.percent; if (!types.has('scroll')) { percent = false; } if (!this.matchMedia) { return; } var prev = percent; percent = ease(uikitUtil.scrolledOver(this.target) / (this.viewport || 1), this.easing); return { percent: percent, style: prev !== percent ? this.getCss(percent) : false }; }, write: function(ref) { var style = ref.style; if (!this.matchMedia) { this.reset(); return; } style && uikitUtil.css(this.$el, style); }, events: ['scroll', 'resize'] } }; function ease(percent, easing) { return uikitUtil.clamp(percent * (1 - (easing - easing * percent))); } // SVG elements do not inherit from HTMLElement function getOffsetElement(el) { return el ? 'offsetTop' in el ? el : getOffsetElement(uikitUtil.parent(el)) : document.body; } if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('parallax', Component); } return Component; })));
'use strict'; var gulp = require('gulp'); var paths = gulp.paths; var util = require('util'); var browserSync = require('browser-sync'); var middleware = require('./proxy'); function browserSyncInit(baseDir, files, browser) { browser = browser === undefined ? 'default' : browser; var routes = null; if(baseDir === paths.src || (util.isArray(baseDir) && baseDir.indexOf(paths.src) !== -1)) { routes = { '/bower_components': 'bower_components' }; } browserSync.instance = browserSync.init(files, { startPath: '/', server: { baseDir: baseDir, middleware: middleware, routes: routes }, browser: browser }); } gulp.task('serve', ['watch'], function () { browserSyncInit([ paths.tmp + '/serve', paths.src, paths.lib ], [ paths.tmp + '/serve/app/**/*.css', paths.src + '/app/**/*.js', paths.lib + '/**/*.js', paths.src + 'src/assets/images/**/*', paths.tmp + '/serve/*.html', paths.tmp + '/serve/app/**/*.html', paths.src + '/app/**/*.html' ]); }); gulp.task('serve:dist', ['build'], function () { browserSyncInit(paths.dist.demo); }); gulp.task('serve:e2e', ['inject'], function () { browserSyncInit([paths.tmp + '/serve', paths.src], null, []); }); gulp.task('serve:e2e-dist', ['build'], function () { browserSyncInit(paths.dist, null, []); });
/* * */ 'use strict'; moduloPlaza.controller('PlazaNewController', ['$scope', '$routeParams', '$location', 'serverService', 'plazaService', 'sharedSpaceService', '$filter', '$uibModal', function ($scope, $routeParams, $location, serverService, plazaService, sharedSpaceService, $filter, $uibModal) { $scope.fields = plazaService.getFields(); $scope.obtitle = plazaService.getObTitle(); $scope.icon = plazaService.getIcon(); $scope.ob = plazaService.getTitle(); $scope.title = "Creando un nuevo " + $scope.obtitle; $scope.op = "new"; $scope.status = null; $scope.debugging = serverService.debugging(); $scope.bean = {}; //---- $scope.bean.obj_usuarioC = {"id": 0}; if ($routeParams.id_usuarioC) { serverService.promise_getOne('usuario', $routeParams.id_usuarioC).then(function (response) { if (response.data.message.id != 0) { $scope.bean.obj_usuarioC = response.data.message; $scope.show_obj_usuarioC = false; $scope.title = "Nuevo usuario con nombre" + $scope.bean.obj_usuarioC.nombre; } }); } else { $scope.show_obj_usuarioC = true; } //---- $scope.bean.obj_usuarioV = {"id": 0}; if ($routeParams.id_usuarioV) { serverService.promise_getOne('usuario', $routeParams.id_usuarioV).then(function (response) { if (response.data.message.id != 0) { $scope.bean.obj_usuarioV = response.data.message; $scope.show_obj_usuarioV = false; $scope.title = "Nuevo usuario con nombre" + $scope.bean.obj_usuarioV.nombre; } }); } else { $scope.show_obj_usuarioV = true; } //---- $scope.bean.obj_oferta = {"id": 0}; if ($routeParams.id_oferta) { serverService.promise_getOne('oferta', $routeParams.id_oferta).then(function (response) { if (response.data.message.id != 0) { $scope.bean.obj_oferta = response.data.message; $scope.show_obj_oferta = false; $scope.title = "Nueva oferta del tipo" + $scope.bean.obj_oferta.id; } }); } else { $scope.show_obj_oferta = true; } //----- $scope.save = function () { if ($scope.bean.obj_oferta.id <= 0) { $scope.bean.obj_oferta.id = null; } if ($scope.bean.obj_usuarioC.id <= 0) { $scope.bean.obj_usuarioC.id = null; } if ($scope.bean.obj_usuarioV.id <= 0) { $scope.bean.obj_usuarioV.id = null; } $scope.bean.fecha_venta = $filter('date')($scope.bean.fecha_venta, "dd/MM/yyyy"); $scope.bean.fecha_compra = $filter('date')($scope.bean.fecha_compra, "dd/MM/yyyy"); var jsonToSend = {json: JSON.stringify(serverService.array_identificarArray($scope.bean))}; serverService.promise_setOne($scope.ob, jsonToSend).then(function (response) { if (response.status == 200) { if (response.data.status == 200) { $scope.response = response; $scope.status = "El registro " + $scope.obtitle + " se ha creado con id = " + response.data.message; $scope.bean.id = response.data.message; } else { $scope.status = "Error en la recepción de datos del servidor"; } } else { $scope.status = "Error en la recepción de datos del servidor"; } }).catch(function (data) { $scope.status = "Error en la recepción de datos del servidor"; }); ; }; $scope.back = function () { window.history.back(); }; $scope.close = function () { $location.path('/home'); }; $scope.plist = function () { $location.path('/' + $scope.ob + '/plist'); }; }]);
/*globals define, module, Symbol */ (function (globals) { 'use strict'; var strings, messages, predicates, functions, assert, not, maybe, collections, slice; strings = { v: 'value', n: 'number', s: 'string', b: 'boolean', o: 'object', t: 'type', a: 'array', al: 'array-like', i: 'iterable', d: 'date', f: 'function', l: 'length' }; messages = {}; predicates = {}; [ { n: 'equal', f: equal, s: 'v' }, { n: 'undefined', f: isUndefined, s: 'v' }, { n: 'null', f: isNull, s: 'v' }, { n: 'assigned', f: assigned, s: 'v' }, { n: 'includes', f: includes, s: 'v' }, { n: 'zero', f: zero, s: 'n' }, { n: 'infinity', f: infinity, s: 'n' }, { n: 'number', f: number, s: 'n' }, { n: 'integer', f: integer, s: 'n' }, { n: 'even', f: even, s: 'n' }, { n: 'odd', f: odd, s: 'n' }, { n: 'greater', f: greater, s: 'n' }, { n: 'less', f: less, s: 'n' }, { n: 'between', f: between, s: 'n' }, { n: 'greaterOrEqual', f: greaterOrEqual, s: 'n' }, { n: 'lessOrEqual', f: lessOrEqual, s: 'n' }, { n: 'inRange', f: inRange, s: 'n' }, { n: 'positive', f: positive, s: 'n' }, { n: 'negative', f: negative, s: 'n' }, { n: 'string', f: string, s: 's' }, { n: 'emptyString', f: emptyString, s: 's' }, { n: 'nonEmptyString', f: nonEmptyString, s: 's' }, { n: 'contains', f: contains, s: 's' }, { n: 'match', f: match, s: 's' }, { n: 'boolean', f: boolean, s: 'b' }, { n: 'object', f: object, s: 'o' }, { n: 'emptyObject', f: emptyObject, s: 'o' }, { n: 'instance', f: instance, s: 't' }, { n: 'builtIn', f: builtIn, s: 't' }, { n: 'userDefined', f: userDefined, s: 't' }, { n: 'like', f: like, s: 't' }, { n: 'array', f: array, s: 'a' }, { n: 'emptyArray', f: emptyArray, s: 'a' }, { n: 'arrayLike', f: arrayLike, s: 'al' }, { n: 'iterable', f: iterable, s: 'i' }, { n: 'date', f: date, s: 'd' }, { n: 'function', f: isFunction, s: 'f' }, { n: 'hasLength', f: hasLength, s: 'l' }, ].map(function (data) { messages[data.n] = 'Invalid ' + strings[data.s]; predicates[data.n] = data.f; }); functions = { apply: apply, map: map, all: all, any: any }; collections = [ 'array', 'arrayLike', 'iterable', 'object' ]; slice = Array.prototype.slice; functions = mixin(functions, predicates); assert = createModifiedPredicates(assertModifier, assertImpl); not = createModifiedPredicates(notModifier, notImpl); maybe = createModifiedPredicates(maybeModifier, maybeImpl); assert.not = createModifiedModifier(assertModifier, not); assert.maybe = createModifiedModifier(assertModifier, maybe); collections.forEach(createOfPredicates); createOfModifiers(assert, assertModifier); createOfModifiers(not, notModifier); collections.forEach(createMaybeOfModifiers); exportFunctions(mixin(functions, { assert: assert, not: not, maybe: maybe })); /** * Public function `equal`. * * Returns true if `lhs` and `rhs` are strictly equal, without coercion. * Returns false otherwise. */ function equal (lhs, rhs) { return lhs === rhs; } /** * Public function `undefined`. * * Returns true if `data` is undefined, false otherwise. */ function isUndefined (data) { return data === undefined; } /** * Public function `null`. * * Returns true if `data` is null, false otherwise. */ function isNull (data) { return data === null; } /** * Public function `assigned`. * * Returns true if `data` is not null or undefined, false otherwise. */ function assigned (data) { return ! isUndefined(data) && ! isNull(data); } /** * Public function `zero`. * * Returns true if `data` is zero, false otherwise. */ function zero (data) { return data === 0; } /** * Public function `infinity`. * * Returns true if `data` is positive or negative infinity, false otherwise. */ function infinity (data) { return data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY; } /** * Public function `number`. * * Returns true if `data` is a number, false otherwise. */ function number (data) { return typeof data === 'number' && isNaN(data) === false && data !== Number.POSITIVE_INFINITY && data !== Number.NEGATIVE_INFINITY; } /** * Public function `integer`. * * Returns true if `data` is an integer, false otherwise. */ function integer (data) { return number(data) && data % 1 === 0; } /** * Public function `even`. * * Returns true if `data` is an even number, false otherwise. */ function even (data) { return number(data) && data % 2 === 0; } /** * Public function `odd`. * * Returns true if `data` is an odd number, false otherwise. */ function odd (data) { return integer(data) && !even(data); } /** * Public function `greater`. * * Returns true if `lhs` is a number greater than `rhs`, false otherwise. */ function greater (lhs, rhs) { return number(lhs) && lhs > rhs; } /** * Public function `less`. * * Returns true if `lhs` is a number less than `rhs`, false otherwise. */ function less (lhs, rhs) { return number(lhs) && lhs < rhs; } /** * Public function `between`. * * Returns true if `data` is a number between `x` and `y`, false otherwise. */ function between (data, x, y) { if (x < y) { return greater(data, x) && less(data, y); } return less(data, x) && greater(data, y); } /** * Public function `greaterOrEqual`. * * Returns true if `lhs` is a number greater than or equal to `rhs`, false * otherwise. */ function greaterOrEqual (lhs, rhs) { return number(lhs) && lhs >= rhs; } /** * Public function `lessOrEqual`. * * Returns true if `lhs` is a number less than or equal to `rhs`, false * otherwise. */ function lessOrEqual (lhs, rhs) { return number(lhs) && lhs <= rhs; } /** * Public function `inRange`. * * Returns true if `data` is a number in the range `x..y`, false otherwise. */ function inRange (data, x, y) { if (x < y) { return greaterOrEqual(data, x) && lessOrEqual(data, y); } return lessOrEqual(data, x) && greaterOrEqual(data, y); } /** * Public function `positive`. * * Returns true if `data` is a positive number, false otherwise. */ function positive (data) { return greater(data, 0); } /** * Public function `negative`. * * Returns true if `data` is a negative number, false otherwise. */ function negative (data) { return less(data, 0); } /** * Public function `string`. * * Returns true if `data` is a string, false otherwise. */ function string (data) { return typeof data === 'string'; } /** * Public function `emptyString`. * * Returns true if `data` is the empty string, false otherwise. */ function emptyString (data) { return data === ''; } /** * Public function `nonEmptyString`. * * Returns true if `data` is a non-empty string, false otherwise. */ function nonEmptyString (data) { return string(data) && data !== ''; } /** * Public function `contains`. * * Returns true if `data` is a string that contains `substring`, false * otherwise. */ function contains (data, substring) { return string(data) && data.indexOf(substring) !== -1; } /** * Public function `match`. * * Returns true if `data` is a string that matches `regex`, false otherwise. */ function match (data, regex) { return string(data) && !! data.match(regex); } /** * Public function `boolean`. * * Returns true if `data` is a boolean value, false otherwise. */ function boolean (data) { return data === false || data === true; } /** * Public function `object`. * * Returns true if `data` is a plain-old JS object, false otherwise. */ function object (data) { return Object.prototype.toString.call(data) === '[object Object]'; } /** * Public function `emptyObject`. * * Returns true if `data` is an empty object, false otherwise. */ function emptyObject (data) { return object(data) && Object.keys(data).length === 0; } /** * Public function `instance`. * * Returns true if `data` is an instance of `prototype`, false otherwise. */ function instance (data, prototype) { try { return data instanceof prototype; } catch (error) { return false; } } /** * Public function `builtIn`. * * Returns true if `data` is an instance of `prototype`, false otherwise. * Assumes `prototype` is a standard built-in object and additionally checks * the result of Object.prototype.toString. */ function builtIn (data, prototype) { try { return instance(data, prototype) || Object.prototype.toString.call(data) === '[object ' + prototype.name + ']'; } catch (error) { return false; } } /** * Public function `userDefined`. * * Returns true if `data` is an instance of `prototype`, false otherwise. * Assumes `prototype` is a user-defined object and additionally checks the * value of constructor.name. */ function userDefined (data, prototype) { try { return instance(data, prototype) || data.constructor.name === prototype.name; } catch (error) { return false; } } /** * Public function `like`. * * Tests whether `data` 'quacks like a duck'. Returns true if `data` has all * of the properties of `archetype` (the 'duck'), false otherwise. */ function like (data, archetype) { var name; for (name in archetype) { if (archetype.hasOwnProperty(name)) { if (data.hasOwnProperty(name) === false || typeof data[name] !== typeof archetype[name]) { return false; } if (object(data[name]) && like(data[name], archetype[name]) === false) { return false; } } } return true; } /** * Public function `array`. * * Returns true if `data` is an array, false otherwise. */ function array (data) { return Array.isArray(data); } /** * Public function `emptyArray`. * * Returns true if `data` is an empty array, false otherwise. */ function emptyArray (data) { return array(data) && data.length === 0; } /** * Public function `arrayLike`. * * Returns true if `data` is an array-like object, false otherwise. */ function arrayLike (data) { return assigned(data) && number(data.length); } /** * Public function `iterable`. * * Returns true if `data` is an iterable, false otherwise. */ function iterable (data) { if (typeof Symbol === 'undefined') { // Fall back to `arrayLike` predicate in pre-ES6 environments. return arrayLike(data); } return assigned(data) && isFunction(data[Symbol.iterator]); } /** * Public function `includes`. * * Returns true if `data` contains `value`, false otherwise. */ function includes (data, value) { var iterator, iteration; if (not.assigned(data)) { return false; } try { if (typeof Symbol !== 'undefined' && data[Symbol.iterator] && isFunction(data.values)) { iterator = data.values(); do { iteration = iterator.next(); if (iteration.value === value) { return true; } } while (! iteration.done); return false; } Object.keys(data).forEach(function (key) { if (data[key] === value) { throw 0; } }); } catch (ignore) { return true; } return false; } /** * Public function `hasLength`. * * Returns true if `data` has a length property that equals `length`, false * otherwise. */ function hasLength (data, length) { return assigned(data) && data.length === length; } /** * Public function `date`. * * Returns true if `data` is a valid date, false otherwise. */ function date (data) { return builtIn(data, Date) && ! isNaN(data.getTime()); } /** * Public function `function`. * * Returns true if `data` is a function, false otherwise. */ function isFunction (data) { return typeof data === 'function'; } /** * Public function `apply`. * * Maps each value from the `data` to the corresponding predicate and returns * the result array. If the same function is to be applied across all of the * data, a single predicate function may be passed in. * */ function apply (data, predicates) { assert.array(data); if (isFunction(predicates)) { return data.map(function (value) { return predicates(value); }); } assert.array(predicates); assert.hasLength(data, predicates.length); return data.map(function (value, index) { return predicates[index](value); }); } /** * Public function `map`. * * Maps each value from the `data` to the corresponding predicate and returns * the result object. Supports nested objects. If the `data` is not nested and * the same function is to be applied across all of it, a single predicate * function may be passed in. * */ function map (data, predicates) { assert.object(data); if (isFunction(predicates)) { return mapSimple(data, predicates); } assert.object(predicates); return mapComplex(data, predicates); } function mapSimple (data, predicate) { var result = {}; Object.keys(data).forEach(function (key) { result[key] = predicate(data[key]); }); return result; } function mapComplex (data, predicates) { var result = {}; Object.keys(predicates).forEach(function (key) { var predicate = predicates[key]; if (isFunction(predicate)) { if (not.assigned(data)) { result[key] = !!predicate._isMaybefied; } else { result[key] = predicate(data[key]); } } else if (object(predicate)) { result[key] = mapComplex(data[key], predicate); } }); return result; } /** * Public function `all` * * Check that all boolean values are true * in an array (returned from `apply`) * or object (returned from `map`). * */ function all (data) { if (array(data)) { return testArray(data, false); } assert.object(data); return testObject(data, false); } function testArray (data, result) { var i; for (i = 0; i < data.length; i += 1) { if (data[i] === result) { return result; } } return !result; } function testObject (data, result) { var key, value; for (key in data) { if (data.hasOwnProperty(key)) { value = data[key]; if (object(value) && testObject(value, result) === result) { return result; } if (value === result) { return result; } } } return !result; } /** * Public function `any` * * Check that at least one boolean value is true * in an array (returned from `apply`) * or object (returned from `map`). * */ function any (data) { if (array(data)) { return testArray(data, true); } assert.object(data); return testObject(data, true); } function mixin (target, source) { Object.keys(source).forEach(function (key) { target[key] = source[key]; }); return target; } /** * Public modifier `assert`. * * Throws if `predicate` returns false. */ function assertModifier (predicate, defaultMessage) { return function () { assertPredicate(predicate, arguments, defaultMessage); }; } function assertPredicate (predicate, args, defaultMessage) { var message = args[args.length - 1]; assertImpl(predicate.apply(null, args), nonEmptyString(message) ? message : defaultMessage); } function assertImpl (value, message) { if (value === false) { throw new Error(message || 'Assertion failed'); } } /** * Public modifier `not`. * * Negates `predicate`. */ function notModifier (predicate) { return function () { return notImpl(predicate.apply(null, arguments)); }; } function notImpl (value) { return !value; } /** * Public modifier `maybe`. * * Returns true if predicate argument is null or undefined, * otherwise propagates the return value from `predicate`. */ function maybeModifier (predicate) { var modifiedPredicate = function () { if (not.assigned(arguments[0])) { return true; } return predicate.apply(null, arguments); }; // Hackishly indicate that this is a maybe.xxx predicate. // Without this flag, the alternative would be to iterate // through the maybe predicates or use indexOf to check, // which would be time-consuming. modifiedPredicate._isMaybefied = true; return modifiedPredicate; } function maybeImpl (value) { if (assigned(value) === false) { return true; } return value; } /** * Public modifier `of`. * * Applies the chained predicate to members of the collection. */ function ofModifier (target, type, predicate) { return function () { var collection, args; collection = arguments[0]; if (target === 'maybe' && not.assigned(collection)) { return true; } if (!type(collection)) { return false; } collection = coerceCollection(type, collection); args = slice.call(arguments, 1); try { collection.forEach(function (item) { if ( (target !== 'maybe' || assigned(item)) && !predicate.apply(null, [ item ].concat(args)) ) { // TODO: Replace with for...of when ES6 is required. throw 0; } }); } catch (ignore) { return false; } return true; }; } function coerceCollection (type, collection) { switch (type) { case arrayLike: return slice.call(collection); case object: return Object.keys(collection).map(function (key) { return collection[key]; }); default: return collection; } } function createModifiedPredicates (modifier, object) { return createModifiedFunctions([ modifier, predicates, object ]); } function createModifiedFunctions (args) { var modifier, object, functions, result; modifier = args.shift(); object = args.pop(); functions = args.pop(); result = object || {}; Object.keys(functions).forEach(function (key) { Object.defineProperty(result, key, { configurable: false, enumerable: true, writable: false, value: modifier.apply(null, args.concat(functions[key], messages[key])) }); }); return result; } function createModifiedModifier (modifier, modified) { return createModifiedFunctions([ modifier, modified, null ]); } function createOfPredicates (key) { predicates[key].of = createModifiedFunctions( [ ofModifier.bind(null, null), predicates[key], predicates, null ] ); } function createOfModifiers (base, modifier) { collections.forEach(function (key) { base[key].of = createModifiedModifier(modifier, predicates[key].of); }); } function createMaybeOfModifiers (key) { maybe[key].of = createModifiedFunctions( [ ofModifier.bind(null, 'maybe'), predicates[key], predicates, null ] ); assert.maybe[key].of = createModifiedModifier(assertModifier, maybe[key].of); assert.not[key].of = createModifiedModifier(assertModifier, not[key].of); } function exportFunctions (functions) { if (typeof define === 'function' && define.amd) { define(function () { return functions; }); } else if (typeof module !== 'undefined' && module !== null && module.exports) { module.exports = functions; } else { globals.check = functions; } } }(this));
var FormWizard = function () { return { init: function () { function e(e) { return e.id ? "<img class='flag' src='../../assets/global/img/flags/" + e.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + e.text : e.text } if (jQuery().bootstrapWizard) { $("#country_list").select2({ placeholder: "Select", allowClear: !0, formatResult: e, width: "auto", formatSelection: e, escapeMarkup: function (e) { return e } }); var r = $("#submit_form"), t = $(".alert-danger", r), i = $(".alert-success", r); r.validate({ doNotHideMessage: !0, errorElement: "span", errorClass: "help-block help-block-error", focusInvalid: !1, rules: { username: {minlength: 5, required: !0}, password: {minlength: 5, required: !0}, rpassword: {minlength: 5, required: !0, equalTo: "#submit_form_password"}, fullname: {required: !0}, email: {required: !0, email: !0}, phone: {required: !0}, gender: {required: !0}, address: {required: !0}, city: {required: !0}, country: {required: !0}, card_name: {required: !0}, card_number: {minlength: 16, maxlength: 16, required: !0}, card_cvc: {digits: !0, required: !0, minlength: 3, maxlength: 4}, card_expiry_date: {required: !0}, "payment[]": {required: !0, minlength: 1} }, messages: { "payment[]": { required: "Please select at least one option", minlength: jQuery.validator.format("Please select at least one option") } }, errorPlacement: function (e, r) { "gender" == r.attr("name") ? e.insertAfter("#form_gender_error") : "payment[]" == r.attr("name") ? e.insertAfter("#form_payment_error") : e.insertAfter(r) }, invalidHandler: function (e, r) { i.hide(), t.show(), App.scrollTo(t, -200) }, highlight: function (e) { $(e).closest(".form-group").removeClass("has-success").addClass("has-error") }, unhighlight: function (e) { $(e).closest(".form-group").removeClass("has-error") }, success: function (e) { "gender" == e.attr("for") || "payment[]" == e.attr("for") ? (e.closest(".form-group").removeClass("has-error").addClass("has-success"), e.remove()) : e.addClass("valid").closest(".form-group").removeClass("has-error").addClass("has-success") }, submitHandler: function (e) { i.show(), t.hide(), e[0].submit() } }); var a = function () { $("#tab4 .form-control-static", r).each(function () { var e = $('[name="' + $(this).attr("data-display") + '"]', r); if (e.is(":radio") && (e = $('[name="' + $(this).attr("data-display") + '"]:checked', r)), e.is(":text") || e.is("textarea")) $(this).html(e.val()); else if (e.is("select")) $(this).html(e.find("option:selected").text()); else if (e.is(":radio") && e.is(":checked")) $(this).html(e.attr("data-title")); else if ("payment[]" == $(this).attr("data-display")) { var t = []; $('[name="payment[]"]:checked', r).each(function () { t.push($(this).attr("data-title")) }), $(this).html(t.join("<br>")) } }) }, o = function (e, r, t) { var i = r.find("li").length, o = t + 1; $(".step-title", $("#form_wizard_1")).text("Step " + (t + 1) + " of " + i), jQuery("li", $("#form_wizard_1")).removeClass("done"); for (var n = r.find("li"), s = 0; s < t; s++) jQuery(n[s]).addClass("done"); 1 == o ? $("#form_wizard_1").find(".button-previous").hide() : $("#form_wizard_1").find(".button-previous").show(), o >= i ? ($("#form_wizard_1").find(".button-next").hide(), $("#form_wizard_1").find(".button-submit").show(), a()) : ($("#form_wizard_1").find(".button-next").show(), $("#form_wizard_1").find(".button-submit").hide()), App.scrollTo($(".page-title")) }; $("#form_wizard_1").bootstrapWizard({ nextSelector: ".button-next", previousSelector: ".button-previous", onTabClick: function (e, r, t, i) { return !1 }, onNext: function (e, a, n) { return i.hide(), t.hide(), 0 != r.valid() && void o(e, a, n) }, onPrevious: function (e, r, a) { i.hide(), t.hide(), o(e, r, a) }, onTabShow: function (e, r, t) { var i = r.find("li").length, a = t + 1, o = a / i * 100; $("#form_wizard_1").find(".progress-bar").css({width: o + "%"}) } }), $("#form_wizard_1").find(".button-previous").hide(), $("#form_wizard_1 .button-submit").click(function () { // alert("Finished! Hope you like it :)") }).hide(), $("#country_list", r).change(function () { r.validate().element($(this)) }) } } } }(); jQuery(document).ready(function () { FormWizard.init() });
import models from '../models' import uuid from 'uuid' export async function findAll (ctx) { return models.Image.findAll() } export async function findById (id) { return models.Image.findOne({ where: { id } }) } export async function create (params) { return models.Image.create({ uuid: uuid.v4(), ...params, }) }
'use strict' module.exports = compile const ejs = require('ejs') const set = require('set-options') const DEFAULT_OPTIONS = { compileDebug: false, rmWhitespace: true, _with: false, strict: true } function compile (content, options, callback) { options = set(options, DEFAULT_OPTIONS) ejs.localsName = options.localsName || 'it' // force `options.client` to `true` to build a standalone compiled function options.client = true let result try { result = ejs.compile(content, options).toString() } catch(e) { return callback(e) } let code = `module.exports = anonymous;\n${result}` callback(null, { code, // map: ejs does not support sourcemap yet // ast: actually, ejs have no ast js: true }) }
app.provider("shared", function () { var sharedProperties = { lastPage: "", currentRegion: "US", currentBracket: { text: "3v3"}, regions: ["us", "eu", "kr", "tw", "cn"], brackets: { "2v2": 2, "3v3": 3, "5v5": 5, "rbg": 10 }, regionLink: function(region) { var url = '/' + region + '/' + this.currentBracket.text; if (this.now) url = url + "/now"; return url; }, bracketLink: function(bracket) { var url = '/' + this.currentRegion + '/' + bracket; if (this.now) url = url + "/now"; return url; }, redirectPage: function () { console.log("REDIRECTING TO LAST PAGE:", this.lastPage); if (this.lastPage) return this.lastPage; else return "/us/3v3"; }, hubReady: {}, // set in appConfig.js adminKey: "" }; this.$get = function ($cookies) { if ($cookies) sharedProperties.lastPage = $cookies.lastPage; return sharedProperties; }; this.$get.$inject = ['$cookies']; // minification protection });
var inText = {top: "2.75rem", left: "0.75rem"}; var outText = {top: "0.5rem", left: 0}; function check() { $(".login").each(function() { if ($(this).val() != "") { $(this).parent().children("label").animate(outText, 250); } else { $(this).parent().children("label").animate(inText, 250); } }) } $(document).ready(function() { // console.log("test2") check(); $(".login-form").on("change", ".login", check); $(".login-form").on("focus", ".login", function() { $(this).parent().children("label").animate(outText, 250); }); $(".login-form").on("focusout", ".login", function() { if ($(this).val() == "") { $(this).parent().children("label").animate(inText, 250); } }); });
/*! * better-scroll / better-scroll * (c) 2016-2021 ustbhuangyi * Released under the MIT License. */ /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* 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 (Object.prototype.hasOwnProperty.call(b, 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 __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } var propertiesConfig$7 = [ { sourceKey: 'scroller.scrollBehaviorX.currentPos', key: 'x' }, { sourceKey: 'scroller.scrollBehaviorY.currentPos', key: 'y' }, { sourceKey: 'scroller.scrollBehaviorX.hasScroll', key: 'hasHorizontalScroll' }, { sourceKey: 'scroller.scrollBehaviorY.hasScroll', key: 'hasVerticalScroll' }, { sourceKey: 'scroller.scrollBehaviorX.contentSize', key: 'scrollerWidth' }, { sourceKey: 'scroller.scrollBehaviorY.contentSize', key: 'scrollerHeight' }, { sourceKey: 'scroller.scrollBehaviorX.maxScrollPos', key: 'maxScrollX' }, { sourceKey: 'scroller.scrollBehaviorY.maxScrollPos', key: 'maxScrollY' }, { sourceKey: 'scroller.scrollBehaviorX.minScrollPos', key: 'minScrollX' }, { sourceKey: 'scroller.scrollBehaviorY.minScrollPos', key: 'minScrollY' }, { sourceKey: 'scroller.scrollBehaviorX.movingDirection', key: 'movingDirectionX' }, { sourceKey: 'scroller.scrollBehaviorY.movingDirection', key: 'movingDirectionY' }, { sourceKey: 'scroller.scrollBehaviorX.direction', key: 'directionX' }, { sourceKey: 'scroller.scrollBehaviorY.direction', key: 'directionY' }, { sourceKey: 'scroller.actions.enabled', key: 'enabled' }, { sourceKey: 'scroller.animater.pending', key: 'pending' }, { sourceKey: 'scroller.animater.stop', key: 'stop' }, { sourceKey: 'scroller.scrollTo', key: 'scrollTo' }, { sourceKey: 'scroller.scrollBy', key: 'scrollBy' }, { sourceKey: 'scroller.scrollToElement', key: 'scrollToElement' }, { sourceKey: 'scroller.resetPosition', key: 'resetPosition' } ]; function warn(msg) { console.error("[BScroll warn]: " + msg); } function assert(condition, msg) { if (!condition) { throw new Error('[BScroll] ' + msg); } } // ssr support var inBrowser = typeof window !== 'undefined'; var ua = inBrowser && navigator.userAgent.toLowerCase(); var isWeChatDevTools = !!(ua && /wechatdevtools/.test(ua)); var isAndroid = ua && ua.indexOf('android') > 0; /* istanbul ignore next */ var isIOSBadVersion = (function () { if (typeof ua === 'string') { var regex = /os (\d\d?_\d(_\d)?)/; var matches = regex.exec(ua); if (!matches) return false; var parts = matches[1].split('_').map(function (item) { return parseInt(item, 10); }); // ios version >= 13.4 issue 982 return !!(parts[0] === 13 && parts[1] >= 4); } return false; })(); /* istanbul ignore next */ var supportsPassive = false; /* istanbul ignore next */ if (inBrowser) { var EventName = 'test-passive'; try { var opts = {}; Object.defineProperty(opts, 'passive', { get: function () { supportsPassive = true; }, }); // https://github.com/facebook/flow/issues/285 window.addEventListener(EventName, function () { }, opts); } catch (e) { } } function getNow() { return window.performance && window.performance.now && window.performance.timing ? window.performance.now() + window.performance.timing.navigationStart : +new Date(); } var extend = function (target, source) { for (var key in source) { target[key] = source[key]; } return target; }; function isUndef(v) { return v === undefined || v === null; } function getDistance(x, y) { return Math.sqrt(x * x + y * y); } function between(x, min, max) { if (x < min) { return min; } if (x > max) { return max; } return x; } function findIndex(ary, fn) { if (ary.findIndex) { return ary.findIndex(fn); } var index = -1; ary.some(function (item, i, ary) { var ret = fn(item, i, ary); if (ret) { index = i; return ret; } }); return index; } var elementStyle = (inBrowser && document.createElement('div').style); var vendor = (function () { /* istanbul ignore if */ if (!inBrowser) { return false; } var transformNames = [ { key: 'standard', value: 'transform', }, { key: 'webkit', value: 'webkitTransform', }, { key: 'Moz', value: 'MozTransform', }, { key: 'O', value: 'OTransform', }, { key: 'ms', value: 'msTransform', }, ]; for (var _i = 0, transformNames_1 = transformNames; _i < transformNames_1.length; _i++) { var obj = transformNames_1[_i]; if (elementStyle[obj.value] !== undefined) { return obj.key; } } /* istanbul ignore next */ return false; })(); /* istanbul ignore next */ function prefixStyle(style) { if (vendor === false) { return style; } if (vendor === 'standard') { if (style === 'transitionEnd') { return 'transitionend'; } return style; } return vendor + style.charAt(0).toUpperCase() + style.substr(1); } function getElement(el) { return (typeof el === 'string' ? document.querySelector(el) : el); } function addEvent(el, type, fn, capture) { var useCapture = supportsPassive ? { passive: false, capture: !!capture, } : !!capture; el.addEventListener(type, fn, useCapture); } function removeEvent(el, type, fn, capture) { el.removeEventListener(type, fn, { capture: !!capture, }); } function offset(el) { var left = 0; var top = 0; while (el) { left -= el.offsetLeft; top -= el.offsetTop; el = el.offsetParent; } return { left: left, top: top, }; } function offsetToBody(el) { var rect = el.getBoundingClientRect(); return { left: -(rect.left + window.pageXOffset), top: -(rect.top + window.pageYOffset), }; } var cssVendor = vendor && vendor !== 'standard' ? '-' + vendor.toLowerCase() + '-' : ''; var transform = prefixStyle('transform'); var transition = prefixStyle('transition'); var hasPerspective = inBrowser && prefixStyle('perspective') in elementStyle; // fix issue #361 var hasTouch = inBrowser && ('ontouchstart' in window || isWeChatDevTools); var hasTransition = inBrowser && transition in elementStyle; var style = { transform: transform, transition: transition, transitionTimingFunction: prefixStyle('transitionTimingFunction'), transitionDuration: prefixStyle('transitionDuration'), transitionDelay: prefixStyle('transitionDelay'), transformOrigin: prefixStyle('transformOrigin'), transitionEnd: prefixStyle('transitionEnd'), transitionProperty: prefixStyle('transitionProperty'), }; var eventTypeMap = { touchstart: 1, touchmove: 1, touchend: 1, touchcancel: 1, mousedown: 2, mousemove: 2, mouseup: 2, }; function getRect(el) { /* istanbul ignore if */ if (el instanceof window.SVGElement) { var rect = el.getBoundingClientRect(); return { top: rect.top, left: rect.left, width: rect.width, height: rect.height, }; } else { return { top: el.offsetTop, left: el.offsetLeft, width: el.offsetWidth, height: el.offsetHeight, }; } } function preventDefaultExceptionFn(el, exceptions) { for (var i in exceptions) { if (exceptions[i].test(el[i])) { return true; } } return false; } var tagExceptionFn = preventDefaultExceptionFn; function tap(e, eventName) { var ev = document.createEvent('Event'); ev.initEvent(eventName, true, true); ev.pageX = e.pageX; ev.pageY = e.pageY; e.target.dispatchEvent(ev); } function click(e, event) { if (event === void 0) { event = 'click'; } var eventSource; if (e.type === 'mouseup') { eventSource = e; } else if (e.type === 'touchend' || e.type === 'touchcancel') { eventSource = e.changedTouches[0]; } var posSrc = {}; if (eventSource) { posSrc.screenX = eventSource.screenX || 0; posSrc.screenY = eventSource.screenY || 0; posSrc.clientX = eventSource.clientX || 0; posSrc.clientY = eventSource.clientY || 0; } var ev; var bubbles = true; var cancelable = true; var ctrlKey = e.ctrlKey, shiftKey = e.shiftKey, altKey = e.altKey, metaKey = e.metaKey; var pressedKeysMap = { ctrlKey: ctrlKey, shiftKey: shiftKey, altKey: altKey, metaKey: metaKey, }; if (typeof MouseEvent !== 'undefined') { try { ev = new MouseEvent(event, extend(__assign({ bubbles: bubbles, cancelable: cancelable }, pressedKeysMap), posSrc)); } catch (e) { /* istanbul ignore next */ createEvent(); } } else { createEvent(); } function createEvent() { ev = document.createEvent('Event'); ev.initEvent(event, bubbles, cancelable); extend(ev, posSrc); } // forwardedTouchEvent set to true in case of the conflict with fastclick ev.forwardedTouchEvent = true; ev._constructed = true; e.target.dispatchEvent(ev); } function dblclick(e) { click(e, 'dblclick'); } function prepend(el, target) { var firstChild = target.firstChild; if (firstChild) { before(el, firstChild); } else { target.appendChild(el); } } function before(el, target) { var parentNode = target.parentNode; parentNode.insertBefore(el, target); } function removeChild(el, child) { el.removeChild(child); } function hasClass(el, className) { var reg = new RegExp('(^|\\s)' + className + '(\\s|$)'); return reg.test(el.className); } function HTMLCollectionToArray(el) { return Array.prototype.slice.call(el, 0); } function getClientSize(el) { return { width: el.clientWidth, height: el.clientHeight, }; } var ease = { // easeOutQuint swipe: { style: 'cubic-bezier(0.23, 1, 0.32, 1)', fn: function (t) { return 1 + --t * t * t * t * t; } }, // easeOutQuard swipeBounce: { style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)', fn: function (t) { return t * (2 - t); } }, // easeOutQuart bounce: { style: 'cubic-bezier(0.165, 0.84, 0.44, 1)', fn: function (t) { return 1 - --t * t * t * t; } } }; var DEFAULT_INTERVAL = 1000 / 60; var windowCompat = inBrowser && window; /* istanbul ignore next */ function noop$1() { } var requestAnimationFrame = (function () { /* istanbul ignore if */ if (!inBrowser) { return noop$1; } return (windowCompat.requestAnimationFrame || windowCompat.webkitRequestAnimationFrame || windowCompat.mozRequestAnimationFrame || windowCompat.oRequestAnimationFrame || // if all else fails, use setTimeout function (callback) { return window.setTimeout(callback, callback.interval || DEFAULT_INTERVAL); // make interval as precise as possible. }); })(); var cancelAnimationFrame = (function () { /* istanbul ignore if */ if (!inBrowser) { return noop$1; } return (windowCompat.cancelAnimationFrame || windowCompat.webkitCancelAnimationFrame || windowCompat.mozCancelAnimationFrame || windowCompat.oCancelAnimationFrame || function (id) { window.clearTimeout(id); }); })(); /* istanbul ignore next */ var noop = function (val) { }; var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop, }; var getProperty = function (obj, key) { var keys = key.split('.'); for (var i = 0; i < keys.length - 1; i++) { obj = obj[keys[i]]; if (typeof obj !== 'object' || !obj) return; } var lastKey = keys.pop(); if (typeof obj[lastKey] === 'function') { return function () { return obj[lastKey].apply(obj, arguments); }; } else { return obj[lastKey]; } }; var setProperty = function (obj, key, value) { var keys = key.split('.'); var temp; for (var i = 0; i < keys.length - 1; i++) { temp = keys[i]; if (!obj[temp]) obj[temp] = {}; obj = obj[temp]; } obj[keys.pop()] = value; }; function propertiesProxy(target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter() { return getProperty(this, sourceKey); }; sharedPropertyDefinition.set = function proxySetter(val) { setProperty(this, sourceKey, val); }; Object.defineProperty(target, key, sharedPropertyDefinition); } var EventEmitter = /** @class */ (function () { function EventEmitter(names) { this.events = {}; this.eventTypes = {}; this.registerType(names); } EventEmitter.prototype.on = function (type, fn, context) { if (context === void 0) { context = this; } this.hasType(type); if (!this.events[type]) { this.events[type] = []; } this.events[type].push([fn, context]); return this; }; EventEmitter.prototype.once = function (type, fn, context) { var _this = this; if (context === void 0) { context = this; } this.hasType(type); var magic = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } _this.off(type, magic); var ret = fn.apply(context, args); if (ret === true) { return ret; } }; magic.fn = fn; this.on(type, magic); return this; }; EventEmitter.prototype.off = function (type, fn) { if (!type && !fn) { this.events = {}; return this; } if (type) { this.hasType(type); if (!fn) { this.events[type] = []; return this; } var events = this.events[type]; if (!events) { return this; } var count = events.length; while (count--) { if (events[count][0] === fn || (events[count][0] && events[count][0].fn === fn)) { events.splice(count, 1); } } return this; } }; EventEmitter.prototype.trigger = function (type) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } this.hasType(type); var events = this.events[type]; if (!events) { return; } var len = events.length; var eventsCopy = __spreadArrays(events); var ret; for (var i = 0; i < len; i++) { var event_1 = eventsCopy[i]; var fn = event_1[0], context = event_1[1]; if (fn) { ret = fn.apply(context, args); if (ret === true) { return ret; } } } }; EventEmitter.prototype.registerType = function (names) { var _this = this; names.forEach(function (type) { _this.eventTypes[type] = type; }); }; EventEmitter.prototype.destroy = function () { this.events = {}; this.eventTypes = {}; }; EventEmitter.prototype.hasType = function (type) { var types = this.eventTypes; var isType = types[type] === type; if (!isType) { warn("EventEmitter has used unknown event type: \"" + type + "\", should be oneof [" + ("" + Object.keys(types).map(function (_) { return JSON.stringify(_); })) + "]"); } }; return EventEmitter; }()); var EventRegister = /** @class */ (function () { function EventRegister(wrapper, events) { this.wrapper = wrapper; this.events = events; this.addDOMEvents(); } EventRegister.prototype.destroy = function () { this.removeDOMEvents(); this.events = []; }; EventRegister.prototype.addDOMEvents = function () { this.handleDOMEvents(addEvent); }; EventRegister.prototype.removeDOMEvents = function () { this.handleDOMEvents(removeEvent); }; EventRegister.prototype.handleDOMEvents = function (eventOperation) { var _this = this; var wrapper = this.wrapper; this.events.forEach(function (event) { eventOperation(wrapper, event.name, _this, !!event.capture); }); }; EventRegister.prototype.handleEvent = function (e) { var eventType = e.type; this.events.some(function (event) { if (event.name === eventType) { event.handler(e); return true; } return false; }); }; return EventRegister; }()); var CustomOptions = /** @class */ (function () { function CustomOptions() { } return CustomOptions; }()); var OptionsConstructor = /** @class */ (function (_super) { __extends(OptionsConstructor, _super); function OptionsConstructor() { var _this = _super.call(this) || this; _this.startX = 0; _this.startY = 0; _this.scrollX = false; _this.scrollY = true; _this.freeScroll = false; _this.directionLockThreshold = 0; _this.eventPassthrough = "" /* None */; _this.click = false; _this.dblclick = false; _this.tap = ''; _this.bounce = { top: true, bottom: true, left: true, right: true, }; _this.bounceTime = 800; _this.momentum = true; _this.momentumLimitTime = 300; _this.momentumLimitDistance = 15; _this.swipeTime = 2500; _this.swipeBounceTime = 500; _this.deceleration = 0.0015; _this.flickLimitTime = 200; _this.flickLimitDistance = 100; _this.resizePolling = 60; _this.probeType = 0 /* Default */; _this.stopPropagation = false; _this.preventDefault = true; _this.preventDefaultException = { tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|AUDIO)$/, }; _this.tagException = { tagName: /^TEXTAREA$/, }; _this.HWCompositing = true; _this.useTransition = true; _this.bindToWrapper = false; _this.bindToTarget = false; _this.disableMouse = hasTouch; _this.disableTouch = !hasTouch; _this.autoBlur = true; _this.autoEndDistance = 5; _this.outOfBoundaryDampingFactor = 1 / 3; _this.specifiedIndexAsContent = 0; _this.quadrant = 1 /* First */; return _this; } OptionsConstructor.prototype.merge = function (options) { if (!options) return this; for (var key in options) { if (key === 'bounce') { this.bounce = this.resolveBounce(options[key]); continue; } this[key] = options[key]; } return this; }; OptionsConstructor.prototype.process = function () { this.translateZ = this.HWCompositing && hasPerspective ? ' translateZ(1px)' : ''; this.useTransition = this.useTransition && hasTransition; this.preventDefault = !this.eventPassthrough && this.preventDefault; // If you want eventPassthrough I have to lock one of the axes this.scrollX = this.eventPassthrough === "horizontal" /* Horizontal */ ? false : this.scrollX; this.scrollY = this.eventPassthrough === "vertical" /* Vertical */ ? false : this.scrollY; // With eventPassthrough we also need lockDirection mechanism this.freeScroll = this.freeScroll && !this.eventPassthrough; // force true when freeScroll is true this.scrollX = this.freeScroll ? true : this.scrollX; this.scrollY = this.freeScroll ? true : this.scrollY; this.directionLockThreshold = this.eventPassthrough ? 0 : this.directionLockThreshold; return this; }; OptionsConstructor.prototype.resolveBounce = function (bounceOptions) { var DEFAULT_BOUNCE = { top: true, right: true, bottom: true, left: true, }; var NEGATED_BOUNCE = { top: false, right: false, bottom: false, left: false, }; var ret; if (typeof bounceOptions === 'object') { ret = extend(DEFAULT_BOUNCE, bounceOptions); } else { ret = bounceOptions ? DEFAULT_BOUNCE : NEGATED_BOUNCE; } return ret; }; return OptionsConstructor; }(CustomOptions)); var ActionsHandler = /** @class */ (function () { function ActionsHandler(wrapper, options) { this.wrapper = wrapper; this.options = options; this.hooks = new EventEmitter([ 'beforeStart', 'start', 'move', 'end', 'click', ]); this.handleDOMEvents(); } ActionsHandler.prototype.handleDOMEvents = function () { var _a = this.options, bindToWrapper = _a.bindToWrapper, disableMouse = _a.disableMouse, disableTouch = _a.disableTouch, click = _a.click; var wrapper = this.wrapper; var target = bindToWrapper ? wrapper : window; var wrapperEvents = []; var targetEvents = []; var shouldRegisterTouch = !disableTouch; var shouldRegisterMouse = !disableMouse; if (click) { wrapperEvents.push({ name: 'click', handler: this.click.bind(this), capture: true, }); } if (shouldRegisterTouch) { wrapperEvents.push({ name: 'touchstart', handler: this.start.bind(this), }); targetEvents.push({ name: 'touchmove', handler: this.move.bind(this), }, { name: 'touchend', handler: this.end.bind(this), }, { name: 'touchcancel', handler: this.end.bind(this), }); } if (shouldRegisterMouse) { wrapperEvents.push({ name: 'mousedown', handler: this.start.bind(this), }); targetEvents.push({ name: 'mousemove', handler: this.move.bind(this), }, { name: 'mouseup', handler: this.end.bind(this), }); } this.wrapperEventRegister = new EventRegister(wrapper, wrapperEvents); this.targetEventRegister = new EventRegister(target, targetEvents); }; ActionsHandler.prototype.beforeHandler = function (e, type) { var _a = this.options, preventDefault = _a.preventDefault, stopPropagation = _a.stopPropagation, preventDefaultException = _a.preventDefaultException; var preventDefaultConditions = { start: function () { return (preventDefault && !preventDefaultExceptionFn(e.target, preventDefaultException)); }, end: function () { return (preventDefault && !preventDefaultExceptionFn(e.target, preventDefaultException)); }, move: function () { return preventDefault; }, }; if (preventDefaultConditions[type]()) { e.preventDefault(); } if (stopPropagation) { e.stopPropagation(); } }; ActionsHandler.prototype.setInitiated = function (type) { if (type === void 0) { type = 0; } this.initiated = type; }; ActionsHandler.prototype.start = function (e) { var _eventType = eventTypeMap[e.type]; if (this.initiated && this.initiated !== _eventType) { return; } this.setInitiated(_eventType); // if textarea or other html tags in options.tagException is manipulated // do not make bs scroll if (tagExceptionFn(e.target, this.options.tagException)) { this.setInitiated(); return; } // only allow mouse left button if (_eventType === 2 /* Mouse */ && e.button !== 0 /* Left */) return; if (this.hooks.trigger(this.hooks.eventTypes.beforeStart, e)) { return; } this.beforeHandler(e, 'start'); var point = (e.touches ? e.touches[0] : e); this.pointX = point.pageX; this.pointY = point.pageY; this.hooks.trigger(this.hooks.eventTypes.start, e); }; ActionsHandler.prototype.move = function (e) { if (eventTypeMap[e.type] !== this.initiated) { return; } this.beforeHandler(e, 'move'); var point = (e.touches ? e.touches[0] : e); var deltaX = point.pageX - this.pointX; var deltaY = point.pageY - this.pointY; this.pointX = point.pageX; this.pointY = point.pageY; if (this.hooks.trigger(this.hooks.eventTypes.move, { deltaX: deltaX, deltaY: deltaY, e: e, })) { return; } // auto end when out of viewport var scrollLeft = document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft; var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; var pX = this.pointX - scrollLeft; var pY = this.pointY - scrollTop; var autoEndDistance = this.options.autoEndDistance; if (pX > document.documentElement.clientWidth - autoEndDistance || pY > document.documentElement.clientHeight - autoEndDistance || pX < autoEndDistance || pY < autoEndDistance) { this.end(e); } }; ActionsHandler.prototype.end = function (e) { if (eventTypeMap[e.type] !== this.initiated) { return; } this.setInitiated(); this.beforeHandler(e, 'end'); this.hooks.trigger(this.hooks.eventTypes.end, e); }; ActionsHandler.prototype.click = function (e) { this.hooks.trigger(this.hooks.eventTypes.click, e); }; ActionsHandler.prototype.setContent = function (content) { if (content !== this.wrapper) { this.wrapper = content; this.rebindDOMEvents(); } }; ActionsHandler.prototype.rebindDOMEvents = function () { this.wrapperEventRegister.destroy(); this.targetEventRegister.destroy(); this.handleDOMEvents(); }; ActionsHandler.prototype.destroy = function () { this.wrapperEventRegister.destroy(); this.targetEventRegister.destroy(); this.hooks.destroy(); }; return ActionsHandler; }()); var translaterMetaData = { x: ['translateX', 'px'], y: ['translateY', 'px'], }; var Translater = /** @class */ (function () { function Translater(content) { this.setContent(content); this.hooks = new EventEmitter(['beforeTranslate', 'translate']); } Translater.prototype.getComputedPosition = function () { var cssStyle = window.getComputedStyle(this.content, null); var matrix = cssStyle[style.transform].split(')')[0].split(', '); var x = +(matrix[12] || matrix[4]) || 0; var y = +(matrix[13] || matrix[5]) || 0; return { x: x, y: y, }; }; Translater.prototype.translate = function (point) { var transformStyle = []; Object.keys(point).forEach(function (key) { if (!translaterMetaData[key]) { return; } var transformFnName = translaterMetaData[key][0]; if (transformFnName) { var transformFnArgUnit = translaterMetaData[key][1]; var transformFnArg = point[key]; transformStyle.push(transformFnName + "(" + transformFnArg + transformFnArgUnit + ")"); } }); this.hooks.trigger(this.hooks.eventTypes.beforeTranslate, transformStyle, point); this.style[style.transform] = transformStyle.join(' '); this.hooks.trigger(this.hooks.eventTypes.translate, point); }; Translater.prototype.setContent = function (content) { if (this.content !== content) { this.content = content; this.style = content.style; } }; Translater.prototype.destroy = function () { this.hooks.destroy(); }; return Translater; }()); var Base = /** @class */ (function () { function Base(content, translater, options) { this.translater = translater; this.options = options; this.timer = 0; this.hooks = new EventEmitter([ 'move', 'end', 'beforeForceStop', 'forceStop', 'callStop', 'time', 'timeFunction', ]); this.setContent(content); } Base.prototype.translate = function (endPoint) { this.translater.translate(endPoint); }; Base.prototype.setPending = function (pending) { this.pending = pending; }; Base.prototype.setForceStopped = function (forceStopped) { this.forceStopped = forceStopped; }; Base.prototype.setCallStop = function (called) { this.callStopWhenPending = called; }; Base.prototype.setContent = function (content) { if (this.content !== content) { this.content = content; this.style = content.style; this.stop(); } }; Base.prototype.clearTimer = function () { if (this.timer) { cancelAnimationFrame(this.timer); this.timer = 0; } }; Base.prototype.destroy = function () { this.hooks.destroy(); cancelAnimationFrame(this.timer); }; return Base; }()); // iOS 13.6 - 14.x, window.getComputedStyle sometimes will get wrong transform value // when bs use transition mode // eg: translateY -100px -> -200px, when the last frame which is about to scroll to -200px // window.getComputedStyle(this.content) will calculate transformY to be -100px(startPoint) // it is weird // so we should validate position caculated by 'window.getComputedStyle' var isValidPostion = function (startPoint, endPoint, currentPos, prePos) { var computeDirection = function (endValue, startValue) { var delta = endValue - startValue; var direction = delta > 0 ? -1 /* Negative */ : delta < 0 ? 1 /* Positive */ : 0 /* Default */; return direction; }; var directionX = computeDirection(endPoint.x, startPoint.x); var directionY = computeDirection(endPoint.y, startPoint.y); var deltaX = currentPos.x - prePos.x; var deltaY = currentPos.y - prePos.y; return directionX * deltaX <= 0 && directionY * deltaY <= 0; }; var Transition = /** @class */ (function (_super) { __extends(Transition, _super); function Transition() { return _super !== null && _super.apply(this, arguments) || this; } Transition.prototype.startProbe = function (startPoint, endPoint) { var _this = this; var prePos = startPoint; var probe = function () { var pos = _this.translater.getComputedPosition(); if (isValidPostion(startPoint, endPoint, pos, prePos)) { _this.hooks.trigger(_this.hooks.eventTypes.move, pos); } // call bs.stop() should not dispatch end hook again. // forceStop hook will do this. /* istanbul ignore if */ if (!_this.pending) { if (_this.callStopWhenPending) { _this.callStopWhenPending = false; } else { // transition ends should dispatch end hook. _this.hooks.trigger(_this.hooks.eventTypes.end, pos); } } prePos = pos; if (_this.pending) { _this.timer = requestAnimationFrame(probe); } }; // when manually call bs.stop(), then bs.scrollTo() // we should reset callStopWhenPending to dispatch end hook if (this.callStopWhenPending) { this.setCallStop(false); } cancelAnimationFrame(this.timer); probe(); }; Transition.prototype.transitionTime = function (time) { if (time === void 0) { time = 0; } this.style[style.transitionDuration] = time + 'ms'; this.hooks.trigger(this.hooks.eventTypes.time, time); }; Transition.prototype.transitionTimingFunction = function (easing) { this.style[style.transitionTimingFunction] = easing; this.hooks.trigger(this.hooks.eventTypes.timeFunction, easing); }; Transition.prototype.transitionProperty = function () { this.style[style.transitionProperty] = style.transform; }; Transition.prototype.move = function (startPoint, endPoint, time, easingFn) { this.setPending(time > 0); this.transitionTimingFunction(easingFn); this.transitionProperty(); this.transitionTime(time); this.translate(endPoint); var isRealtimeProbeType = this.options.probeType === 3 /* Realtime */; if (time && isRealtimeProbeType) { this.startProbe(startPoint, endPoint); } // if we change content's transformY in a tick // such as: 0 -> 50px -> 0 // transitionend will not be triggered // so we forceupdate by reflow if (!time) { this._reflow = this.content.offsetHeight; if (isRealtimeProbeType) { this.hooks.trigger(this.hooks.eventTypes.move, endPoint); } this.hooks.trigger(this.hooks.eventTypes.end, endPoint); } }; Transition.prototype.doStop = function () { var pending = this.pending; this.setForceStopped(false); this.setCallStop(false); // still in transition if (pending) { this.setPending(false); cancelAnimationFrame(this.timer); var _a = this.translater.getComputedPosition(), x = _a.x, y = _a.y; this.transitionTime(); this.translate({ x: x, y: y }); this.setForceStopped(true); this.setCallStop(true); this.hooks.trigger(this.hooks.eventTypes.forceStop, { x: x, y: y }); } return pending; }; Transition.prototype.stop = function () { var stopFromTransition = this.doStop(); if (stopFromTransition) { this.hooks.trigger(this.hooks.eventTypes.callStop); } }; return Transition; }(Base)); var Animation = /** @class */ (function (_super) { __extends(Animation, _super); function Animation() { return _super !== null && _super.apply(this, arguments) || this; } Animation.prototype.move = function (startPoint, endPoint, time, easingFn) { // time is 0 if (!time) { this.translate(endPoint); if (this.options.probeType === 3 /* Realtime */) { this.hooks.trigger(this.hooks.eventTypes.move, endPoint); } this.hooks.trigger(this.hooks.eventTypes.end, endPoint); return; } this.animate(startPoint, endPoint, time, easingFn); }; Animation.prototype.animate = function (startPoint, endPoint, duration, easingFn) { var _this = this; var startTime = getNow(); var destTime = startTime + duration; var isRealtimeProbeType = this.options.probeType === 3 /* Realtime */; var step = function () { var now = getNow(); // js animation end if (now >= destTime) { _this.translate(endPoint); if (isRealtimeProbeType) { _this.hooks.trigger(_this.hooks.eventTypes.move, endPoint); } _this.hooks.trigger(_this.hooks.eventTypes.end, endPoint); return; } now = (now - startTime) / duration; var easing = easingFn(now); var newPoint = {}; Object.keys(endPoint).forEach(function (key) { var startValue = startPoint[key]; var endValue = endPoint[key]; newPoint[key] = (endValue - startValue) * easing + startValue; }); _this.translate(newPoint); if (isRealtimeProbeType) { _this.hooks.trigger(_this.hooks.eventTypes.move, newPoint); } if (_this.pending) { _this.timer = requestAnimationFrame(step); } // call bs.stop() should not dispatch end hook again. // forceStop hook will do this. /* istanbul ignore if */ if (!_this.pending) { if (_this.callStopWhenPending) { _this.callStopWhenPending = false; } else { // raf ends should dispatch end hook. _this.hooks.trigger(_this.hooks.eventTypes.end, endPoint); } } }; this.setPending(true); // when manually call bs.stop(), then bs.scrollTo() // we should reset callStopWhenPending to dispatch end hook if (this.callStopWhenPending) { this.setCallStop(false); } cancelAnimationFrame(this.timer); step(); }; Animation.prototype.doStop = function () { var pending = this.pending; this.setForceStopped(false); this.setCallStop(false); // still in requestFrameAnimation if (pending) { this.setPending(false); cancelAnimationFrame(this.timer); var pos = this.translater.getComputedPosition(); this.setForceStopped(true); this.setCallStop(true); this.hooks.trigger(this.hooks.eventTypes.forceStop, pos); } return pending; }; Animation.prototype.stop = function () { var stopFromAnimation = this.doStop(); if (stopFromAnimation) { this.hooks.trigger(this.hooks.eventTypes.callStop); } }; return Animation; }(Base)); function createAnimater(element, translater, options) { var useTransition = options.useTransition; var animaterOptions = {}; Object.defineProperty(animaterOptions, 'probeType', { enumerable: true, configurable: false, get: function () { return options.probeType; }, }); if (useTransition) { return new Transition(element, translater, animaterOptions); } else { return new Animation(element, translater, animaterOptions); } } var Behavior = /** @class */ (function () { function Behavior(wrapper, content, options) { this.wrapper = wrapper; this.options = options; this.hooks = new EventEmitter([ 'beforeComputeBoundary', 'computeBoundary', 'momentum', 'end', 'ignoreHasScroll' ]); this.refresh(content); } Behavior.prototype.start = function () { this.dist = 0; this.setMovingDirection(0 /* Default */); this.setDirection(0 /* Default */); }; Behavior.prototype.move = function (delta) { delta = this.hasScroll ? delta : 0; this.setMovingDirection(delta); return this.performDampingAlgorithm(delta, this.options.outOfBoundaryDampingFactor); }; Behavior.prototype.setMovingDirection = function (delta) { this.movingDirection = delta > 0 ? -1 /* Negative */ : delta < 0 ? 1 /* Positive */ : 0 /* Default */; }; Behavior.prototype.setDirection = function (delta) { this.direction = delta > 0 ? -1 /* Negative */ : delta < 0 ? 1 /* Positive */ : 0 /* Default */; }; Behavior.prototype.performDampingAlgorithm = function (delta, dampingFactor) { var newPos = this.currentPos + delta; // Slow down or stop if outside of the boundaries if (newPos > this.minScrollPos || newPos < this.maxScrollPos) { if ((newPos > this.minScrollPos && this.options.bounces[0]) || (newPos < this.maxScrollPos && this.options.bounces[1])) { newPos = this.currentPos + delta * dampingFactor; } else { newPos = newPos > this.minScrollPos ? this.minScrollPos : this.maxScrollPos; } } return newPos; }; Behavior.prototype.end = function (duration) { var momentumInfo = { duration: 0 }; var absDist = Math.abs(this.currentPos - this.startPos); // start momentum animation if needed if (this.options.momentum && duration < this.options.momentumLimitTime && absDist > this.options.momentumLimitDistance) { var wrapperSize = (this.direction === -1 /* Negative */ && this.options.bounces[0]) || (this.direction === 1 /* Positive */ && this.options.bounces[1]) ? this.wrapperSize : 0; momentumInfo = this.hasScroll ? this.momentum(this.currentPos, this.startPos, duration, this.maxScrollPos, this.minScrollPos, wrapperSize, this.options) : { destination: this.currentPos, duration: 0 }; } else { this.hooks.trigger(this.hooks.eventTypes.end, momentumInfo); } return momentumInfo; }; Behavior.prototype.momentum = function (current, start, time, lowerMargin, upperMargin, wrapperSize, options) { if (options === void 0) { options = this.options; } var distance = current - start; var speed = Math.abs(distance) / time; var deceleration = options.deceleration, swipeBounceTime = options.swipeBounceTime, swipeTime = options.swipeTime; var duration = Math.min(swipeTime, (speed * 2) / deceleration); var momentumData = { destination: current + ((speed * speed) / deceleration) * (distance < 0 ? -1 : 1), duration: duration, rate: 15 }; this.hooks.trigger(this.hooks.eventTypes.momentum, momentumData, distance); if (momentumData.destination < lowerMargin) { momentumData.destination = wrapperSize ? Math.max(lowerMargin - wrapperSize / 4, lowerMargin - (wrapperSize / momentumData.rate) * speed) : lowerMargin; momentumData.duration = swipeBounceTime; } else if (momentumData.destination > upperMargin) { momentumData.destination = wrapperSize ? Math.min(upperMargin + wrapperSize / 4, upperMargin + (wrapperSize / momentumData.rate) * speed) : upperMargin; momentumData.duration = swipeBounceTime; } momentumData.destination = Math.round(momentumData.destination); return momentumData; }; Behavior.prototype.updateDirection = function () { var absDist = this.currentPos - this.absStartPos; this.setDirection(absDist); }; Behavior.prototype.refresh = function (content) { var _a = this.options.rect, size = _a.size, position = _a.position; var isWrapperStatic = window.getComputedStyle(this.wrapper, null).position === 'static'; // Force reflow var wrapperRect = getRect(this.wrapper); // use client is more fair than offset this.wrapperSize = this.wrapper[size === 'width' ? 'clientWidth' : 'clientHeight']; this.setContent(content); var contentRect = getRect(this.content); this.contentSize = contentRect[size]; this.relativeOffset = contentRect[position]; /* istanbul ignore if */ if (isWrapperStatic) { this.relativeOffset -= wrapperRect[position]; } this.computeBoundary(); this.setDirection(0 /* Default */); }; Behavior.prototype.setContent = function (content) { if (content !== this.content) { this.content = content; this.resetState(); } }; Behavior.prototype.resetState = function () { this.currentPos = 0; this.startPos = 0; this.dist = 0; this.setDirection(0 /* Default */); this.setMovingDirection(0 /* Default */); this.resetStartPos(); }; Behavior.prototype.computeBoundary = function () { this.hooks.trigger(this.hooks.eventTypes.beforeComputeBoundary); var boundary = { minScrollPos: 0, maxScrollPos: this.wrapperSize - this.contentSize }; if (boundary.maxScrollPos < 0) { boundary.maxScrollPos -= this.relativeOffset; if (this.options.specifiedIndexAsContent === 0) { boundary.minScrollPos = -this.relativeOffset; } } this.hooks.trigger(this.hooks.eventTypes.computeBoundary, boundary); this.minScrollPos = boundary.minScrollPos; this.maxScrollPos = boundary.maxScrollPos; this.hasScroll = this.options.scrollable && this.maxScrollPos < this.minScrollPos; if (!this.hasScroll && this.minScrollPos < this.maxScrollPos) { this.maxScrollPos = this.minScrollPos; this.contentSize = this.wrapperSize; } }; Behavior.prototype.updatePosition = function (pos) { this.currentPos = pos; }; Behavior.prototype.getCurrentPos = function () { return this.currentPos; }; Behavior.prototype.checkInBoundary = function () { var position = this.adjustPosition(this.currentPos); var inBoundary = position === this.getCurrentPos(); return { position: position, inBoundary: inBoundary }; }; // adjust position when out of boundary Behavior.prototype.adjustPosition = function (pos) { if (!this.hasScroll && !this.hooks.trigger(this.hooks.eventTypes.ignoreHasScroll)) { pos = this.minScrollPos; } else if (pos > this.minScrollPos) { pos = this.minScrollPos; } else if (pos < this.maxScrollPos) { pos = this.maxScrollPos; } return pos; }; Behavior.prototype.updateStartPos = function () { this.startPos = this.currentPos; }; Behavior.prototype.updateAbsStartPos = function () { this.absStartPos = this.currentPos; }; Behavior.prototype.resetStartPos = function () { this.updateStartPos(); this.updateAbsStartPos(); }; Behavior.prototype.getAbsDist = function (delta) { this.dist += delta; return Math.abs(this.dist); }; Behavior.prototype.destroy = function () { this.hooks.destroy(); }; return Behavior; }()); var _a, _b, _c, _d; var PassthroughHandlers = (_a = {}, _a["yes" /* Yes */] = function (e) { return true; }, _a["no" /* No */] = function (e) { e.preventDefault(); return false; }, _a); var DirectionMap = (_b = {}, _b["horizontal" /* Horizontal */] = (_c = {}, _c["yes" /* Yes */] = "horizontal" /* Horizontal */, _c["no" /* No */] = "vertical" /* Vertical */, _c), _b["vertical" /* Vertical */] = (_d = {}, _d["yes" /* Yes */] = "vertical" /* Vertical */, _d["no" /* No */] = "horizontal" /* Horizontal */, _d), _b); var DirectionLockAction = /** @class */ (function () { function DirectionLockAction(directionLockThreshold, freeScroll, eventPassthrough) { this.directionLockThreshold = directionLockThreshold; this.freeScroll = freeScroll; this.eventPassthrough = eventPassthrough; this.reset(); } DirectionLockAction.prototype.reset = function () { this.directionLocked = "" /* Default */; }; DirectionLockAction.prototype.checkMovingDirection = function (absDistX, absDistY, e) { this.computeDirectionLock(absDistX, absDistY); return this.handleEventPassthrough(e); }; DirectionLockAction.prototype.adjustDelta = function (deltaX, deltaY) { if (this.directionLocked === "horizontal" /* Horizontal */) { deltaY = 0; } else if (this.directionLocked === "vertical" /* Vertical */) { deltaX = 0; } return { deltaX: deltaX, deltaY: deltaY }; }; DirectionLockAction.prototype.computeDirectionLock = function (absDistX, absDistY) { // If you are scrolling in one direction, lock it if (this.directionLocked === "" /* Default */ && !this.freeScroll) { if (absDistX > absDistY + this.directionLockThreshold) { this.directionLocked = "horizontal" /* Horizontal */; // lock horizontally } else if (absDistY >= absDistX + this.directionLockThreshold) { this.directionLocked = "vertical" /* Vertical */; // lock vertically } else { this.directionLocked = "none" /* None */; // no lock } } }; DirectionLockAction.prototype.handleEventPassthrough = function (e) { var handleMap = DirectionMap[this.directionLocked]; if (handleMap) { if (this.eventPassthrough === handleMap["yes" /* Yes */]) { return PassthroughHandlers["yes" /* Yes */](e); } else if (this.eventPassthrough === handleMap["no" /* No */]) { return PassthroughHandlers["no" /* No */](e); } } return false; }; return DirectionLockAction; }()); var applyQuadrantTransformation = function (deltaX, deltaY, quadrant) { if (quadrant === 2 /* Second */) { return [deltaY, -deltaX]; } else if (quadrant === 3 /* Third */) { return [-deltaX, -deltaY]; } else if (quadrant === 4 /* Forth */) { return [-deltaY, deltaX]; } else { return [deltaX, deltaY]; } }; var ScrollerActions = /** @class */ (function () { function ScrollerActions(scrollBehaviorX, scrollBehaviorY, actionsHandler, animater, options) { this.hooks = new EventEmitter([ 'start', 'beforeMove', 'scrollStart', 'scroll', 'beforeEnd', 'end', 'scrollEnd', 'contentNotMoved', 'detectMovingDirection', 'coordinateTransformation', ]); this.scrollBehaviorX = scrollBehaviorX; this.scrollBehaviorY = scrollBehaviorY; this.actionsHandler = actionsHandler; this.animater = animater; this.options = options; this.directionLockAction = new DirectionLockAction(options.directionLockThreshold, options.freeScroll, options.eventPassthrough); this.enabled = true; this.bindActionsHandler(); } ScrollerActions.prototype.bindActionsHandler = function () { var _this = this; // [mouse|touch]start event this.actionsHandler.hooks.on(this.actionsHandler.hooks.eventTypes.start, function (e) { if (!_this.enabled) return true; return _this.handleStart(e); }); // [mouse|touch]move event this.actionsHandler.hooks.on(this.actionsHandler.hooks.eventTypes.move, function (_a) { var deltaX = _a.deltaX, deltaY = _a.deltaY, e = _a.e; if (!_this.enabled) return true; var _b = applyQuadrantTransformation(deltaX, deltaY, _this.options.quadrant), transformateDeltaX = _b[0], transformateDeltaY = _b[1]; var transformateDeltaData = { deltaX: transformateDeltaX, deltaY: transformateDeltaY, }; _this.hooks.trigger(_this.hooks.eventTypes.coordinateTransformation, transformateDeltaData); return _this.handleMove(transformateDeltaData.deltaX, transformateDeltaData.deltaY, e); }); // [mouse|touch]end event this.actionsHandler.hooks.on(this.actionsHandler.hooks.eventTypes.end, function (e) { if (!_this.enabled) return true; return _this.handleEnd(e); }); // click this.actionsHandler.hooks.on(this.actionsHandler.hooks.eventTypes.click, function (e) { // handle native click event if (_this.enabled && !e._constructed) { _this.handleClick(e); } }); }; ScrollerActions.prototype.handleStart = function (e) { var timestamp = getNow(); this.fingerMoved = false; this.contentMoved = false; this.startTime = timestamp; this.directionLockAction.reset(); this.scrollBehaviorX.start(); this.scrollBehaviorY.start(); // force stopping last transition or animation this.animater.doStop(); this.scrollBehaviorX.resetStartPos(); this.scrollBehaviorY.resetStartPos(); this.hooks.trigger(this.hooks.eventTypes.start, e); }; ScrollerActions.prototype.handleMove = function (deltaX, deltaY, e) { if (this.hooks.trigger(this.hooks.eventTypes.beforeMove, e)) { return; } var absDistX = this.scrollBehaviorX.getAbsDist(deltaX); var absDistY = this.scrollBehaviorY.getAbsDist(deltaY); var timestamp = getNow(); // We need to move at least momentumLimitDistance pixels // for the scrolling to initiate if (this.checkMomentum(absDistX, absDistY, timestamp)) { return true; } if (this.directionLockAction.checkMovingDirection(absDistX, absDistY, e)) { this.actionsHandler.setInitiated(); return true; } var delta = this.directionLockAction.adjustDelta(deltaX, deltaY); var prevX = this.scrollBehaviorX.getCurrentPos(); var newX = this.scrollBehaviorX.move(delta.deltaX); var prevY = this.scrollBehaviorY.getCurrentPos(); var newY = this.scrollBehaviorY.move(delta.deltaY); if (this.hooks.trigger(this.hooks.eventTypes.detectMovingDirection)) { return; } if (!this.fingerMoved) { this.fingerMoved = true; } var positionChanged = newX !== prevX || newY !== prevY; if (!this.contentMoved && !positionChanged) { this.hooks.trigger(this.hooks.eventTypes.contentNotMoved); } if (!this.contentMoved && positionChanged) { this.contentMoved = true; this.hooks.trigger(this.hooks.eventTypes.scrollStart); } if (this.contentMoved && positionChanged) { this.animater.translate({ x: newX, y: newY, }); this.dispatchScroll(timestamp); } }; ScrollerActions.prototype.dispatchScroll = function (timestamp) { // dispatch scroll in interval time if (timestamp - this.startTime > this.options.momentumLimitTime) { // refresh time and starting position to initiate a momentum this.startTime = timestamp; this.scrollBehaviorX.updateStartPos(); this.scrollBehaviorY.updateStartPos(); if (this.options.probeType === 1 /* Throttle */) { this.hooks.trigger(this.hooks.eventTypes.scroll, this.getCurrentPos()); } } // dispatch scroll all the time if (this.options.probeType > 1 /* Throttle */) { this.hooks.trigger(this.hooks.eventTypes.scroll, this.getCurrentPos()); } }; ScrollerActions.prototype.checkMomentum = function (absDistX, absDistY, timestamp) { return (timestamp - this.endTime > this.options.momentumLimitTime && absDistY < this.options.momentumLimitDistance && absDistX < this.options.momentumLimitDistance); }; ScrollerActions.prototype.handleEnd = function (e) { if (this.hooks.trigger(this.hooks.eventTypes.beforeEnd, e)) { return; } var currentPos = this.getCurrentPos(); this.scrollBehaviorX.updateDirection(); this.scrollBehaviorY.updateDirection(); if (this.hooks.trigger(this.hooks.eventTypes.end, e, currentPos)) { return true; } currentPos = this.ensureIntegerPos(currentPos); this.animater.translate(currentPos); this.endTime = getNow(); var duration = this.endTime - this.startTime; this.hooks.trigger(this.hooks.eventTypes.scrollEnd, currentPos, duration); }; ScrollerActions.prototype.ensureIntegerPos = function (currentPos) { this.ensuringInteger = true; var x = currentPos.x, y = currentPos.y; var _a = this.scrollBehaviorX, minScrollPosX = _a.minScrollPos, maxScrollPosX = _a.maxScrollPos; var _b = this.scrollBehaviorY, minScrollPosY = _b.minScrollPos, maxScrollPosY = _b.maxScrollPos; x = x > 0 ? Math.ceil(x) : Math.floor(x); y = y > 0 ? Math.ceil(y) : Math.floor(y); x = between(x, maxScrollPosX, minScrollPosX); y = between(y, maxScrollPosY, minScrollPosY); return { x: x, y: y }; }; ScrollerActions.prototype.handleClick = function (e) { if (!preventDefaultExceptionFn(e.target, this.options.preventDefaultException)) { e.preventDefault(); e.stopPropagation(); } }; ScrollerActions.prototype.getCurrentPos = function () { return { x: this.scrollBehaviorX.getCurrentPos(), y: this.scrollBehaviorY.getCurrentPos(), }; }; ScrollerActions.prototype.refresh = function () { this.endTime = 0; }; ScrollerActions.prototype.destroy = function () { this.hooks.destroy(); }; return ScrollerActions; }()); function createActionsHandlerOptions(bsOptions) { var options = [ 'click', 'bindToWrapper', 'disableMouse', 'disableTouch', 'preventDefault', 'stopPropagation', 'tagException', 'preventDefaultException', 'autoEndDistance', ].reduce(function (prev, cur) { prev[cur] = bsOptions[cur]; return prev; }, {}); return options; } function createBehaviorOptions(bsOptions, extraProp, bounces, rect) { var options = [ 'momentum', 'momentumLimitTime', 'momentumLimitDistance', 'deceleration', 'swipeBounceTime', 'swipeTime', 'outOfBoundaryDampingFactor', 'specifiedIndexAsContent', ].reduce(function (prev, cur) { prev[cur] = bsOptions[cur]; return prev; }, {}); // add extra property options.scrollable = !!bsOptions[extraProp]; options.bounces = bounces; options.rect = rect; return options; } function bubbling(source, target, events) { events.forEach(function (event) { var sourceEvent; var targetEvent; if (typeof event === 'string') { sourceEvent = targetEvent = event; } else { sourceEvent = event.source; targetEvent = event.target; } source.on(sourceEvent, function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return target.trigger.apply(target, __spreadArrays([targetEvent], args)); }); }); } function isSamePoint(startPoint, endPoint) { // keys of startPoint and endPoint should be equal var keys = Object.keys(startPoint); for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var key = keys_1[_i]; if (startPoint[key] !== endPoint[key]) return false; } return true; } var MIN_SCROLL_DISTANCE = 1; var Scroller = /** @class */ (function () { function Scroller(wrapper, content, options) { this.wrapper = wrapper; this.content = content; this.resizeTimeout = 0; this.hooks = new EventEmitter([ 'beforeStart', 'beforeMove', 'beforeScrollStart', 'scrollStart', 'scroll', 'beforeEnd', 'scrollEnd', 'resize', 'touchEnd', 'end', 'flick', 'scrollCancel', 'momentum', 'scrollTo', 'minDistanceScroll', 'scrollToElement', 'beforeRefresh', ]); this.options = options; var _a = this.options.bounce, left = _a.left, right = _a.right, top = _a.top, bottom = _a.bottom; // direction X this.scrollBehaviorX = new Behavior(wrapper, content, createBehaviorOptions(options, 'scrollX', [left, right], { size: 'width', position: 'left', })); // direction Y this.scrollBehaviorY = new Behavior(wrapper, content, createBehaviorOptions(options, 'scrollY', [top, bottom], { size: 'height', position: 'top', })); this.translater = new Translater(this.content); this.animater = createAnimater(this.content, this.translater, this.options); this.actionsHandler = new ActionsHandler(this.options.bindToTarget ? this.content : wrapper, createActionsHandlerOptions(this.options)); this.actions = new ScrollerActions(this.scrollBehaviorX, this.scrollBehaviorY, this.actionsHandler, this.animater, this.options); var resizeHandler = this.resize.bind(this); this.resizeRegister = new EventRegister(window, [ { name: 'orientationchange', handler: resizeHandler, }, { name: 'resize', handler: resizeHandler, }, ]); this.registerTransitionEnd(); this.init(); } Scroller.prototype.init = function () { var _this = this; this.bindTranslater(); this.bindAnimater(); this.bindActions(); // enable pointer events when scrolling ends this.hooks.on(this.hooks.eventTypes.scrollEnd, function () { _this.togglePointerEvents(true); }); }; Scroller.prototype.registerTransitionEnd = function () { this.transitionEndRegister = new EventRegister(this.content, [ { name: style.transitionEnd, handler: this.transitionEnd.bind(this), }, ]); }; Scroller.prototype.bindTranslater = function () { var _this = this; var hooks = this.translater.hooks; hooks.on(hooks.eventTypes.beforeTranslate, function (transformStyle) { if (_this.options.translateZ) { transformStyle.push(_this.options.translateZ); } }); // disable pointer events when scrolling hooks.on(hooks.eventTypes.translate, function (pos) { var prevPos = _this.getCurrentPos(); _this.updatePositions(pos); // scrollEnd will dispatch when scroll is force stopping in touchstart handler // so in touchend handler, don't toggle pointer-events if (_this.actions.ensuringInteger === true) { _this.actions.ensuringInteger = false; return; } // a valid translate if (pos.x !== prevPos.x || pos.y !== prevPos.y) { _this.togglePointerEvents(false); } }); }; Scroller.prototype.bindAnimater = function () { var _this = this; // reset position this.animater.hooks.on(this.animater.hooks.eventTypes.end, function (pos) { if (!_this.resetPosition(_this.options.bounceTime)) { _this.animater.setPending(false); _this.hooks.trigger(_this.hooks.eventTypes.scrollEnd, pos); } }); bubbling(this.animater.hooks, this.hooks, [ { source: this.animater.hooks.eventTypes.move, target: this.hooks.eventTypes.scroll, }, { source: this.animater.hooks.eventTypes.forceStop, target: this.hooks.eventTypes.scrollEnd, }, ]); }; Scroller.prototype.bindActions = function () { var _this = this; var actions = this.actions; bubbling(actions.hooks, this.hooks, [ { source: actions.hooks.eventTypes.start, target: this.hooks.eventTypes.beforeStart, }, { source: actions.hooks.eventTypes.start, target: this.hooks.eventTypes.beforeScrollStart, }, { source: actions.hooks.eventTypes.beforeMove, target: this.hooks.eventTypes.beforeMove, }, { source: actions.hooks.eventTypes.scrollStart, target: this.hooks.eventTypes.scrollStart, }, { source: actions.hooks.eventTypes.scroll, target: this.hooks.eventTypes.scroll, }, { source: actions.hooks.eventTypes.beforeEnd, target: this.hooks.eventTypes.beforeEnd, }, ]); actions.hooks.on(actions.hooks.eventTypes.end, function (e, pos) { _this.hooks.trigger(_this.hooks.eventTypes.touchEnd, pos); if (_this.hooks.trigger(_this.hooks.eventTypes.end, pos)) { return true; } // check if it is a click operation if (!actions.fingerMoved) { _this.hooks.trigger(_this.hooks.eventTypes.scrollCancel); if (_this.checkClick(e)) { return true; } } // reset if we are outside of the boundaries if (_this.resetPosition(_this.options.bounceTime, ease.bounce)) { _this.animater.setForceStopped(false); return true; } }); actions.hooks.on(actions.hooks.eventTypes.scrollEnd, function (pos, duration) { var deltaX = Math.abs(pos.x - _this.scrollBehaviorX.startPos); var deltaY = Math.abs(pos.y - _this.scrollBehaviorY.startPos); if (_this.checkFlick(duration, deltaX, deltaY)) { _this.animater.setForceStopped(false); _this.hooks.trigger(_this.hooks.eventTypes.flick); return; } if (_this.momentum(pos, duration)) { _this.animater.setForceStopped(false); return; } if (actions.contentMoved) { _this.hooks.trigger(_this.hooks.eventTypes.scrollEnd, pos); } if (_this.animater.forceStopped) { _this.animater.setForceStopped(false); } }); }; Scroller.prototype.checkFlick = function (duration, deltaX, deltaY) { var flickMinMovingDistance = 1; // distinguish flick from click if (this.hooks.events.flick.length > 1 && duration < this.options.flickLimitTime && deltaX < this.options.flickLimitDistance && deltaY < this.options.flickLimitDistance && (deltaY > flickMinMovingDistance || deltaX > flickMinMovingDistance)) { return true; } }; Scroller.prototype.momentum = function (pos, duration) { var meta = { time: 0, easing: ease.swiper, newX: pos.x, newY: pos.y, }; // start momentum animation if needed var momentumX = this.scrollBehaviorX.end(duration); var momentumY = this.scrollBehaviorY.end(duration); meta.newX = isUndef(momentumX.destination) ? meta.newX : momentumX.destination; meta.newY = isUndef(momentumY.destination) ? meta.newY : momentumY.destination; meta.time = Math.max(momentumX.duration, momentumY.duration); this.hooks.trigger(this.hooks.eventTypes.momentum, meta, this); // when x or y changed, do momentum animation now! if (meta.newX !== pos.x || meta.newY !== pos.y) { // change easing function when scroller goes out of the boundaries if (meta.newX > this.scrollBehaviorX.minScrollPos || meta.newX < this.scrollBehaviorX.maxScrollPos || meta.newY > this.scrollBehaviorY.minScrollPos || meta.newY < this.scrollBehaviorY.maxScrollPos) { meta.easing = ease.swipeBounce; } this.scrollTo(meta.newX, meta.newY, meta.time, meta.easing); return true; } }; Scroller.prototype.checkClick = function (e) { var cancelable = { preventClick: this.animater.forceStopped, }; // we scrolled less than momentumLimitDistance pixels if (this.hooks.trigger(this.hooks.eventTypes.checkClick)) { this.animater.setForceStopped(false); return true; } if (!cancelable.preventClick) { var _dblclick = this.options.dblclick; var dblclickTrigged = false; if (_dblclick && this.lastClickTime) { var _a = _dblclick.delay, delay = _a === void 0 ? 300 : _a; if (getNow() - this.lastClickTime < delay) { dblclickTrigged = true; dblclick(e); } } if (this.options.tap) { tap(e, this.options.tap); } if (this.options.click && !preventDefaultExceptionFn(e.target, this.options.preventDefaultException)) { click(e); } this.lastClickTime = dblclickTrigged ? null : getNow(); return true; } return false; }; Scroller.prototype.resize = function () { var _this = this; if (!this.actions.enabled) { return; } // fix a scroll problem under Android condition /* istanbul ignore if */ if (isAndroid) { this.wrapper.scrollTop = 0; } clearTimeout(this.resizeTimeout); this.resizeTimeout = window.setTimeout(function () { _this.hooks.trigger(_this.hooks.eventTypes.resize); }, this.options.resizePolling); }; /* istanbul ignore next */ Scroller.prototype.transitionEnd = function (e) { if (e.target !== this.content || !this.animater.pending) { return; } var animater = this.animater; animater.transitionTime(); if (!this.resetPosition(this.options.bounceTime, ease.bounce)) { this.animater.setPending(false); if (this.options.probeType !== 3 /* Realtime */) { this.hooks.trigger(this.hooks.eventTypes.scrollEnd, this.getCurrentPos()); } } }; Scroller.prototype.togglePointerEvents = function (enabled) { if (enabled === void 0) { enabled = true; } var el = this.content.children.length ? this.content.children : [this.content]; var pointerEvents = enabled ? 'auto' : 'none'; for (var i = 0; i < el.length; i++) { var node = el[i]; // ignore BetterScroll instance's wrapper DOM /* istanbul ignore if */ if (node.isBScrollContainer) { continue; } node.style.pointerEvents = pointerEvents; } }; Scroller.prototype.refresh = function (content) { var contentChanged = this.setContent(content); this.hooks.trigger(this.hooks.eventTypes.beforeRefresh); this.scrollBehaviorX.refresh(content); this.scrollBehaviorY.refresh(content); if (contentChanged) { this.translater.setContent(content); this.animater.setContent(content); this.transitionEndRegister.destroy(); this.registerTransitionEnd(); if (this.options.bindToTarget) { this.actionsHandler.setContent(content); } } this.actions.refresh(); this.wrapperOffset = offset(this.wrapper); }; Scroller.prototype.setContent = function (content) { var contentChanged = content !== this.content; if (contentChanged) { this.content = content; } return contentChanged; }; Scroller.prototype.scrollBy = function (deltaX, deltaY, time, easing) { if (time === void 0) { time = 0; } var _a = this.getCurrentPos(), x = _a.x, y = _a.y; easing = !easing ? ease.bounce : easing; deltaX += x; deltaY += y; this.scrollTo(deltaX, deltaY, time, easing); }; Scroller.prototype.scrollTo = function (x, y, time, easing, extraTransform) { if (time === void 0) { time = 0; } if (easing === void 0) { easing = ease.bounce; } if (extraTransform === void 0) { extraTransform = { start: {}, end: {}, }; } var easingFn = this.options.useTransition ? easing.style : easing.fn; var currentPos = this.getCurrentPos(); var startPoint = __assign({ x: currentPos.x, y: currentPos.y }, extraTransform.start); var endPoint = __assign({ x: x, y: y }, extraTransform.end); this.hooks.trigger(this.hooks.eventTypes.scrollTo, endPoint); // it is an useless move if (isSamePoint(startPoint, endPoint)) return; var deltaX = Math.abs(endPoint.x - startPoint.x); var deltaY = Math.abs(endPoint.y - startPoint.y); // considering of browser compatibility for decimal transform value // force translating immediately if (deltaX < MIN_SCROLL_DISTANCE && deltaY < MIN_SCROLL_DISTANCE) { time = 0; this.hooks.trigger(this.hooks.eventTypes.minDistanceScroll); } this.animater.move(startPoint, endPoint, time, easingFn); }; Scroller.prototype.scrollToElement = function (el, time, offsetX, offsetY, easing) { var targetEle = getElement(el); var pos = offset(targetEle); var getOffset = function (offset, size, wrapperSize) { if (typeof offset === 'number') { return offset; } // if offsetX/Y are true we center the element to the screen return offset ? Math.round(size / 2 - wrapperSize / 2) : 0; }; offsetX = getOffset(offsetX, targetEle.offsetWidth, this.wrapper.offsetWidth); offsetY = getOffset(offsetY, targetEle.offsetHeight, this.wrapper.offsetHeight); var getPos = function (pos, wrapperPos, offset, scrollBehavior) { pos -= wrapperPos; pos = scrollBehavior.adjustPosition(pos - offset); return pos; }; pos.left = getPos(pos.left, this.wrapperOffset.left, offsetX, this.scrollBehaviorX); pos.top = getPos(pos.top, this.wrapperOffset.top, offsetY, this.scrollBehaviorY); if (this.hooks.trigger(this.hooks.eventTypes.scrollToElement, targetEle, pos)) { return; } this.scrollTo(pos.left, pos.top, time, easing); }; Scroller.prototype.resetPosition = function (time, easing) { if (time === void 0) { time = 0; } if (easing === void 0) { easing = ease.bounce; } var _a = this.scrollBehaviorX.checkInBoundary(), x = _a.position, xInBoundary = _a.inBoundary; var _b = this.scrollBehaviorY.checkInBoundary(), y = _b.position, yInBoundary = _b.inBoundary; if (xInBoundary && yInBoundary) { return false; } /* istanbul ignore if */ if (isIOSBadVersion) { // fix ios 13.4 bouncing // see it in issues 982 this.reflow(); } // out of boundary this.scrollTo(x, y, time, easing); return true; }; /* istanbul ignore next */ Scroller.prototype.reflow = function () { this._reflow = this.content.offsetHeight; }; Scroller.prototype.updatePositions = function (pos) { this.scrollBehaviorX.updatePosition(pos.x); this.scrollBehaviorY.updatePosition(pos.y); }; Scroller.prototype.getCurrentPos = function () { return this.actions.getCurrentPos(); }; Scroller.prototype.enable = function () { this.actions.enabled = true; }; Scroller.prototype.disable = function () { cancelAnimationFrame(this.animater.timer); this.actions.enabled = false; }; Scroller.prototype.destroy = function () { var _this = this; var keys = [ 'resizeRegister', 'transitionEndRegister', 'actionsHandler', 'actions', 'hooks', 'animater', 'translater', 'scrollBehaviorX', 'scrollBehaviorY', ]; keys.forEach(function (key) { return _this[key].destroy(); }); }; return Scroller; }()); var BScrollConstructor = /** @class */ (function (_super) { __extends(BScrollConstructor, _super); function BScrollConstructor(el, options) { var _this = _super.call(this, [ 'refresh', 'contentChanged', 'enable', 'disable', 'beforeScrollStart', 'scrollStart', 'scroll', 'scrollEnd', 'scrollCancel', 'touchEnd', 'flick', 'destroy' ]) || this; var wrapper = getElement(el); if (!wrapper) { warn('Can not resolve the wrapper DOM.'); return _this; } _this.plugins = {}; _this.options = new OptionsConstructor().merge(options).process(); if (!_this.setContent(wrapper).valid) { return _this; } _this.hooks = new EventEmitter([ 'refresh', 'enable', 'disable', 'destroy', 'beforeInitialScrollTo', 'contentChanged' ]); _this.init(wrapper); return _this; } BScrollConstructor.use = function (ctor) { var name = ctor.pluginName; var installed = BScrollConstructor.plugins.some(function (plugin) { return ctor === plugin.ctor; }); if (installed) return BScrollConstructor; if (isUndef(name)) { warn("Plugin Class must specify plugin's name in static property by 'pluginName' field."); return BScrollConstructor; } BScrollConstructor.pluginsMap[name] = true; BScrollConstructor.plugins.push({ name: name, applyOrder: ctor.applyOrder, ctor: ctor }); return BScrollConstructor; }; BScrollConstructor.prototype.setContent = function (wrapper) { var contentChanged = false; var valid = true; var content = wrapper.children[this.options.specifiedIndexAsContent]; if (!content) { warn('The wrapper need at least one child element to be content element to scroll.'); valid = false; } else { contentChanged = this.content !== content; if (contentChanged) { this.content = content; } } return { valid: valid, contentChanged: contentChanged }; }; BScrollConstructor.prototype.init = function (wrapper) { var _this = this; this.wrapper = wrapper; // mark wrapper to recognize bs instance by DOM attribute wrapper.isBScrollContainer = true; this.scroller = new Scroller(wrapper, this.content, this.options); this.scroller.hooks.on(this.scroller.hooks.eventTypes.resize, function () { _this.refresh(); }); this.eventBubbling(); this.handleAutoBlur(); this.enable(); this.proxy(propertiesConfig$7); this.applyPlugins(); // maybe boundary has changed, should refresh this.refreshWithoutReset(this.content); var _a = this.options, startX = _a.startX, startY = _a.startY; var position = { x: startX, y: startY }; // maybe plugins want to control scroll position if (this.hooks.trigger(this.hooks.eventTypes.beforeInitialScrollTo, position)) { return; } this.scroller.scrollTo(position.x, position.y); }; BScrollConstructor.prototype.applyPlugins = function () { var _this = this; var options = this.options; BScrollConstructor.plugins .sort(function (a, b) { var _a; var applyOrderMap = (_a = {}, _a["pre" /* Pre */] = -1, _a["post" /* Post */] = 1, _a); var aOrder = a.applyOrder ? applyOrderMap[a.applyOrder] : 0; var bOrder = b.applyOrder ? applyOrderMap[b.applyOrder] : 0; return aOrder - bOrder; }) .forEach(function (item) { var ctor = item.ctor; if (options[item.name] && typeof ctor === 'function') { _this.plugins[item.name] = new ctor(_this); } }); }; BScrollConstructor.prototype.handleAutoBlur = function () { /* istanbul ignore if */ if (this.options.autoBlur) { this.on(this.eventTypes.beforeScrollStart, function () { var activeElement = document.activeElement; if (activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA')) { activeElement.blur(); } }); } }; BScrollConstructor.prototype.eventBubbling = function () { bubbling(this.scroller.hooks, this, [ this.eventTypes.beforeScrollStart, this.eventTypes.scrollStart, this.eventTypes.scroll, this.eventTypes.scrollEnd, this.eventTypes.scrollCancel, this.eventTypes.touchEnd, this.eventTypes.flick ]); }; BScrollConstructor.prototype.refreshWithoutReset = function (content) { this.scroller.refresh(content); this.hooks.trigger(this.hooks.eventTypes.refresh, content); this.trigger(this.eventTypes.refresh, content); }; BScrollConstructor.prototype.proxy = function (propertiesConfig) { var _this = this; propertiesConfig.forEach(function (_a) { var key = _a.key, sourceKey = _a.sourceKey; propertiesProxy(_this, sourceKey, key); }); }; BScrollConstructor.prototype.refresh = function () { var _a = this.setContent(this.wrapper), contentChanged = _a.contentChanged, valid = _a.valid; if (valid) { var content = this.content; this.refreshWithoutReset(content); if (contentChanged) { this.hooks.trigger(this.hooks.eventTypes.contentChanged, content); this.trigger(this.eventTypes.contentChanged, content); } this.scroller.resetPosition(); } }; BScrollConstructor.prototype.enable = function () { this.scroller.enable(); this.hooks.trigger(this.hooks.eventTypes.enable); this.trigger(this.eventTypes.enable); }; BScrollConstructor.prototype.disable = function () { this.scroller.disable(); this.hooks.trigger(this.hooks.eventTypes.disable); this.trigger(this.eventTypes.disable); }; BScrollConstructor.prototype.destroy = function () { this.hooks.trigger(this.hooks.eventTypes.destroy); this.trigger(this.eventTypes.destroy); this.scroller.destroy(); }; BScrollConstructor.prototype.eventRegister = function (names) { this.registerType(names); }; BScrollConstructor.plugins = []; BScrollConstructor.pluginsMap = {}; return BScrollConstructor; }(EventEmitter)); function createBScroll(el, options) { var bs = new BScrollConstructor(el, options); return bs; } createBScroll.use = BScrollConstructor.use; createBScroll.plugins = BScrollConstructor.plugins; createBScroll.pluginsMap = BScrollConstructor.pluginsMap; var BScroll = createBScroll; var MouseWheel = /** @class */ (function () { function MouseWheel(scroll) { this.scroll = scroll; this.wheelEndTimer = 0; this.wheelMoveTimer = 0; this.wheelStart = false; this.init(); } MouseWheel.prototype.init = function () { this.handleBScroll(); this.handleOptions(); this.handleHooks(); this.registerEvent(); }; MouseWheel.prototype.handleBScroll = function () { this.scroll.registerType([ 'alterOptions', 'mousewheelStart', 'mousewheelMove', 'mousewheelEnd', ]); }; MouseWheel.prototype.handleOptions = function () { var userOptions = (this.scroll.options.mouseWheel === true ? {} : this.scroll.options.mouseWheel); var defaultOptions = { speed: 20, invert: false, easeTime: 300, discreteTime: 400, throttleTime: 0, dampingFactor: 0.1, }; this.mouseWheelOpt = extend(defaultOptions, userOptions); }; MouseWheel.prototype.handleHooks = function () { this.hooksFn = []; this.registerHooks(this.scroll.hooks, 'destroy', this.destroy); }; MouseWheel.prototype.registerEvent = function () { this.eventRegister = new EventRegister(this.scroll.scroller.wrapper, [ { name: 'wheel', handler: this.wheelHandler.bind(this), }, { name: 'mousewheel', handler: this.wheelHandler.bind(this), }, { name: 'DOMMouseScroll', handler: this.wheelHandler.bind(this), }, ]); }; MouseWheel.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; MouseWheel.prototype.wheelHandler = function (e) { if (!this.scroll.enabled) { return; } this.beforeHandler(e); // start if (!this.wheelStart) { this.wheelStartHandler(e); this.wheelStart = true; } // move var delta = this.getWheelDelta(e); this.wheelMoveHandler(delta); // end this.wheelEndDetector(delta); }; MouseWheel.prototype.wheelStartHandler = function (e) { this.cleanCache(); var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; scrollBehaviorX.setMovingDirection(0 /* Default */); scrollBehaviorY.setMovingDirection(0 /* Default */); scrollBehaviorX.setDirection(0 /* Default */); scrollBehaviorY.setDirection(0 /* Default */); this.scroll.trigger(this.scroll.eventTypes.alterOptions, this.mouseWheelOpt); this.scroll.trigger(this.scroll.eventTypes.mousewheelStart); }; MouseWheel.prototype.cleanCache = function () { this.deltaCache = []; }; MouseWheel.prototype.wheelMoveHandler = function (delta) { var _this = this; var _a = this.mouseWheelOpt, throttleTime = _a.throttleTime, dampingFactor = _a.dampingFactor; if (throttleTime && this.wheelMoveTimer) { this.deltaCache.push(delta); } else { var cachedDelta = this.deltaCache.reduce(function (prev, current) { return { x: prev.x + current.x, y: prev.y + current.y, }; }, { x: 0, y: 0 }); this.cleanCache(); var _b = this.scroll.scroller, scrollBehaviorX = _b.scrollBehaviorX, scrollBehaviorY = _b.scrollBehaviorY; scrollBehaviorX.setMovingDirection(-delta.directionX); scrollBehaviorY.setMovingDirection(-delta.directionY); scrollBehaviorX.setDirection(delta.x); scrollBehaviorY.setDirection(delta.y); // when out of boundary, perform a damping scroll var newX = scrollBehaviorX.performDampingAlgorithm(Math.round(delta.x) + cachedDelta.x, dampingFactor); var newY = scrollBehaviorY.performDampingAlgorithm(Math.round(delta.y) + cachedDelta.x, dampingFactor); if (!this.scroll.trigger(this.scroll.eventTypes.mousewheelMove, { x: newX, y: newY, })) { var easeTime = this.getEaseTime(); if (newX !== this.scroll.x || newY !== this.scroll.y) { this.scroll.scrollTo(newX, newY, easeTime); } } if (throttleTime) { this.wheelMoveTimer = window.setTimeout(function () { _this.wheelMoveTimer = 0; }, throttleTime); } } }; MouseWheel.prototype.wheelEndDetector = function (delta) { var _this = this; window.clearTimeout(this.wheelEndTimer); this.wheelEndTimer = window.setTimeout(function () { _this.wheelStart = false; window.clearTimeout(_this.wheelMoveTimer); _this.wheelMoveTimer = 0; _this.scroll.trigger(_this.scroll.eventTypes.mousewheelEnd, delta); }, this.mouseWheelOpt.discreteTime); }; MouseWheel.prototype.getWheelDelta = function (e) { var _a = this.mouseWheelOpt, speed = _a.speed, invert = _a.invert; var wheelDeltaX = 0; var wheelDeltaY = 0; var direction = invert ? -1 /* Negative */ : 1 /* Positive */; switch (true) { case 'deltaX' in e: if (e.deltaMode === 1) { wheelDeltaX = -e.deltaX * speed; wheelDeltaY = -e.deltaY * speed; } else { wheelDeltaX = -e.deltaX; wheelDeltaY = -e.deltaY; } break; case 'wheelDeltaX' in e: wheelDeltaX = (e.wheelDeltaX / 120) * speed; wheelDeltaY = (e.wheelDeltaY / 120) * speed; break; case 'wheelDelta' in e: wheelDeltaX = wheelDeltaY = (e.wheelDelta / 120) * speed; break; case 'detail' in e: wheelDeltaX = wheelDeltaY = (-e.detail / 3) * speed; break; } wheelDeltaX *= direction; wheelDeltaY *= direction; if (!this.scroll.hasVerticalScroll) { if (Math.abs(wheelDeltaY) > Math.abs(wheelDeltaX)) { wheelDeltaX = wheelDeltaY; } wheelDeltaY = 0; } if (!this.scroll.hasHorizontalScroll) { wheelDeltaX = 0; } var directionX = wheelDeltaX > 0 ? -1 /* Negative */ : wheelDeltaX < 0 ? 1 /* Positive */ : 0 /* Default */; var directionY = wheelDeltaY > 0 ? -1 /* Negative */ : wheelDeltaY < 0 ? 1 /* Positive */ : 0 /* Default */; return { x: wheelDeltaX, y: wheelDeltaY, directionX: directionX, directionY: directionY, }; }; MouseWheel.prototype.beforeHandler = function (e) { var _a = this.scroll.options, preventDefault = _a.preventDefault, stopPropagation = _a.stopPropagation, preventDefaultException = _a.preventDefaultException; if (preventDefault && !preventDefaultExceptionFn(e.target, preventDefaultException)) { e.preventDefault(); } if (stopPropagation) { e.stopPropagation(); } }; MouseWheel.prototype.getEaseTime = function () { var SAFE_EASETIME = 100; var easeTime = this.mouseWheelOpt.easeTime; // scrollEnd event will be triggered in every calling of scrollTo when easeTime is too small // easeTime needs to be greater than 100 if (easeTime < SAFE_EASETIME) { warn("easeTime should be greater than 100." + "If mouseWheel easeTime is too small," + "scrollEnd will be triggered many times."); } return Math.max(easeTime, SAFE_EASETIME); }; MouseWheel.prototype.destroy = function () { this.eventRegister.destroy(); window.clearTimeout(this.wheelEndTimer); window.clearTimeout(this.wheelMoveTimer); this.hooksFn.forEach(function (item) { var hooks = item[0]; var hooksName = item[1]; var handlerFn = item[2]; hooks.off(hooksName, handlerFn); }); }; MouseWheel.pluginName = 'mouseWheel'; MouseWheel.applyOrder = "pre" /* Pre */; return MouseWheel; }()); var ObserveDOM = /** @class */ (function () { function ObserveDOM(scroll) { this.scroll = scroll; this.stopObserver = false; this.init(); } ObserveDOM.prototype.init = function () { this.handleMutationObserver(); this.handleHooks(); }; ObserveDOM.prototype.handleMutationObserver = function () { var _this = this; if (typeof MutationObserver !== 'undefined') { var timer_1 = 0; this.observer = new MutationObserver(function (mutations) { _this.mutationObserverHandler(mutations, timer_1); }); this.startObserve(this.observer); } else { this.checkDOMUpdate(); } }; ObserveDOM.prototype.handleHooks = function () { var _this = this; this.hooksFn = []; this.registerHooks(this.scroll.hooks, this.scroll.hooks.eventTypes.contentChanged, function () { _this.stopObserve(); // launch a new mutationObserver _this.handleMutationObserver(); }); this.registerHooks(this.scroll.hooks, this.scroll.hooks.eventTypes.enable, function () { if (_this.stopObserver) { _this.handleMutationObserver(); } }); this.registerHooks(this.scroll.hooks, this.scroll.hooks.eventTypes.disable, function () { _this.stopObserve(); }); this.registerHooks(this.scroll.hooks, this.scroll.hooks.eventTypes.destroy, function () { _this.destroy(); }); }; ObserveDOM.prototype.mutationObserverHandler = function (mutations, timer) { var _this = this; if (this.shouldNotRefresh()) { return; } var immediateRefresh = false; var deferredRefresh = false; for (var i = 0; i < mutations.length; i++) { var mutation = mutations[i]; if (mutation.type !== 'attributes') { immediateRefresh = true; break; } else { if (mutation.target !== this.scroll.scroller.content) { deferredRefresh = true; break; } } } if (immediateRefresh) { this.scroll.refresh(); } else if (deferredRefresh) { // attributes changes too often clearTimeout(timer); timer = window.setTimeout(function () { if (!_this.shouldNotRefresh()) { _this.scroll.refresh(); } }, 60); } }; ObserveDOM.prototype.startObserve = function (observer) { var config = { attributes: true, childList: true, subtree: true, }; observer.observe(this.scroll.scroller.content, config); }; ObserveDOM.prototype.shouldNotRefresh = function () { var scroller = this.scroll.scroller; var scrollBehaviorX = scroller.scrollBehaviorX, scrollBehaviorY = scroller.scrollBehaviorY; var outsideBoundaries = scrollBehaviorX.currentPos > scrollBehaviorX.minScrollPos || scrollBehaviorX.currentPos < scrollBehaviorX.maxScrollPos || scrollBehaviorY.currentPos > scrollBehaviorY.minScrollPos || scrollBehaviorY.currentPos < scrollBehaviorY.maxScrollPos; return scroller.animater.pending || outsideBoundaries; }; ObserveDOM.prototype.checkDOMUpdate = function () { var _this = this; var content = this.scroll.scroller.content; var contentRect = getRect(content); var oldWidth = contentRect.width; var oldHeight = contentRect.height; var check = function () { if (_this.stopObserver) { return; } contentRect = getRect(content); var newWidth = contentRect.width; var newHeight = contentRect.height; if (oldWidth !== newWidth || oldHeight !== newHeight) { _this.scroll.refresh(); } oldWidth = newWidth; oldHeight = newHeight; next(); }; var next = function () { setTimeout(function () { check(); }, 1000); }; next(); }; ObserveDOM.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; ObserveDOM.prototype.stopObserve = function () { this.stopObserver = true; if (this.observer) { this.observer.disconnect(); } }; ObserveDOM.prototype.destroy = function () { this.stopObserve(); this.hooksFn.forEach(function (item) { var hooks = item[0]; var hooksName = item[1]; var handlerFn = item[2]; hooks.off(hooksName, handlerFn); }); this.hooksFn.length = 0; }; ObserveDOM.pluginName = 'observeDOM'; return ObserveDOM; }()); var sourcePrefix$6 = 'plugins.pullDownRefresh'; var propertiesMap$6 = [ { key: 'finishPullDown', name: 'finishPullDown' }, { key: 'openPullDown', name: 'openPullDown' }, { key: 'closePullDown', name: 'closePullDown' }, { key: 'autoPullDownRefresh', name: 'autoPullDownRefresh' } ]; var propertiesConfig$6 = propertiesMap$6.map(function (item) { return { key: item.key, sourceKey: sourcePrefix$6 + "." + item.name }; }); var PULLING_DOWN_EVENT = 'pullingDown'; var ENTER_THRESHOLD_EVENT = 'enterThreshold'; var LEAVE_THRESHOLD_EVENT = 'leaveThreshold'; var PullDown = /** @class */ (function () { function PullDown(scroll) { this.scroll = scroll; this.pulling = 0 /* DEFAULT */; this.thresholdBoundary = 0 /* DEFAULT */; this.init(); } PullDown.prototype.setPulling = function (status) { this.pulling = status; }; PullDown.prototype.setThresholdBoundary = function (boundary) { this.thresholdBoundary = boundary; }; PullDown.prototype.init = function () { this.handleBScroll(); this.handleOptions(this.scroll.options.pullDownRefresh); this.handleHooks(); this.watch(); }; PullDown.prototype.handleBScroll = function () { this.scroll.registerType([ PULLING_DOWN_EVENT, ENTER_THRESHOLD_EVENT, LEAVE_THRESHOLD_EVENT, ]); this.scroll.proxy(propertiesConfig$6); }; PullDown.prototype.handleOptions = function (userOptions) { if (userOptions === void 0) { userOptions = {}; } userOptions = (userOptions === true ? {} : userOptions); var defaultOptions = { threshold: 90, stop: 40, }; this.options = extend(defaultOptions, userOptions); this.scroll.options.probeType = 3 /* Realtime */; }; PullDown.prototype.handleHooks = function () { var _this = this; this.hooksFn = []; var scroller = this.scroll.scroller; var scrollBehaviorY = scroller.scrollBehaviorY; this.currentMinScrollY = this.cachedOriginanMinScrollY = scrollBehaviorY.minScrollPos; this.registerHooks(this.scroll.hooks, this.scroll.hooks.eventTypes.contentChanged, function () { _this.finishPullDown(); }); this.registerHooks(scrollBehaviorY.hooks, scrollBehaviorY.hooks.eventTypes.computeBoundary, function (boundary) { // content is smaller than wrapper if (boundary.maxScrollPos > 0) { // allow scrolling when content is not full of wrapper boundary.maxScrollPos = -1; } boundary.minScrollPos = _this.currentMinScrollY; }); // integrate with mousewheel if (this.hasMouseWheelPlugin()) { this.registerHooks(this.scroll, this.scroll.eventTypes.alterOptions, function (mouseWheelOptions) { var SANE_DISCRETE_TIME = 300; var SANE_EASE_TIME = 350; mouseWheelOptions.discreteTime = SANE_DISCRETE_TIME; // easeTime > discreteTime ensure goInto checkPullDown function mouseWheelOptions.easeTime = SANE_EASE_TIME; }); this.registerHooks(this.scroll, this.scroll.eventTypes.mousewheelEnd, function () { // mouseWheel need trigger checkPullDown manually scroller.hooks.trigger(scroller.hooks.eventTypes.end); }); } }; PullDown.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; PullDown.prototype.hasMouseWheelPlugin = function () { return !!this.scroll.eventTypes.alterOptions; }; PullDown.prototype.watch = function () { var scroller = this.scroll.scroller; this.watching = true; this.registerHooks(scroller.hooks, scroller.hooks.eventTypes.end, this.checkPullDown); this.registerHooks(this.scroll, this.scroll.eventTypes.scrollStart, this.resetStateBeforeScrollStart); this.registerHooks(this.scroll, this.scroll.eventTypes.scroll, this.checkLocationOfThresholdBoundary); if (this.hasMouseWheelPlugin()) { this.registerHooks(this.scroll, this.scroll.eventTypes.mousewheelStart, this.resetStateBeforeScrollStart); } }; PullDown.prototype.resetStateBeforeScrollStart = function () { // current fetching pulldownRefresh has ended if (!this.isFetchingStatus()) { this.setPulling(1 /* MOVING */); this.setThresholdBoundary(0 /* DEFAULT */); } }; PullDown.prototype.checkLocationOfThresholdBoundary = function () { // pulldownRefresh is in the phase of Moving if (this.pulling === 1 /* MOVING */) { var scroll_1 = this.scroll; // enter threshold boundary var enteredThresholdBoundary = this.thresholdBoundary !== 1 /* INSIDE */ && this.locateInsideThresholdBoundary(); // leave threshold boundary var leftThresholdBoundary = this.thresholdBoundary !== 2 /* OUTSIDE */ && !this.locateInsideThresholdBoundary(); if (enteredThresholdBoundary) { this.setThresholdBoundary(1 /* INSIDE */); scroll_1.trigger(ENTER_THRESHOLD_EVENT); } if (leftThresholdBoundary) { this.setThresholdBoundary(2 /* OUTSIDE */); scroll_1.trigger(LEAVE_THRESHOLD_EVENT); } } }; PullDown.prototype.locateInsideThresholdBoundary = function () { return this.scroll.y <= this.options.threshold; }; PullDown.prototype.unwatch = function () { var scroll = this.scroll; var scroller = scroll.scroller; this.watching = false; scroller.hooks.off(scroller.hooks.eventTypes.end, this.checkPullDown); scroll.off(scroll.eventTypes.scrollStart, this.resetStateBeforeScrollStart); scroll.off(scroll.eventTypes.scroll, this.checkLocationOfThresholdBoundary); if (this.hasMouseWheelPlugin()) { scroll.off(scroll.eventTypes.mousewheelStart, this.resetStateBeforeScrollStart); } }; PullDown.prototype.checkPullDown = function () { var _a = this.options, threshold = _a.threshold, stop = _a.stop; // check if a real pull down action if (this.scroll.y < threshold) { return false; } if (this.pulling === 1 /* MOVING */) { this.modifyBehaviorYBoundary(stop); this.setPulling(2 /* FETCHING */); this.scroll.trigger(PULLING_DOWN_EVENT); } this.scroll.scrollTo(this.scroll.x, stop, this.scroll.options.bounceTime, ease.bounce); return this.isFetchingStatus(); }; PullDown.prototype.isFetchingStatus = function () { return this.pulling === 2 /* FETCHING */; }; PullDown.prototype.modifyBehaviorYBoundary = function (stopDistance) { var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY; // manually modify minScrollPos for a hang animation // to prevent from resetPosition this.cachedOriginanMinScrollY = scrollBehaviorY.minScrollPos; this.currentMinScrollY = stopDistance; scrollBehaviorY.computeBoundary(); }; PullDown.prototype.finishPullDown = function () { if (this.isFetchingStatus()) { var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY; // restore minScrollY since the hang animation has ended this.currentMinScrollY = this.cachedOriginanMinScrollY; scrollBehaviorY.computeBoundary(); this.setPulling(0 /* DEFAULT */); this.scroll.resetPosition(this.scroll.options.bounceTime, ease.bounce); } }; // allow 'true' type is compat for beta version implements PullDown.prototype.openPullDown = function (config) { if (config === void 0) { config = {}; } this.handleOptions(config); if (!this.watching) { this.watch(); } }; PullDown.prototype.closePullDown = function () { this.unwatch(); }; PullDown.prototype.autoPullDownRefresh = function () { var _a = this.options, threshold = _a.threshold, stop = _a.stop; if (this.isFetchingStatus() || !this.watching) { return; } this.modifyBehaviorYBoundary(stop); this.scroll.trigger(this.scroll.eventTypes.scrollStart); this.scroll.scrollTo(this.scroll.x, threshold); this.setPulling(2 /* FETCHING */); this.scroll.trigger(PULLING_DOWN_EVENT); this.scroll.scrollTo(this.scroll.x, stop, this.scroll.options.bounceTime, ease.bounce); }; PullDown.pluginName = 'pullDownRefresh'; return PullDown; }()); var sourcePrefix$5 = 'plugins.pullUpLoad'; var propertiesMap$5 = [ { key: 'finishPullUp', name: 'finishPullUp' }, { key: 'openPullUp', name: 'openPullUp' }, { key: 'closePullUp', name: 'closePullUp' }, { key: 'autoPullUpLoad', name: 'autoPullUpLoad' } ]; var propertiesConfig$5 = propertiesMap$5.map(function (item) { return { key: item.key, sourceKey: sourcePrefix$5 + "." + item.name }; }); var PULL_UP_HOOKS_NAME = 'pullingUp'; var PullUp = /** @class */ (function () { function PullUp(scroll) { this.scroll = scroll; this.pulling = false; this.watching = false; this.init(); } PullUp.prototype.init = function () { this.handleBScroll(); this.handleOptions(this.scroll.options.pullUpLoad); this.handleHooks(); this.watch(); }; PullUp.prototype.handleBScroll = function () { this.scroll.registerType([PULL_UP_HOOKS_NAME]); this.scroll.proxy(propertiesConfig$5); }; PullUp.prototype.handleOptions = function (userOptions) { if (userOptions === void 0) { userOptions = {}; } userOptions = (userOptions === true ? {} : userOptions); var defaultOptions = { threshold: 0, }; this.options = extend(defaultOptions, userOptions); this.scroll.options.probeType = 3 /* Realtime */; }; PullUp.prototype.handleHooks = function () { var _this = this; this.hooksFn = []; var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY; this.registerHooks(this.scroll.hooks, this.scroll.hooks.eventTypes.contentChanged, function () { _this.finishPullUp(); }); this.registerHooks(scrollBehaviorY.hooks, scrollBehaviorY.hooks.eventTypes.computeBoundary, function (boundary) { // content is smaller than wrapper if (boundary.maxScrollPos > 0) { // allow scrolling when content is not full of wrapper boundary.maxScrollPos = -1; } }); }; PullUp.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; PullUp.prototype.watch = function () { if (this.watching) { return; } this.watching = true; this.registerHooks(this.scroll, this.scroll.eventTypes.scroll, this.checkPullUp); }; PullUp.prototype.unwatch = function () { this.watching = false; this.scroll.off(this.scroll.eventTypes.scroll, this.checkPullUp); }; PullUp.prototype.checkPullUp = function (pos) { var _this = this; var threshold = this.options.threshold; if (this.scroll.movingDirectionY === 1 /* Positive */ && pos.y <= this.scroll.maxScrollY + threshold) { this.pulling = true; // must reset pulling after scrollEnd this.scroll.once(this.scroll.eventTypes.scrollEnd, function () { _this.pulling = false; }); this.unwatch(); this.scroll.trigger(PULL_UP_HOOKS_NAME); } }; PullUp.prototype.finishPullUp = function () { var _this = this; // reset Direction, fix #936 this.scroll.scroller.scrollBehaviorY.setMovingDirection(0 /* Default */); if (this.pulling) { this.scroll.once(this.scroll.eventTypes.scrollEnd, function () { _this.watch(); }); } else { this.watch(); } }; // allow 'true' type is compat for beta version implements PullUp.prototype.openPullUp = function (config) { if (config === void 0) { config = {}; } this.handleOptions(config); this.watch(); }; PullUp.prototype.closePullUp = function () { this.unwatch(); }; PullUp.prototype.autoPullUpLoad = function () { var threshold = this.options.threshold; var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY; if (this.pulling || !this.watching) { return; } // simulate a pullUp action var NEGATIVE_VALUE = -1; var outOfBoundaryPos = scrollBehaviorY.maxScrollPos + threshold + NEGATIVE_VALUE; this.scroll.scroller.scrollBehaviorY.setMovingDirection(NEGATIVE_VALUE); this.scroll.scrollTo(this.scroll.x, outOfBoundaryPos, this.scroll.options.bounceTime); }; PullUp.pluginName = 'pullUpLoad'; return PullUp; }()); var EventHandler = /** @class */ (function () { function EventHandler(indicator, options) { this.indicator = indicator; this.options = options; this.hooks = new EventEmitter(['touchStart', 'touchMove', 'touchEnd']); this.registerEvents(); } EventHandler.prototype.registerEvents = function () { var _a = this.options, disableMouse = _a.disableMouse, disableTouch = _a.disableTouch; var startEvents = []; var moveEvents = []; var endEvents = []; if (!disableMouse) { startEvents.push({ name: 'mousedown', handler: this.start.bind(this), }); moveEvents.push({ name: 'mousemove', handler: this.move.bind(this), }); endEvents.push({ name: 'mouseup', handler: this.end.bind(this), }); } if (!disableTouch) { startEvents.push({ name: 'touchstart', handler: this.start.bind(this), }); moveEvents.push({ name: 'touchmove', handler: this.move.bind(this), }); endEvents.push({ name: 'touchend', handler: this.end.bind(this), }, { name: 'touchcancel', handler: this.end.bind(this), }); } this.startEventRegister = new EventRegister(this.indicator.indicatorEl, startEvents); this.moveEventRegister = new EventRegister(window, moveEvents); this.endEventRegister = new EventRegister(window, endEvents); }; EventHandler.prototype.BScrollIsDisabled = function () { return !this.indicator.scroll.enabled; }; EventHandler.prototype.start = function (e) { if (this.BScrollIsDisabled()) { return; } var point = (e.touches ? e.touches[0] : e); e.preventDefault(); e.stopPropagation(); this.initiated = true; this.lastPoint = point[this.indicator.keysMap.point]; this.hooks.trigger(this.hooks.eventTypes.touchStart); }; EventHandler.prototype.move = function (e) { if (!this.initiated) { return; } var point = (e.touches ? e.touches[0] : e); var pointPos = point[this.indicator.keysMap.point]; e.preventDefault(); e.stopPropagation(); var delta = pointPos - this.lastPoint; this.lastPoint = pointPos; this.hooks.trigger(this.hooks.eventTypes.touchMove, delta); }; EventHandler.prototype.end = function (e) { if (!this.initiated) { return; } this.initiated = false; e.preventDefault(); e.stopPropagation(); this.hooks.trigger(this.hooks.eventTypes.touchEnd); }; EventHandler.prototype.destroy = function () { this.startEventRegister.destroy(); this.moveEventRegister.destroy(); this.endEventRegister.destroy(); }; return EventHandler; }()); var Indicator$1 = /** @class */ (function () { function Indicator(scroll, options) { this.scroll = scroll; this.options = options; this.hooksFn = []; this.wrapper = options.wrapper; this.direction = options.direction; this.indicatorEl = this.wrapper.children[0]; this.keysMap = this.getKeysMap(); this.handleFade(); this.handleHooks(); } Indicator.prototype.handleFade = function () { if (this.options.fade) { this.wrapper.style.opacity = '0'; } }; Indicator.prototype.handleHooks = function () { var _this = this; var _a = this.options, fade = _a.fade, interactive = _a.interactive, scrollbarTrackClickable = _a.scrollbarTrackClickable; var scroll = this.scroll; var scrollHooks = scroll.hooks; var translaterHooks = scroll.scroller.translater.hooks; var animaterHooks = scroll.scroller.animater.hooks; this.registerHooks(scrollHooks, scrollHooks.eventTypes.refresh, this.refresh); this.registerHooks(translaterHooks, translaterHooks.eventTypes.translate, function (pos) { var hasScrollKey = _this.keysMap.hasScroll; if (_this.scroll[hasScrollKey]) { _this.updatePosition(pos); } }); this.registerHooks(animaterHooks, animaterHooks.eventTypes.time, this.transitionTime); this.registerHooks(animaterHooks, animaterHooks.eventTypes.timeFunction, this.transitionTimingFunction); if (fade) { this.registerHooks(scroll, scroll.eventTypes.scrollEnd, function () { _this.fade(); }); this.registerHooks(scroll, scroll.eventTypes.scrollStart, function () { _this.fade(true); }); // for mousewheel event if (scroll.eventTypes.mousewheelStart && scroll.eventTypes.mousewheelEnd) { this.registerHooks(scroll, scroll.eventTypes.mousewheelStart, function () { _this.fade(true); }); this.registerHooks(scroll, scroll.eventTypes.mousewheelMove, function () { _this.fade(true); }); this.registerHooks(scroll, scroll.eventTypes.mousewheelEnd, function () { _this.fade(); }); } } if (interactive) { var _b = this.scroll.options, disableMouse = _b.disableMouse, disableTouch = _b.disableTouch; this.eventHandler = new EventHandler(this, { disableMouse: disableMouse, disableTouch: disableTouch, }); var eventHandlerHooks = this.eventHandler.hooks; this.registerHooks(eventHandlerHooks, eventHandlerHooks.eventTypes.touchStart, this.startHandler); this.registerHooks(eventHandlerHooks, eventHandlerHooks.eventTypes.touchMove, this.moveHandler); this.registerHooks(eventHandlerHooks, eventHandlerHooks.eventTypes.touchEnd, this.endHandler); } if (scrollbarTrackClickable) { this.bindClick(); } }; Indicator.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; Indicator.prototype.bindClick = function () { var wrapper = this.wrapper; this.clickEventRegister = new EventRegister(wrapper, [ { name: 'click', handler: this.handleClick.bind(this), }, ]); }; Indicator.prototype.handleClick = function (e) { var newPos = this.calculateclickOffsetPos(e); var _a = this.scroll, x = _a.x, y = _a.y; x = this.direction === "horizontal" /* Horizontal */ ? newPos : x; y = this.direction === "vertical" /* Vertical */ ? newPos : y; this.scroll.scrollTo(x, y, this.options.scrollbarTrackOffsetTime); }; Indicator.prototype.calculateclickOffsetPos = function (e) { var _a = this.keysMap, poinKey = _a.point, domRectKey = _a.domRect; var scrollbarTrackOffsetType = this.options.scrollbarTrackOffsetType; var clickPointOffset = e[poinKey] - this.wrapperRect[domRectKey]; var scrollToWhere = clickPointOffset < this.currentPos ? -1 /* Up */ : 1 /* Down */; var delta = 0; var currentPos = this.currentPos; if (scrollbarTrackOffsetType === "step" /* Step */) { delta = this.scrollInfo.baseSize * scrollToWhere; } else { delta = 0; currentPos = clickPointOffset; } return this.newPos(currentPos, delta, this.scrollInfo); }; Indicator.prototype.getKeysMap = function () { if (this.direction === "vertical" /* Vertical */) { return { hasScroll: 'hasVerticalScroll', size: 'height', wrapperSize: 'clientHeight', scrollerSize: 'scrollerHeight', maxScrollPos: 'maxScrollY', pos: 'y', point: 'pageY', translateProperty: 'translateY', domRect: 'top', }; } return { hasScroll: 'hasHorizontalScroll', size: 'width', wrapperSize: 'clientWidth', scrollerSize: 'scrollerWidth', maxScrollPos: 'maxScrollX', pos: 'x', point: 'pageX', translateProperty: 'translateX', domRect: 'left', }; }; Indicator.prototype.fade = function (visible) { var _a = this.options, fadeInTime = _a.fadeInTime, fadeOutTime = _a.fadeOutTime; var time = visible ? fadeInTime : fadeOutTime; var wrapper = this.wrapper; wrapper.style[style.transitionDuration] = time + 'ms'; wrapper.style.opacity = visible ? '1' : '0'; }; Indicator.prototype.refresh = function () { var hasScrollKey = this.keysMap.hasScroll; var scroll = this.scroll; var x = scroll.x, y = scroll.y; this.wrapperRect = this.wrapper.getBoundingClientRect(); if (this.canScroll(scroll[hasScrollKey])) { var _a = this.keysMap, wrapperSizeKey = _a.wrapperSize, scrollerSizeKey = _a.scrollerSize, maxScrollPosKey = _a.maxScrollPos; this.scrollInfo = this.refreshScrollInfo(this.wrapper[wrapperSizeKey], scroll[scrollerSizeKey], scroll[maxScrollPosKey], this.indicatorEl[wrapperSizeKey]); this.updatePosition({ x: x, y: y, }); } }; Indicator.prototype.transitionTime = function (time) { if (time === void 0) { time = 0; } this.indicatorEl.style[style.transitionDuration] = time + 'ms'; }; Indicator.prototype.transitionTimingFunction = function (easing) { this.indicatorEl.style[style.transitionTimingFunction] = easing; }; Indicator.prototype.canScroll = function (hasScroll) { this.wrapper.style.display = hasScroll ? 'block' : 'none'; return hasScroll; }; Indicator.prototype.refreshScrollInfo = function (wrapperSize, scrollerSize, maxScrollPos, indicatorElSize) { var baseSize = Math.max(Math.round((wrapperSize * wrapperSize) / (scrollerSize || wrapperSize || 1)), this.options.minSize); if (this.options.isCustom) { baseSize = indicatorElSize; } var maxIndicatorScrollPos = wrapperSize - baseSize; // sizeRatio is negative var sizeRatio = maxIndicatorScrollPos / maxScrollPos; return { baseSize: baseSize, maxScrollPos: maxIndicatorScrollPos, minScrollPos: 0, sizeRatio: sizeRatio, }; }; Indicator.prototype.updatePosition = function (point) { var _a = this.caculatePosAndSize(point, this.scrollInfo), pos = _a.pos, size = _a.size; this.refreshStyle(size, pos); this.currentPos = pos; }; Indicator.prototype.caculatePosAndSize = function (point, scrollInfo) { var posKey = this.keysMap.pos; var sizeRatio = scrollInfo.sizeRatio, baseSize = scrollInfo.baseSize, maxScrollPos = scrollInfo.maxScrollPos, minScrollPos = scrollInfo.minScrollPos; var minSize = this.options.minSize; var pos = Math.round(sizeRatio * point[posKey]); var size; // when out of boundary, slow down size reduction if (pos < minScrollPos) { size = Math.max(baseSize + pos * 3, minSize); pos = minScrollPos; } else if (pos > maxScrollPos) { size = Math.max(baseSize - (pos - maxScrollPos) * 3, minSize); pos = maxScrollPos + baseSize - size; } else { size = baseSize; } return { pos: pos, size: size, }; }; Indicator.prototype.refreshStyle = function (size, pos) { var _a = this.keysMap, translatePropertyKey = _a.translateProperty, sizeKey = _a.size; var translateZ = this.scroll.options.translateZ; this.indicatorEl.style[sizeKey] = size + "px"; this.indicatorEl.style[style.transform] = translatePropertyKey + "(" + pos + "px)" + translateZ; }; Indicator.prototype.startHandler = function () { this.moved = false; this.startTime = getNow(); this.transitionTime(); this.scroll.scroller.hooks.trigger(this.scroll.scroller.hooks.eventTypes.beforeScrollStart); }; Indicator.prototype.moveHandler = function (delta) { if (!this.moved && !this.indicatorNotMoved(delta)) { this.moved = true; this.scroll.scroller.hooks.trigger(this.scroll.scroller.hooks.eventTypes.scrollStart); } if (this.moved) { var newPos = this.newPos(this.currentPos, delta, this.scrollInfo); this.syncBScroll(newPos); } }; Indicator.prototype.endHandler = function () { if (this.moved) { var _a = this.scroll, x = _a.x, y = _a.y; this.scroll.scroller.hooks.trigger(this.scroll.scroller.hooks.eventTypes.scrollEnd, { x: x, y: y, }); } }; Indicator.prototype.indicatorNotMoved = function (delta) { var currentPos = this.currentPos; var _a = this.scrollInfo, maxScrollPos = _a.maxScrollPos, minScrollPos = _a.minScrollPos; var notMoved = (currentPos === minScrollPos && delta <= 0) || (currentPos === maxScrollPos && delta >= 0); return notMoved; }; Indicator.prototype.syncBScroll = function (newPos) { var timestamp = getNow(); var _a = this.scroll, x = _a.x, y = _a.y, options = _a.options, scroller = _a.scroller, maxScrollY = _a.maxScrollY, minScrollY = _a.minScrollY, maxScrollX = _a.maxScrollX, minScrollX = _a.minScrollX; var probeType = options.probeType, momentumLimitTime = options.momentumLimitTime; var position = { x: x, y: y }; if (this.direction === "vertical" /* Vertical */) { position.y = between(newPos, maxScrollY, minScrollY); } else { position.x = between(newPos, maxScrollX, minScrollX); } scroller.translater.translate(position); // dispatch scroll in interval time if (timestamp - this.startTime > momentumLimitTime) { this.startTime = timestamp; if (probeType === 1 /* Throttle */) { scroller.hooks.trigger(scroller.hooks.eventTypes.scroll, position); } } // dispatch scroll all the time if (probeType > 1 /* Throttle */) { scroller.hooks.trigger(scroller.hooks.eventTypes.scroll, position); } }; Indicator.prototype.newPos = function (currentPos, delta, scrollInfo) { var maxScrollPos = scrollInfo.maxScrollPos, sizeRatio = scrollInfo.sizeRatio, minScrollPos = scrollInfo.minScrollPos; var newPos = currentPos + delta; newPos = between(newPos, minScrollPos, maxScrollPos); return Math.round(newPos / sizeRatio); }; Indicator.prototype.destroy = function () { var _a = this.options, interactive = _a.interactive, scrollbarTrackClickable = _a.scrollbarTrackClickable, isCustom = _a.isCustom; if (interactive) { this.eventHandler.destroy(); } if (scrollbarTrackClickable) { this.clickEventRegister.destroy(); } if (!isCustom) { this.wrapper.parentNode.removeChild(this.wrapper); } this.hooksFn.forEach(function (item) { var hooks = item[0]; var hooksName = item[1]; var handlerFn = item[2]; hooks.off(hooksName, handlerFn); }); this.hooksFn.length = 0; }; return Indicator; }()); var ScrollBar = /** @class */ (function () { function ScrollBar(scroll) { this.scroll = scroll; this.handleOptions(); this.createIndicators(); this.handleHooks(); } ScrollBar.prototype.handleHooks = function () { var _this = this; var scroll = this.scroll; scroll.hooks.on(scroll.hooks.eventTypes.destroy, function () { for (var _i = 0, _a = _this.indicators; _i < _a.length; _i++) { var indicator = _a[_i]; indicator.destroy(); } }); }; ScrollBar.prototype.handleOptions = function () { var userOptions = (this.scroll.options.scrollbar === true ? {} : this.scroll.options.scrollbar); var defaultOptions = { fade: true, fadeInTime: 250, fadeOutTime: 500, interactive: false, customElements: [], minSize: 8, scrollbarTrackClickable: false, scrollbarTrackOffsetType: "step" /* Step */, scrollbarTrackOffsetTime: 300, }; this.options = extend(defaultOptions, userOptions); }; ScrollBar.prototype.createIndicators = function () { var indicatorOptions; var scroll = this.scroll; var indicators = []; var scrollDirectionConfigKeys = ['scrollX', 'scrollY']; var indicatorDirections = [ "horizontal" /* Horizontal */, "vertical" /* Vertical */, ]; var customScrollbarEls = this.options.customElements; for (var i = 0; i < scrollDirectionConfigKeys.length; i++) { var key = scrollDirectionConfigKeys[i]; // wanna scroll in specified direction if (scroll.options[key]) { var customElement = customScrollbarEls.shift(); var direction = indicatorDirections[i]; var isCustom = false; var scrollbarWrapper = customElement ? customElement : this.createScrollbarElement(direction); // internal scrollbar if (scrollbarWrapper !== customElement) { scroll.wrapper.appendChild(scrollbarWrapper); } else { // custom scrollbar passed by users isCustom = true; } indicatorOptions = __assign(__assign({ wrapper: scrollbarWrapper, direction: direction }, this.options), { isCustom: isCustom }); indicators.push(new Indicator$1(scroll, indicatorOptions)); } } this.indicators = indicators; }; ScrollBar.prototype.createScrollbarElement = function (direction, scrollbarTrackClickable) { if (scrollbarTrackClickable === void 0) { scrollbarTrackClickable = this.options.scrollbarTrackClickable; } var scrollbarWrapperEl = document.createElement('div'); var scrollbarIndicatorEl = document.createElement('div'); scrollbarWrapperEl.style.cssText = 'position:absolute;z-index:9999;overflow:hidden;'; scrollbarIndicatorEl.style.cssText = 'box-sizing:border-box;position:absolute;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);border-radius:3px;'; scrollbarIndicatorEl.className = 'bscroll-indicator'; if (direction === "horizontal" /* Horizontal */) { scrollbarWrapperEl.style.cssText += 'height:7px;left:2px;right:2px;bottom:0;'; scrollbarIndicatorEl.style.height = '100%'; scrollbarWrapperEl.className = 'bscroll-horizontal-scrollbar'; } else { scrollbarWrapperEl.style.cssText += 'width:7px;bottom:2px;top:2px;right:1px;'; scrollbarIndicatorEl.style.width = '100%'; scrollbarWrapperEl.className = 'bscroll-vertical-scrollbar'; } if (!scrollbarTrackClickable) { scrollbarWrapperEl.style.cssText += 'pointer-events:none;'; } scrollbarWrapperEl.appendChild(scrollbarIndicatorEl); return scrollbarWrapperEl; }; ScrollBar.pluginName = 'scrollbar'; return ScrollBar; }()); var PagesMatrix = /** @class */ (function () { function PagesMatrix(scroll) { this.scroll = scroll; this.init(); } PagesMatrix.prototype.init = function () { var scroller = this.scroll.scroller; var scrollBehaviorX = scroller.scrollBehaviorX, scrollBehaviorY = scroller.scrollBehaviorY; this.wrapperWidth = scrollBehaviorX.wrapperSize; this.wrapperHeight = scrollBehaviorY.wrapperSize; this.scrollerHeight = scrollBehaviorY.contentSize; this.scrollerWidth = scrollBehaviorX.contentSize; this.pages = this.buildPagesMatrix(this.wrapperWidth, this.wrapperHeight); this.pageLengthOfX = this.pages ? this.pages.length : 0; this.pageLengthOfY = this.pages && this.pages[0] ? this.pages[0].length : 0; }; PagesMatrix.prototype.getPageStats = function (pageX, pageY) { return this.pages[pageX][pageY]; }; PagesMatrix.prototype.getNearestPageIndex = function (x, y) { var pageX = 0; var pageY = 0; var l = this.pages.length; for (; pageX < l - 1; pageX++) { if (x >= this.pages[pageX][0].cx) { break; } } l = this.pages[pageX].length; for (; pageY < l - 1; pageY++) { if (y >= this.pages[0][pageY].cy) { break; } } return { pageX: pageX, pageY: pageY, }; }; // (n x 1) matrix for horizontal scroll or // (1 * n) matrix for vertical scroll PagesMatrix.prototype.buildPagesMatrix = function (stepX, stepY) { var pages = []; var x = 0; var y; var cx; var cy; var i = 0; var l; var maxScrollPosX = this.scroll.scroller.scrollBehaviorX.maxScrollPos; var maxScrollPosY = this.scroll.scroller.scrollBehaviorY.maxScrollPos; cx = Math.round(stepX / 2); cy = Math.round(stepY / 2); while (x > -this.scrollerWidth) { pages[i] = []; l = 0; y = 0; while (y > -this.scrollerHeight) { pages[i][l] = { x: Math.max(x, maxScrollPosX), y: Math.max(y, maxScrollPosY), width: stepX, height: stepY, cx: x - cx, cy: y - cy, }; y -= stepY; l++; } x -= stepX; i++; } return pages; }; return PagesMatrix; }()); var BASE_PAGE = { pageX: 0, pageY: 0, x: 0, y: 0, }; var SlidePages = /** @class */ (function () { function SlidePages(scroll, slideOptions) { this.scroll = scroll; this.slideOptions = slideOptions; this.slideX = false; this.slideY = false; this.currentPage = extend({}, BASE_PAGE); } SlidePages.prototype.refresh = function () { this.pagesMatrix = new PagesMatrix(this.scroll); this.checkSlideLoop(); this.currentPage = this.getAdjustedCurrentPage(); }; SlidePages.prototype.getAdjustedCurrentPage = function () { var _a = this.currentPage, pageX = _a.pageX, pageY = _a.pageY; // page index should be handled // because page counts may reduce pageX = Math.min(pageX, this.pagesMatrix.pageLengthOfX - 1); pageY = Math.min(pageY, this.pagesMatrix.pageLengthOfY - 1); // loop scene should also be respected // because clonedNode will cause pageLength increasing if (this.loopX) { pageX = Math.min(pageX, this.pagesMatrix.pageLengthOfX - 2); } if (this.loopY) { pageY = Math.min(pageY, this.pagesMatrix.pageLengthOfY - 2); } var _b = this.pagesMatrix.getPageStats(pageX, pageY), x = _b.x, y = _b.y; return { pageX: pageX, pageY: pageY, x: x, y: y }; }; SlidePages.prototype.setCurrentPage = function (newPage) { this.currentPage = newPage; }; SlidePages.prototype.getInternalPage = function (pageX, pageY) { if (pageX >= this.pagesMatrix.pageLengthOfX) { pageX = this.pagesMatrix.pageLengthOfX - 1; } else if (pageX < 0) { pageX = 0; } if (pageY >= this.pagesMatrix.pageLengthOfY) { pageY = this.pagesMatrix.pageLengthOfY - 1; } else if (pageY < 0) { pageY = 0; } var _a = this.pagesMatrix.getPageStats(pageX, pageY), x = _a.x, y = _a.y; return { pageX: pageX, pageY: pageY, x: x, y: y, }; }; SlidePages.prototype.getInitialPage = function (showFirstPage, firstInitialised) { if (showFirstPage === void 0) { showFirstPage = false; } if (firstInitialised === void 0) { firstInitialised = false; } var _a = this.slideOptions, startPageXIndex = _a.startPageXIndex, startPageYIndex = _a.startPageYIndex; var firstPageX = this.loopX ? 1 : 0; var firstPageY = this.loopY ? 1 : 0; var pageX = showFirstPage ? firstPageX : this.currentPage.pageX; var pageY = showFirstPage ? firstPageY : this.currentPage.pageY; if (firstInitialised) { pageX = this.loopX ? startPageXIndex + 1 : startPageXIndex; pageY = this.loopY ? startPageYIndex + 1 : startPageYIndex; } else { pageX = showFirstPage ? firstPageX : this.currentPage.pageX; pageY = showFirstPage ? firstPageY : this.currentPage.pageY; } var _b = this.pagesMatrix.getPageStats(pageX, pageY), x = _b.x, y = _b.y; return { pageX: pageX, pageY: pageY, x: x, y: y, }; }; SlidePages.prototype.getExposedPage = function (page) { var exposedPage = extend({}, page); // only pageX or pageY need fix if (this.loopX) { exposedPage.pageX = this.fixedPage(exposedPage.pageX, this.pagesMatrix.pageLengthOfX - 2); } if (this.loopY) { exposedPage.pageY = this.fixedPage(exposedPage.pageY, this.pagesMatrix.pageLengthOfY - 2); } return exposedPage; }; SlidePages.prototype.getExposedPageByPageIndex = function (pageIndexX, pageIndexY) { var page = { pageX: pageIndexX, pageY: pageIndexY, }; if (this.loopX) { page.pageX = pageIndexX + 1; } if (this.loopY) { page.pageY = pageIndexY + 1; } var _a = this.pagesMatrix.getPageStats(page.pageX, page.pageY), x = _a.x, y = _a.y; return { x: x, y: y, pageX: pageIndexX, pageY: pageIndexY, }; }; SlidePages.prototype.getWillChangedPage = function (page) { page = extend({}, page); // Page need fix if (this.loopX) { page.pageX = this.fixedPage(page.pageX, this.pagesMatrix.pageLengthOfX - 2); page.x = this.pagesMatrix.getPageStats(page.pageX + 1, 0).x; } if (this.loopY) { page.pageY = this.fixedPage(page.pageY, this.pagesMatrix.pageLengthOfY - 2); page.y = this.pagesMatrix.getPageStats(0, page.pageY + 1).y; } return page; }; SlidePages.prototype.fixedPage = function (page, realPageLen) { var pageIndex = []; for (var i = 0; i < realPageLen; i++) { pageIndex.push(i); } pageIndex.unshift(realPageLen - 1); pageIndex.push(0); return pageIndex[page]; }; SlidePages.prototype.getPageStats = function () { return this.pagesMatrix.getPageStats(this.currentPage.pageX, this.currentPage.pageY); }; SlidePages.prototype.getValidPageIndex = function (x, y) { var lastX = this.pagesMatrix.pageLengthOfX - 1; var lastY = this.pagesMatrix.pageLengthOfY - 1; var firstX = 0; var firstY = 0; if (this.loopX) { x += 1; firstX = firstX + 1; lastX = lastX - 1; } if (this.loopY) { y += 1; firstY = firstY + 1; lastY = lastY - 1; } x = between(x, firstX, lastX); y = between(y, firstY, lastY); return { pageX: x, pageY: y, }; }; SlidePages.prototype.nextPageIndex = function () { return this.getPageIndexByDirection("positive" /* Positive */); }; SlidePages.prototype.prevPageIndex = function () { return this.getPageIndexByDirection("negative" /* Negative */); }; SlidePages.prototype.getNearestPage = function (x, y) { var pageIndex = this.pagesMatrix.getNearestPageIndex(x, y); var pageX = pageIndex.pageX, pageY = pageIndex.pageY; var newX = this.pagesMatrix.getPageStats(pageX, 0).x; var newY = this.pagesMatrix.getPageStats(0, pageY).y; return { x: newX, y: newY, pageX: pageX, pageY: pageY, }; }; SlidePages.prototype.getPageByDirection = function (page, directionX, directionY) { var pageX = page.pageX, pageY = page.pageY; if (pageX === this.currentPage.pageX) { pageX = between(pageX + directionX, 0, this.pagesMatrix.pageLengthOfX - 1); } if (pageY === this.currentPage.pageY) { pageY = between(pageY + directionY, 0, this.pagesMatrix.pageLengthOfY - 1); } var x = this.pagesMatrix.getPageStats(pageX, 0).x; var y = this.pagesMatrix.getPageStats(0, pageY).y; return { x: x, y: y, pageX: pageX, pageY: pageY, }; }; SlidePages.prototype.resetLoopPage = function () { if (this.loopX) { if (this.currentPage.pageX === 0) { return { pageX: this.pagesMatrix.pageLengthOfX - 2, pageY: this.currentPage.pageY, }; } if (this.currentPage.pageX === this.pagesMatrix.pageLengthOfX - 1) { return { pageX: 1, pageY: this.currentPage.pageY, }; } } if (this.loopY) { if (this.currentPage.pageY === 0) { return { pageX: this.currentPage.pageX, pageY: this.pagesMatrix.pageLengthOfY - 2, }; } if (this.currentPage.pageY === this.pagesMatrix.pageLengthOfY - 1) { return { pageX: this.currentPage.pageX, pageY: 1, }; } } }; SlidePages.prototype.getPageIndexByDirection = function (direction) { var x = this.currentPage.pageX; var y = this.currentPage.pageY; if (this.slideX) { x = direction === "negative" /* Negative */ ? x - 1 : x + 1; } if (this.slideY) { y = direction === "negative" /* Negative */ ? y - 1 : y + 1; } return { pageX: x, pageY: y, }; }; SlidePages.prototype.checkSlideLoop = function () { this.wannaLoop = this.slideOptions.loop; if (this.pagesMatrix.pageLengthOfX > 1) { this.slideX = true; } else { this.slideX = false; } if (this.pagesMatrix.pages[0] && this.pagesMatrix.pageLengthOfY > 1) { this.slideY = true; } else { this.slideY = false; } this.loopX = this.wannaLoop && this.slideX; this.loopY = this.wannaLoop && this.slideY; if (this.slideX && this.slideY) { warn('slide does not support two direction at the same time.'); } }; return SlidePages; }()); var sourcePrefix$4 = 'plugins.slide'; var propertiesMap$4 = [ { key: 'next', name: 'next', }, { key: 'prev', name: 'prev', }, { key: 'goToPage', name: 'goToPage', }, { key: 'getCurrentPage', name: 'getCurrentPage', }, { key: 'startPlay', name: 'startPlay', }, { key: 'pausePlay', name: 'pausePlay', }, ]; var propertiesConfig$4 = propertiesMap$4.map(function (item) { return { key: item.key, sourceKey: sourcePrefix$4 + "." + item.name, }; }); var samePage = function (p1, p2) { return p1.pageX === p2.pageX && p1.pageY === p2.pageY; }; var Slide = /** @class */ (function () { function Slide(scroll) { this.scroll = scroll; this.cachedClonedPageDOM = []; this.resetLooping = false; this.autoplayTimer = 0; if (!this.satisfyInitialization()) { return; } this.init(); } Slide.prototype.satisfyInitialization = function () { if (this.scroll.scroller.content.children.length <= 0) { warn("slide need at least one slide page to be initialised." + "please check your DOM layout."); return false; } return true; }; Slide.prototype.init = function () { this.willChangeToPage = extend({}, BASE_PAGE); this.handleBScroll(); this.handleOptions(); this.handleHooks(); this.createPages(); }; Slide.prototype.createPages = function () { this.pages = new SlidePages(this.scroll, this.options); }; Slide.prototype.handleBScroll = function () { this.scroll.registerType(['slideWillChange', 'slidePageChanged']); this.scroll.proxy(propertiesConfig$4); }; Slide.prototype.handleOptions = function () { var userOptions = (this.scroll.options.slide === true ? {} : this.scroll.options.slide); var defaultOptions = { loop: true, threshold: 0.1, speed: 400, easing: ease.bounce, listenFlick: true, autoplay: true, interval: 3000, startPageXIndex: 0, startPageYIndex: 0, }; this.options = extend(defaultOptions, userOptions); }; Slide.prototype.handleLoop = function (prevSlideContent) { var loop = this.options.loop; var slideContent = this.scroll.scroller.content; var currentSlidePagesLength = slideContent.children.length; // only should respect loop scene if (loop) { if (slideContent !== prevSlideContent) { this.resetLoopChangedStatus(); this.removeClonedSlidePage(prevSlideContent); currentSlidePagesLength > 1 && this.cloneFirstAndLastSlidePage(slideContent); } else { // many pages reduce to one page if (currentSlidePagesLength === 3 && this.initialised) { this.removeClonedSlidePage(slideContent); this.moreToOnePageInLoop = true; this.oneToMorePagesInLoop = false; } else if (currentSlidePagesLength > 1) { // one page increases to many page if (this.initialised && this.cachedClonedPageDOM.length === 0) { this.oneToMorePagesInLoop = true; this.moreToOnePageInLoop = false; } else { this.removeClonedSlidePage(slideContent); this.resetLoopChangedStatus(); } this.cloneFirstAndLastSlidePage(slideContent); } else { this.resetLoopChangedStatus(); } } } }; Slide.prototype.resetLoopChangedStatus = function () { this.moreToOnePageInLoop = false; this.oneToMorePagesInLoop = false; }; Slide.prototype.handleHooks = function () { var _this = this; var scrollHooks = this.scroll.hooks; var scrollerHooks = this.scroll.scroller.hooks; var listenFlick = this.options.listenFlick; this.prevContent = this.scroll.scroller.content; this.hooksFn = []; // scroll this.registerHooks(this.scroll, this.scroll.eventTypes.beforeScrollStart, this.pausePlay); this.registerHooks(this.scroll, this.scroll.eventTypes.scrollEnd, this.modifyCurrentPage); this.registerHooks(this.scroll, this.scroll.eventTypes.scrollEnd, this.startPlay); // for mousewheel event if (this.scroll.eventTypes.mousewheelMove) { this.registerHooks(this.scroll, this.scroll.eventTypes.mousewheelMove, function () { // prevent default action of mousewheelMove return true; }); this.registerHooks(this.scroll, this.scroll.eventTypes.mousewheelEnd, function (delta) { if (delta.directionX === 1 /* Positive */ || delta.directionY === 1 /* Positive */) { _this.next(); } if (delta.directionX === -1 /* Negative */ || delta.directionY === -1 /* Negative */) { _this.prev(); } }); } // scrollHooks this.registerHooks(scrollHooks, scrollHooks.eventTypes.refresh, this.refreshHandler); this.registerHooks(scrollHooks, scrollHooks.eventTypes.destroy, this.destroy); // scroller this.registerHooks(scrollerHooks, scrollerHooks.eventTypes.beforeRefresh, function () { _this.handleLoop(_this.prevContent); _this.setSlideInlineStyle(); }); this.registerHooks(scrollerHooks, scrollerHooks.eventTypes.momentum, this.modifyScrollMetaHandler); this.registerHooks(scrollerHooks, scrollerHooks.eventTypes.scroll, this.scrollHandler); // a click operation will clearTimer, so restart a new one this.registerHooks(scrollerHooks, scrollerHooks.eventTypes.checkClick, this.startPlay); if (listenFlick) { this.registerHooks(scrollerHooks, scrollerHooks.eventTypes.flick, this.flickHandler); } }; Slide.prototype.startPlay = function () { var _this = this; var _a = this.options, interval = _a.interval, autoplay = _a.autoplay; if (autoplay) { clearTimeout(this.autoplayTimer); this.autoplayTimer = window.setTimeout(function () { _this.next(); }, interval); } }; Slide.prototype.pausePlay = function () { if (this.options.autoplay) { clearTimeout(this.autoplayTimer); } }; Slide.prototype.setSlideInlineStyle = function () { var styleConfigurations = [ { direction: 'scrollX', sizeType: 'offsetWidth', styleType: 'width', }, { direction: 'scrollY', sizeType: 'offsetHeight', styleType: 'height', }, ]; var _a = this.scroll.scroller, slideContent = _a.content, slideWrapper = _a.wrapper; var scrollOptions = this.scroll.options; styleConfigurations.forEach(function (_a) { var direction = _a.direction, sizeType = _a.sizeType, styleType = _a.styleType; // wanna scroll in this direction if (scrollOptions[direction]) { var size = slideWrapper[sizeType]; var children = slideContent.children; var length_1 = children.length; for (var i = 0; i < length_1; i++) { var slidePageDOM = children[i]; slidePageDOM.style[styleType] = size + 'px'; } slideContent.style[styleType] = size * length_1 + 'px'; } }); }; Slide.prototype.next = function (time, easing) { var _a = this.pages.nextPageIndex(), pageX = _a.pageX, pageY = _a.pageY; this.goTo(pageX, pageY, time, easing); }; Slide.prototype.prev = function (time, easing) { var _a = this.pages.prevPageIndex(), pageX = _a.pageX, pageY = _a.pageY; this.goTo(pageX, pageY, time, easing); }; Slide.prototype.goToPage = function (pageX, pageY, time, easing) { var pageIndex = this.pages.getValidPageIndex(pageX, pageY); this.goTo(pageIndex.pageX, pageIndex.pageY, time, easing); }; Slide.prototype.getCurrentPage = function () { return this.exposedPage || this.pages.getInitialPage(false, true); }; Slide.prototype.setCurrentPage = function (page) { this.pages.setCurrentPage(page); this.exposedPage = this.pages.getExposedPage(page); }; Slide.prototype.nearestPage = function (x, y) { var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; var maxScrollPosX = scrollBehaviorX.maxScrollPos, minScrollPosX = scrollBehaviorX.minScrollPos; var maxScrollPosY = scrollBehaviorY.maxScrollPos, minScrollPosY = scrollBehaviorY.minScrollPos; return this.pages.getNearestPage(between(x, maxScrollPosX, minScrollPosX), between(y, maxScrollPosY, minScrollPosY)); }; Slide.prototype.satisfyThreshold = function (x, y) { var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; var satisfied = true; if (Math.abs(x - scrollBehaviorX.absStartPos) <= this.thresholdX && Math.abs(y - scrollBehaviorY.absStartPos) <= this.thresholdY) { satisfied = false; } return satisfied; }; Slide.prototype.refreshHandler = function (content) { var _this = this; if (!this.satisfyInitialization()) { return; } this.pages.refresh(); this.computeThreshold(); var contentChanged = (this.contentChanged = this.prevContent !== content); if (contentChanged) { this.prevContent = content; } var initPage = this.pages.getInitialPage(this.oneToMorePagesInLoop || this.moreToOnePageInLoop, contentChanged || !this.initialised); if (this.initialised) { this.goTo(initPage.pageX, initPage.pageY, 0); } else { this.registerHooks(this.scroll.hooks, this.scroll.hooks.eventTypes.beforeInitialScrollTo, function (position) { _this.initialised = true; position.x = initPage.x; position.y = initPage.y; }); } this.startPlay(); }; Slide.prototype.computeThreshold = function () { var threshold = this.options.threshold; // Integer if (threshold % 1 === 0) { this.thresholdX = threshold; this.thresholdY = threshold; } else { // decimal var _a = this.pages.getPageStats(), width = _a.width, height = _a.height; this.thresholdX = Math.round(width * threshold); this.thresholdY = Math.round(height * threshold); } }; Slide.prototype.cloneFirstAndLastSlidePage = function (slideContent) { var children = slideContent.children; var preprendDOM = children[children.length - 1].cloneNode(true); var appendDOM = children[0].cloneNode(true); prepend(preprendDOM, slideContent); slideContent.appendChild(appendDOM); this.cachedClonedPageDOM = [preprendDOM, appendDOM]; }; Slide.prototype.removeClonedSlidePage = function (slideContent) { // maybe slideContent has removed from DOM Tree var slidePages = (slideContent && slideContent.children) || []; if (slidePages.length) { this.cachedClonedPageDOM.forEach(function (el) { removeChild(slideContent, el); }); } this.cachedClonedPageDOM = []; }; Slide.prototype.modifyCurrentPage = function (point) { var _a = this.getCurrentPage(), prevExposedPageX = _a.pageX, prevExposedPageY = _a.pageY; var newPage = this.nearestPage(point.x, point.y); this.setCurrentPage(newPage); /* istanbul ignore if */ if (this.contentChanged) { this.contentChanged = false; return true; } var _b = this.getCurrentPage(), currentExposedPageX = _b.pageX, currentExposedPageY = _b.pageY; this.pageWillChangeTo(newPage); // loop is true, and one page becomes many pages when call bs.refresh if (this.oneToMorePagesInLoop) { this.oneToMorePagesInLoop = false; return true; } // loop is true, and many page becomes one page when call bs.refresh // if prevPage > 0, dispatch slidePageChanged and scrollEnd events /* istanbul ignore if */ if (this.moreToOnePageInLoop && prevExposedPageX === 0 && prevExposedPageY === 0) { this.moreToOnePageInLoop = false; return true; } if (prevExposedPageX !== currentExposedPageX || prevExposedPageY !== currentExposedPageY) { // only trust pageX & pageY when loop is true var page = this.pages.getExposedPageByPageIndex(currentExposedPageX, currentExposedPageY); this.scroll.trigger(this.scroll.eventTypes.slidePageChanged, page); } // triggered by resetLoop if (this.resetLooping) { this.resetLooping = false; return; } var changePage = this.pages.resetLoopPage(); if (changePage) { this.resetLooping = true; this.goTo(changePage.pageX, changePage.pageY, 0); // stop user's scrollEnd // since it is a seamless scroll return true; } }; Slide.prototype.goTo = function (pageX, pageY, time, easing) { var newPage = this.pages.getInternalPage(pageX, pageY); var scrollEasing = easing || this.options.easing || ease.bounce; var x = newPage.x, y = newPage.y; var deltaX = x - this.scroll.scroller.scrollBehaviorX.currentPos; var deltaY = y - this.scroll.scroller.scrollBehaviorY.currentPos; /* istanbul ignore if */ if (!deltaX && !deltaY) { this.scroll.scroller.togglePointerEvents(true); return; } time = time === undefined ? this.getEaseTime(deltaX, deltaY) : time; this.scroll.scroller.scrollTo(x, y, time, scrollEasing); }; Slide.prototype.flickHandler = function () { var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; var currentPosX = scrollBehaviorX.currentPos, startPosX = scrollBehaviorX.startPos, directionX = scrollBehaviorX.direction; var currentPosY = scrollBehaviorY.currentPos, startPosY = scrollBehaviorY.startPos, directionY = scrollBehaviorY.direction; var _b = this.pages.currentPage, pageX = _b.pageX, pageY = _b.pageY; var time = this.getEaseTime(currentPosX - startPosX, currentPosY - startPosY); this.goTo(pageX + directionX, pageY + directionY, time); }; Slide.prototype.getEaseTime = function (deltaX, deltaY) { return (this.options.speed || Math.max(Math.max(Math.min(Math.abs(deltaX), 1000), Math.min(Math.abs(deltaY), 1000)), 300)); }; Slide.prototype.modifyScrollMetaHandler = function (scrollMeta) { var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY, animater = _a.animater; var newX = scrollMeta.newX; var newY = scrollMeta.newY; var newPage = this.satisfyThreshold(newX, newY) || animater.forceStopped ? this.pages.getPageByDirection(this.nearestPage(newX, newY), scrollBehaviorX.direction, scrollBehaviorY.direction) : this.pages.currentPage; scrollMeta.time = this.getEaseTime(scrollMeta.newX - newPage.x, scrollMeta.newY - newPage.y); scrollMeta.newX = newPage.x; scrollMeta.newY = newPage.y; scrollMeta.easing = this.options.easing || ease.bounce; }; Slide.prototype.scrollHandler = function (_a) { var x = _a.x, y = _a.y; if (this.satisfyThreshold(x, y)) { var newPage = this.nearestPage(x, y); this.pageWillChangeTo(newPage); } }; Slide.prototype.pageWillChangeTo = function (newPage) { var changeToPage = this.pages.getWillChangedPage(newPage); if (!samePage(this.willChangeToPage, changeToPage)) { this.willChangeToPage = changeToPage; this.scroll.trigger(this.scroll.eventTypes.slideWillChange, this.willChangeToPage); } }; Slide.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; Slide.prototype.destroy = function () { var slideContent = this.scroll.scroller.content; var _a = this.options, loop = _a.loop, autoplay = _a.autoplay; if (loop) { this.removeClonedSlidePage(slideContent); } if (autoplay) { clearTimeout(this.autoplayTimer); } this.hooksFn.forEach(function (item) { var hooks = item[0]; var hooksName = item[1]; var handlerFn = item[2]; if (hooks.eventTypes[hooksName]) { hooks.off(hooksName, handlerFn); } }); this.hooksFn.length = 0; }; Slide.pluginName = 'slide'; return Slide; }()); var sourcePrefix$3 = 'plugins.wheel'; var propertiesMap$3 = [ { key: 'wheelTo', name: 'wheelTo', }, { key: 'getSelectedIndex', name: 'getSelectedIndex', }, { key: 'restorePosition', name: 'restorePosition', }, ]; var propertiesConfig$3 = propertiesMap$3.map(function (item) { return { key: item.key, sourceKey: sourcePrefix$3 + "." + item.name, }; }); var WHEEL_INDEX_CHANGED_EVENT_NAME = 'wheelIndexChanged'; var CONSTANTS = { rate: 4 }; var Wheel = /** @class */ (function () { function Wheel(scroll) { this.scroll = scroll; this.init(); } Wheel.prototype.init = function () { this.handleBScroll(); this.handleOptions(); this.handleHooks(); // init boundary for Wheel this.refreshBoundary(); this.setSelectedIndex(this.options.selectedIndex); }; Wheel.prototype.handleBScroll = function () { this.scroll.proxy(propertiesConfig$3); this.scroll.registerType([WHEEL_INDEX_CHANGED_EVENT_NAME]); }; Wheel.prototype.handleOptions = function () { var userOptions = (this.scroll.options.wheel === true ? {} : this.scroll.options.wheel); var defaultOptions = { wheelWrapperClass: 'wheel-scroll', wheelItemClass: 'wheel-item', rotate: 25, adjustTime: 400, selectedIndex: 0, wheelDisabledItemClass: 'wheel-disabled-item' }; this.options = extend(defaultOptions, userOptions); }; Wheel.prototype.handleHooks = function () { var _this = this; var scroll = this.scroll; var scroller = this.scroll.scroller; var actionsHandler = scroller.actionsHandler, scrollBehaviorX = scroller.scrollBehaviorX, scrollBehaviorY = scroller.scrollBehaviorY, animater = scroller.animater; var prevContent = scroller.content; // BScroll scroll.on(scroll.eventTypes.scrollEnd, function (position) { var index = _this.findNearestValidWheel(position.y).index; if (scroller.animater.forceStopped && !_this.isAdjustingPosition) { _this.target = _this.items[index]; // since stopped from an animation. // prevent user's scrollEnd callback triggered twice return true; } else { _this.setSelectedIndex(index); if (_this.isAdjustingPosition) { _this.isAdjustingPosition = false; } } }); // BScroll.hooks this.scroll.hooks.on(this.scroll.hooks.eventTypes.refresh, function (content) { if (content !== prevContent) { prevContent = content; _this.setSelectedIndex(_this.options.selectedIndex, true); } // rotate all wheel-items // because position may not change _this.rotateX(_this.scroll.y); // check we are stop at a disable item or not _this.wheelTo(_this.selectedIndex, 0); }); this.scroll.hooks.on(this.scroll.hooks.eventTypes.beforeInitialScrollTo, function (position) { // selectedIndex has higher priority than bs.options.startY position.x = 0; position.y = -(_this.selectedIndex * _this.itemHeight); }); // Scroller scroller.hooks.on(scroller.hooks.eventTypes.checkClick, function () { var index = HTMLCollectionToArray(_this.items).indexOf(_this.target); if (index === -1) return true; _this.wheelTo(index, _this.options.adjustTime, ease.swipe); return true; }); scroller.hooks.on(scroller.hooks.eventTypes.scrollTo, function (endPoint) { endPoint.y = _this.findNearestValidWheel(endPoint.y).y; }); // when content is scrolling // click wheel-item DOM repeatedly and crazily will cause scrollEnd not triggered // so reset forceStopped scroller.hooks.on(scroller.hooks.eventTypes.minDistanceScroll, function () { var animater = scroller.animater; if (animater.forceStopped === true) { animater.forceStopped = false; } }); scroller.hooks.on(scroller.hooks.eventTypes.scrollToElement, function (el, pos) { if (!hasClass(el, _this.options.wheelItemClass)) { return true; } else { pos.top = _this.findNearestValidWheel(pos.top).y; } }); // ActionsHandler actionsHandler.hooks.on(actionsHandler.hooks.eventTypes.beforeStart, function (e) { _this.target = e.target; }); // ScrollBehaviorX // Wheel has no x direction now scrollBehaviorX.hooks.on(scrollBehaviorX.hooks.eventTypes.computeBoundary, function (boundary) { boundary.maxScrollPos = 0; boundary.minScrollPos = 0; }); // ScrollBehaviorY scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.computeBoundary, function (boundary) { _this.items = _this.scroll.scroller.content.children; _this.checkWheelAllDisabled(); _this.itemHeight = _this.items.length > 0 ? scrollBehaviorY.contentSize / _this.items.length : 0; boundary.maxScrollPos = -_this.itemHeight * (_this.items.length - 1); boundary.minScrollPos = 0; }); scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.momentum, function (momentumInfo) { momentumInfo.rate = CONSTANTS.rate; momentumInfo.destination = _this.findNearestValidWheel(momentumInfo.destination).y; }); scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.end, function (momentumInfo) { var validWheel = _this.findNearestValidWheel(scrollBehaviorY.currentPos); momentumInfo.destination = validWheel.y; momentumInfo.duration = _this.options.adjustTime; }); // Animater animater.hooks.on(animater.hooks.eventTypes.time, function (time) { _this.transitionDuration(time); }); animater.hooks.on(animater.hooks.eventTypes.timeFunction, function (easing) { _this.timeFunction(easing); }); // bs.stop() to make wheel stop at a correct position when pending animater.hooks.on(animater.hooks.eventTypes.callStop, function () { var index = _this.findNearestValidWheel(_this.scroll.y).index; _this.isAdjustingPosition = true; _this.wheelTo(index, 0); }); // Translater animater.translater.hooks.on(animater.translater.hooks.eventTypes.translate, function (endPoint) { _this.rotateX(endPoint.y); }); }; Wheel.prototype.refreshBoundary = function () { var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY, content = _a.content; scrollBehaviorX.refresh(content); scrollBehaviorY.refresh(content); }; Wheel.prototype.setSelectedIndex = function (index, contentChanged) { if (contentChanged === void 0) { contentChanged = false; } var prevSelectedIndex = this.selectedIndex; this.selectedIndex = index; // if content DOM changed, should not trigger event if (prevSelectedIndex !== index && !contentChanged) { this.scroll.trigger(WHEEL_INDEX_CHANGED_EVENT_NAME, index); } }; Wheel.prototype.getSelectedIndex = function () { return this.selectedIndex; }; Wheel.prototype.wheelTo = function (index, time, ease) { if (index === void 0) { index = 0; } if (time === void 0) { time = 0; } var y = -index * this.itemHeight; this.scroll.scrollTo(0, y, time, ease); }; Wheel.prototype.restorePosition = function () { // bs is scrolling var isPending = this.scroll.pending; if (isPending) { var selectedIndex = this.getSelectedIndex(); this.scroll.scroller.animater.clearTimer(); this.wheelTo(selectedIndex, 0); } }; Wheel.prototype.transitionDuration = function (time) { for (var i = 0; i < this.items.length; i++) { this.items[i].style[style.transitionDuration] = time + 'ms'; } }; Wheel.prototype.timeFunction = function (easing) { for (var i = 0; i < this.items.length; i++) { this.items[i].style[style.transitionTimingFunction] = easing; } }; Wheel.prototype.rotateX = function (y) { var _a = this.options.rotate, rotate = _a === void 0 ? 25 : _a; for (var i = 0; i < this.items.length; i++) { var deg = rotate * (y / this.itemHeight + i); // Too small value is invalid in some phones, issue 1026 var SafeDeg = deg.toFixed(3); this.items[i].style[style.transform] = "rotateX(" + SafeDeg + "deg)"; } }; Wheel.prototype.findNearestValidWheel = function (y) { y = y > 0 ? 0 : y < this.scroll.maxScrollY ? this.scroll.maxScrollY : y; var currentIndex = Math.abs(Math.round(-y / this.itemHeight)); var cacheIndex = currentIndex; var items = this.items; var wheelDisabledItemClassName = this.options .wheelDisabledItemClass; // implement web native select element // first, check whether there is a enable item whose index is smaller than currentIndex // then, check whether there is a enable item whose index is bigger than currentIndex // otherwise, there are all disabled items, just keep currentIndex unchange while (currentIndex >= 0) { if (!hasClass(items[currentIndex], wheelDisabledItemClassName)) { break; } currentIndex--; } if (currentIndex < 0) { currentIndex = cacheIndex; while (currentIndex <= items.length - 1) { if (!hasClass(items[currentIndex], wheelDisabledItemClassName)) { break; } currentIndex++; } } // keep it unchange when all the items are disabled if (currentIndex === items.length) { currentIndex = cacheIndex; } // when all the items are disabled, selectedIndex should always be -1 return { index: this.wheelItemsAllDisabled ? -1 : currentIndex, y: -currentIndex * this.itemHeight }; }; Wheel.prototype.checkWheelAllDisabled = function () { var wheelDisabledItemClassName = this.options.wheelDisabledItemClass; var items = this.items; this.wheelItemsAllDisabled = true; for (var i = 0; i < items.length; i++) { if (!hasClass(items[i], wheelDisabledItemClassName)) { this.wheelItemsAllDisabled = false; break; } } }; Wheel.pluginName = 'wheel'; return Wheel; }()); var sourcePrefix$2 = 'plugins.zoom'; var propertiesMap$2 = [ { key: 'zoomTo', name: 'zoomTo' } ]; var propertiesConfig$2 = propertiesMap$2.map(function (item) { return { key: item.key, sourceKey: sourcePrefix$2 + "." + item.name }; }); var TWO_FINGERS = 2; var RAW_SCALE = 1; var Zoom = /** @class */ (function () { function Zoom(scroll) { this.scroll = scroll; this.scale = RAW_SCALE; this.prevScale = 1; this.init(); } Zoom.prototype.init = function () { this.handleBScroll(); this.handleOptions(); this.handleHooks(); this.tryInitialZoomTo(this.zoomOpt); }; Zoom.prototype.zoomTo = function (scale, x, y, bounceTime) { var _a = this.resolveOrigin(x, y), originX = _a.originX, originY = _a.originY; var origin = { x: originX, y: originY, baseScale: this.scale, }; this._doZoomTo(scale, origin, bounceTime, true); }; Zoom.prototype.handleBScroll = function () { this.scroll.proxy(propertiesConfig$2); this.scroll.registerType([ 'beforeZoomStart', 'zoomStart', 'zooming', 'zoomEnd', ]); }; Zoom.prototype.handleOptions = function () { var userOptions = (this.scroll.options.zoom === true ? {} : this.scroll.options.zoom); var defaultOptions = { start: 1, min: 1, max: 4, initialOrigin: [0, 0], minimalZoomDistance: 5, bounceTime: 800, }; this.zoomOpt = extend(defaultOptions, userOptions); }; Zoom.prototype.handleHooks = function () { var _this = this; var scroll = this.scroll; var scroller = this.scroll.scroller; this.wrapper = this.scroll.scroller.wrapper; this.setTransformOrigin(this.scroll.scroller.content); var scrollBehaviorX = scroller.scrollBehaviorX; var scrollBehaviorY = scroller.scrollBehaviorY; this.hooksFn = []; // BScroll this.registerHooks(scroll.hooks, scroll.hooks.eventTypes.contentChanged, function (content) { _this.setTransformOrigin(content); _this.scale = RAW_SCALE; _this.tryInitialZoomTo(_this.zoomOpt); }); this.registerHooks(scroll.hooks, scroll.hooks.eventTypes.beforeInitialScrollTo, function () { // if perform a zoom action, we should prevent initial scroll when initialised if (_this.zoomOpt.start !== RAW_SCALE) { return true; } }); // enlarge boundary this.registerHooks(scrollBehaviorX.hooks, scrollBehaviorX.hooks.eventTypes.beforeComputeBoundary, function () { // content may change, don't cache it's size var contentSize = getRect(_this.scroll.scroller.content); scrollBehaviorX.contentSize = Math.floor(contentSize.width * _this.scale); }); this.registerHooks(scrollBehaviorY.hooks, scrollBehaviorY.hooks.eventTypes.beforeComputeBoundary, function () { // content may change, don't cache it's size var contentSize = getRect(_this.scroll.scroller.content); scrollBehaviorY.contentSize = Math.floor(contentSize.height * _this.scale); }); // touch event this.registerHooks(scroller.actions.hooks, scroller.actions.hooks.eventTypes.start, function (e) { var numberOfFingers = (e.touches && e.touches.length) || 0; _this.fingersOperation(numberOfFingers); if (numberOfFingers === TWO_FINGERS) { _this.zoomStart(e); } }); this.registerHooks(scroller.actions.hooks, scroller.actions.hooks.eventTypes.beforeMove, function (e) { var numberOfFingers = (e.touches && e.touches.length) || 0; _this.fingersOperation(numberOfFingers); if (numberOfFingers === TWO_FINGERS) { _this.zoom(e); return true; } }); this.registerHooks(scroller.actions.hooks, scroller.actions.hooks.eventTypes.beforeEnd, function (e) { var numberOfFingers = _this.fingersOperation(); if (numberOfFingers === TWO_FINGERS) { _this.zoomEnd(); return true; } }); this.registerHooks(scroller.translater.hooks, scroller.translater.hooks.eventTypes.beforeTranslate, function (transformStyle, point) { var scale = point.scale ? point.scale : _this.prevScale; _this.prevScale = scale; transformStyle.push("scale(" + scale + ")"); }); this.registerHooks(scroller.hooks, scroller.hooks.eventTypes.scrollEnd, function () { if (_this.fingersOperation() === TWO_FINGERS) { _this.scroll.trigger(_this.scroll.eventTypes.zoomEnd, { scale: _this.scale, }); } }); this.registerHooks(this.scroll.hooks, 'destroy', this.destroy); }; Zoom.prototype.setTransformOrigin = function (content) { content.style[style.transformOrigin] = '0 0'; }; Zoom.prototype.tryInitialZoomTo = function (options) { var start = options.start, initialOrigin = options.initialOrigin; var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; if (start !== RAW_SCALE) { // Movable plugin may wanna modify minScrollPos or maxScrollPos // so we force Movable to caculate them this.resetBoundaries([scrollBehaviorX, scrollBehaviorY]); this.zoomTo(start, initialOrigin[0], initialOrigin[1], 0); } }; // getter or setter operation Zoom.prototype.fingersOperation = function (amounts) { if (typeof amounts === 'number') { this.numberOfFingers = amounts; } else { return this.numberOfFingers; } }; Zoom.prototype._doZoomTo = function (scale, origin, time, useCurrentPos) { var _this = this; if (time === void 0) { time = this.zoomOpt.bounceTime; } if (useCurrentPos === void 0) { useCurrentPos = false; } var _a = this.zoomOpt, min = _a.min, max = _a.max; var fromScale = this.scale; var toScale = between(scale, min, max); (function () { if (time === 0) { _this.scroll.trigger(_this.scroll.eventTypes.zooming, { scale: toScale, }); return; } if (time > 0) { var timer_1; var startTime_1 = getNow(); var endTime_1 = startTime_1 + time; var scheduler_1 = function () { var now = getNow(); if (now >= endTime_1) { _this.scroll.trigger(_this.scroll.eventTypes.zooming, { scale: toScale, }); cancelAnimationFrame(timer_1); return; } var ratio = ease.bounce.fn((now - startTime_1) / time); var currentScale = ratio * (toScale - fromScale) + fromScale; _this.scroll.trigger(_this.scroll.eventTypes.zooming, { scale: currentScale, }); timer_1 = requestAnimationFrame(scheduler_1); }; // start scheduler job scheduler_1(); } })(); // suppose you are zooming by two fingers this.fingersOperation(2); this._zoomTo(toScale, fromScale, origin, time, useCurrentPos); }; Zoom.prototype._zoomTo = function (toScale, fromScale, origin, time, useCurrentPos) { if (useCurrentPos === void 0) { useCurrentPos = false; } var ratio = toScale / origin.baseScale; this.setScale(toScale); var scroller = this.scroll.scroller; var scrollBehaviorX = scroller.scrollBehaviorX, scrollBehaviorY = scroller.scrollBehaviorY; this.resetBoundaries([scrollBehaviorX, scrollBehaviorY]); // position is restrained in boundary var newX = this.getNewPos(origin.x, ratio, scrollBehaviorX, true, useCurrentPos); var newY = this.getNewPos(origin.y, ratio, scrollBehaviorY, true, useCurrentPos); if (scrollBehaviorX.currentPos !== Math.round(newX) || scrollBehaviorY.currentPos !== Math.round(newY) || toScale !== fromScale) { scroller.scrollTo(newX, newY, time, ease.bounce, { start: { scale: fromScale, }, end: { scale: toScale, }, }); } }; Zoom.prototype.resolveOrigin = function (x, y) { var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; var resolveFormula = { left: function () { return 0; }, top: function () { return 0; }, right: function () { return scrollBehaviorX.contentSize; }, bottom: function () { return scrollBehaviorY.contentSize; }, center: function (index) { var baseSize = index === 0 ? scrollBehaviorX.contentSize : scrollBehaviorY.contentSize; return baseSize / 2; }, }; return { originX: typeof x === 'number' ? x : resolveFormula[x](0), originY: typeof y === 'number' ? y : resolveFormula[y](1), }; }; Zoom.prototype.zoomStart = function (e) { var firstFinger = e.touches[0]; var secondFinger = e.touches[1]; this.startDistance = this.getFingerDistance(e); this.startScale = this.scale; var _a = offsetToBody(this.wrapper), left = _a.left, top = _a.top; this.origin = { x: Math.abs(firstFinger.pageX + secondFinger.pageX) / 2 + left - this.scroll.x, y: Math.abs(firstFinger.pageY + secondFinger.pageY) / 2 + top - this.scroll.y, baseScale: this.startScale, }; this.scroll.trigger(this.scroll.eventTypes.beforeZoomStart); }; Zoom.prototype.zoom = function (e) { var currentDistance = this.getFingerDistance(e); // at least minimalZoomDistance pixels for the zoom to initiate if (!this.zoomed && Math.abs(currentDistance - this.startDistance) < this.zoomOpt.minimalZoomDistance) { return; } // when out of boundary , perform a damping algorithm var endScale = this.dampingScale((currentDistance / this.startDistance) * this.startScale); var ratio = endScale / this.startScale; this.setScale(endScale); if (!this.zoomed) { this.zoomed = true; this.scroll.trigger(this.scroll.eventTypes.zoomStart); } var scroller = this.scroll.scroller; var scrollBehaviorX = scroller.scrollBehaviorX, scrollBehaviorY = scroller.scrollBehaviorY; var x = this.getNewPos(this.origin.x, ratio, scrollBehaviorX, false, false); var y = this.getNewPos(this.origin.y, ratio, scrollBehaviorY, false, false); this.scroll.trigger(this.scroll.eventTypes.zooming, { scale: this.scale, }); scroller.translater.translate({ x: x, y: y, scale: endScale }); }; Zoom.prototype.zoomEnd = function () { if (!this.zoomed) return; // if out of boundary, do rebound! if (this.shouldRebound()) { this._doZoomTo(this.scale, this.origin, this.zoomOpt.bounceTime); return; } this.scroll.trigger(this.scroll.eventTypes.zoomEnd, { scale: this.scale }); }; Zoom.prototype.getFingerDistance = function (e) { var firstFinger = e.touches[0]; var secondFinger = e.touches[1]; var deltaX = Math.abs(firstFinger.pageX - secondFinger.pageX); var deltaY = Math.abs(firstFinger.pageY - secondFinger.pageY); return getDistance(deltaX, deltaY); }; Zoom.prototype.shouldRebound = function () { var _a = this.zoomOpt, min = _a.min, max = _a.max; var currentScale = this.scale; // scale exceeded! if (currentScale !== between(currentScale, min, max)) { return true; } var _b = this.scroll.scroller, scrollBehaviorX = _b.scrollBehaviorX, scrollBehaviorY = _b.scrollBehaviorY; // enlarge boundaries manually when zoom is end this.resetBoundaries([scrollBehaviorX, scrollBehaviorY]); var xInBoundary = scrollBehaviorX.checkInBoundary().inBoundary; var yInBoundary = scrollBehaviorX.checkInBoundary().inBoundary; return !(xInBoundary && yInBoundary); }; Zoom.prototype.dampingScale = function (scale) { var _a = this.zoomOpt, min = _a.min, max = _a.max; if (scale < min) { scale = 0.5 * min * Math.pow(2.0, scale / min); } else if (scale > max) { scale = 2.0 * max * Math.pow(0.5, max / scale); } return scale; }; Zoom.prototype.setScale = function (scale) { this.scale = scale; }; Zoom.prototype.resetBoundaries = function (scrollBehaviorPairs) { scrollBehaviorPairs.forEach(function (behavior) { return behavior.computeBoundary(); }); }; Zoom.prototype.getNewPos = function (origin, lastScale, scrollBehavior, shouldInBoundary, useCurrentPos) { if (useCurrentPos === void 0) { useCurrentPos = false; } var newPos = origin - origin * lastScale + (useCurrentPos ? scrollBehavior.currentPos : scrollBehavior.startPos); if (shouldInBoundary) { newPos = between(newPos, scrollBehavior.maxScrollPos, scrollBehavior.minScrollPos); } // maxScrollPos or minScrollPos maybe a negative or positive digital return newPos > 0 ? Math.floor(newPos) : Math.ceil(newPos); }; Zoom.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; Zoom.prototype.destroy = function () { this.hooksFn.forEach(function (item) { var hooks = item[0]; var hooksName = item[1]; var handlerFn = item[2]; hooks.off(hooksName, handlerFn); }); this.hooksFn.length = 0; }; Zoom.pluginName = 'zoom'; return Zoom; }()); var BScrollFamily = /** @class */ (function () { function BScrollFamily(scroll) { this.ancestors = []; this.descendants = []; this.hooksManager = []; this.analyzed = false; this.selfScroll = scroll; } BScrollFamily.create = function (scroll) { return new BScrollFamily(scroll); }; BScrollFamily.prototype.hasAncestors = function (bscrollFamily) { var index = findIndex(this.ancestors, function (_a) { var item = _a[0]; return item === bscrollFamily; }); return index > -1; }; BScrollFamily.prototype.hasDescendants = function (bscrollFamily) { var index = findIndex(this.descendants, function (_a) { var item = _a[0]; return item === bscrollFamily; }); return index > -1; }; BScrollFamily.prototype.addAncestor = function (bscrollFamily, distance) { var ancestors = this.ancestors; ancestors.push([bscrollFamily, distance]); // by ascend ancestors.sort(function (a, b) { return a[1] - b[1]; }); }; BScrollFamily.prototype.addDescendant = function (bscrollFamily, distance) { var descendants = this.descendants; descendants.push([bscrollFamily, distance]); // by ascend descendants.sort(function (a, b) { return a[1] - b[1]; }); }; BScrollFamily.prototype.removeAncestor = function (bscrollFamily) { var ancestors = this.ancestors; if (ancestors.length) { var index = findIndex(this.ancestors, function (_a) { var item = _a[0]; return item === bscrollFamily; }); if (index > -1) { return ancestors.splice(index, 1); } } }; BScrollFamily.prototype.removeDescendant = function (bscrollFamily) { var descendants = this.descendants; if (descendants.length) { var index = findIndex(this.descendants, function (_a) { var item = _a[0]; return item === bscrollFamily; }); if (index > -1) { return descendants.splice(index, 1); } } }; BScrollFamily.prototype.registerHooks = function (hook, eventType, handler) { hook.on(eventType, handler); this.hooksManager.push([hook, eventType, handler]); }; BScrollFamily.prototype.setAnalyzed = function (flag) { if (flag === void 0) { flag = false; } this.analyzed = flag; }; BScrollFamily.prototype.purge = function () { var _this = this; // remove self from graph this.ancestors.forEach(function (_a) { var bscrollFamily = _a[0]; bscrollFamily.removeDescendant(_this); }); this.descendants.forEach(function (_a) { var bscrollFamily = _a[0]; bscrollFamily.removeAncestor(_this); }); // remove all hook handlers this.hooksManager.forEach(function (_a) { var hooks = _a[0], eventType = _a[1], handler = _a[2]; hooks.off(eventType, handler); }); this.hooksManager = []; }; return BScrollFamily; }()); var sourcePrefix$1 = 'plugins.nestedScroll'; var propertiesMap$1 = [ { key: 'purgeNestedScroll', name: 'purgeNestedScroll', }, ]; var propertiesConfig$1 = propertiesMap$1.map(function (item) { return { key: item.key, sourceKey: sourcePrefix$1 + "." + item.name, }; }); var DEFAUL_GROUP_ID = 'INTERNAL_NESTED_SCROLL'; var forceScrollStopHandler = function (scrolls) { scrolls.forEach(function (scroll) { if (scroll.pending) { scroll.stop(); scroll.resetPosition(); } }); }; var enableScrollHander = function (scrolls) { scrolls.forEach(function (scroll) { scroll.enable(); }); }; var disableScrollHander = function (scrolls, currentScroll) { scrolls.forEach(function (scroll) { if (scroll.hasHorizontalScroll === currentScroll.hasHorizontalScroll || scroll.hasVerticalScroll === currentScroll.hasVerticalScroll) { scroll.disable(); } }); }; var syncTouchstartData = function (scrolls) { scrolls.forEach(function (scroll) { var _a = scroll.scroller, actions = _a.actions, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; // prevent click triggering many times actions.fingerMoved = true; actions.contentMoved = false; actions.directionLockAction.reset(); scrollBehaviorX.start(); scrollBehaviorY.start(); scrollBehaviorX.resetStartPos(); scrollBehaviorY.resetStartPos(); actions.startTime = +new Date(); }); }; var isOutOfBoundary = function (scroll) { var hasHorizontalScroll = scroll.hasHorizontalScroll, hasVerticalScroll = scroll.hasVerticalScroll, x = scroll.x, y = scroll.y, minScrollX = scroll.minScrollX, maxScrollX = scroll.maxScrollX, minScrollY = scroll.minScrollY, maxScrollY = scroll.maxScrollY, movingDirectionX = scroll.movingDirectionX, movingDirectionY = scroll.movingDirectionY; var ret = false; var outOfLeftBoundary = x >= minScrollX && movingDirectionX === -1 /* Negative */; var outOfRightBoundary = x <= maxScrollX && movingDirectionX === 1 /* Positive */; var outOfTopBoundary = y >= minScrollY && movingDirectionY === -1 /* Negative */; var outOfBottomBoundary = y <= maxScrollY && movingDirectionY === 1 /* Positive */; if (hasVerticalScroll) { ret = outOfTopBoundary || outOfBottomBoundary; } else if (hasHorizontalScroll) { ret = outOfLeftBoundary || outOfRightBoundary; } return ret; }; var isResettingPosition = function (scroll) { var hasHorizontalScroll = scroll.hasHorizontalScroll, hasVerticalScroll = scroll.hasVerticalScroll, x = scroll.x, y = scroll.y, minScrollX = scroll.minScrollX, maxScrollX = scroll.maxScrollX, minScrollY = scroll.minScrollY, maxScrollY = scroll.maxScrollY; var ret = false; var outOfLeftBoundary = x > minScrollX; var outOfRightBoundary = x < maxScrollX; var outOfTopBoundary = y > minScrollY; var outOfBottomBoundary = y < maxScrollY; if (hasVerticalScroll) { ret = outOfTopBoundary || outOfBottomBoundary; } else if (hasHorizontalScroll) { ret = outOfLeftBoundary || outOfRightBoundary; } return ret; }; var resetPositionHandler = function (scroll) { scroll.scroller.reflow(); scroll.resetPosition(0 /* Immediately */); }; var calculateDistance = function (childNode, parentNode) { var distance = 0; var parent = childNode.parentNode; while (parent && parent !== parentNode) { distance++; parent = parent.parentNode; } return distance; }; var NestedScroll = /** @class */ (function () { function NestedScroll(scroll) { var groupId = this.handleOptions(scroll); var instance = NestedScroll.instancesMap[groupId]; if (!instance) { instance = NestedScroll.instancesMap[groupId] = this; instance.store = []; instance.hooksFn = []; } instance.init(scroll); return instance; } NestedScroll.getAllNestedScrolls = function () { var instancesMap = NestedScroll.instancesMap; return Object.keys(instancesMap).map(function (key) { return instancesMap[key]; }); }; NestedScroll.purgeAllNestedScrolls = function () { var nestedScrolls = NestedScroll.getAllNestedScrolls(); nestedScrolls.forEach(function (ns) { return ns.purgeNestedScroll(); }); }; NestedScroll.prototype.handleOptions = function (scroll) { var userOptions = (scroll.options.nestedScroll === true ? {} : scroll.options.nestedScroll); var defaultOptions = { groupId: DEFAUL_GROUP_ID, }; this.options = extend(defaultOptions, userOptions); var groupIdType = typeof this.options.groupId; if (groupIdType !== 'string' && groupIdType !== 'number') { warn('groupId must be string or number for NestedScroll plugin'); } return this.options.groupId; }; NestedScroll.prototype.init = function (scroll) { scroll.proxy(propertiesConfig$1); this.addBScroll(scroll); this.buildBScrollGraph(); this.analyzeBScrollGraph(); this.ensureEventInvokeSequence(); this.handleHooks(scroll); }; NestedScroll.prototype.handleHooks = function (scroll) { var _this = this; this.registerHooks(scroll.hooks, scroll.hooks.eventTypes.destroy, function () { _this.deleteScroll(scroll); }); }; NestedScroll.prototype.deleteScroll = function (scroll) { var wrapper = scroll.wrapper; wrapper.isBScrollContainer = undefined; var store = this.store; var hooksFn = this.hooksFn; var i = findIndex(store, function (bscrollFamily) { return bscrollFamily.selfScroll === scroll; }); if (i > -1) { var bscrollFamily = store[i]; bscrollFamily.purge(); store.splice(i, 1); } var k = findIndex(hooksFn, function (_a) { var hooks = _a[0]; return hooks === scroll.hooks; }); if (k > -1) { var _a = hooksFn[k], hooks = _a[0], eventType = _a[1], handler = _a[2]; hooks.off(eventType, handler); hooksFn.splice(k, 1); } }; NestedScroll.prototype.addBScroll = function (scroll) { this.store.push(BScrollFamily.create(scroll)); }; NestedScroll.prototype.buildBScrollGraph = function () { var store = this.store; var bf1; var bf2; var wrapper1; var wrapper2; var len = this.store.length; // build graph for (var i = 0; i < len; i++) { bf1 = store[i]; wrapper1 = bf1.selfScroll.wrapper; for (var j = 0; j < len; j++) { bf2 = store[j]; wrapper2 = bf2.selfScroll.wrapper; // same bs if (bf1 === bf2) continue; if (!wrapper1.contains(wrapper2)) continue; // bs1 contains bs2 var distance = calculateDistance(wrapper2, wrapper1); if (!bf1.hasDescendants(bf2)) { bf1.addDescendant(bf2, distance); } if (!bf2.hasAncestors(bf1)) { bf2.addAncestor(bf1, distance); } } } }; NestedScroll.prototype.analyzeBScrollGraph = function () { this.store.forEach(function (bscrollFamily) { if (bscrollFamily.analyzed) { return; } var ancestors = bscrollFamily.ancestors, descendants = bscrollFamily.descendants, currentScroll = bscrollFamily.selfScroll; var beforeScrollStartHandler = function () { // always get the latest scroll var ancestorScrolls = ancestors.map(function (_a) { var bscrollFamily = _a[0]; return bscrollFamily.selfScroll; }); var descendantScrolls = descendants.map(function (_a) { var bscrollFamily = _a[0]; return bscrollFamily.selfScroll; }); forceScrollStopHandler(__spreadArrays(ancestorScrolls, descendantScrolls)); if (isResettingPosition(currentScroll)) { resetPositionHandler(currentScroll); } syncTouchstartData(ancestorScrolls); disableScrollHander(ancestorScrolls, currentScroll); }; var touchEndHandler = function () { var ancestorScrolls = ancestors.map(function (_a) { var bscrollFamily = _a[0]; return bscrollFamily.selfScroll; }); var descendantScrolls = descendants.map(function (_a) { var bscrollFamily = _a[0]; return bscrollFamily.selfScroll; }); enableScrollHander(__spreadArrays(ancestorScrolls, descendantScrolls)); }; bscrollFamily.registerHooks(currentScroll, currentScroll.eventTypes.beforeScrollStart, beforeScrollStartHandler); bscrollFamily.registerHooks(currentScroll, currentScroll.eventTypes.touchEnd, touchEndHandler); var selfActionsHooks = currentScroll.scroller.actions.hooks; bscrollFamily.registerHooks(selfActionsHooks, selfActionsHooks.eventTypes.detectMovingDirection, function () { var ancestorScrolls = ancestors.map(function (_a) { var bscrollFamily = _a[0]; return bscrollFamily.selfScroll; }); var parentScroll = ancestorScrolls[0]; var otherAncestorScrolls = ancestorScrolls.slice(1); var contentMoved = currentScroll.scroller.actions.contentMoved; var isTopScroll = ancestorScrolls.length === 0; if (contentMoved) { disableScrollHander(ancestorScrolls, currentScroll); } else if (!isTopScroll) { if (isOutOfBoundary(currentScroll)) { disableScrollHander([currentScroll], currentScroll); if (parentScroll) { enableScrollHander([parentScroll]); } disableScrollHander(otherAncestorScrolls, currentScroll); return true; } } }); bscrollFamily.setAnalyzed(true); }); }; // make sure touchmove|touchend invoke from child to parent NestedScroll.prototype.ensureEventInvokeSequence = function () { var copied = this.store.slice(); var sequencedScroll = copied.sort(function (a, b) { return a.descendants.length - b.descendants.length; }); sequencedScroll.forEach(function (bscrollFamily) { var scroll = bscrollFamily.selfScroll; scroll.scroller.actionsHandler.rebindDOMEvents(); }); }; NestedScroll.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; NestedScroll.prototype.purgeNestedScroll = function () { var groupId = this.options.groupId; this.store.forEach(function (bscrollFamily) { bscrollFamily.purge(); }); this.store = []; this.hooksFn.forEach(function (_a) { var hooks = _a[0], eventType = _a[1], handler = _a[2]; hooks.off(eventType, handler); }); this.hooksFn = []; delete NestedScroll.instancesMap[groupId]; }; NestedScroll.pluginName = 'nestedScroll'; NestedScroll.instancesMap = {}; return NestedScroll; }()); var PRE_NUM = 10; var POST_NUM = 30; var IndexCalculator = /** @class */ (function () { function IndexCalculator(wrapperHeight, tombstoneHeight) { this.wrapperHeight = wrapperHeight; this.tombstoneHeight = tombstoneHeight; this.lastDirection = 1 /* DOWN */; this.lastPos = 0; } IndexCalculator.prototype.calculate = function (pos, list) { var offset = pos - this.lastPos; this.lastPos = pos; var direction = this.getDirection(offset); // important! start index is much more important than end index. var start = this.calculateIndex(0, pos, list); var end = this.calculateIndex(start, pos + this.wrapperHeight, list); if (direction === 1 /* DOWN */) { start -= PRE_NUM; end += POST_NUM; } else { start -= POST_NUM; end += PRE_NUM; } if (start < 0) { start = 0; } return { start: start, end: end, }; }; IndexCalculator.prototype.getDirection = function (offset) { var direction; if (offset > 0) { direction = 1 /* DOWN */; } else if (offset < 0) { direction = 0 /* UP */; } else { return this.lastDirection; } this.lastDirection = direction; return direction; }; IndexCalculator.prototype.calculateIndex = function (start, offset, list) { if (offset <= 0) { return start; } var i = start; var startPos = list[i] && list[i].pos !== -1 ? list[i].pos : 0; var lastPos = startPos; var tombstone = 0; while (i < list.length && list[i].pos < offset) { lastPos = list[i].pos; i++; } if (i === list.length) { tombstone = Math.floor((offset - lastPos) / this.tombstoneHeight); } i += tombstone; return i; }; IndexCalculator.prototype.resetState = function () { this.lastDirection = 1 /* DOWN */; this.lastPos = 0; }; return IndexCalculator; }()); var ListItem = /** @class */ (function () { function ListItem() { this.data = null; this.dom = null; this.tombstone = null; this.width = 0; this.height = 0; this.pos = 0; } return ListItem; }()); var DataManager = /** @class */ (function () { function DataManager(list, fetchFn, onFetchFinish) { this.fetchFn = fetchFn; this.onFetchFinish = onFetchFinish; this.loadedNum = 0; this.fetching = false; this.hasMore = true; this.list = list || []; } DataManager.prototype.update = function (end) { return __awaiter(this, void 0, void 0, function () { var len; return __generator(this, function (_a) { if (!this.hasMore) { end = Math.min(end, this.list.length); } // add data placeholder if (end > this.list.length) { len = end - this.list.length; this.addEmptyData(len); } // tslint:disable-next-line: no-floating-promises return [2 /*return*/, this.checkToFetch(end)]; }); }); }; DataManager.prototype.add = function (data) { for (var i = 0; i < data.length; i++) { if (!this.list[this.loadedNum]) { this.list[this.loadedNum] = { data: data[i] }; } else { this.list[this.loadedNum] = __assign(__assign({}, this.list[this.loadedNum]), { data: data[i] }); } this.loadedNum++; } return this.list; }; DataManager.prototype.addEmptyData = function (len) { for (var i = 0; i < len; i++) { this.list.push(new ListItem()); } return this.list; }; DataManager.prototype.fetch = function (len) { return __awaiter(this, void 0, void 0, function () { var data; return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.fetching) { return [2 /*return*/, []]; } this.fetching = true; return [4 /*yield*/, this.fetchFn(len)]; case 1: data = _a.sent(); this.fetching = false; return [2 /*return*/, data]; } }); }); }; DataManager.prototype.checkToFetch = function (end) { return __awaiter(this, void 0, void 0, function () { var min, newData, currentEnd; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this.hasMore) { return [2 /*return*/]; } if (end <= this.loadedNum) { return [2 /*return*/]; } min = end - this.loadedNum; return [4 /*yield*/, this.fetch(min)]; case 1: newData = _a.sent(); if (newData instanceof Array && newData.length) { this.add(newData); currentEnd = this.onFetchFinish(this.list, true); return [2 /*return*/, this.checkToFetch(currentEnd)]; } else if (typeof newData === 'boolean' && newData === false) { this.hasMore = false; this.list.splice(this.loadedNum); this.onFetchFinish(this.list, false); } return [2 /*return*/]; } }); }); }; DataManager.prototype.getList = function () { return this.list; }; DataManager.prototype.resetState = function () { this.loadedNum = 0; this.fetching = false; this.hasMore = true; this.list = []; }; return DataManager; }()); var Tombstone = /** @class */ (function () { function Tombstone(create) { this.create = create; this.cached = []; this.width = 0; this.height = 0; this.initialed = false; this.getSize(); } Tombstone.isTombstone = function (el) { if (el && el.classList) { return el.classList.contains('tombstone'); } return false; }; Tombstone.prototype.getSize = function () { if (!this.initialed) { var tombstone = this.create(); tombstone.style.position = 'absolute'; document.body.appendChild(tombstone); tombstone.style.display = ''; this.height = tombstone.offsetHeight; this.width = tombstone.offsetWidth; document.body.removeChild(tombstone); this.cached.push(tombstone); } }; Tombstone.prototype.getOne = function () { var tombstone = this.cached.pop(); if (tombstone) { var tombstoneStyle = tombstone.style; tombstoneStyle.display = ''; tombstoneStyle.opacity = '1'; tombstoneStyle[style.transform] = ''; tombstoneStyle[style.transition] = ''; return tombstone; } return this.create(); }; Tombstone.prototype.recycle = function (tombstones) { for (var _i = 0, tombstones_1 = tombstones; _i < tombstones_1.length; _i++) { var tombstone = tombstones_1[_i]; tombstone.style.display = 'none'; this.cached.push(tombstone); } return this.cached; }; Tombstone.prototype.recycleOne = function (tombstone) { this.cached.push(tombstone); return this.cached; }; return Tombstone; }()); var ANIMATION_DURATION_MS = 200; var DomManager = /** @class */ (function () { function DomManager(content, renderFn, tombstone) { this.renderFn = renderFn; this.tombstone = tombstone; this.unusedDom = []; this.timers = []; this.setContent(content); } DomManager.prototype.update = function (list, start, end) { if (start >= list.length) { start = list.length - 1; } if (end > list.length) { end = list.length; } this.collectUnusedDom(list, start, end); this.createDom(list, start, end); this.cacheHeight(list, start, end); var _a = this.positionDom(list, start, end), startPos = _a.startPos, startDelta = _a.startDelta, endPos = _a.endPos; return { start: start, startPos: startPos, startDelta: startDelta, end: end, endPos: endPos, }; }; DomManager.prototype.collectUnusedDom = function (list, start, end) { // TODO optimise for (var i = 0; i < list.length; i++) { if (i === start) { i = end - 1; continue; } if (list[i].dom) { var dom = list[i].dom; if (Tombstone.isTombstone(dom)) { this.tombstone.recycleOne(dom); dom.style.display = 'none'; } else { this.unusedDom.push(dom); } list[i].dom = null; } } return list; }; DomManager.prototype.createDom = function (list, start, end) { for (var i = start; i < end; i++) { var dom = list[i].dom; var data = list[i].data; if (dom) { if (Tombstone.isTombstone(dom) && data) { list[i].tombstone = dom; list[i].dom = null; } else { continue; } } dom = data ? this.renderFn(data, this.unusedDom.pop()) : this.tombstone.getOne(); dom.style.position = 'absolute'; list[i].dom = dom; list[i].pos = -1; this.content.appendChild(dom); } }; DomManager.prototype.cacheHeight = function (list, start, end) { for (var i = start; i < end; i++) { if (list[i].data && !list[i].height) { list[i].height = list[i].dom.offsetHeight; } } }; DomManager.prototype.positionDom = function (list, start, end) { var _this = this; var tombstoneEles = []; var _a = this.getStartPos(list, start, end), startPos = _a.start, startDelta = _a.delta; var pos = startPos; for (var i = start; i < end; i++) { var tombstone = list[i].tombstone; if (tombstone) { var tombstoneStyle = tombstone.style; tombstoneStyle[style.transition] = cssVendor + "transform " + ANIMATION_DURATION_MS + "ms, opacity " + ANIMATION_DURATION_MS + "ms"; tombstoneStyle[style.transform] = "translateY(" + pos + "px)"; tombstoneStyle.opacity = '0'; list[i].tombstone = null; tombstoneEles.push(tombstone); } if (list[i].dom && list[i].pos !== pos) { list[i].dom.style[style.transform] = "translateY(" + pos + "px)"; list[i].pos = pos; } pos += list[i].height || this.tombstone.height; } var timerId = window.setTimeout(function () { _this.tombstone.recycle(tombstoneEles); }, ANIMATION_DURATION_MS); this.timers.push(timerId); return { startPos: startPos, startDelta: startDelta, endPos: pos, }; }; DomManager.prototype.getStartPos = function (list, start, end) { if (list[start] && list[start].pos !== -1) { return { start: list[start].pos, delta: 0, }; } // TODO optimise var pos = list[0].pos === -1 ? 0 : list[0].pos; for (var i_1 = 0; i_1 < start; i_1++) { pos += list[i_1].height || this.tombstone.height; } var originPos = pos; var i; for (i = start; i < end; i++) { if (!Tombstone.isTombstone(list[i].dom) && list[i].pos !== -1) { pos = list[i].pos; break; } } var x = i; if (x < end) { while (x > start) { pos -= list[x - 1].height; x--; } } var delta = originPos - pos; return { start: pos, delta: delta, }; }; DomManager.prototype.removeTombstone = function () { var tombstones = this.content.querySelectorAll('.tombstone'); for (var i = tombstones.length - 1; i >= 0; i--) { this.content.removeChild(tombstones[i]); } }; DomManager.prototype.setContent = function (content) { if (content !== this.content) { this.content = content; } }; DomManager.prototype.destroy = function () { this.removeTombstone(); this.timers.forEach(function (id) { clearTimeout(id); }); }; DomManager.prototype.resetState = function () { this.destroy(); this.timers = []; this.unusedDom = []; }; return DomManager; }()); var EXTRA_SCROLL_Y = -2000; var InfinityScroll = /** @class */ (function () { function InfinityScroll(scroll) { this.scroll = scroll; this.start = 0; this.end = 0; this.init(); } InfinityScroll.prototype.init = function () { var _this = this; this.handleOptions(); var _a = this.options, fetchFn = _a.fetch, renderFn = _a.render, createTombstoneFn = _a.createTombstone; this.tombstone = new Tombstone(createTombstoneFn); this.indexCalculator = new IndexCalculator(this.scroll.scroller.scrollBehaviorY.wrapperSize, this.tombstone.height); this.domManager = new DomManager(this.scroll.scroller.content, renderFn, this.tombstone); this.dataManager = new DataManager([], fetchFn, this.onFetchFinish.bind(this)); this.scroll.on(this.scroll.eventTypes.destroy, this.destroy, this); this.scroll.on(this.scroll.eventTypes.scroll, this.update, this); this.scroll.on(this.scroll.eventTypes.contentChanged, function (content) { _this.domManager.setContent(content); _this.indexCalculator.resetState(); _this.domManager.resetState(); _this.dataManager.resetState(); _this.update({ y: 0 }); }); var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY; scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.computeBoundary, this.modifyBoundary, this); this.update({ y: 0 }); }; InfinityScroll.prototype.modifyBoundary = function (boundary) { // manually set position to allow scroll boundary.maxScrollPos = EXTRA_SCROLL_Y; }; InfinityScroll.prototype.handleOptions = function () { // narrow down type to an object var infinityOptions = this.scroll.options.infinity; if (infinityOptions) { if (typeof infinityOptions.fetch !== 'function') { warn('Infinity plugin need fetch Function to new data.'); } if (typeof infinityOptions.render !== 'function') { warn('Infinity plugin need render Function to render each item.'); } if (typeof infinityOptions.render !== 'function') { warn('Infinity plugin need createTombstone Function to create tombstone.'); } this.options = infinityOptions; } this.scroll.options.probeType = 3 /* Realtime */; }; InfinityScroll.prototype.update = function (pos) { var position = Math.round(-pos.y); // important! calculate start/end index to render var _a = this.indexCalculator.calculate(position, this.dataManager.getList()), start = _a.start, end = _a.end; this.start = start; this.end = end; // tslint:disable-next-line: no-floating-promises this.dataManager.update(end); this.updateDom(this.dataManager.getList()); }; InfinityScroll.prototype.onFetchFinish = function (list, hasMore) { var end = this.updateDom(list).end; if (!hasMore) { this.domManager.removeTombstone(); this.scroll.scroller.animater.stop(); this.scroll.resetPosition(); } // tslint:disable-next-line: no-floating-promises return end; }; InfinityScroll.prototype.updateDom = function (list) { var _a = this.domManager.update(list, this.start, this.end), end = _a.end, startPos = _a.startPos, endPos = _a.endPos, startDelta = _a.startDelta; if (startDelta) { this.scroll.minScrollY = startDelta; } if (endPos > this.scroll.maxScrollY) { this.scroll.maxScrollY = -(endPos - this.scroll.scroller.scrollBehaviorY.wrapperSize); } return { end: end, startPos: startPos, endPos: endPos, }; }; InfinityScroll.prototype.destroy = function () { var _a = this.scroll.scroller, content = _a.content, scrollBehaviorY = _a.scrollBehaviorY; while (content.firstChild) { content.removeChild(content.firstChild); } this.domManager.destroy(); this.scroll.off('scroll', this.update); this.scroll.off('destroy', this.destroy); scrollBehaviorY.hooks.off(scrollBehaviorY.hooks.eventTypes.computeBoundary); }; InfinityScroll.pluginName = 'infinity'; return InfinityScroll; }()); var sourcePrefix = 'plugins.movable'; var propertiesMap = [ { key: 'putAt', name: 'putAt', }, ]; var propertiesConfig = propertiesMap.map(function (item) { return { key: item.key, sourceKey: sourcePrefix + "." + item.name, }; }); var Movable = /** @class */ (function () { function Movable(scroll) { this.scroll = scroll; this.handleBScroll(); this.handleHooks(); } Movable.prototype.handleBScroll = function () { this.scroll.proxy(propertiesConfig); }; Movable.prototype.handleHooks = function () { var _this = this; this.hooksFn = []; var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; var computeBoundary = function (boundary, behavior) { if (boundary.maxScrollPos > 0) { // content is smaller than wrapper boundary.minScrollPos = behavior.wrapperSize - behavior.contentSize; boundary.maxScrollPos = 0; } }; this.registerHooks(scrollBehaviorX.hooks, scrollBehaviorX.hooks.eventTypes.ignoreHasScroll, function () { return true; }); this.registerHooks(scrollBehaviorX.hooks, scrollBehaviorX.hooks.eventTypes.computeBoundary, function (boundary) { computeBoundary(boundary, scrollBehaviorX); }); this.registerHooks(scrollBehaviorY.hooks, scrollBehaviorY.hooks.eventTypes.ignoreHasScroll, function () { return true; }); this.registerHooks(scrollBehaviorY.hooks, scrollBehaviorY.hooks.eventTypes.computeBoundary, function (boundary) { computeBoundary(boundary, scrollBehaviorY); }); this.registerHooks(this.scroll.hooks, this.scroll.hooks.eventTypes.destroy, function () { _this.destroy(); }); }; Movable.prototype.putAt = function (x, y, time, easing) { if (time === void 0) { time = this.scroll.options.bounceTime; } if (easing === void 0) { easing = ease.bounce; } var position = this.resolvePostion(x, y); this.scroll.scrollTo(position.x, position.y, time, easing); }; Movable.prototype.resolvePostion = function (x, y) { var _a = this.scroll.scroller, scrollBehaviorX = _a.scrollBehaviorX, scrollBehaviorY = _a.scrollBehaviorY; var resolveFormula = { left: function () { return 0; }, top: function () { return 0; }, right: function () { return scrollBehaviorX.minScrollPos; }, bottom: function () { return scrollBehaviorY.minScrollPos; }, center: function (index) { var baseSize = index === 0 ? scrollBehaviorX.minScrollPos : scrollBehaviorY.minScrollPos; return baseSize / 2; }, }; return { x: typeof x === 'number' ? x : resolveFormula[x](0), y: typeof y === 'number' ? y : resolveFormula[y](1), }; }; Movable.prototype.destroy = function () { this.hooksFn.forEach(function (item) { var hooks = item[0]; var hooksName = item[1]; var handlerFn = item[2]; hooks.off(hooksName, handlerFn); }); this.hooksFn.length = 0; }; Movable.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; Movable.pluginName = 'movable'; Movable.applyOrder = "pre" /* Pre */; return Movable; }()); var isImageTag = function (el) { return el.tagName.toLowerCase() === 'img'; }; var ObserveImage = /** @class */ (function () { function ObserveImage(scroll) { this.scroll = scroll; this.refreshTimer = 0; this.init(); } ObserveImage.prototype.init = function () { this.handleOptions(this.scroll.options.observeImage); this.bindEventsToWrapper(); }; ObserveImage.prototype.handleOptions = function (userOptions) { if (userOptions === void 0) { userOptions = {}; } userOptions = (userOptions === true ? {} : userOptions); var defaultOptions = { debounceTime: 100, }; this.options = extend(defaultOptions, userOptions); }; ObserveImage.prototype.bindEventsToWrapper = function () { var wrapper = this.scroll.scroller.wrapper; this.imageLoadEventRegister = new EventRegister(wrapper, [ { name: 'load', handler: this.load.bind(this), capture: true, }, ]); this.imageErrorEventRegister = new EventRegister(wrapper, [ { name: 'error', handler: this.load.bind(this), capture: true, }, ]); }; ObserveImage.prototype.load = function (e) { var _this = this; var target = e.target; var debounceTime = this.options.debounceTime; if (target && isImageTag(target)) { if (debounceTime === 0) { this.scroll.refresh(); } else { clearTimeout(this.refreshTimer); this.refreshTimer = window.setTimeout(function () { _this.scroll.refresh(); }, this.options.debounceTime); } } }; ObserveImage.pluginName = 'observeImage'; return ObserveImage; }()); var resolveRatioOption = function (ratioConfig) { var ret = { ratioX: 0, ratioY: 0, }; /* istanbul ignore if */ if (!ratioConfig) { return ret; } if (typeof ratioConfig === 'number') { ret.ratioX = ret.ratioY = ratioConfig; } else if (typeof ratioConfig === 'object' && ratioConfig) { ret.ratioX = ratioConfig.x || 0; ret.ratioY = ratioConfig.y || 0; } return ret; }; var handleBubbleAndCancelable = function (e) { e.preventDefault(); e.stopPropagation(); }; var Indicator = /** @class */ (function () { function Indicator(scroll, options) { this.scroll = scroll; this.options = options; this.currentPos = { x: 0, y: 0, }; this.hooksFn = []; this.handleDOM(); this.handleHooks(); this.handleInteractive(); } Indicator.prototype.handleDOM = function () { var _a = this.options, relationElement = _a.relationElement, _b = _a.relationElementHandleElementIndex, relationElementHandleElementIndex = _b === void 0 ? 0 : _b; this.wrapper = relationElement; this.indicatorEl = this.wrapper.children[relationElementHandleElementIndex]; }; Indicator.prototype.handleHooks = function () { var _this = this; var scroll = this.scroll; var scrollHooks = scroll.hooks; var translaterHooks = scroll.scroller.translater.hooks; var animaterHooks = scroll.scroller.animater.hooks; this.registerHooks(scrollHooks, scrollHooks.eventTypes.refresh, this.refresh); this.registerHooks(translaterHooks, translaterHooks.eventTypes.translate, function (pos) { _this.updatePosition(pos); }); this.registerHooks(animaterHooks, animaterHooks.eventTypes.time, this.transitionTime); this.registerHooks(animaterHooks, animaterHooks.eventTypes.timeFunction, this.transitionTimingFunction); }; Indicator.prototype.transitionTime = function (time) { if (time === void 0) { time = 0; } this.indicatorEl.style[style.transitionDuration] = time + 'ms'; }; Indicator.prototype.transitionTimingFunction = function (easing) { this.indicatorEl.style[style.transitionTimingFunction] = easing; }; Indicator.prototype.handleInteractive = function () { if (this.options.interactive !== false) { this.registerEvents(); } }; Indicator.prototype.registerHooks = function (hooks, name, handler) { hooks.on(name, handler, this); this.hooksFn.push([hooks, name, handler]); }; Indicator.prototype.registerEvents = function () { var _a = this.scroll.options, disableMouse = _a.disableMouse, disableTouch = _a.disableTouch; var startEvents = []; var moveEvents = []; var endEvents = []; if (!disableMouse) { startEvents.push({ name: 'mousedown', handler: this.start.bind(this), }); moveEvents.push({ name: 'mousemove', handler: this.move.bind(this), }); endEvents.push({ name: 'mouseup', handler: this.end.bind(this), }); } if (!disableTouch) { startEvents.push({ name: 'touchstart', handler: this.start.bind(this), }); moveEvents.push({ name: 'touchmove', handler: this.move.bind(this), }); endEvents.push({ name: 'touchend', handler: this.end.bind(this), }, { name: 'touchcancel', handler: this.end.bind(this), }); } this.startEventRegister = new EventRegister(this.indicatorEl, startEvents); this.moveEventRegister = new EventRegister(window, moveEvents); this.endEventRegister = new EventRegister(window, endEvents); }; Indicator.prototype.refresh = function () { var _a = this.scroll, x = _a.x, y = _a.y, hasHorizontalScroll = _a.hasHorizontalScroll, hasVerticalScroll = _a.hasVerticalScroll, maxBScrollX = _a.maxScrollX, maxBScrollY = _a.maxScrollY; var _b = resolveRatioOption(this.options.ratio), ratioX = _b.ratioX, ratioY = _b.ratioY; var _c = getClientSize(this.wrapper), wrapperWidth = _c.width, wrapperHeight = _c.height; var _d = getRect(this.indicatorEl), indicatorWidth = _d.width, indicatorHeight = _d.height; if (hasHorizontalScroll) { this.maxScrollX = wrapperWidth - indicatorWidth; this.translateXSign = this.maxScrollX > 0 ? -1 /* Positive */ : 1 /* NotPositive */; this.minScrollX = 0; // ensure positive this.ratioX = ratioX ? ratioX : Math.abs(this.maxScrollX / maxBScrollX); } if (hasVerticalScroll) { this.maxScrollY = wrapperHeight - indicatorHeight; this.translateYSign = this.maxScrollY > 0 ? -1 /* Positive */ : 1 /* NotPositive */; this.minScrollY = 0; this.ratioY = ratioY ? ratioY : Math.abs(this.maxScrollY / maxBScrollY); } this.updatePosition({ x: x, y: y, }); }; Indicator.prototype.start = function (e) { if (this.BScrollIsDisabled()) { return; } var point = (e.touches ? e.touches[0] : e); handleBubbleAndCancelable(e); this.initiated = true; this.moved = false; this.lastPointX = point.pageX; this.lastPointY = point.pageY; this.startTime = getNow(); this.scroll.scroller.hooks.trigger(this.scroll.scroller.hooks.eventTypes.beforeScrollStart); }; Indicator.prototype.BScrollIsDisabled = function () { return !this.scroll.enabled; }; Indicator.prototype.move = function (e) { if (!this.initiated) { return; } var point = (e.touches ? e.touches[0] : e); var pointX = point.pageX; var pointY = point.pageY; handleBubbleAndCancelable(e); var deltaX = pointX - this.lastPointX; var deltaY = pointY - this.lastPointY; this.lastPointX = pointX; this.lastPointY = pointY; if (!this.moved && !this.indicatorNotMoved(deltaX, deltaY)) { this.moved = true; this.scroll.scroller.hooks.trigger(this.scroll.scroller.hooks.eventTypes.scrollStart); } if (this.moved) { var newPos = this.getBScrollPosByRatio(this.currentPos, deltaX, deltaY); this.syncBScroll(newPos); } }; Indicator.prototype.end = function (e) { if (!this.initiated) { return; } this.initiated = false; handleBubbleAndCancelable(e); if (this.moved) { var _a = this.scroll, x = _a.x, y = _a.y; this.scroll.scroller.hooks.trigger(this.scroll.scroller.hooks.eventTypes.scrollEnd, { x: x, y: y, }); } }; Indicator.prototype.getBScrollPosByRatio = function (currentPos, deltaX, deltaY) { var currentX = currentPos.x, currentY = currentPos.y; var _a = this.scroll, hasHorizontalScroll = _a.hasHorizontalScroll, hasVerticalScroll = _a.hasVerticalScroll, BScrollMinScrollX = _a.minScrollX, BScrollMaxScrollX = _a.maxScrollX, BScrollMinScrollY = _a.minScrollY, BScrollMaxScrollY = _a.maxScrollY; var _b = this.scroll, x = _b.x, y = _b.y; if (hasHorizontalScroll) { var newPosX = between(currentX + deltaX, Math.min(this.minScrollX, this.maxScrollX), Math.max(this.minScrollX, this.maxScrollX)); var roundX = Math.round((newPosX / this.ratioX) * this.translateXSign); x = between(roundX, BScrollMaxScrollX, BScrollMinScrollX); } if (hasVerticalScroll) { var newPosY = between(currentY + deltaY, Math.min(this.minScrollY, this.maxScrollY), Math.max(this.minScrollY, this.maxScrollY)); var roundY = Math.round((newPosY / this.ratioY) * this.translateYSign); y = between(roundY, BScrollMaxScrollY, BScrollMinScrollY); } return { x: x, y: y }; }; Indicator.prototype.indicatorNotMoved = function (deltaX, deltaY) { var _a = this.currentPos, x = _a.x, y = _a.y; var xNotMoved = (x === this.minScrollX && deltaX <= 0) || (x === this.maxScrollX && deltaX >= 0); var yNotMoved = (y === this.minScrollY && deltaY <= 0) || (y === this.maxScrollY && deltaY >= 0); return xNotMoved && yNotMoved; }; Indicator.prototype.syncBScroll = function (newPos) { var timestamp = getNow(); var _a = this.scroll, options = _a.options, scroller = _a.scroller; var probeType = options.probeType, momentumLimitTime = options.momentumLimitTime; scroller.translater.translate(newPos); // dispatch scroll in interval time if (timestamp - this.startTime > momentumLimitTime) { this.startTime = timestamp; if (probeType === 1 /* Throttle */) { scroller.hooks.trigger(scroller.hooks.eventTypes.scroll, newPos); } } // dispatch scroll all the time if (probeType > 1 /* Throttle */) { scroller.hooks.trigger(scroller.hooks.eventTypes.scroll, newPos); } }; Indicator.prototype.updatePosition = function (BScrollPos) { var newIndicatorPos = this.getIndicatorPosByRatio(BScrollPos); this.applyTransformProperty(newIndicatorPos); this.currentPos = __assign({}, newIndicatorPos); }; Indicator.prototype.applyTransformProperty = function (pos) { var translateZ = this.scroll.options.translateZ; var transformProperties = [ "translateX(" + pos.x + "px)", "translateY(" + pos.y + "px)", "" + translateZ, ]; this.indicatorEl.style[style.transform] = transformProperties.join(' '); }; Indicator.prototype.getIndicatorPosByRatio = function (BScrollPos) { var x = BScrollPos.x, y = BScrollPos.y; var _a = this.scroll, hasHorizontalScroll = _a.hasHorizontalScroll, hasVerticalScroll = _a.hasVerticalScroll; var position = __assign({}, this.currentPos); if (hasHorizontalScroll) { var roundX = Math.round(this.ratioX * x * this.translateXSign); // maybe maxScrollX is negative position.x = between(roundX, Math.min(this.minScrollX, this.maxScrollX), Math.max(this.minScrollX, this.maxScrollX)); } if (hasVerticalScroll) { var roundY = Math.round(this.ratioY * y * this.translateYSign); // maybe maxScrollY is negative position.y = between(roundY, Math.min(this.minScrollY, this.maxScrollY), Math.max(this.minScrollY, this.maxScrollY)); } return position; }; Indicator.prototype.destroy = function () { if (this.options.interactive !== false) { this.startEventRegister.destroy(); this.moveEventRegister.destroy(); this.endEventRegister.destroy(); } this.hooksFn.forEach(function (item) { var hooks = item[0]; var hooksName = item[1]; var handlerFn = item[2]; hooks.off(hooksName, handlerFn); }); this.hooksFn.length = 0; }; return Indicator; }()); var Indicators = /** @class */ (function () { function Indicators(scroll) { this.scroll = scroll; this.options = []; this.indicators = []; this.handleOptions(); this.handleHooks(); } Indicators.prototype.handleOptions = function () { var UserIndicatorsOptions = this.scroll.options.indicators; assert(Array.isArray(UserIndicatorsOptions), "'indicators' must be an array."); for (var _i = 0, UserIndicatorsOptions_1 = UserIndicatorsOptions; _i < UserIndicatorsOptions_1.length; _i++) { var indicatorOptions = UserIndicatorsOptions_1[_i]; assert(!!indicatorOptions.relationElement, "'relationElement' must be a HTMLElement."); this.createIndicators(indicatorOptions); } }; Indicators.prototype.createIndicators = function (options) { this.indicators.push(new Indicator(this.scroll, options)); }; Indicators.prototype.handleHooks = function () { var _this = this; var scrollHooks = this.scroll.hooks; scrollHooks.on(scrollHooks.eventTypes.destroy, function () { for (var _i = 0, _a = _this.indicators; _i < _a.length; _i++) { var indicator = _a[_i]; indicator.destroy(); } _this.indicators = []; }); }; Indicators.pluginName = 'indicators'; return Indicators; }()); BScroll.use(MouseWheel) .use(ObserveDOM) .use(PullDown) .use(PullUp) .use(ScrollBar) .use(Slide) .use(Wheel) .use(Zoom) .use(NestedScroll) .use(InfinityScroll) .use(Movable) .use(ObserveImage) .use(Indicators); export default BScroll; export { Behavior, CustomOptions, Indicators, InfinityScroll, MouseWheel, Movable, NestedScroll, ObserveDOM as ObserveDom, ObserveImage, PullDown as PullDownRefresh, PullUp as PullUpLoad, ScrollBar, Slide, Wheel, Zoom, createBScroll };
/** * @file index * @author Jim Bulkowski <jim.b@paperelectron.com> * @project Paperelectron.com * @license MIT {@link http://opensource.org/licenses/MIT} */ /** * Main routes * @module index */ module.exports = function(Router){ Router.get('/', function(req, res){ res.render('Frontpage'); }) return Router };
/*! * phone-codes/phone-be.js * https://github.com/RobinHerbots/Inputmask * Copyright (c) 2010 - 2018 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 4.0.0-beta.42 */ !function(factory) { "function" == typeof define && define.amd ? define([ "../inputmask" ], factory) : "object" == typeof exports ? module.exports = factory(require("../inputmask")) : factory(window.Inputmask); }(function(Inputmask) { return Inputmask.extendAliases({ phonebe: { alias: "abstractphone", countrycode: "32", phoneCodes: [ { mask: "+32(53)##-##-##", cc: "BE", cd: "Belgium", city: "Aalst (Alost)" }, { mask: "+32(3)###-##-##", cc: "BE", cd: "Belgium", city: "Antwerpen (Anvers)" }, { mask: "+32(63)##-##-##", cc: "BE", cd: "Belgium", city: "Arlon" }, { mask: "+32(68)##-##-##", cc: "BE", cd: "Belgium", city: "Ath" }, { mask: "+32(50)##-##-##", cc: "BE", cd: "Belgium", city: "Brugge (Bruges)" }, { mask: "+32(2)###-##-##", cc: "BE", cd: "Belgium", city: "Brussel/Bruxelles (Brussels)" }, { mask: "+32(71)##-##-##", cc: "BE", cd: "Belgium", city: "Charleroi" }, { mask: "+32(60)##-##-##", cc: "BE", cd: "Belgium", city: "Chimay" }, { mask: "+32(83)##-##-##", cc: "BE", cd: "Belgium", city: "Ciney" }, { mask: "+32(56)##-##-##", cc: "BE", cd: "Belgium", city: "Courtrai, Comines-Warneton, Mouscron" }, { mask: "+32(52)##-##-##", cc: "BE", cd: "Belgium", city: "Dendermonde" }, { mask: "+32(13)##-##-##", cc: "BE", cd: "Belgium", city: "Diest" }, { mask: "+32(82)##-##-##", cc: "BE", cd: "Belgium", city: "Dinant" }, { mask: "+32(86)##-##-##", cc: "BE", cd: "Belgium", city: "Durbuy" }, { mask: "+32(89)##-##-##", cc: "BE", cd: "Belgium", city: "Genk" }, { mask: "+32(9)###-##-##", cc: "BE", cd: "Belgium", city: "Gent (Gand)" }, { mask: "+32(11)##-##-##", cc: "BE", cd: "Belgium", city: "Hasselt" }, { mask: "+32(14)##-##-##", cc: "BE", cd: "Belgium", city: "Herentals" }, { mask: "+32(85)##-##-##", cc: "BE", cd: "Belgium", city: "Huy (Hoei)" }, { mask: "+32(57)##-##-##", cc: "BE", cd: "Belgium", city: "Ieper (Ypres)" }, { mask: "+32(64)##-##-##", cc: "BE", cd: "Belgium", city: "La Louvière" }, { mask: "+32(16)##-##-##", cc: "BE", cd: "Belgium", city: "Leuven (Louvain)" }, { mask: "+32(61)##-##-##", cc: "BE", cd: "Belgium", city: "Libramont" }, { mask: "+32(4)###-##-##", cc: "BE", cd: "Belgium", city: "Liège (Luik)" }, { mask: "+32(84)###-##-##", cc: "BE", cd: "Belgium", city: "Marche-en-Famenne" }, { mask: "+32(15)##-##-##", cc: "BE", cd: "Belgium", city: "Mechelen (Malines)" }, { mask: "+32(46#)##-##-##", cc: "BE", cd: "Belgium", city: "Mobile Phones" }, { mask: "+32(47#)##-##-##", cc: "BE", cd: "Belgium", city: "Mobile Phones" }, { mask: "+32(48#)##-##-##", cc: "BE", cd: "Belgium", city: "Mobile Phones" }, { mask: "+32(49#)##-##-##", cc: "BE", cd: "Belgium", city: "Mobile Phones" }, { mask: "+32(461)8#-##-##", cc: "BE", cd: "Belgium", city: "GSM-R (NMBS)" }, { mask: "+32(65)##-##-##", cc: "BE", cd: "Belgium", city: "Mons (Bergen)" }, { mask: "+32(81)##-##-##", cc: "BE", cd: "Belgium", city: "Namur (Namen)" }, { mask: "+32(58)##-##-##", cc: "BE", cd: "Belgium", city: "Nieuwpoort (Nieuport)" }, { mask: "+32(54)##-##-##", cc: "BE", cd: "Belgium", city: "Ninove" }, { mask: "+32(67)##-##-##", cc: "BE", cd: "Belgium", city: "Nivelles (Nijvel)" }, { mask: "+32(59)##-##-##", cc: "BE", cd: "Belgium", city: "Oostende (Ostende)" }, { mask: "+32(51)##-##-##", cc: "BE", cd: "Belgium", city: "Roeselare (Roulers)" }, { mask: "+32(55)##-##-##", cc: "BE", cd: "Belgium", city: "Ronse" }, { mask: "+32(80)##-##-##", cc: "BE", cd: "Belgium", city: "Stavelot" }, { mask: "+32(12)##-##-##", cc: "BE", cd: "Belgium", city: "Tongeren (Tongres)" }, { mask: "+32(69)##-##-##", cc: "BE", cd: "Belgium", city: "Tounai" }, { mask: "+32(14)##-##-##", cc: "BE", cd: "Belgium", city: "Turnhout" }, { mask: "+32(87)##-##-##", cc: "BE", cd: "Belgium", city: "Verviers" }, { mask: "+32(58)##-##-##", cc: "BE", cd: "Belgium", city: "Veurne" }, { mask: "+32(19)##-##-##", cc: "BE", cd: "Belgium", city: "Waremme" }, { mask: "+32(10)##-##-##", cc: "BE", cd: "Belgium", city: "Wavre (Waver)" }, { mask: "+32(50)##-##-##", cc: "BE", cd: "Belgium", city: "Zeebrugge" } ] } }), Inputmask; });
/** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Egret-Labs.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY EGRET-LABS.ORG AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL EGRET-LABS.ORG AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var egret; (function (egret) { /** * 这个类是HTML5的WebWrapper的第一个版本 */ var Browser = (function (_super) { __extends(Browser, _super); function Browser() { _super.call(this); this.ua = navigator.userAgent.toLowerCase(); this.trans = this._getTrans(); } Browser.getInstance = function () { if (Browser.instance == null) { Browser.instance = new Browser(); } return Browser.instance; }; Object.defineProperty(Browser.prototype, "isMobile", { /** * @deprecated * @returns {boolean} */ get: function () { egret.Logger.warning("Browser.isMobile接口参数已经变更,请尽快调整用法为 egret.MainContext.deviceType == egret.MainContext.DEVICE_MOBILE "); return egret.MainContext.deviceType == egret.MainContext.DEVICE_MOBILE; }, enumerable: true, configurable: true }); Browser.prototype._getHeader = function (tempStyle) { if ("transform" in tempStyle) { return ""; } var transArr = ["webkit", "ms", "Moz", "O"]; for (var i = 0; i < transArr.length; i++) { var transform = transArr[i] + 'Transform'; if (transform in tempStyle) return transArr[i]; } return ""; }; Browser.prototype._getTrans = function () { var tempStyle = document.createElement('div').style; var _header = this._getHeader(tempStyle); var type = "transform"; if (_header == "") { return type; } return _header + type.charAt(0).toUpperCase() + type.substr(1); }; Browser.prototype.$new = function (x) { return this.$(document.createElement(x)); }; Browser.prototype.$ = function (x) { var parent = document; var el = (x instanceof HTMLElement) ? x : parent.querySelector(x); if (el) { el.find = el.find || this.$; el.hasClass = el.hasClass || function (cls) { return this.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); }; el.addClass = el.addClass || function (cls) { if (!this.hasClass(cls)) { if (this.className) { this.className += " "; } this.className += cls; } return this; }; el.removeClass = el.removeClass || function (cls) { if (this.hasClass(cls)) { this.className = this.className.replace(cls, ''); } return this; }; el.remove = el.remove || function () { // if (this.parentNode) // this.parentNode.removeChild(this); // return this; }; el.appendTo = el.appendTo || function (x) { x.appendChild(this); return this; }; el.prependTo = el.prependTo || function (x) { (x.childNodes[0]) ? x.insertBefore(this, x.childNodes[0]) : x.appendChild(this); return this; }; el.transforms = el.transforms || function () { this.style[Browser.getInstance().trans] = Browser.getInstance().translate(this.position) + Browser.getInstance().rotate(this.rotation) + Browser.getInstance().scale(this.scale) + Browser.getInstance().skew(this.skew); return this; }; el.position = el.position || { x: 0, y: 0 }; el.rotation = el.rotation || 0; el.scale = el.scale || { x: 1, y: 1 }; el.skew = el.skew || { x: 0, y: 0 }; el.translates = function (x, y) { this.position.x = x; this.position.y = y - egret.MainContext.instance.stage.stageHeight; this.transforms(); return this; }; el.rotate = function (x) { this.rotation = x; this.transforms(); return this; }; el.resize = function (x, y) { this.scale.x = x; this.scale.y = y; this.transforms(); return this; }; el.setSkew = function (x, y) { this.skew.x = x; this.skew.y = y; this.transforms(); return this; }; } return el; }; Browser.prototype.translate = function (a) { return "translate(" + a.x + "px, " + a.y + "px) "; }; Browser.prototype.rotate = function (a) { return "rotate(" + a + "deg) "; }; Browser.prototype.scale = function (a) { return "scale(" + a.x + ", " + a.y + ") "; }; Browser.prototype.skew = function (a) { return "skewX(" + -a.x + "deg) skewY(" + a.y + "deg)"; }; return Browser; })(egret.HashObject); egret.Browser = Browser; Browser.prototype.__class__ = "egret.Browser"; })(egret || (egret = {}));
/** * * Bucket Settings Component * @parent ToolSettings * @author Robert P. * */ import React from 'react'; import BaseComponent from '../../../base-component/base-component'; import {branch} from 'baobab-react/higher-order'; import ColorPicker from 'react-color'; import * as actions from '../../actions'; const displayName = 'Bucket Settings'; class BucketSettings extends BaseComponent { constructor(props) { super(props); this._bind('_handleChange'); } _handleChange(color) { let color2 = '#' + color.hex; this.props.actions.updateColor(color2); } render() { const props = this.props; return ( <aside> <p className="settingsTitle">Bucket settings</p> <div className="settings settings--short"> <ColorPicker color = {props.color} onChange = {this._handleChange} type="chrome" /> </div> </aside> ); } } export default branch(BucketSettings, { cursors: { color: ['color'] }, actions: { updateColor: actions.updateColor } });
/* @flow */ declare module 'meteor/mhagmajer:server-router' { declare type Path = {| path: string, options?: {| sensitive?: boolean, strict?: boolean, end?: boolean, delimiter?: string, |}, args: ArgsMapper, route: Route, |}; declare type ArgsMapper = ( params: { [key: string]: string | Array<string> }, query: { [key: string]: string } ) => Array<any>; declare type Route = (...args: Array<any>) => Promise<void | boolean>; declare type Routes = { [name: string]: Route | Routes } declare export type ServerRouterContext = { req: http$IncomingMessage, res: http$ServerResponse, userId: ?string, }; declare type Middleware = (req: http$IncomingMessage, res: http$ServerResponse, next: (error?: any) => void) => void; declare type ServerRouterOptions = {| routes?: Routes, defaultRoutePath?: string, paths?: Array<Path>, |}; declare export class ServerRouter { static middleware(options?: ServerRouterOptions): Middleware; constructor(options?: ServerRouterOptions): this; addPath(data: Path): void; addPaths(data: Array<Path>): void; addRoutes(routes: Routes): void; middleware: Middleware; } declare export class AuthenticationRequiredError { } declare export class ServerRouterClient<R: Routes> { constructor(options?: {| routes?: R, defaultRoutePath?: string, |}): this; redirect: R; path: R; redirectTo(path: string): Promise<void>; redirectToRoute(name: string, ...args: Array<any>): Promise<void>; authenticatePath(path: string): Promise<string>; getRoutePath(name: string, ...args: Array<any>): string; } }
// Chat actions export const UPDATE_CHAT = 'UPDATE_CHAT'; export const FLUSH_CHAT_MESSAGES = 'FLUSH_CHAT_MESSAGES'; // Room actions export const GET_ROOMS = 'GET_ROOMS'; export const CREATE_ROOM = 'CREATE_ROOM'; export const ADD_USER_TO_ROOM = 'ADD_USER_TO_ROOM'; export const REMOVE_USER_FROM_ROOM = 'REMOVE_USER_FROM_ROOM'; // Session actions export const INIT_STATE = 'INIT_STATE'; export const SET_USER_SIGN = 'SET_USER_SIGN'; export const SET_USER_INTERNAL = 'SET_USER_INTERNAL'; // Tic Tac Toe actions export const RESTART_GAME = 'RESTART_GAME'; export const SELECT_TILE = 'SELECT_TILE'; export const ADD_PLAYER_TO_GAME = 'ADD_PLAYER_TO_GAME'; export const REMOVE_PLAYER_FROM_GAME = 'REMOVE_PLAYER_FROM_GAME'; export const ADD_POINT = 'ADD_POINT'; export const ROTATE_TURN = 'ROTATE_TURN'; // User actions export const SET_USER = 'SET_USER';
'use strict'; var yeoman = require('yeoman-generator'); module.exports = yeoman.generators.Base.extend({ initializing: function() { this.argument('name', {type: String, required: true}); this.composeWith('yangular:filter', { args: [this.name], options: { scriptsDir: this.config.get('scriptsDir') } }); } });
(function () { module.exports = { load: function (plugin) { plugin.on('fire-scene:open', function () { plugin.openPanel('default'); }); }, unload: function (plugin) { }, }; })();
/*! * css-vars-ponyfill * v2.4.3 * https://jhildenbiddle.github.io/css-vars-ponyfill/ * (c) 2018-2021 John Hildenbiddle <http://hildenbiddle.com> * MIT license */ function _extends() { _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /*! * get-css-data * v2.0.0 * https://github.com/jhildenbiddle/get-css-data * (c) 2018-2021 John Hildenbiddle <http://hildenbiddle.com> * MIT license */ function getUrls(urls) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var settings = { mimeType: options.mimeType || null, onBeforeSend: options.onBeforeSend || Function.prototype, onSuccess: options.onSuccess || Function.prototype, onError: options.onError || Function.prototype, onComplete: options.onComplete || Function.prototype }; var urlArray = Array.isArray(urls) ? urls : [ urls ]; var urlQueue = Array.apply(null, Array(urlArray.length)).map((function(x) { return null; })); function isValidCss(cssText) { var isHTML = cssText && cssText.trim().charAt(0) === "<"; return cssText && !isHTML; } function onError(xhr, urlIndex) { settings.onError(xhr, urlArray[urlIndex], urlIndex); } function onSuccess(responseText, urlIndex) { var returnVal = settings.onSuccess(responseText, urlArray[urlIndex], urlIndex); responseText = returnVal === false ? "" : returnVal || responseText; urlQueue[urlIndex] = responseText; if (urlQueue.indexOf(null) === -1) { settings.onComplete(urlQueue); } } var parser = document.createElement("a"); urlArray.forEach((function(url, i) { parser.setAttribute("href", url); parser.href = String(parser.href); var isIElte9 = Boolean(document.all && !window.atob); var isIElte9CORS = isIElte9 && parser.host.split(":")[0] !== location.host.split(":")[0]; if (isIElte9CORS) { var isSameProtocol = parser.protocol === location.protocol; if (isSameProtocol) { var xdr = new XDomainRequest; xdr.open("GET", url); xdr.timeout = 0; xdr.onprogress = Function.prototype; xdr.ontimeout = Function.prototype; xdr.onload = function() { if (isValidCss(xdr.responseText)) { onSuccess(xdr.responseText, i); } else { onError(xdr, i); } }; xdr.onerror = function(err) { onError(xdr, i); }; setTimeout((function() { xdr.send(); }), 0); } else { console.warn("Internet Explorer 9 Cross-Origin (CORS) requests must use the same protocol (".concat(url, ")")); onError(null, i); } } else { var xhr = new XMLHttpRequest; xhr.open("GET", url); if (settings.mimeType && xhr.overrideMimeType) { xhr.overrideMimeType(settings.mimeType); } settings.onBeforeSend(xhr, url, i); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status < 400 && isValidCss(xhr.responseText)) { onSuccess(xhr.responseText, i); } else if (xhr.status === 0 && isValidCss(xhr.responseText)) { onSuccess(xhr.responseText, i); } else { onError(xhr, i); } } }; xhr.send(); } })); } /** * Gets CSS data from <style> and <link> nodes (including @imports), then * returns data in order processed by DOM. Allows specifying nodes to * include/exclude and filtering CSS data using RegEx. * * @preserve * @param {object} [options] The options object * @param {object} [options.rootElement=document] Root element to traverse for * <link> and <style> nodes. * @param {string} [options.include] CSS selector matching <link> and <style> * nodes to include * @param {string} [options.exclude] CSS selector matching <link> and <style> * nodes to exclude * @param {object} [options.filter] Regular expression used to filter node CSS * data. Each block of CSS data is tested against the filter, * and only matching data is included. * @param {boolean} [options.skipDisabled=true] Determines if disabled * stylesheets will be skipped while collecting CSS data. * @param {boolean} [options.useCSSOM=false] Determines if CSS data will be * collected from a stylesheet's runtime values instead of its * text content. This is required to get accurate CSS data * when a stylesheet has been modified using the deleteRule() * or insertRule() methods because these modifications will * not be reflected in the stylesheet's text content. * @param {function} [options.onBeforeSend] Callback before XHR is sent. Passes * 1) the XHR object, 2) source node reference, and 3) the * source URL as arguments. * @param {function} [options.onSuccess] Callback on each CSS node read. Passes * 1) CSS text, 2) source node reference, and 3) the source * URL as arguments. * @param {function} [options.onError] Callback on each error. Passes 1) the XHR * object for inspection, 2) soure node reference, and 3) the * source URL that failed (either a <link> href or an @import) * as arguments * @param {function} [options.onComplete] Callback after all nodes have been * processed. Passes 1) concatenated CSS text, 2) an array of * CSS text in DOM order, and 3) an array of nodes in DOM * order as arguments. * * @example * * getCssData({ * rootElement : document, * include : 'style,link[rel="stylesheet"]', * exclude : '[href="skip.css"]', * filter : /red/, * skipDisabled: true, * useCSSOM : false, * onBeforeSend(xhr, node, url) { * // ... * } * onSuccess(cssText, node, url) { * // ... * } * onError(xhr, node, url) { * // ... * }, * onComplete(cssText, cssArray, nodeArray) { * // ... * } * }); */ function getCssData(options) { var regex = { cssComments: /\/\*[\s\S]+?\*\//g, cssImports: /(?:@import\s*)(?:url\(\s*)?(?:['"])([^'"]*)(?:['"])(?:\s*\))?(?:[^;]*;)/g }; var settings = { rootElement: options.rootElement || document, include: options.include || 'style,link[rel="stylesheet"]', exclude: options.exclude || null, filter: options.filter || null, skipDisabled: options.skipDisabled !== false, useCSSOM: options.useCSSOM || false, onBeforeSend: options.onBeforeSend || Function.prototype, onSuccess: options.onSuccess || Function.prototype, onError: options.onError || Function.prototype, onComplete: options.onComplete || Function.prototype }; var sourceNodes = Array.apply(null, settings.rootElement.querySelectorAll(settings.include)).filter((function(node) { return !matchesSelector(node, settings.exclude); })); var cssArray = Array.apply(null, Array(sourceNodes.length)).map((function(x) { return null; })); function handleComplete() { var isComplete = cssArray.indexOf(null) === -1; if (isComplete) { cssArray.reduce((function(skipIndices, value, i) { if (value === "") { skipIndices.push(i); } return skipIndices; }), []).reverse().forEach((function(skipIndex) { return [ sourceNodes, cssArray ].forEach((function(arr) { return arr.splice(skipIndex, 1); })); })); var cssText = cssArray.join(""); settings.onComplete(cssText, cssArray, sourceNodes); } } function handleSuccess(cssText, cssIndex, node, sourceUrl) { var returnVal = settings.onSuccess(cssText, node, sourceUrl); cssText = returnVal !== undefined && Boolean(returnVal) === false ? "" : returnVal || cssText; resolveImports(cssText, node, sourceUrl, (function(resolvedCssText, errorData) { if (cssArray[cssIndex] === null) { errorData.forEach((function(data) { return settings.onError(data.xhr, node, data.url); })); if (!settings.filter || settings.filter.test(resolvedCssText)) { cssArray[cssIndex] = resolvedCssText; } else { cssArray[cssIndex] = ""; } handleComplete(); } })); } function parseImportData(cssText, baseUrl) { var ignoreRules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var importData = {}; importData.rules = (cssText.replace(regex.cssComments, "").match(regex.cssImports) || []).filter((function(rule) { return ignoreRules.indexOf(rule) === -1; })); importData.urls = importData.rules.map((function(rule) { return rule.replace(regex.cssImports, "$1"); })); importData.absoluteUrls = importData.urls.map((function(url) { return getFullUrl(url, baseUrl); })); importData.absoluteRules = importData.rules.map((function(rule, i) { var oldUrl = importData.urls[i]; var newUrl = getFullUrl(importData.absoluteUrls[i], baseUrl); return rule.replace(oldUrl, newUrl); })); return importData; } function resolveImports(cssText, node, baseUrl, callbackFn) { var __errorData = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; var __errorRules = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; var importData = parseImportData(cssText, baseUrl, __errorRules); if (importData.rules.length) { getUrls(importData.absoluteUrls, { onBeforeSend: function onBeforeSend(xhr, url, urlIndex) { settings.onBeforeSend(xhr, node, url); }, onSuccess: function onSuccess(cssText, url, urlIndex) { var returnVal = settings.onSuccess(cssText, node, url); cssText = returnVal === false ? "" : returnVal || cssText; var responseImportData = parseImportData(cssText, url, __errorRules); responseImportData.rules.forEach((function(rule, i) { cssText = cssText.replace(rule, responseImportData.absoluteRules[i]); })); return cssText; }, onError: function onError(xhr, url, urlIndex) { __errorData.push({ xhr: xhr, url: url }); __errorRules.push(importData.rules[urlIndex]); resolveImports(cssText, node, baseUrl, callbackFn, __errorData, __errorRules); }, onComplete: function onComplete(responseArray) { responseArray.forEach((function(importText, i) { cssText = cssText.replace(importData.rules[i], importText); })); resolveImports(cssText, node, baseUrl, callbackFn, __errorData, __errorRules); } }); } else { callbackFn(cssText, __errorData); } } if (sourceNodes.length) { sourceNodes.forEach((function(node, i) { var linkHref = node.getAttribute("href"); var linkRel = node.getAttribute("rel"); var isLink = node.nodeName.toLowerCase() === "link" && linkHref && linkRel && linkRel.toLowerCase().indexOf("stylesheet") !== -1; var isSkip = settings.skipDisabled === false ? false : node.disabled; var isStyle = node.nodeName.toLowerCase() === "style"; if (isLink && !isSkip) { getUrls(linkHref, { mimeType: "text/css", onBeforeSend: function onBeforeSend(xhr, url, urlIndex) { settings.onBeforeSend(xhr, node, url); }, onSuccess: function onSuccess(cssText, url, urlIndex) { var sourceUrl = getFullUrl(linkHref); handleSuccess(cssText, i, node, sourceUrl); }, onError: function onError(xhr, url, urlIndex) { cssArray[i] = ""; settings.onError(xhr, node, url); handleComplete(); } }); } else if (isStyle && !isSkip) { var cssText = node.textContent; if (settings.useCSSOM) { cssText = Array.apply(null, node.sheet.cssRules).map((function(rule) { return rule.cssText; })).join(""); } handleSuccess(cssText, i, node, location.href); } else { cssArray[i] = ""; handleComplete(); } })); } else { settings.onComplete("", []); } } function getFullUrl(url, base) { var d = document.implementation.createHTMLDocument(""); var b = d.createElement("base"); var a = d.createElement("a"); d.head.appendChild(b); d.body.appendChild(a); b.href = base || document.baseURI || (document.querySelector("base") || {}).href || location.href; a.href = url; return a.href; } function matchesSelector(elm, selector) { var matches = elm.matches || elm.matchesSelector || elm.webkitMatchesSelector || elm.mozMatchesSelector || elm.msMatchesSelector || elm.oMatchesSelector; return matches.call(elm, selector); } var balancedMatch = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } function parseCss(css) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var defaults = { preserveStatic: true, removeComments: false }; var settings = _extends({}, defaults, options); var errors = []; function error(msg) { throw new Error("CSS parse error: ".concat(msg)); } function match(re) { var m = re.exec(css); if (m) { css = css.slice(m[0].length); return m; } } function open() { return match(/^{\s*/); } function close() { return match(/^}/); } function whitespace() { match(/^\s*/); } function comment() { whitespace(); if (css[0] !== "/" || css[1] !== "*") { return; } var i = 2; while (css[i] && (css[i] !== "*" || css[i + 1] !== "/")) { i++; } if (!css[i]) { return error("end of comment is missing"); } var str = css.slice(2, i); css = css.slice(i + 2); return { type: "comment", comment: str }; } function comments() { var cmnts = []; var c; while (c = comment()) { cmnts.push(c); } return settings.removeComments ? [] : cmnts; } function selector() { whitespace(); while (css[0] === "}") { error("extra closing bracket"); } var m = match(/^(("(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^{])+)/); if (m) { return m[0].trim().replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, "").replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, (function(m) { return m.replace(/,/g, "‌"); })).split(/\s*(?![^(]*\)),\s*/).map((function(s) { return s.replace(/\u200C/g, ","); })); } } function declaration() { if (css[0] === "@") { return at_rule(); } match(/^([;\s]*)+/); var comment_regexp = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g; var prop = match(/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/); if (!prop) { return; } prop = prop[0].trim(); if (!match(/^:\s*/)) { return error("property missing ':'"); } var val = match(/^((?:\/\*.*?\*\/|'(?:\\'|.)*?'|"(?:\\"|.)*?"|\((\s*'(?:\\'|.)*?'|"(?:\\"|.)*?"|[^)]*?)\s*\)|[^};])+)/); var ret = { type: "declaration", property: prop.replace(comment_regexp, ""), value: val ? val[0].replace(comment_regexp, "").trim() : "" }; match(/^[;\s]*/); return ret; } function declarations() { if (!open()) { return error("missing '{'"); } var d; var decls = comments(); while (d = declaration()) { decls.push(d); decls = decls.concat(comments()); } if (!close()) { return error("missing '}'"); } return decls; } function keyframe() { whitespace(); var vals = []; var m; while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) { vals.push(m[1]); match(/^,\s*/); } if (vals.length) { return { type: "keyframe", values: vals, declarations: declarations() }; } } function at_keyframes() { var m = match(/^@([-\w]+)?keyframes\s*/); if (!m) { return; } var vendor = m[1]; m = match(/^([-\w]+)\s*/); if (!m) { return error("@keyframes missing name"); } var name = m[1]; if (!open()) { return error("@keyframes missing '{'"); } var frame; var frames = comments(); while (frame = keyframe()) { frames.push(frame); frames = frames.concat(comments()); } if (!close()) { return error("@keyframes missing '}'"); } return { type: "keyframes", name: name, vendor: vendor, keyframes: frames }; } function at_page() { var m = match(/^@page */); if (m) { var sel = selector() || []; return { type: "page", selectors: sel, declarations: declarations() }; } } function at_page_margin_box() { var m = match(/@(top|bottom|left|right)-(left|center|right|top|middle|bottom)-?(corner)?\s*/); if (m) { var name = "".concat(m[1], "-").concat(m[2]) + (m[3] ? "-".concat(m[3]) : ""); return { type: "page-margin-box", name: name, declarations: declarations() }; } } function at_fontface() { var m = match(/^@font-face\s*/); if (m) { return { type: "font-face", declarations: declarations() }; } } function at_supports() { var m = match(/^@supports *([^{]+)/); if (m) { return { type: "supports", supports: m[1].trim(), rules: rules() }; } } function at_host() { var m = match(/^@host\s*/); if (m) { return { type: "host", rules: rules() }; } } function at_media() { var m = match(/^@media([^{]+)*/); if (m) { return { type: "media", media: (m[1] || "").trim(), rules: rules() }; } } function at_custom_m() { var m = match(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/); if (m) { return { type: "custom-media", name: m[1].trim(), media: m[2].trim() }; } } function at_document() { var m = match(/^@([-\w]+)?document *([^{]+)/); if (m) { return { type: "document", document: m[2].trim(), vendor: m[1] ? m[1].trim() : null, rules: rules() }; } } function at_x() { var m = match(/^@(import|charset|namespace)\s*([^;]+);/); if (m) { return { type: m[1], name: m[2].trim() }; } } function at_rule() { whitespace(); if (css[0] === "@") { var ret = at_x() || at_fontface() || at_media() || at_keyframes() || at_supports() || at_document() || at_custom_m() || at_host() || at_page() || at_page_margin_box(); if (ret && !settings.preserveStatic) { var hasVarFunc = false; if (ret.declarations) { hasVarFunc = ret.declarations.some((function(decl) { return /var\(/.test(decl.value); })); } else { var arr = ret.keyframes || ret.rules || []; hasVarFunc = arr.some((function(obj) { return (obj.declarations || []).some((function(decl) { return /var\(/.test(decl.value); })); })); } return hasVarFunc ? ret : {}; } return ret; } } function rule() { if (!settings.preserveStatic) { var balancedMatch$1 = balancedMatch("{", "}", css); if (balancedMatch$1) { var hasVarDecl = /:(?:root|host)(?![.:#(])/.test(balancedMatch$1.pre) && /--\S*\s*:/.test(balancedMatch$1.body); var hasVarFunc = /var\(/.test(balancedMatch$1.body); if (!hasVarDecl && !hasVarFunc) { css = css.slice(balancedMatch$1.end + 1); return {}; } } } var sel = selector() || []; var decls = settings.preserveStatic ? declarations() : declarations().filter((function(decl) { var hasVarDecl = sel.some((function(s) { return /:(?:root|host)(?![.:#(])/.test(s); })) && /^--\S/.test(decl.property); var hasVarFunc = /var\(/.test(decl.value); return hasVarDecl || hasVarFunc; })); if (!sel.length) { error("selector missing"); } return { type: "rule", selectors: sel, declarations: decls }; } function rules(core) { if (!core && !open()) { return error("missing '{'"); } var node; var rules = comments(); while (css.length && (core || css[0] !== "}") && (node = at_rule() || rule())) { if (node.type) { rules.push(node); } rules = rules.concat(comments()); } if (!core && !close()) { return error("missing '}'"); } return rules; } return { type: "stylesheet", stylesheet: { rules: rules(true), errors: errors } }; } function parseVars(cssData) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var defaults = { parseHost: false, store: {}, onWarning: function onWarning() {} }; var settings = _extends({}, defaults, options); var reVarDeclSelectors = new RegExp(":".concat(settings.parseHost ? "host" : "root", "$")); if (typeof cssData === "string") { cssData = parseCss(cssData, settings); } cssData.stylesheet.rules.forEach((function(rule) { if (rule.type !== "rule" || !rule.selectors.some((function(s) { return reVarDeclSelectors.test(s); }))) { return; } rule.declarations.forEach((function(decl, i) { var prop = decl.property; var value = decl.value; if (prop && prop.indexOf("--") === 0) { settings.store[prop] = value; } })); })); return settings.store; } function stringifyCss(tree) { var delim = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; var cb = arguments.length > 2 ? arguments[2] : undefined; var renderMethods = { charset: function charset(node) { return "@charset " + node.name + ";"; }, comment: function comment(node) { return node.comment.indexOf("__CSSVARSPONYFILL") === 0 ? "/*" + node.comment + "*/" : ""; }, "custom-media": function customMedia(node) { return "@custom-media " + node.name + " " + node.media + ";"; }, declaration: function declaration(node) { return node.property + ":" + node.value + ";"; }, document: function document(node) { return "@" + (node.vendor || "") + "document " + node.document + "{" + visit(node.rules) + "}"; }, "font-face": function fontFace(node) { return "@font-face" + "{" + visit(node.declarations) + "}"; }, host: function host(node) { return "@host" + "{" + visit(node.rules) + "}"; }, import: function _import(node) { return "@import " + node.name + ";"; }, keyframe: function keyframe(node) { return node.values.join(",") + "{" + visit(node.declarations) + "}"; }, keyframes: function keyframes(node) { return "@" + (node.vendor || "") + "keyframes " + node.name + "{" + visit(node.keyframes) + "}"; }, media: function media(node) { return "@media " + node.media + "{" + visit(node.rules) + "}"; }, namespace: function namespace(node) { return "@namespace " + node.name + ";"; }, page: function page(node) { return "@page " + (node.selectors.length ? node.selectors.join(", ") : "") + "{" + visit(node.declarations) + "}"; }, "page-margin-box": function pageMarginBox(node) { return "@" + node.name + "{" + visit(node.declarations) + "}"; }, rule: function rule(node) { var decls = node.declarations; if (decls.length) { return node.selectors.join(",") + "{" + visit(decls) + "}"; } }, supports: function supports(node) { return "@supports " + node.supports + "{" + visit(node.rules) + "}"; } }; function visit(nodes) { var buf = ""; for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; if (cb) { cb(n); } var txt = renderMethods[n.type](n); if (txt) { buf += txt; if (txt.length && n.selectors) { buf += delim; } } } return buf; } return visit(tree.stylesheet.rules); } function walkCss(node, fn) { node.rules.forEach((function(rule) { if (rule.rules) { walkCss(rule, fn); return; } if (rule.keyframes) { rule.keyframes.forEach((function(keyframe) { if (keyframe.type === "keyframe") { fn(keyframe.declarations, rule); } })); return; } if (!rule.declarations) { return; } fn(rule.declarations, node); })); } var VAR_PROP_IDENTIFIER = "--"; var VAR_FUNC_IDENTIFIER = "var"; function transformCss(cssData) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var defaults = { preserveStatic: true, preserveVars: false, variables: {}, onWarning: function onWarning() {} }; var settings = _extends({}, defaults, options); if (typeof cssData === "string") { cssData = parseCss(cssData, settings); } walkCss(cssData.stylesheet, (function(declarations, node) { for (var i = 0; i < declarations.length; i++) { var decl = declarations[i]; var type = decl.type; var prop = decl.property; var value = decl.value; if (type !== "declaration") { continue; } if (!settings.preserveVars && prop && prop.indexOf(VAR_PROP_IDENTIFIER) === 0) { declarations.splice(i, 1); i--; continue; } if (value.indexOf(VAR_FUNC_IDENTIFIER + "(") !== -1) { var resolvedValue = resolveValue(value, settings); if (resolvedValue !== decl.value) { resolvedValue = fixNestedCalc(resolvedValue); if (!settings.preserveVars) { decl.value = resolvedValue; } else { declarations.splice(i, 0, { type: type, property: prop, value: resolvedValue }); i++; } } } } })); return stringifyCss(cssData); } function fixNestedCalc(value) { var reCalcVal = /calc\(([^)]+)\)/g; (value.match(reCalcVal) || []).forEach((function(match) { var newVal = "calc".concat(match.split("calc").join("")); value = value.replace(match, newVal); })); return value; } function resolveValue(value) { var settings = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var __recursiveFallback = arguments.length > 2 ? arguments[2] : undefined; if (value.indexOf("var(") === -1) { return value; } var valueData = balancedMatch("(", ")", value); function resolveFunc(value) { var name = value.split(",")[0].replace(/[\s\n\t]/g, ""); var fallback = (value.match(/(?:\s*,\s*){1}(.*)?/) || [])[1]; var match = Object.prototype.hasOwnProperty.call(settings.variables, name) ? String(settings.variables[name]) : undefined; var replacement = match || (fallback ? String(fallback) : undefined); var unresolvedFallback = __recursiveFallback || value; if (!match) { settings.onWarning('variable "'.concat(name, '" is undefined')); } if (replacement && replacement !== "undefined" && replacement.length > 0) { return resolveValue(replacement, settings, unresolvedFallback); } else { return "var(".concat(unresolvedFallback, ")"); } } if (!valueData) { if (value.indexOf("var(") !== -1) { settings.onWarning('missing closing ")" in the value "'.concat(value, '"')); } return value; } else if (valueData.pre.slice(-3) === "var") { var isEmptyVarFunc = valueData.body.trim().length === 0; if (isEmptyVarFunc) { settings.onWarning("var() must contain a non-whitespace string"); return value; } else { return valueData.pre.slice(0, -3) + resolveFunc(valueData.body) + resolveValue(valueData.post, settings); } } else { return valueData.pre + "(".concat(resolveValue(valueData.body, settings), ")") + resolveValue(valueData.post, settings); } } var isBrowser = typeof window !== "undefined"; var isNativeSupport = isBrowser && window.CSS && window.CSS.supports && window.CSS.supports("(--a: 0)"); var counters = { group: 0, job: 0 }; var defaults = { rootElement: isBrowser ? document : null, shadowDOM: false, include: "style,link[rel=stylesheet]", exclude: "", variables: {}, onlyLegacy: true, preserveStatic: true, preserveVars: false, silent: false, updateDOM: true, updateURLs: true, watch: null, onBeforeSend: function onBeforeSend() {}, onError: function onError() {}, onWarning: function onWarning() {}, onSuccess: function onSuccess() {}, onComplete: function onComplete() {}, onFinally: function onFinally() {} }; var regex = { cssComments: /\/\*[\s\S]+?\*\//g, cssKeyframes: /@(?:-\w*-)?keyframes/, cssMediaQueries: /@media[^{]+\{([\s\S]+?})\s*}/g, cssUrls: /url\((?!['"]?(?:data|http|\/\/):)['"]?([^'")]*)['"]?\)/g, cssVarDeclRules: /(?::(?:root|host)(?![.:#(])[\s,]*[^{]*{\s*[^}]*})/g, cssVarDecls: /(?:[\s;]*)(-{2}\w[\w-]*)(?:\s*:\s*)([^;]*);/g, cssVarFunc: /var\(\s*--[\w-]/, cssVars: /(?:(?::(?:root|host)(?![.:#(])[\s,]*[^{]*{\s*[^;]*;*\s*)|(?:var\(\s*))(--[^:)]+)(?:\s*[:)])/ }; var variableStore = { dom: {}, job: {}, user: {} }; var cssVarsIsRunning = false; var cssVarsObserver = null; var cssVarsSrcNodeCount = 0; var debounceTimer = null; var isShadowDOMReady = false; /** * Fetches, parses, and transforms CSS custom properties from specified * <style> and <link> elements into static values, then appends a new <style> * element with static values to the DOM to provide CSS custom property * compatibility for legacy browsers. Also provides a single interface for * live updates of runtime values in both modern and legacy browsers. * * @preserve * @param {object} [options] Options object * @param {object} [options.rootElement=document] Root element to traverse for * <link> and <style> nodes * @param {boolean} [options.shadowDOM=false] Determines if shadow DOM <link> * and <style> nodes will be processed. * @param {string} [options.include="style,link[rel=stylesheet]"] CSS selector * matching <link re="stylesheet"> and <style> nodes to * process * @param {string} [options.exclude] CSS selector matching <link * rel="stylehseet"> and <style> nodes to exclude from those * matches by options.include * @param {object} [options.variables] A map of custom property name/value * pairs. Property names can omit or include the leading * double-hyphen (—), and values specified will override * previous values * @param {boolean} [options.onlyLegacy=true] Determines if the ponyfill will * only generate legacy-compatible CSS in browsers that lack * native support (i.e., legacy browsers) * @param {boolean} [options.preserveStatic=true] Determines if CSS * declarations that do not reference a custom property will * be preserved in the transformed CSS * @param {boolean} [options.preserveVars=false] Determines if CSS custom * property declarations will be preserved in the transformed * CSS * @param {boolean} [options.silent=false] Determines if warning and error * messages will be displayed on the console * @param {boolean} [options.updateDOM=true] Determines if the ponyfill will * update the DOM after processing CSS custom properties * @param {boolean} [options.updateURLs=true] Determines if relative url() * paths will be converted to absolute urls in external CSS * @param {boolean} [options.watch=false] Determines if a MutationObserver will * be created that will execute the ponyfill when a <link> or * <style> DOM mutation is observed * @param {function} [options.onBeforeSend] Callback before XHR is sent. Passes * 1) the XHR object, 2) source node reference, and 3) the * source URL as arguments * @param {function} [options.onError] Callback after a CSS parsing error has * occurred or an XHR request has failed. Passes 1) an error * message, and 2) source node reference, 3) xhr, and 4 url as * arguments. * @param {function} [options.onWarning] Callback after each CSS parsing warning * has occurred. Passes 1) a warning message as an argument. * @param {function} [options.onSuccess] Callback after CSS data has been * collected from each node and before CSS custom properties * have been transformed. Allows modifying the CSS data before * it is transformed by returning any string value (or false * to skip). Passes 1) CSS text, 2) source node reference, and * 3) the source URL as arguments. * @param {function} [options.onComplete] Callback after all CSS has been * processed, legacy-compatible CSS has been generated, and * (optionally) the DOM has been updated. Passes 1) a CSS * string with CSS variable values resolved, 2) an array of * output <style> node references that have been appended to * the DOM, 3) an object containing all custom properies names * and values, and 4) the ponyfill execution time in * milliseconds. * @param {function} [options.onFinally] Callback in modern and legacy browsers * after the ponyfill has finished all tasks. Passes 1) a * boolean indicating if the last ponyfill call resulted in a * style change, 2) a boolean indicating if the current * browser provides native support for CSS custom properties, * and 3) the ponyfill execution time in milliseconds. * @example * * cssVars({ * rootElement : document, * shadowDOM : false, * include : 'style,link[rel="stylesheet"]', * exclude : '', * variables : {}, * onlyLegacy : true, * preserveStatic: true, * preserveVars : false, * silent : false, * updateDOM : true, * updateURLs : true, * watch : false, * onBeforeSend(xhr, node, url) {}, * onError(message, node, xhr, url) {}, * onWarning(message) {}, * onSuccess(cssText, node, url) {}, * onComplete(cssText, styleNode, cssVariables, benchmark) {}, * onFinally(hasChanged, hasNativeSupport, benchmark) * }); */ function cssVars() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var msgPrefix = "cssVars(): "; var settings = _extends({}, defaults, options); function handleError(message, sourceNode, xhr, url) { if (!settings.silent && window.console) { console.error("".concat(msgPrefix).concat(message, "\n"), sourceNode); } settings.onError(message, sourceNode, xhr, url); } function handleWarning(message) { if (!settings.silent && window.console) { console.warn("".concat(msgPrefix).concat(message)); } settings.onWarning(message); } function handleFinally(hasChanged) { settings.onFinally(Boolean(hasChanged), isNativeSupport, getTimeStamp() - settings.__benchmark); } if (!isBrowser) { return; } if (settings.watch) { settings.watch = defaults.watch; addMutationObserver(settings); cssVars(settings); return; } else if (settings.watch === false && cssVarsObserver) { cssVarsObserver.disconnect(); cssVarsObserver = null; } if (!settings.__benchmark) { if (cssVarsIsRunning === settings.rootElement) { cssVarsDebounced(options); return; } var srcNodes = Array.apply(null, settings.rootElement.querySelectorAll('[data-cssvars]:not([data-cssvars="out"])')); settings.__benchmark = getTimeStamp(); settings.exclude = [ cssVarsObserver ? '[data-cssvars]:not([data-cssvars=""])' : '[data-cssvars="out"]', "link[disabled]:not([data-cssvars])", settings.exclude ].filter((function(selector) { return selector; })).join(","); settings.variables = fixVarNames(settings.variables); srcNodes.forEach((function(srcNode) { var hasStyleCache = srcNode.nodeName.toLowerCase() === "style" && srcNode.__cssVars.text; var hasStyleChanged = hasStyleCache && srcNode.textContent !== srcNode.__cssVars.text; if (hasStyleCache && hasStyleChanged) { srcNode.sheet && (srcNode.sheet.disabled = false); srcNode.setAttribute("data-cssvars", ""); } })); if (!cssVarsObserver) { var outNodes = Array.apply(null, settings.rootElement.querySelectorAll('[data-cssvars="out"]')); outNodes.forEach((function(outNode) { var dataGroup = outNode.getAttribute("data-cssvars-group"); var srcNode = dataGroup ? settings.rootElement.querySelector('[data-cssvars="src"][data-cssvars-group="'.concat(dataGroup, '"]')) : null; if (!srcNode) { outNode.parentNode.removeChild(outNode); } })); if (cssVarsSrcNodeCount && srcNodes.length < cssVarsSrcNodeCount) { cssVarsSrcNodeCount = srcNodes.length; variableStore.dom = {}; } } } if (document.readyState !== "loading") { if (isNativeSupport && settings.onlyLegacy) { var hasVarChange = false; if (settings.updateDOM) { var targetElm = settings.rootElement.host || (settings.rootElement === document ? document.documentElement : settings.rootElement); Object.keys(settings.variables).forEach((function(key) { var varValue = settings.variables[key]; hasVarChange = hasVarChange || varValue !== getComputedStyle(targetElm).getPropertyValue(key); targetElm.style.setProperty(key, varValue); })); } handleFinally(hasVarChange); } else if (!isShadowDOMReady && (settings.shadowDOM || settings.rootElement.shadowRoot || settings.rootElement.host)) { getCssData({ rootElement: defaults.rootElement, include: defaults.include, exclude: settings.exclude, skipDisabled: false, onSuccess: function onSuccess(cssText, node, url) { var isUserDisabled = (node.sheet || {}).disabled && !node.__cssVars; if (isUserDisabled) { return false; } cssText = cssText.replace(regex.cssComments, "").replace(regex.cssMediaQueries, ""); cssText = (cssText.match(regex.cssVarDeclRules) || []).join(""); return cssText || false; }, onComplete: function onComplete(cssText, cssArray, nodeArray) { parseVars(cssText, { store: variableStore.dom, onWarning: handleWarning }); isShadowDOMReady = true; cssVars(settings); } }); } else { cssVarsIsRunning = settings.rootElement; getCssData({ rootElement: settings.rootElement, include: settings.include, exclude: settings.exclude, skipDisabled: false, onBeforeSend: settings.onBeforeSend, onError: function onError(xhr, node, url) { var responseUrl = xhr.responseURL || getFullUrl$1(url, location.href); var statusText = xhr.statusText ? "(".concat(xhr.statusText, ")") : "Unspecified Error" + (xhr.status === 0 ? " (possibly CORS related)" : ""); var errorMsg = "CSS XHR Error: ".concat(responseUrl, " ").concat(xhr.status, " ").concat(statusText); handleError(errorMsg, node, xhr, responseUrl); }, onSuccess: function onSuccess(cssText, node, url) { var isUserDisabled = (node.sheet || {}).disabled && !node.__cssVars; if (isUserDisabled) { return false; } var isLink = node.nodeName.toLowerCase() === "link"; var isStyleImport = node.nodeName.toLowerCase() === "style" && cssText !== node.textContent; var returnVal = settings.onSuccess(cssText, node, url); cssText = returnVal !== undefined && Boolean(returnVal) === false ? "" : returnVal || cssText; if (settings.updateURLs && (isLink || isStyleImport)) { cssText = fixRelativeCssUrls(cssText, url); } return cssText; }, onComplete: function onComplete(cssText, cssArray) { var nodeArray = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; var currentVars = _extends({}, variableStore.dom, variableStore.user); var hasVarChange = false; variableStore.job = {}; nodeArray.forEach((function(node, i) { var nodeCSS = cssArray[i]; node.__cssVars = node.__cssVars || {}; node.__cssVars.text = nodeCSS; if (regex.cssVars.test(nodeCSS)) { try { var cssTree = parseCss(nodeCSS, { preserveStatic: settings.preserveStatic, removeComments: true }); parseVars(cssTree, { parseHost: Boolean(settings.rootElement.host), store: variableStore.dom, onWarning: handleWarning }); node.__cssVars.tree = cssTree; } catch (err) { handleError(err.message, node); } } })); _extends(variableStore.job, variableStore.dom); if (settings.updateDOM) { _extends(variableStore.user, settings.variables); _extends(variableStore.job, variableStore.user); } else { _extends(variableStore.job, variableStore.user, settings.variables); _extends(currentVars, settings.variables); } hasVarChange = counters.job > 0 && Boolean(Object.keys(variableStore.job).length > Object.keys(currentVars).length || Boolean(Object.keys(currentVars).length && Object.keys(variableStore.job).some((function(key) { return variableStore.job[key] !== currentVars[key]; })))); if (hasVarChange) { resetCssNodes(settings.rootElement); cssVars(settings); } else { var outCssArray = []; var outNodeArray = []; var hasKeyframesWithVars = false; if (settings.updateDOM) { counters.job++; } nodeArray.forEach((function(node, i) { var isSkip = !node.__cssVars.tree; if (node.__cssVars.tree) { try { transformCss(node.__cssVars.tree, _extends({}, settings, { variables: variableStore.job, onWarning: handleWarning })); var outCss = stringifyCss(node.__cssVars.tree); if (settings.updateDOM) { var nodeCSS = cssArray[i]; var hasCSSVarFunc = regex.cssVarFunc.test(nodeCSS); if (!node.getAttribute("data-cssvars")) { node.setAttribute("data-cssvars", "src"); } if (outCss.length && hasCSSVarFunc) { var dataGroup = node.getAttribute("data-cssvars-group") || ++counters.group; var outCssNoSpaces = outCss.replace(/\s/g, ""); var outNode = settings.rootElement.querySelector('[data-cssvars="out"][data-cssvars-group="'.concat(dataGroup, '"]')) || document.createElement("style"); hasKeyframesWithVars = hasKeyframesWithVars || regex.cssKeyframes.test(outCss); if (settings.preserveStatic) { node.sheet && (node.sheet.disabled = true); } if (!outNode.hasAttribute("data-cssvars")) { outNode.setAttribute("data-cssvars", "out"); } if (outCssNoSpaces === node.textContent.replace(/\s/g, "")) { isSkip = true; if (outNode && outNode.parentNode) { node.removeAttribute("data-cssvars-group"); outNode.parentNode.removeChild(outNode); } } else if (outCssNoSpaces !== outNode.textContent.replace(/\s/g, "")) { [ node, outNode ].forEach((function(n) { n.setAttribute("data-cssvars-job", counters.job); n.setAttribute("data-cssvars-group", dataGroup); })); outNode.textContent = outCss; outCssArray.push(outCss); outNodeArray.push(outNode); if (!outNode.parentNode) { node.parentNode.insertBefore(outNode, node.nextSibling); } } } } else { if (node.textContent.replace(/\s/g, "") !== outCss) { outCssArray.push(outCss); } } } catch (err) { handleError(err.message, node); } } if (isSkip) { node.setAttribute("data-cssvars", "skip"); } if (!node.hasAttribute("data-cssvars-job")) { node.setAttribute("data-cssvars-job", counters.job); } })); cssVarsSrcNodeCount = settings.rootElement.querySelectorAll('[data-cssvars]:not([data-cssvars="out"])').length; if (settings.shadowDOM) { var elms = [].concat(settings.rootElement).concat(Array.apply(null, settings.rootElement.querySelectorAll("*"))); for (var i = 0, elm; elm = elms[i]; ++i) { if (elm.shadowRoot && elm.shadowRoot.querySelector("style")) { var shadowSettings = _extends({}, settings, { rootElement: elm.shadowRoot }); cssVars(shadowSettings); } } } if (settings.updateDOM && hasKeyframesWithVars) { fixKeyframes(settings.rootElement); } cssVarsIsRunning = false; settings.onComplete(outCssArray.join(""), outNodeArray, JSON.parse(JSON.stringify(variableStore.job)), getTimeStamp() - settings.__benchmark); handleFinally(outNodeArray.length); } } }); } } else { document.addEventListener("DOMContentLoaded", (function init(evt) { cssVars(options); document.removeEventListener("DOMContentLoaded", init); })); } } cssVars.reset = function() { counters.job = 0; counters.group = 0; cssVarsIsRunning = false; if (cssVarsObserver) { cssVarsObserver.disconnect(); cssVarsObserver = null; } cssVarsSrcNodeCount = 0; debounceTimer = null; isShadowDOMReady = false; for (var prop in variableStore) { variableStore[prop] = {}; } }; function addMutationObserver(settings) { function isDisabled(node) { var isDisabledAttr = isLink(node) && node.hasAttribute("disabled"); var isDisabledSheet = (node.sheet || {}).disabled; return isDisabledAttr || isDisabledSheet; } function isLink(node) { var isStylesheet = node.nodeName.toLowerCase() === "link" && (node.getAttribute("rel") || "").indexOf("stylesheet") !== -1; return isStylesheet; } function isStyle(node) { return node.nodeName.toLowerCase() === "style"; } function isValidAttributeMutation(mutation) { var isValid = false; if (mutation.type === "attributes" && isLink(mutation.target) && !isDisabled(mutation.target)) { var isEnabledMutation = mutation.attributeName === "disabled"; var isHrefMutation = mutation.attributeName === "href"; var isSkipNode = mutation.target.getAttribute("data-cssvars") === "skip"; var isSrcNode = mutation.target.getAttribute("data-cssvars") === "src"; if (isEnabledMutation) { isValid = !isSkipNode && !isSrcNode; } else if (isHrefMutation) { if (isSkipNode) { mutation.target.setAttribute("data-cssvars", ""); } else if (isSrcNode) { resetCssNodes(settings.rootElement, true); } isValid = true; } } return isValid; } function isValidStyleTextMutation(mutation) { var isValid = false; if (mutation.type === "childList") { var isStyleElm = isStyle(mutation.target); var isOutNode = mutation.target.getAttribute("data-cssvars") === "out"; isValid = isStyleElm && !isOutNode; } return isValid; } function isValidAddMutation(mutation) { var isValid = false; if (mutation.type === "childList") { isValid = Array.apply(null, mutation.addedNodes).some((function(node) { var isElm = node.nodeType === 1; var hasAttr = isElm && node.hasAttribute("data-cssvars"); var isStyleWithVars = isStyle(node) && regex.cssVars.test(node.textContent); var isValid = !hasAttr && (isLink(node) || isStyleWithVars); return isValid && !isDisabled(node); })); } return isValid; } function isValidRemoveMutation(mutation) { var isValid = false; if (mutation.type === "childList") { isValid = Array.apply(null, mutation.removedNodes).some((function(node) { var isElm = node.nodeType === 1; var isOutNode = isElm && node.getAttribute("data-cssvars") === "out"; var isSrcNode = isElm && node.getAttribute("data-cssvars") === "src"; var isValid = isSrcNode; if (isSrcNode || isOutNode) { var dataGroup = node.getAttribute("data-cssvars-group"); var orphanNode = settings.rootElement.querySelector('[data-cssvars-group="'.concat(dataGroup, '"]')); if (isSrcNode) { resetCssNodes(settings.rootElement, true); } if (orphanNode) { orphanNode.parentNode.removeChild(orphanNode); } } return isValid; })); } return isValid; } if (!window.MutationObserver) { return; } if (cssVarsObserver) { cssVarsObserver.disconnect(); cssVarsObserver = null; } cssVarsObserver = new MutationObserver((function(mutations) { var hasValidMutation = mutations.some((function(mutation) { return isValidAttributeMutation(mutation) || isValidStyleTextMutation(mutation) || isValidAddMutation(mutation) || isValidRemoveMutation(mutation); })); if (hasValidMutation) { cssVars(settings); } })); cssVarsObserver.observe(document.documentElement, { attributes: true, attributeFilter: [ "disabled", "href" ], childList: true, subtree: true }); } function cssVarsDebounced(settings) { var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100; clearTimeout(debounceTimer); debounceTimer = setTimeout((function() { settings.__benchmark = null; cssVars(settings); }), delay); } function fixKeyframes(rootElement) { var animationNameProp = [ "animation-name", "-moz-animation-name", "-webkit-animation-name" ].filter((function(prop) { return getComputedStyle(document.body)[prop]; }))[0]; if (animationNameProp) { var allNodes = rootElement.getElementsByTagName("*"); var keyframeNodes = []; var nameMarker = "__CSSVARSPONYFILL-KEYFRAMES__"; for (var i = 0, len = allNodes.length; i < len; i++) { var node = allNodes[i]; var animationName = getComputedStyle(node)[animationNameProp]; if (animationName !== "none") { node.style[animationNameProp] += nameMarker; keyframeNodes.push(node); } } void document.body.offsetHeight; for (var _i = 0, _len = keyframeNodes.length; _i < _len; _i++) { var nodeStyle = keyframeNodes[_i].style; nodeStyle[animationNameProp] = nodeStyle[animationNameProp].replace(nameMarker, ""); } } } function fixRelativeCssUrls(cssText, baseUrl) { var cssUrls = cssText.replace(regex.cssComments, "").match(regex.cssUrls) || []; cssUrls.forEach((function(cssUrl) { var oldUrl = cssUrl.replace(regex.cssUrls, "$1"); var newUrl = getFullUrl$1(oldUrl, baseUrl); cssText = cssText.replace(cssUrl, cssUrl.replace(oldUrl, newUrl)); })); return cssText; } function fixVarNames() { var varObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var reLeadingHyphens = /^-{2}/; return Object.keys(varObj).reduce((function(obj, value) { var key = reLeadingHyphens.test(value) ? value : "--".concat(value.replace(/^-+/, "")); obj[key] = varObj[value]; return obj; }), {}); } function getFullUrl$1(url) { var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : location.href; var d = document.implementation.createHTMLDocument(""); var b = d.createElement("base"); var a = d.createElement("a"); d.head.appendChild(b); d.body.appendChild(a); b.href = base; a.href = url; return a.href; } function getTimeStamp() { return isBrowser && (window.performance || {}).now ? window.performance.now() : (new Date).getTime(); } function resetCssNodes(rootElement) { var resetDOMVariableStore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var resetNodes = Array.apply(null, rootElement.querySelectorAll('[data-cssvars="skip"],[data-cssvars="src"]')); resetNodes.forEach((function(node) { return node.setAttribute("data-cssvars", ""); })); if (resetDOMVariableStore) { variableStore.dom = {}; } } export default cssVars; //# sourceMappingURL=css-vars-ponyfill.esm.js.map
import React from 'react'; import { Link } from 'mirrorx'; import { List, DataTable, TextField, EditButton, ShowButton, RemoveButton } from '../../../../src'; import Filters from './Filters'; export default (props) => ( <List model="users" filters={<Filters />} {...props}> <DataTable> <TextField source="id" /> <TextField source="name" format={(value, record) => <Link to={`/users/${record.id}/show`}>{value}</Link>} sorter={true} /> <TextField source="username"/> <TextField source="email"/> <TextField source="phone"/> <TextField source="website"/> <ShowButton simple /> <EditButton simple /> <RemoveButton simple/> </DataTable> </List> )
// // _ _ _ // (_) | | | | // _ __ ___ _ _ __ ___| |_ _ __ ___| | // | '_ ` _ \| | '_ \/ __| __| '__/ _ \ | // | | | | | | | | | \__ \ |_| | | __/ | // |_| |_| |_|_|_| |_|___/\__|_| \___|_| // // Author: Alberto Pettarin (www.albertopettarin.it) // Copyright: Copyright 2013-2015, ReadBeyond Srl (www.readbeyond.it) // License: MIT // Email: minstrel@readbeyond.it // Web: http://www.readbeyond.it/minstrel/ // Status: Production // // be strict, be safe 'use strict'; /** @namespace RB */ var RB = RB || {}; /** @namespace RB.Settings */ RB.Settings = RB.Settings || {}; /* constants */ // UI RB.Settings.UI = {}; RB.Settings.UI.lstFormats = 'lstFormats'; RB.Settings.UI.divSettingsChangeStorageDirectory = 'divSettingsChangeStorageDirectory'; RB.Settings.UI.divSettingsChangeMediaPlayerMode = 'divSettingsChangeMediaPlayerMode'; RB.Settings.UI.divSettingsChangeUIBrightness = 'divSettingsChangeUIBrightness'; RB.Settings.UI.colSettingsScreen = 'colSettingsScreen'; RB.Settings.UI.colSettingsLibrary = 'colSettingsLibrary'; RB.Settings.UI.colSettingsAudio = 'colSettingsAudio'; RB.Settings.UI.colSettingsAdvanced = 'colSettingsAdvanced'; /* variables */ RB.Settings.pluginsLoadedWhenOpen = null; RB.Settings.createdManagers = false; RB.Settings.drs = null; /* functions */ // initialize UI // this method is called BEFORE the page is shown // do NOT call plugins here RB.Settings.initializeUI = function() { // load localization RB.UI.loadLocalization(); // hide if not Android var isAndroid = RB.App.isAndroid(); RB.UI.showHide(RB.Settings.UI.divSettingsChangeStorageDirectory, isAndroid); RB.UI.showHide(RB.Settings.UI.divSettingsChangeMediaPlayerMode, isAndroid); // hide brightness if not enabled RB.UI.showHide(RB.Settings.UI.divSettingsChangeUIBrightness, RB.Storage.isAppParameterTrue(RB.Storage.Keys.UI_ENABLE_BRIGHTNESS)); // populate format list // NOTE: PLUGINS_LOADED is actually a dictionary, but here we get it as a string for comparing on exit RB.Settings.pluginsLoadedWhenOpen = RB.Storage.get(RB.Storage.Keys.PLUGINS_LOADED); RB.Settings.populateFormatList(); // create manager objects RB.Settings.createManagers(); RB.Settings.drs.update(); }; // initialize page RB.Settings.initializePage = function() { // bind events RB.Settings.bindEvents(); // dim system bar RB.UI.dimSystemBar(); }; // bind events RB.Settings.bindEvents = function() { // scroll when collapsible is expanded RB.UI.bindScrollOnCollapsibleExpanded(RB.Settings.UI); }; // handle back button RB.Settings.onBackButton = function() { // if the list of plugins loaded is if (RB.Storage.get(RB.Storage.Keys.PLUGINS_LOADED) !== RB.Settings.pluginsLoadedWhenOpen) { RB.Storage.set(RB.Storage.Keys.PLUGINS_LOADED_CHANGED, true); } // go back RB.UI.onBackButton(); }; // populate format list RB.Settings.populateFormatList = function() { var lv_id = RB.Settings.UI.lstFormats; RB.UI.empty(lv_id); // DEBUG //RB.Storage.setArray(RB.Storage.Keys.PLUGINS_LOADED, []); //RB.Storage.setDictionary(RB.Storage.Keys.PLUGINS_LOADED, {'epub': true}); //RB.Storage.setArray(RB.Storage.Keys.PLUGINS_LOADED, ['abz', 'epub']); var available_formats = RB.Plugins.Format.availablePlugins; var loaded_formats = RB.Storage.getDictionary(RB.Storage.Keys.PLUGINS_LOADED); if (available_formats.length > 0) { for (var i = 0; i < available_formats.length; i++) { var f = available_formats[i]; var icon = 'check-empty'; if (f in loaded_formats) { icon = 'check'; } var listItem = '<li id="format-' + f + '">'; listItem += '<a onclick="RB.Settings.openFormatSettings(\'' + f + '\');">'; listItem += '<img src="' + RB.Plugins[f].settingsIcon + '" class="smaller-icon"/>'; listItem += '<h4><strong>' + RB.UI.i18n('txtSettingsFormatSettingsLabel') + ' ' + RB.Plugins[f].settingsLabel + '</strong></h4>'; listItem += '<p>(' + RB.Utilities.joinStrings(RB.Plugins[f].settingsFileExtensions, ', ', '') + ')</p>'; listItem += '</a>'; listItem += '<a data-icon="' + icon + '" onclick="RB.Settings.toggleFormat(\'' + f + '\');"></a>'; listItem += '</li>'; RB.UI.append(lv_id, listItem); } RB.UI.refreshListview(lv_id); } }; RB.Settings.openFormatSettings = function(format) { var page = RB.Plugins[format].settingsFilePath; if (page) { RB.App.openPage(page); } }; RB.Settings.toggleFormat = function(format) { var loaded_formats = RB.Storage.getDictionary(RB.Storage.Keys.PLUGINS_LOADED); if (format in loaded_formats) { delete loaded_formats[format] } else { loaded_formats[format] = true; } RB.Storage.setDictionary(RB.Storage.Keys.PLUGINS_LOADED, loaded_formats); RB.Settings.populateFormatList(); }; // create manager objects RB.Settings.createManagers = function() { // if already created, abort if (RB.Settings.createdManagers) { return; } // preference manager object RB.Settings.drs = new RB.App.drsManager(null, null, true); var booleans = [ ['LIBRARY_SHOW_HIDDEN_BOOKS', 'chkToggleShowHiddenBooks', null], ['LIBRARY_HIDE_BOOKS_ON_SORT', 'chkToggleHideBooksOnSort', null], ['LIBRARY_OPEN_NEW_BOOK', 'chkToggleOpenNewBook', null], ['LIBRARY_CACHE_METADATA', 'chkToggleCacheMetadata', null], ['MEDIAPLAYER_ENABLE_PLAYBACK_SPEED', 'chkToggleEnablePlaybackSpeed', null], ['UI_NIGHT_MODE', 'btnToggleUINightMode', RB.UI.applyNightMode], ['UI_ENABLE_BRIGHTNESS', 'btnSettingsChangeEnableBrightness', RB.Settings.applyBrightness], ['UI_ANIMATED_MENU', 'btnToggleUIAnimatedMenu', null], ['OPEN_URLS_IN_SYSTEM_BROWSER', 'btnSettingsChangeOpenURLsInSystemBrowser', null] ]; for (var i = 0; i < booleans.length; i++) { RB.Settings.drs.registerSetting(booleans[i][0], 'boolean', null, [ { 'id': booleans[i][1], 'callback': booleans[i][2] } ]); } var cycles = [ ['UI_LANGUAGE', RB.Config.UI.availableLanguages, 'btnSettingsChangeLanguage', false, RB.Settings.applyLanguage], ['UI_FONT', RB.Config.UI.availableFonts, 'btnSettingsChangeUIFont', true, RB.UI.applyUIFont], ['UI_BRIGHTNESS', RB.Config.UI.availableBrightnessValues, 'btnSettingsChangeUIBrightness', true, RB.Settings.applyBrightness], ['UI_ORIENTATION', RB.Config.UI.availableOrientations, 'btnSettingsChangeOrientation', true, RB.UI.applyOrientation], ['MEDIAPLAYER_MODE', RB.Config.availableMediaPlayerModes, 'btnSettingsChangeMediaPlayerMode', true, null], ]; for (var i = 0; i < cycles.length; i++) { RB.Settings.drs.registerSetting(cycles[i][0], 'cycle', cycles[i][1], [ { 'id': cycles[i][2], 'notification': false, 'circular': true, 'increase': true, 'compact': cycles[i][3], 'callback': cycles[i][4] } ]); } // register simple buttons RB.UI.bindSimpleButtonEvents('btnDeleteRecentInfos', { 'click': RB.Settings.deleteRecentInfos }, false); RB.UI.bindSimpleButtonEvents('btnDeleteReadingPositions', { 'click': RB.Settings.deleteReadingPositions }, false); RB.UI.bindSimpleButtonEvents('btnDeleteLibraryItems', { 'click': RB.Settings.deleteLibraryItems }, false); RB.UI.bindSimpleButtonEvents('btnReinitialize', { 'click': RB.Settings.reinitializeSettings }, false); RB.UI.bindSimpleButtonEvents('btnSettingsChangeStorageDirectory', { 'click': RB.Settings.changeStorageDirectory }, false); // reset flag RB.Settings.createdManagers = true; }; // apply language and reload UI RB.Settings.applyLanguage = function() { RB.UI.language = RB.Storage.get(RB.Storage.Keys.UI_LANGUAGE); RB.Settings.initializeUI(); }; // apply brightness RB.Settings.applyBrightness = function() { if (RB.Storage.isAppParameterTrue(RB.Storage.Keys.UI_ENABLE_BRIGHTNESS)) { RB.UI.show(RB.Settings.UI.divSettingsChangeUIBrightness); var value = RB.Storage.get(RB.Storage.Keys.UI_BRIGHTNESS); RB.UI.setBrightness(value); } else { RB.UI.hide(RB.Settings.UI.divSettingsChangeUIBrightness); RB.UI.setBrightness(-1.0); } }; // change storage directory RB.Settings.changeStorageDirectory = function() { RB.App.openPage(RB.App.PagesEnum.FILECHOOSER); }; // delete recent info for all items RB.Settings.deleteRecentInfos = function() { RB.UI.showNotification(RB.UI.i18n('txtDeleteRecentInfosDone')); RB.Settings.resetItemsData('resetRecentInfo'); RB.UI.collapse(RB.Settings.UI.colSettingsAdvanced); }; // delete reading position for all items RB.Settings.deleteReadingPositions = function() { RB.UI.showNotification(RB.UI.i18n('txtDeleteReadingPositionsDone')); RB.Settings.resetItemsData('resetReadingPosition'); RB.UI.collapse(RB.Settings.UI.colSettingsAdvanced); }; // delete library items RB.Settings.deleteLibraryItems = function() { RB.UI.showNotification(RB.UI.i18n('txtDeleteLibraryItemsDone')); var items = RB.Storage.getDictionary(RB.Storage.Keys.LIBRARY_BOOKS); var ids = Object.keys(items); for (var i = 0; i < ids.length; i++) { RB.App.deleteItemData(ids[i]); } RB.Storage.setDictionary(RB.Storage.Keys.LIBRARY_BOOKS, {}); RB.UI.collapse(RB.Settings.UI.colSettingsAdvanced); }; // reinitialize all settings RB.Settings.reinitializeSettings = function() { RB.UI.showNotification(RB.UI.i18n('txtReinitializeDone')); RB.App.resetAppSettings(); RB.App.openPage(RB.App.PagesEnum.SETTINGS); RB.UI.collapse(RB.Settings.UI.colSettingsAdvanced); }; // delete from extra RB.Settings.resetItemsData = function(mode) { // delete from item data var books = RB.Storage.getDictionary(RB.Storage.Keys.LIBRARY_BOOKS); var arr = Object.keys(books); for (var j = 0; j < arr.length; ++j) { var itemID = arr[j]; if (mode === 'resetRecentInfo') { RB.App.saveItemData(itemID, ['library', 'lastTimeOpened'], null); } if (mode === 'resetReadingPosition') { RB.App.saveItemData(itemID, ['library', 'isNew'], true); RB.App.deleteItemData(itemID, ['position']); } if (mode === 'resetMetadata') { RB.App.deleteItemData(itemID, ['metadata']); RB.App.deleteItemData(itemID, ['structure']); } } };
/** * @license Highmaps JS v8.2.0 (2020-08-20) * @module highcharts/highmaps * * (c) 2011-2018 Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import Highcharts from './highcharts.src.js'; import './modules/map.src.js'; Highcharts.product = 'Highmaps'; export default Highcharts;
// // index GET tournaments // // create POST tournaments // // show GET tournaments/:tournament // // update PUT tournaments/:tournament // // destroy DELETE tournaments/:tournament // // start POST tournaments/:tournament/start // // finalize POST tournaments/:tournament/finalize // // reset POST tournaments/:tournament/reset var util = require('util'); var Client = require('./client').Client; var Tournaments = exports.Tournaments = function(options) { Client.call(this, options); // call parent constructor this.getRawSubdomain = function() { return this.options.get('subdomain').replace('-',''); }; }; // Inherit from Client base object util.inherits(Tournaments, Client); Tournaments.prototype.index = function(obj) { obj.method = 'GET'; // generate the subdomain property from the subdomain // url we generate in the client constructor if (this.getRawSubdomain()) { obj.subdomain = this.getRawSubdomain(); } this.makeRequest(obj); }; Tournaments.prototype.create = function(obj) { // generate the subdomain property from the subdomain // url we generate in the client constructor if (this.getRawSubdomain()) { obj.tournament.subdomain = this.getRawSubdomain(); } obj.method = 'POST'; this.makeRequest(obj); }; Tournaments.prototype.show = function(obj) { obj.path = '/' + this.options.get('subdomain') + obj.id; delete obj.id; obj.method = 'GET'; this.makeRequest(obj); }; Tournaments.prototype.update = function(obj) { obj.path = '/' + this.options.get('subdomain') + obj.id; delete obj.id; obj.method = 'PUT'; this.makeRequest(obj); }; Tournaments.prototype.destroy = function(obj) { obj.path = '/' + this.options.get('subdomain') + obj.id; delete obj.id; obj.method = 'DELETE'; this.makeRequest(obj); }; Tournaments.prototype.start = function(obj) { obj.path = '/' + this.options.get('subdomain') + obj.id + '/start'; delete obj.id; obj.method = 'POST'; this.makeRequest(obj); }; Tournaments.prototype.finalize = function(obj) { obj.path = '/' + this.options.get('subdomain') + obj.id + '/finalize'; delete obj.id; obj.method = 'POST'; this.makeRequest(obj); }; Tournaments.prototype.reset = function(obj) { obj.path = '/' + this.options.get('subdomain') + obj.id + '/reset'; delete obj.id; obj.method = 'POST'; this.makeRequest(obj); };
/** * @ngdoc object * @name ui.router.util.type:UrlMatcher * * @description * Matches URLs against patterns and extracts named parameters from the path or the search * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list * of search parameters. Multiple search parameter names are separated by '&'. Search parameters * do not influence whether or not a URL is matched, but their values are passed through into * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}. * * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace * syntax, which optionally allows a regular expression for the parameter to be specified: * * * `':'` name - colon placeholder * * `'*'` name - catch-all placeholder * * `'{' name '}'` - curly placeholder * * `'{' name ':' regexp '}'` - curly placeholder with regexp. Should the regexp itself contain * curly braces, they must be in matched pairs or escaped with a backslash. * * Parameter names may contain only word characters (latin letters, digits, and underscore) and * must be unique within the pattern (across both path and search parameters). For colon * placeholders or curly placeholders without an explicit regexp, a path parameter matches any * number of characters other than '/'. For catch-all placeholders the path parameter matches * any number of characters. * * Examples: * * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for * trailing slashes, and patterns have to match the entire path, not just a prefix. * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. * * `'/user/{id:[^/]*}'` - Same as the previous example. * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id * parameter consists of 1 to 8 hex digits. * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the * path into the parameter 'path'. * * `'/files/*path'` - ditto. * * @param {string} pattern the pattern to compile into a matcher. * * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns * non-null) will start with this prefix. * * @property {string} source The pattern that was passed into the contructor * * @property {string} sourcePath The path portion of the source property * * @property {string} sourceSearch The search portion of the source property * * @property {string} regex The constructed regex that will be used to match against the url when * it is time to determine which url will match. * * @returns {Object} New UrlMatcher object */ function UrlMatcher(pattern) { // Find all placeholders and create a compiled pattern, using either classic or curly syntax: // '*' name // ':' name // '{' name '}' // '{' name ':' regexp '}' // The regular expression is somewhat complicated due to the need to allow curly braces // inside the regular expression. The placeholder regexp breaks down as follows: // ([:*])(\w+) classic placeholder ($1 / $2) // \{(\w+)(?:\:( ... ))?\} curly brace placeholder ($3) with optional regexp ... ($4) // (?: ... | ... | ... )+ the regexp consists of any number of atoms, an atom being either // [^{}\\]+ - anything other than curly braces or backslash // \\. - a backslash escape // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms var placeholder = /([:*])(\w+)|\{(\w+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, names = {}, compiled = '^', last = 0, m, segments = this.segments = [], params = this.params = []; function addParameter(id) { if (!/^\w+(-+\w+)*$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'"); if (names[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'"); names[id] = true; params.push(id); } function quoteRegExp(string) { return string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&"); } this.source = pattern; // Split into static segments separated by path parameter placeholders. // The number of segments is always 1 more than the number of parameters. var id, regexp, segment; while ((m = placeholder.exec(pattern))) { id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null regexp = m[4] || (m[1] == '*' ? '.*' : '[^/]*'); segment = pattern.substring(last, m.index); if (segment.indexOf('?') >= 0) break; // we're into the search part compiled += quoteRegExp(segment) + '(' + regexp + ')'; addParameter(id); segments.push(segment); last = placeholder.lastIndex; } segment = pattern.substring(last); // Find any search parameter names and remove them from the last segment var i = segment.indexOf('?'); if (i >= 0) { var search = this.sourceSearch = segment.substring(i); segment = segment.substring(0, i); this.sourcePath = pattern.substring(0, last+i); // Allow parameters to be separated by '?' as well as '&' to make concat() easier forEach(search.substring(1).split(/[&?]/), addParameter); } else { this.sourcePath = pattern; this.sourceSearch = ''; } compiled += quoteRegExp(segment) + '$'; segments.push(segment); this.regexp = new RegExp(compiled); this.prefix = segments[0]; } /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#concat * @methodOf ui.router.util.type:UrlMatcher * * @description * Returns a new matcher for a pattern constructed by appending the path part and adding the * search parameters of the specified pattern to this pattern. The current pattern is not * modified. This can be understood as creating a pattern for URLs that are relative to (or * suffixes of) the current pattern. * * @example * The following two matchers are equivalent: * ``` * new UrlMatcher('/user/{id}?q').concat('/details?date'); * new UrlMatcher('/user/{id}/details?q&date'); * ``` * * @param {string} pattern The pattern to append. * @returns {ui.router.util.type:UrlMatcher} A matcher for the concatenated pattern. */ UrlMatcher.prototype.concat = function (pattern) { // Because order of search parameters is irrelevant, we can add our own search // parameters to the end of the new pattern. Parse the new pattern by itself // and then join the bits together, but it's much easier to do this on a string level. return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch); }; UrlMatcher.prototype.toString = function () { return this.source; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#exec * @methodOf ui.router.util.type:UrlMatcher * * @description * Tests the specified path against this matcher, and returns an object containing the captured * parameter values, or null if the path does not match. The returned object contains the values * of any search parameters that are mentioned in the pattern, but their value may be null if * they are not present in `searchParams`. This means that search parameters are always treated * as optional. * * @example * ``` * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', { x:'1', q:'hello' }); * // returns { id:'bob', q:'hello', r:null } * ``` * * @param {string} path The URL path to match, e.g. `$location.path()`. * @param {Object} searchParams URL search parameters, e.g. `$location.search()`. * @returns {Object} The captured parameter values. */ UrlMatcher.prototype.exec = function (path, searchParams) { var m = this.regexp.exec(path); if (!m) return null; var params = this.params, nTotal = params.length, nPath = this.segments.length-1, values = {}, i; if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'"); for (i=0; i<nPath; i++) values[params[i]] = m[i+1]; for (/**/; i<nTotal; i++) values[params[i]] = searchParams[params[i]]; return values; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#parameters * @methodOf ui.router.util.type:UrlMatcher * * @description * Returns the names of all path and search parameters of this pattern in an unspecified order. * * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the * pattern has no parameters, an empty array is returned. */ UrlMatcher.prototype.parameters = function () { return this.params; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#format * @methodOf ui.router.util.type:UrlMatcher * * @description * Creates a URL that matches this pattern by substituting the specified values * for the path and search parameters. Null values for path parameters are * treated as empty strings. * * @example * ``` * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' }); * // returns '/user/bob?q=yes' * ``` * * @param {Object} values the values to substitute for the parameters in this pattern. * @returns {string} the formatted URL (path and optionally search part). */ UrlMatcher.prototype.format = function (values) { var segments = this.segments, params = this.params; if (!values) return segments.join(''); var nPath = segments.length-1, nTotal = params.length, result = segments[0], i, search, value; for (i=0; i<nPath; i++) { value = values[params[i]]; // TODO: Maybe we should throw on null here? It's not really good style to use '' and null interchangeabley if (value != null) result += encodeURIComponent(value); result += segments[i+1]; } for (/**/; i<nTotal; i++) { value = values[params[i]]; if (value != null) { result += (search ? '&' : '?') + params[i] + '=' + encodeURIComponent(value); search = true; } } return result; }; /** * @ngdoc object * @name ui.router.util.$urlMatcherFactory * * @description * Factory for {@link ui.router.util.type:UrlMatcher} instances. The factory is also available to providers * under the name `$urlMatcherFactoryProvider`. */ function $UrlMatcherFactory() { /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#compile * @methodOf ui.router.util.$urlMatcherFactory * * @description * Creates a {@link ui.router.util.type:UrlMatcher} for the specified pattern. * * @param {string} pattern The URL pattern. * @returns {ui.router.util.type:UrlMatcher} The UrlMatcher. */ this.compile = function (pattern) { return new UrlMatcher(pattern); }; /** * @ngdoc function * @name ui.router.util.$urlMatcherFactory#isMatcher * @methodOf ui.router.util.$urlMatcherFactory * * @description * Returns true if the specified object is a UrlMatcher, or false otherwise. * * @param {Object} object The object to perform the type check against. * @returns {Boolean} Returns `true` if the object has the following functions: `exec`, `format`, and `concat`. */ this.isMatcher = function (o) { return isObject(o) && isFunction(o.exec) && isFunction(o.format) && isFunction(o.concat); }; /* No need to document $get, since it returns this */ this.$get = function () { return this; }; } // Register as a provider so it's available to other providers angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /** * Base class for ccs.ComRender * @class * @extends ccs.Component */ ccs.ComRender = ccs.Component.extend(/** @lends ccs.ComRender# */{ _render: null, ctor: function (node, comName) { cc.Component.prototype.ctor.call(this); this._render = node; this._name = comName; }, onEnter: function () { if (this._owner != null) { this._owner.addChild(this._render); } }, onExit: function () { this._render = null; }, /** * Node getter * @returns {cc.Node} */ getNode: function () { return this._render; }, /** * Node setter * @param {cc.Node} node */ setNode: function (node) { this._render = node; } }); /** * allocates and initializes a ComRender. * @constructs * @return {ccs.ComRender} * @example * // example * var com = ccs.ComRender.create(); */ ccs.ComRender.create = function (node, comName) { var com = new ccs.ComRender(node, comName); if (com && com.init()) { return com; } return null; };
module.exports = { execQuery: function () { var query, cb; if (arguments.length == 2) { query = arguments[0]; cb = arguments[1]; } else if (arguments.length == 3) { query = this.query.escape(arguments[0], arguments[1]); cb = arguments[2]; } return this.execSimpleQuery(query, cb); }, eagerQuery: function (association, opts, keys, cb) { var desiredKey = Object.keys(association.field); var assocKey = Object.keys(association.mergeAssocId); var where = {}; where[desiredKey] = keys; var query = this.query.select() .from(association.model.table) .select(opts.only) .from(association.mergeTable, assocKey, opts.keys) .select(desiredKey).as("$p") .where(association.mergeTable, where) .build(); this.execSimpleQuery(query, cb); } };
'use strict'; var path = require('path'); var util = require('util'); var yeoman = require('yeoman-generator'); var Generator = module.exports = function Generator() { yeoman.generators.Base.apply(this, arguments); }; util.inherits(Generator, yeoman.generators.Base); Generator.prototype.setupEnv = function setupEnv() { var join = path.join; this.sourceRoot(join(__dirname, '../templates/common/root')); this.copy('.editorconfig'); this.copy('.gitattributes'); this.copy('.jshintrc'); this.copy('.yo-rc.json'); this.copy('gitignore', '.gitignore'); this.directory('test'); this.sourceRoot(join(__dirname, '../templates/common')); var appPath = this.options.appPath; var copy = function (dest) { this.copy(join('app', dest), join(appPath, dest)); }.bind(this); copy('.buildignore'); copy('.htaccess'); copy('404.html'); copy('favicon.ico'); copy('robots.txt'); copy('views/main.html'); this.directory(join('app', 'images'), join(appPath, 'images')); };
"use strict"; exports.__esModule = true; exports.default = function (Ctor, val) { return val != null && val.constructor === Ctor || val instanceof Ctor; };
(function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === "object" && typeof module === "object") module.exports = factory(); else if (typeof define === "function" && define.amd) define([], factory); else { var a = factory(); for (var i in a) (typeof exports === "object" ? exports : root)[i] = a[i]; } })(window, (function() { return function() { "use strict"; var __webpack_require__ = {}; !function() { __webpack_require__.d = function(exports, definition) { for (var key in definition) { if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); } } }; }(); !function() { __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }; }(); !function() { __webpack_require__.r = function(exports) { if (typeof Symbol !== "undefined" && Symbol.toStringTag) { Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); } Object.defineProperty(exports, "__esModule", { value: true }); }; }(); var __webpack_exports__ = {}; __webpack_require__.r(__webpack_exports__); __webpack_require__.d(__webpack_exports__, { loadSizeUpdater: function() { return loadSizeUpdater; } }); class Circle_Circle extends(null && Range){ constructor(x, y, radius) { super(x, y); this.radius = radius; } contains(point) { return getDistance(point, this.position) <= this.radius; } intersects(range) { const rect = range; const circle = range; const pos1 = this.position; const pos2 = range.position; const xDist = Math.abs(pos2.x - pos1.x); const yDist = Math.abs(pos2.y - pos1.y); const r = this.radius; if (circle.radius !== undefined) { const rSum = r + circle.radius; const dist = Math.sqrt(xDist * xDist + yDist + yDist); return rSum > dist; } else if (rect.size !== undefined) { const w = rect.size.width; const h = rect.size.height; const edges = Math.pow(xDist - w, 2) + Math.pow(yDist - h, 2); if (xDist > r + w || yDist > r + h) { return false; } if (xDist <= w || yDist <= h) { return true; } return edges <= r * r; } return false; } } class CircleWarp_CircleWarp extends(null && Circle){ constructor(x, y, radius, canvasSize) { super(x, y, radius); this.canvasSize = canvasSize; this.canvasSize = { height: canvasSize.height, width: canvasSize.width }; } contains(point) { if (super.contains(point)) { return true; } const posNE = { x: point.x - this.canvasSize.width, y: point.y }; if (super.contains(posNE)) { return true; } const posSE = { x: point.x - this.canvasSize.width, y: point.y - this.canvasSize.height }; if (super.contains(posSE)) { return true; } const posSW = { x: point.x, y: point.y - this.canvasSize.height }; return super.contains(posSW); } intersects(range) { if (super.intersects(range)) { return true; } const rect = range; const circle = range; const newPos = { x: range.position.x - this.canvasSize.width, y: range.position.y - this.canvasSize.height }; if (circle.radius !== undefined) { const biggerCircle = new Circle(newPos.x, newPos.y, circle.radius * 2); return super.intersects(biggerCircle); } else if (rect.size !== undefined) { const rectSW = new Rectangle(newPos.x, newPos.y, rect.size.width * 2, rect.size.height * 2); return super.intersects(rectSW); } return false; } } class Constants_Constants {} Constants_Constants.generatedAttribute = "generated"; Constants_Constants.randomColorValue = "random"; Constants_Constants.midColorValue = "mid"; Constants_Constants.touchEndEvent = "touchend"; Constants_Constants.mouseDownEvent = "mousedown"; Constants_Constants.mouseUpEvent = "mouseup"; Constants_Constants.mouseMoveEvent = "mousemove"; Constants_Constants.touchStartEvent = "touchstart"; Constants_Constants.touchMoveEvent = "touchmove"; Constants_Constants.mouseLeaveEvent = "mouseleave"; Constants_Constants.mouseOutEvent = "mouseout"; Constants_Constants.touchCancelEvent = "touchcancel"; Constants_Constants.resizeEvent = "resize"; Constants_Constants.visibilityChangeEvent = "visibilitychange"; Constants_Constants.noPolygonDataLoaded = "No polygon data loaded."; Constants_Constants.noPolygonFound = "No polygon found, you need to specify SVG url in config."; function manageListener(element, event, handler, add, options) { if (add) { let addOptions = { passive: true }; if (typeof options === "boolean") { addOptions.capture = options; } else if (options !== undefined) { addOptions = options; } element.addEventListener(event, handler, addOptions); } else { const removeOptions = options; element.removeEventListener(event, handler, removeOptions); } } class EventListeners_EventListeners { constructor(container) { this.container = container; this.canPush = true; this.mouseMoveHandler = e => this.mouseTouchMove(e); this.touchStartHandler = e => this.mouseTouchMove(e); this.touchMoveHandler = e => this.mouseTouchMove(e); this.touchEndHandler = () => this.mouseTouchFinish(); this.mouseLeaveHandler = () => this.mouseTouchFinish(); this.touchCancelHandler = () => this.mouseTouchFinish(); this.touchEndClickHandler = e => this.mouseTouchClick(e); this.mouseUpHandler = e => this.mouseTouchClick(e); this.mouseDownHandler = () => this.mouseDown(); this.visibilityChangeHandler = () => this.handleVisibilityChange(); this.themeChangeHandler = e => this.handleThemeChange(e); this.oldThemeChangeHandler = e => this.handleThemeChange(e); this.resizeHandler = () => this.handleWindowResize(); } addListeners() { this.manageListeners(true); } removeListeners() { this.manageListeners(false); } manageListeners(add) { var _a; const container = this.container; const options = container.actualOptions; const detectType = options.interactivity.detectsOn; let mouseLeaveEvent = Constants.mouseLeaveEvent; if (detectType === "window") { container.interactivity.element = window; mouseLeaveEvent = Constants.mouseOutEvent; } else if (detectType === "parent" && container.canvas.element) { const canvasEl = container.canvas.element; container.interactivity.element = (_a = canvasEl.parentElement) !== null && _a !== void 0 ? _a : canvasEl.parentNode; } else { container.interactivity.element = container.canvas.element; } const mediaMatch = !isSsr() && typeof matchMedia !== "undefined" && matchMedia("(prefers-color-scheme: dark)"); if (mediaMatch) { if (mediaMatch.addEventListener !== undefined) { manageListener(mediaMatch, "change", this.themeChangeHandler, add); } else if (mediaMatch.addListener !== undefined) { if (add) { mediaMatch.addListener(this.oldThemeChangeHandler); } else { mediaMatch.removeListener(this.oldThemeChangeHandler); } } } const interactivityEl = container.interactivity.element; if (!interactivityEl) { return; } const html = interactivityEl; if (options.interactivity.events.onHover.enable || options.interactivity.events.onClick.enable) { manageListener(interactivityEl, Constants.mouseMoveEvent, this.mouseMoveHandler, add); manageListener(interactivityEl, Constants.touchStartEvent, this.touchStartHandler, add); manageListener(interactivityEl, Constants.touchMoveEvent, this.touchMoveHandler, add); if (!options.interactivity.events.onClick.enable) { manageListener(interactivityEl, Constants.touchEndEvent, this.touchEndHandler, add); } else { manageListener(interactivityEl, Constants.touchEndEvent, this.touchEndClickHandler, add); manageListener(interactivityEl, Constants.mouseUpEvent, this.mouseUpHandler, add); manageListener(interactivityEl, Constants.mouseDownEvent, this.mouseDownHandler, add); } manageListener(interactivityEl, mouseLeaveEvent, this.mouseLeaveHandler, add); manageListener(interactivityEl, Constants.touchCancelEvent, this.touchCancelHandler, add); } if (container.canvas.element) { container.canvas.element.style.pointerEvents = html === container.canvas.element ? "initial" : "none"; } if (options.interactivity.events.resize) { if (typeof ResizeObserver !== "undefined") { if (this.resizeObserver && !add) { if (container.canvas.element) { this.resizeObserver.unobserve(container.canvas.element); } this.resizeObserver.disconnect(); delete this.resizeObserver; } else if (!this.resizeObserver && add && container.canvas.element) { this.resizeObserver = new ResizeObserver((entries => { const entry = entries.find((e => e.target === container.canvas.element)); if (!entry) { return; } this.handleWindowResize(); })); this.resizeObserver.observe(container.canvas.element); } } else { manageListener(window, Constants.resizeEvent, this.resizeHandler, add); } } if (document) { manageListener(document, Constants.visibilityChangeEvent, this.visibilityChangeHandler, add, false); } } handleWindowResize() { if (this.resizeTimeout) { clearTimeout(this.resizeTimeout); delete this.resizeTimeout; } this.resizeTimeout = setTimeout((async () => { var _a; return await ((_a = this.container.canvas) === null || _a === void 0 ? void 0 : _a.windowResize()); }), 500); } handleVisibilityChange() { const container = this.container; const options = container.actualOptions; this.mouseTouchFinish(); if (!options.pauseOnBlur) { return; } if (document === null || document === void 0 ? void 0 : document.hidden) { container.pageHidden = true; container.pause(); } else { container.pageHidden = false; if (container.getAnimationStatus()) { container.play(true); } else { container.draw(true); } } } mouseDown() { const interactivity = this.container.interactivity; if (interactivity) { const mouse = interactivity.mouse; mouse.clicking = true; mouse.downPosition = mouse.position; } } mouseTouchMove(e) { var _a, _b, _c, _d, _e, _f, _g; const container = this.container; const options = container.actualOptions; if (((_a = container.interactivity) === null || _a === void 0 ? void 0 : _a.element) === undefined) { return; } container.interactivity.mouse.inside = true; let pos; const canvas = container.canvas.element; if (e.type.startsWith("mouse")) { this.canPush = true; const mouseEvent = e; if (container.interactivity.element === window) { if (canvas) { const clientRect = canvas.getBoundingClientRect(); pos = { x: mouseEvent.clientX - clientRect.left, y: mouseEvent.clientY - clientRect.top }; } } else if (options.interactivity.detectsOn === "parent") { const source = mouseEvent.target; const target = mouseEvent.currentTarget; const canvasEl = container.canvas.element; if (source && target && canvasEl) { const sourceRect = source.getBoundingClientRect(); const targetRect = target.getBoundingClientRect(); const canvasRect = canvasEl.getBoundingClientRect(); pos = { x: mouseEvent.offsetX + 2 * sourceRect.left - (targetRect.left + canvasRect.left), y: mouseEvent.offsetY + 2 * sourceRect.top - (targetRect.top + canvasRect.top) }; } else { pos = { x: (_b = mouseEvent.offsetX) !== null && _b !== void 0 ? _b : mouseEvent.clientX, y: (_c = mouseEvent.offsetY) !== null && _c !== void 0 ? _c : mouseEvent.clientY }; } } else { if (mouseEvent.target === container.canvas.element) { pos = { x: (_d = mouseEvent.offsetX) !== null && _d !== void 0 ? _d : mouseEvent.clientX, y: (_e = mouseEvent.offsetY) !== null && _e !== void 0 ? _e : mouseEvent.clientY }; } } } else { this.canPush = e.type !== "touchmove"; const touchEvent = e; const lastTouch = touchEvent.touches[touchEvent.touches.length - 1]; const canvasRect = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect(); pos = { x: lastTouch.clientX - ((_f = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.left) !== null && _f !== void 0 ? _f : 0), y: lastTouch.clientY - ((_g = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.top) !== null && _g !== void 0 ? _g : 0) }; } const pxRatio = container.retina.pixelRatio; if (pos) { pos.x *= pxRatio; pos.y *= pxRatio; } container.interactivity.mouse.position = pos; container.interactivity.status = Constants.mouseMoveEvent; } mouseTouchFinish() { const interactivity = this.container.interactivity; if (interactivity === undefined) { return; } const mouse = interactivity.mouse; delete mouse.position; delete mouse.clickPosition; delete mouse.downPosition; interactivity.status = Constants.mouseLeaveEvent; mouse.inside = false; mouse.clicking = false; } mouseTouchClick(e) { const container = this.container; const options = container.actualOptions; const mouse = container.interactivity.mouse; mouse.inside = true; let handled = false; const mousePosition = mouse.position; if (mousePosition === undefined || !options.interactivity.events.onClick.enable) { return; } for (const [, plugin] of container.plugins) { if (plugin.clickPositionValid !== undefined) { handled = plugin.clickPositionValid(mousePosition); if (handled) { break; } } } if (!handled) { this.doMouseTouchClick(e); } mouse.clicking = false; } doMouseTouchClick(e) { const container = this.container; const options = container.actualOptions; if (this.canPush) { const mousePos = container.interactivity.mouse.position; if (mousePos) { container.interactivity.mouse.clickPosition = { x: mousePos.x, y: mousePos.y }; } else { return; } container.interactivity.mouse.clickTime = (new Date).getTime(); const onClick = options.interactivity.events.onClick; if (onClick.mode instanceof Array) { for (const mode of onClick.mode) { this.handleClickMode(mode); } } else { this.handleClickMode(onClick.mode); } } if (e.type === "touchend") { setTimeout((() => this.mouseTouchFinish()), 500); } } handleThemeChange(e) { const mediaEvent = e; const themeName = mediaEvent.matches ? this.container.options.defaultDarkTheme : this.container.options.defaultLightTheme; const theme = this.container.options.themes.find((theme => theme.name === themeName)); if (theme && theme.default.auto) { this.container.loadTheme(themeName); } } handleClickMode(mode) { const container = this.container; const options = container.actualOptions; const pushNb = options.interactivity.modes.push.quantity; const removeNb = options.interactivity.modes.remove.quantity; switch (mode) { case "push": { if (pushNb > 0) { const pushOptions = options.interactivity.modes.push; const group = itemFromArray([ undefined, ...pushOptions.groups ]); const groupOptions = group !== undefined ? container.actualOptions.particles.groups[group] : undefined; container.particles.push(pushNb, container.interactivity.mouse, groupOptions, group); } break; } case "remove": container.particles.removeQuantity(removeNb); break; case "bubble": container.bubble.clicking = true; break; case "repulse": container.repulse.clicking = true; container.repulse.count = 0; for (const particle of container.repulse.particles) { particle.velocity.setTo(particle.initialVelocity); } container.repulse.particles = []; container.repulse.finish = false; setTimeout((() => { if (!container.destroyed) { container.repulse.clicking = false; } }), options.interactivity.modes.repulse.duration * 1e3); break; case "attract": container.attract.clicking = true; container.attract.count = 0; for (const particle of container.attract.particles) { particle.velocity.setTo(particle.initialVelocity); } container.attract.particles = []; container.attract.finish = false; setTimeout((() => { if (!container.destroyed) { container.attract.clicking = false; } }), options.interactivity.modes.attract.duration * 1e3); break; case "pause": if (container.getAnimationStatus()) { container.pause(); } else { container.play(); } break; } for (const [, plugin] of container.plugins) { if (plugin.handleClickMode) { plugin.handleClickMode(mode); } } } } var __classPrivateFieldSet = undefined && undefined.__classPrivateFieldSet || function(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var __classPrivateFieldGet = undefined && undefined.__classPrivateFieldGet || function(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _InteractionManager_engine; class InteractionManager_InteractionManager { constructor(engine, container) { this.container = container; _InteractionManager_engine.set(this, void 0); __classPrivateFieldSet(this, _InteractionManager_engine, engine, "f"); this.externalInteractors = []; this.particleInteractors = []; this.init(); } init() { const interactors = __classPrivateFieldGet(this, _InteractionManager_engine, "f").plugins.getInteractors(this.container, true); this.externalInteractors = []; this.particleInteractors = []; for (const interactor of interactors) { switch (interactor.type) { case 0: this.externalInteractors.push(interactor); break; case 1: this.particleInteractors.push(interactor); break; } } } async externalInteract(delta) { for (const interactor of this.externalInteractors) { if (interactor.isEnabled()) { await interactor.interact(delta); } } } async particlesInteract(particle, delta) { for (const interactor of this.externalInteractors) { interactor.reset(particle); } for (const interactor of this.particleInteractors) { if (interactor.isEnabled(particle)) { await interactor.interact(particle, delta); } } } } _InteractionManager_engine = new WeakMap; function applyDistance(particle) { const initialPosition = particle.initialPosition; const {dx: dx, dy: dy} = getDistances(initialPosition, particle.position); const dxFixed = Math.abs(dx), dyFixed = Math.abs(dy); const hDistance = particle.retina.maxDistance.horizontal; const vDistance = particle.retina.maxDistance.vertical; if (!hDistance && !vDistance) { return; } if ((hDistance && dxFixed >= hDistance || vDistance && dyFixed >= vDistance) && !particle.misplaced) { particle.misplaced = !!hDistance && dxFixed > hDistance || !!vDistance && dyFixed > vDistance; if (hDistance) { particle.velocity.x = particle.velocity.y / 2 - particle.velocity.x; } if (vDistance) { particle.velocity.y = particle.velocity.x / 2 - particle.velocity.y; } } else if ((!hDistance || dxFixed < hDistance) && (!vDistance || dyFixed < vDistance) && particle.misplaced) { particle.misplaced = false; } else if (particle.misplaced) { const pos = particle.position, vel = particle.velocity; if (hDistance && (pos.x < initialPosition.x && vel.x < 0 || pos.x > initialPosition.x && vel.x > 0)) { vel.x *= -Math.random(); } if (vDistance && (pos.y < initialPosition.y && vel.y < 0 || pos.y > initialPosition.y && vel.y > 0)) { vel.y *= -Math.random(); } } } class ParticlesMover_ParticlesMover { constructor(container) { this.container = container; } move(particle, delta) { if (particle.destroyed) { return; } this.moveParticle(particle, delta); this.moveParallax(particle); } moveParticle(particle, delta) { var _a, _b, _c; var _d, _e; const particleOptions = particle.options; const moveOptions = particleOptions.move; if (!moveOptions.enable) { return; } const container = this.container, slowFactor = this.getProximitySpeedFactor(particle), baseSpeed = ((_a = (_d = particle.retina).moveSpeed) !== null && _a !== void 0 ? _a : _d.moveSpeed = getRangeValue(moveOptions.speed) * container.retina.pixelRatio) * container.retina.reduceFactor, moveDrift = (_b = (_e = particle.retina).moveDrift) !== null && _b !== void 0 ? _b : _e.moveDrift = getRangeValue(particle.options.move.drift) * container.retina.pixelRatio, maxSize = getRangeMax(particleOptions.size.value) * container.retina.pixelRatio, sizeFactor = moveOptions.size ? particle.getRadius() / maxSize : 1, diffFactor = 2, speedFactor = sizeFactor * slowFactor * (delta.factor || 1) / diffFactor, moveSpeed = baseSpeed * speedFactor; this.applyPath(particle, delta); const gravityOptions = particle.gravity; const gravityFactor = gravityOptions.enable && gravityOptions.inverse ? -1 : 1; if (gravityOptions.enable && moveSpeed) { particle.velocity.y += gravityFactor * (gravityOptions.acceleration * delta.factor) / (60 * moveSpeed); } if (moveDrift && moveSpeed) { particle.velocity.x += moveDrift * delta.factor / (60 * moveSpeed); } const decay = particle.moveDecay; if (decay != 1) { particle.velocity.multTo(decay); } const velocity = particle.velocity.mult(moveSpeed); const maxSpeed = (_c = particle.retina.maxSpeed) !== null && _c !== void 0 ? _c : container.retina.maxSpeed; if (gravityOptions.enable && maxSpeed > 0 && (!gravityOptions.inverse && velocity.y >= 0 && velocity.y >= maxSpeed || gravityOptions.inverse && velocity.y <= 0 && velocity.y <= -maxSpeed)) { velocity.y = gravityFactor * maxSpeed; if (moveSpeed) { particle.velocity.y = velocity.y / moveSpeed; } } const zIndexOptions = particle.options.zIndex, zVelocityFactor = (1 - particle.zIndexFactor) ** zIndexOptions.velocityRate; if (moveOptions.spin.enable) { this.spin(particle, moveSpeed); } else { if (zVelocityFactor != 1) { velocity.multTo(zVelocityFactor); } particle.position.addTo(velocity); if (moveOptions.vibrate) { particle.position.x += Math.sin(particle.position.x * Math.cos(particle.position.y)); particle.position.y += Math.cos(particle.position.y * Math.sin(particle.position.x)); } } applyDistance(particle); } spin(particle, moveSpeed) { const container = this.container; if (!particle.spin) { return; } const updateFunc = { x: particle.spin.direction === "clockwise" ? Math.cos : Math.sin, y: particle.spin.direction === "clockwise" ? Math.sin : Math.cos }; particle.position.x = particle.spin.center.x + particle.spin.radius * updateFunc.x(particle.spin.angle); particle.position.y = particle.spin.center.y + particle.spin.radius * updateFunc.y(particle.spin.angle); particle.spin.radius += particle.spin.acceleration; const maxCanvasSize = Math.max(container.canvas.size.width, container.canvas.size.height); if (particle.spin.radius > maxCanvasSize / 2) { particle.spin.radius = maxCanvasSize / 2; particle.spin.acceleration *= -1; } else if (particle.spin.radius < 0) { particle.spin.radius = 0; particle.spin.acceleration *= -1; } particle.spin.angle += moveSpeed / 100 * (1 - particle.spin.radius / maxCanvasSize); } applyPath(particle, delta) { const particlesOptions = particle.options; const pathOptions = particlesOptions.move.path; const pathEnabled = pathOptions.enable; if (!pathEnabled) { return; } const container = this.container; if (particle.lastPathTime <= particle.pathDelay) { particle.lastPathTime += delta.value; return; } const path = container.pathGenerator.generate(particle); particle.velocity.addTo(path); if (pathOptions.clamp) { particle.velocity.x = clamp(particle.velocity.x, -1, 1); particle.velocity.y = clamp(particle.velocity.y, -1, 1); } particle.lastPathTime -= particle.pathDelay; } moveParallax(particle) { const container = this.container; const options = container.actualOptions; if (isSsr() || !options.interactivity.events.onHover.parallax.enable) { return; } const parallaxForce = options.interactivity.events.onHover.parallax.force; const mousePos = container.interactivity.mouse.position; if (!mousePos) { return; } const canvasCenter = { x: container.canvas.size.width / 2, y: container.canvas.size.height / 2 }; const parallaxSmooth = options.interactivity.events.onHover.parallax.smooth; const factor = particle.getRadius() / parallaxForce; const tmp = { x: (mousePos.x - canvasCenter.x) * factor, y: (mousePos.y - canvasCenter.y) * factor }; particle.offset.x += (tmp.x - particle.offset.x) / parallaxSmooth; particle.offset.y += (tmp.y - particle.offset.y) / parallaxSmooth; } getProximitySpeedFactor(particle) { const container = this.container; const options = container.actualOptions; const active = isInArray("slow", options.interactivity.events.onHover.mode); if (!active) { return 1; } const mousePos = this.container.interactivity.mouse.position; if (!mousePos) { return 1; } const particlePos = particle.getPosition(); const dist = getDistance(mousePos, particlePos); const radius = container.retina.slowModeRadius; if (dist > radius) { return 1; } const proximityFactor = dist / radius || 0; const slowFactor = options.interactivity.modes.slow.factor; return proximityFactor / slowFactor; } } var Plugins_classPrivateFieldSet = undefined && undefined.__classPrivateFieldSet || function(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var _Plugins_engine; class Plugins { constructor(engine) { _Plugins_engine.set(this, void 0); Plugins_classPrivateFieldSet(this, _Plugins_engine, engine, "f"); this.plugins = []; this.interactorsInitializers = new Map; this.updatersInitializers = new Map; this.interactors = new Map; this.updaters = new Map; this.presets = new Map; this.drawers = new Map; this.pathGenerators = new Map; } getPlugin(plugin) { return this.plugins.find((t => t.id === plugin)); } addPlugin(plugin) { if (!this.getPlugin(plugin.id)) { this.plugins.push(plugin); } } getAvailablePlugins(container) { const res = new Map; for (const plugin of this.plugins) { if (!plugin.needsPlugin(container.actualOptions)) { continue; } res.set(plugin.id, plugin.getPlugin(container)); } return res; } loadOptions(options, sourceOptions) { for (const plugin of this.plugins) { plugin.loadOptions(options, sourceOptions); } } getPreset(preset) { return this.presets.get(preset); } addPreset(presetKey, options, override = false) { if (override || !this.getPreset(presetKey)) { this.presets.set(presetKey, options); } } addShapeDrawer(type, drawer) { if (!this.getShapeDrawer(type)) { this.drawers.set(type, drawer); } } getShapeDrawer(type) { return this.drawers.get(type); } getSupportedShapes() { return this.drawers.keys(); } getPathGenerator(type) { return this.pathGenerators.get(type); } addPathGenerator(type, pathGenerator) { if (!this.getPathGenerator(type)) { this.pathGenerators.set(type, pathGenerator); } } getInteractors(container, force = false) { let res = this.interactors.get(container); if (!res || force) { res = [ ...this.interactorsInitializers.values() ].map((t => t(container))); this.interactors.set(container, res); } return res; } addInteractor(name, initInteractor) { this.interactorsInitializers.set(name, initInteractor); } getUpdaters(container, force = false) { let res = this.updaters.get(container); if (!res || force) { res = [ ...this.updatersInitializers.values() ].map((t => t(container))); this.updaters.set(container, res); } return res; } addParticleUpdater(name, initUpdater) { this.updatersInitializers.set(name, initUpdater); } } _Plugins_engine = new WeakMap; class QuadTree_QuadTree { constructor(rectangle, capacity) { this.rectangle = rectangle; this.capacity = capacity; this.points = []; this.divided = false; } subdivide() { const x = this.rectangle.position.x; const y = this.rectangle.position.y; const w = this.rectangle.size.width; const h = this.rectangle.size.height; const capacity = this.capacity; this.northEast = new QuadTree_QuadTree(new Rectangle(x, y, w / 2, h / 2), capacity); this.northWest = new QuadTree_QuadTree(new Rectangle(x + w / 2, y, w / 2, h / 2), capacity); this.southEast = new QuadTree_QuadTree(new Rectangle(x, y + h / 2, w / 2, h / 2), capacity); this.southWest = new QuadTree_QuadTree(new Rectangle(x + w / 2, y + h / 2, w / 2, h / 2), capacity); this.divided = true; } insert(point) { var _a, _b, _c, _d, _e; if (!this.rectangle.contains(point.position)) { return false; } if (this.points.length < this.capacity) { this.points.push(point); return true; } if (!this.divided) { this.subdivide(); } return (_e = ((_a = this.northEast) === null || _a === void 0 ? void 0 : _a.insert(point)) || ((_b = this.northWest) === null || _b === void 0 ? void 0 : _b.insert(point)) || ((_c = this.southEast) === null || _c === void 0 ? void 0 : _c.insert(point)) || ((_d = this.southWest) === null || _d === void 0 ? void 0 : _d.insert(point))) !== null && _e !== void 0 ? _e : false; } queryCircle(position, radius) { return this.query(new Circle(position.x, position.y, radius)); } queryCircleWarp(position, radius, containerOrSize) { const container = containerOrSize; const size = containerOrSize; return this.query(new CircleWarp(position.x, position.y, radius, container.canvas !== undefined ? container.canvas.size : size)); } queryRectangle(position, size) { return this.query(new Rectangle(position.x, position.y, size.width, size.height)); } query(range, found) { var _a, _b, _c, _d; const res = found !== null && found !== void 0 ? found : []; if (!range.intersects(this.rectangle)) { return []; } else { for (const p of this.points) { if (!range.contains(p.position) && getDistance(range.position, p.position) > p.particle.getRadius()) { continue; } res.push(p.particle); } if (this.divided) { (_a = this.northEast) === null || _a === void 0 ? void 0 : _a.query(range, res); (_b = this.northWest) === null || _b === void 0 ? void 0 : _b.query(range, res); (_c = this.southEast) === null || _c === void 0 ? void 0 : _c.query(range, res); (_d = this.southWest) === null || _d === void 0 ? void 0 : _d.query(range, res); } } return res; } } class Canvas_Canvas { constructor(container) { this.container = container; this.size = { height: 0, width: 0 }; this.context = null; this.generatedCanvas = false; } init() { this.resize(); this.initStyle(); this.initCover(); this.initTrail(); this.initBackground(); this.paint(); } loadCanvas(canvas) { var _a; if (this.generatedCanvas) { (_a = this.element) === null || _a === void 0 ? void 0 : _a.remove(); } this.generatedCanvas = canvas.dataset && Constants.generatedAttribute in canvas.dataset ? canvas.dataset[Constants.generatedAttribute] === "true" : this.generatedCanvas; this.element = canvas; this.originalStyle = deepExtend({}, this.element.style); this.size.height = canvas.offsetHeight; this.size.width = canvas.offsetWidth; this.context = this.element.getContext("2d"); this.container.retina.init(); this.initBackground(); } destroy() { var _a; if (this.generatedCanvas) { (_a = this.element) === null || _a === void 0 ? void 0 : _a.remove(); } this.draw((ctx => { clear(ctx, this.size); })); } paint() { const options = this.container.actualOptions; this.draw((ctx => { if (options.backgroundMask.enable && options.backgroundMask.cover && this.coverColor) { clear(ctx, this.size); this.paintBase(getStyleFromRgb(this.coverColor, this.coverColor.a)); } else { this.paintBase(); } })); } clear() { const options = this.container.actualOptions; const trail = options.particles.move.trail; if (options.backgroundMask.enable) { this.paint(); } else if (trail.enable && trail.length > 0 && this.trailFillColor) { this.paintBase(getStyleFromRgb(this.trailFillColor, 1 / trail.length)); } else { this.draw((ctx => { clear(ctx, this.size); })); } } async windowResize() { if (!this.element) { return; } const container = this.container; this.resize(); const needsRefresh = container.updateActualOptions(); container.particles.setDensity(); for (const [, plugin] of container.plugins) { if (plugin.resize !== undefined) { plugin.resize(); } } if (needsRefresh) { await container.refresh(); } } resize() { if (!this.element) { return; } const container = this.container; const pxRatio = container.retina.pixelRatio; const size = container.canvas.size; const oldSize = Object.assign({}, size); size.width = this.element.offsetWidth * pxRatio; size.height = this.element.offsetHeight * pxRatio; this.element.width = size.width; this.element.height = size.height; if (this.container.started) { this.resizeFactor = { width: size.width / oldSize.width, height: size.height / oldSize.height }; } } drawConnectLine(p1, p2) { this.draw((ctx => { var _a; const lineStyle = this.lineStyle(p1, p2); if (!lineStyle) { return; } const pos1 = p1.getPosition(); const pos2 = p2.getPosition(); drawConnectLine(ctx, (_a = p1.retina.linksWidth) !== null && _a !== void 0 ? _a : this.container.retina.linksWidth, lineStyle, pos1, pos2); })); } drawGrabLine(particle, lineColor, opacity, mousePos) { const container = this.container; this.draw((ctx => { var _a; const beginPos = particle.getPosition(); drawGrabLine(ctx, (_a = particle.retina.linksWidth) !== null && _a !== void 0 ? _a : container.retina.linksWidth, beginPos, mousePos, lineColor, opacity); })); } drawParticle(particle, delta) { var _a, _b, _c, _d, _e, _f; if (particle.spawning || particle.destroyed) { return; } const pfColor = particle.getFillColor(); const psColor = (_a = particle.getStrokeColor()) !== null && _a !== void 0 ? _a : pfColor; if (!pfColor && !psColor) { return; } let [fColor, sColor] = this.getPluginParticleColors(particle); const pOptions = particle.options; const twinkle = pOptions.twinkle.particles; const twinkling = twinkle.enable && Math.random() < twinkle.frequency; if (!fColor || !sColor) { const twinkleRgb = colorToHsl(twinkle.color); if (!fColor) { fColor = twinkling && twinkleRgb !== undefined ? twinkleRgb : pfColor ? pfColor : undefined; } if (!sColor) { sColor = twinkling && twinkleRgb !== undefined ? twinkleRgb : psColor ? psColor : undefined; } } const options = this.container.actualOptions; const zIndexOptions = particle.options.zIndex; const zOpacityFactor = (1 - particle.zIndexFactor) ** zIndexOptions.opacityRate; const radius = particle.getRadius(); const opacity = twinkling ? getRangeValue(twinkle.opacity) : (_d = (_b = particle.bubble.opacity) !== null && _b !== void 0 ? _b : (_c = particle.opacity) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : 1; const strokeOpacity = (_f = (_e = particle.stroke) === null || _e === void 0 ? void 0 : _e.opacity) !== null && _f !== void 0 ? _f : opacity; const zOpacity = opacity * zOpacityFactor; const fillColorValue = fColor ? getStyleFromHsl(fColor, zOpacity) : undefined; if (!fillColorValue && !sColor) { return; } this.draw((ctx => { const zSizeFactor = (1 - particle.zIndexFactor) ** zIndexOptions.sizeRate; const zStrokeOpacity = strokeOpacity * zOpacityFactor; const strokeColorValue = sColor ? getStyleFromHsl(sColor, zStrokeOpacity) : fillColorValue; if (radius <= 0) { return; } const container = this.container; for (const updater of container.particles.updaters) { if (updater.beforeDraw) { updater.beforeDraw(particle); } } drawParticle(this.container, ctx, particle, delta, fillColorValue, strokeColorValue, options.backgroundMask.enable, options.backgroundMask.composite, radius * zSizeFactor, zOpacity, particle.options.shadow, particle.gradient); for (const updater of container.particles.updaters) { if (updater.afterDraw) { updater.afterDraw(particle); } } })); } drawPlugin(plugin, delta) { this.draw((ctx => { drawPlugin(ctx, plugin, delta); })); } drawParticlePlugin(plugin, particle, delta) { this.draw((ctx => { drawParticlePlugin(ctx, plugin, particle, delta); })); } initBackground() { const options = this.container.actualOptions; const background = options.background; const element = this.element; const elementStyle = element === null || element === void 0 ? void 0 : element.style; if (!elementStyle) { return; } if (background.color) { const color = colorToRgb(background.color); elementStyle.backgroundColor = color ? getStyleFromRgb(color, background.opacity) : ""; } else { elementStyle.backgroundColor = ""; } elementStyle.backgroundImage = background.image || ""; elementStyle.backgroundPosition = background.position || ""; elementStyle.backgroundRepeat = background.repeat || ""; elementStyle.backgroundSize = background.size || ""; } draw(cb) { if (!this.context) { return; } return cb(this.context); } initCover() { const options = this.container.actualOptions; const cover = options.backgroundMask.cover; const color = cover.color; const coverRgb = colorToRgb(color); if (coverRgb) { this.coverColor = { r: coverRgb.r, g: coverRgb.g, b: coverRgb.b, a: cover.opacity }; } } initTrail() { const options = this.container.actualOptions; const trail = options.particles.move.trail; const fillColor = colorToRgb(trail.fillColor); if (fillColor) { const trail = options.particles.move.trail; this.trailFillColor = { r: fillColor.r, g: fillColor.g, b: fillColor.b, a: 1 / trail.length }; } } getPluginParticleColors(particle) { let fColor; let sColor; for (const [, plugin] of this.container.plugins) { if (!fColor && plugin.particleFillColor) { fColor = colorToHsl(plugin.particleFillColor(particle)); } if (!sColor && plugin.particleStrokeColor) { sColor = colorToHsl(plugin.particleStrokeColor(particle)); } if (fColor && sColor) { break; } } return [ fColor, sColor ]; } initStyle() { const element = this.element, options = this.container.actualOptions; if (!element) { return; } const originalStyle = this.originalStyle; if (options.fullScreen.enable) { this.originalStyle = deepExtend({}, element.style); element.style.setProperty("position", "fixed", "important"); element.style.setProperty("z-index", options.fullScreen.zIndex.toString(10), "important"); element.style.setProperty("top", "0", "important"); element.style.setProperty("left", "0", "important"); element.style.setProperty("width", "100%", "important"); element.style.setProperty("height", "100%", "important"); } else if (originalStyle) { element.style.position = originalStyle.position; element.style.zIndex = originalStyle.zIndex; element.style.top = originalStyle.top; element.style.left = originalStyle.left; element.style.width = originalStyle.width; element.style.height = originalStyle.height; } for (const key in options.style) { if (!key || !options.style) { continue; } const value = options.style[key]; if (!value) { continue; } element.style.setProperty(key, value, "important"); } } paintBase(baseColor) { this.draw((ctx => { paintBase(ctx, this.size, baseColor); })); } lineStyle(p1, p2) { return this.draw((ctx => { const options = this.container.actualOptions; const connectOptions = options.interactivity.modes.connect; return gradient(ctx, p1, p2, connectOptions.links.opacity); })); } } class Trail_Trail { constructor() { this.delay = 1; this.pauseOnStop = false; this.quantity = 1; } load(data) { if (data === undefined) { return; } if (data.delay !== undefined) { this.delay = data.delay; } if (data.quantity !== undefined) { this.quantity = data.quantity; } if (data.particles !== undefined) { this.particles = deepExtend({}, data.particles); } if (data.pauseOnStop !== undefined) { this.pauseOnStop = data.pauseOnStop; } } } class Modes_Modes { constructor() { this.attract = new Attract; this.bounce = new Bounce; this.bubble = new Bubble; this.connect = new Connect; this.grab = new Grab; this.light = new Light; this.push = new Push; this.remove = new Remove; this.repulse = new Repulse; this.slow = new Slow; this.trail = new Trail; } load(data) { if (data === undefined) { return; } this.attract.load(data.attract); this.bubble.load(data.bubble); this.connect.load(data.connect); this.grab.load(data.grab); this.light.load(data.light); this.push.load(data.push); this.remove.load(data.remove); this.repulse.load(data.repulse); this.slow.load(data.slow); this.trail.load(data.trail); } } class Interactivity_Interactivity { constructor() { this.detectsOn = "window"; this.events = new Events; this.modes = new Modes; } get detect_on() { return this.detectsOn; } set detect_on(value) { this.detectsOn = value; } load(data) { var _a, _b, _c; if (data === undefined) { return; } const detectsOn = (_a = data.detectsOn) !== null && _a !== void 0 ? _a : data.detect_on; if (detectsOn !== undefined) { this.detectsOn = detectsOn; } this.events.load(data.events); this.modes.load(data.modes); if (((_c = (_b = data.modes) === null || _b === void 0 ? void 0 : _b.slow) === null || _c === void 0 ? void 0 : _c.active) === true) { if (this.events.onHover.mode instanceof Array) { if (this.events.onHover.mode.indexOf("slow") < 0) { this.events.onHover.mode.push("slow"); } } else if (this.events.onHover.mode !== "slow") { this.events.onHover.mode = [ this.events.onHover.mode, "slow" ]; } } } } class ManualParticle_ManualParticle { load(data) { var _a, _b; if (!data) { return; } if (data.position !== undefined) { this.position = { x: (_a = data.position.x) !== null && _a !== void 0 ? _a : 50, y: (_b = data.position.y) !== null && _b !== void 0 ? _b : 50 }; } if (data.options !== undefined) { this.options = deepExtend({}, data.options); } } } class ColorAnimation_ColorAnimation { constructor() { this.count = 0; this.enable = false; this.offset = 0; this.speed = 1; this.sync = true; } load(data) { if (data === undefined) { return; } if (data.count !== undefined) { this.count = setRangeValue(data.count); } if (data.enable !== undefined) { this.enable = data.enable; } if (data.offset !== undefined) { this.offset = setRangeValue(data.offset); } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } if (data.sync !== undefined) { this.sync = data.sync; } } } class HslAnimation_HslAnimation { constructor() { this.h = new ColorAnimation; this.s = new ColorAnimation; this.l = new ColorAnimation; } load(data) { if (!data) { return; } this.h.load(data.h); this.s.load(data.s); this.l.load(data.l); } } class AnimatableColor_AnimatableColor extends(null && OptionsColor){ constructor() { super(); this.animation = new HslAnimation; } static create(source, data) { const color = new AnimatableColor_AnimatableColor; color.load(source); if (data !== undefined) { if (typeof data === "string" || data instanceof Array) { color.load({ value: data }); } else { color.load(data); } } return color; } load(data) { super.load(data); if (!data) { return; } const colorAnimation = data.animation; if (colorAnimation !== undefined) { if (colorAnimation.enable !== undefined) { this.animation.h.load(colorAnimation); } else { this.animation.load(data.animation); } } } } class AnimatableGradient_AnimatableGradient { constructor() { this.angle = new GradientAngle; this.colors = []; this.type = "random"; } load(data) { if (!data) { return; } this.angle.load(data.angle); if (data.colors !== undefined) { this.colors = data.colors.map((s => { const tmp = new AnimatableGradientColor; tmp.load(s); return tmp; })); } if (data.type !== undefined) { this.type = data.type; } } } class GradientAngle { constructor() { this.value = 0; this.animation = new GradientAngleAnimation; this.direction = "clockwise"; } load(data) { if (!data) { return; } this.animation.load(data.animation); if (data.value !== undefined) { this.value = data.value; } if (data.direction !== undefined) { this.direction = data.direction; } } } class GradientColorOpacity { constructor() { this.value = 0; this.animation = new GradientColorOpacityAnimation; } load(data) { if (!data) { return; } this.animation.load(data.animation); if (data.value !== undefined) { this.value = setRangeValue(data.value); } } } class AnimatableGradientColor { constructor() { this.stop = 0; this.value = new AnimatableColor; } load(data) { if (!data) { return; } if (data.stop !== undefined) { this.stop = data.stop; } this.value = AnimatableColor.create(this.value, data.value); if (data.opacity !== undefined) { this.opacity = new GradientColorOpacity; if (typeof data.opacity === "number") { this.opacity.value = data.opacity; } else { this.opacity.load(data.opacity); } } } } class GradientAngleAnimation { constructor() { this.count = 0; this.enable = false; this.speed = 0; this.sync = false; } load(data) { if (!data) { return; } if (data.count !== undefined) { this.count = setRangeValue(data.count); } if (data.enable !== undefined) { this.enable = data.enable; } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } if (data.sync !== undefined) { this.sync = data.sync; } } } class GradientColorOpacityAnimation { constructor() { this.count = 0; this.enable = false; this.speed = 0; this.sync = false; this.startValue = "random"; } load(data) { if (!data) { return; } if (data.count !== undefined) { this.count = setRangeValue(data.count); } if (data.enable !== undefined) { this.enable = data.enable; } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } if (data.sync !== undefined) { this.sync = data.sync; } if (data.startValue !== undefined) { this.startValue = data.startValue; } } } class ValueWithRandom_ValueWithRandom { constructor() { this.random = new Random; this.value = 0; } load(data) { if (!data) { return; } if (typeof data.random === "boolean") { this.random.enable = data.random; } else { this.random.load(data.random); } if (data.value !== undefined) { this.value = setRangeValue(data.value, this.random.enable ? this.random.minimumValue : undefined); } } } class BounceFactor_BounceFactor extends(null && ValueWithRandom){ constructor() { super(); this.random.minimumValue = .1; this.value = 1; } } class Bounce_Bounce { constructor() { this.horizontal = new BounceFactor; this.vertical = new BounceFactor; } load(data) { if (!data) { return; } this.horizontal.load(data.horizontal); this.vertical.load(data.vertical); } } class Collisions_Collisions { constructor() { this.bounce = new Bounce; this.enable = false; this.mode = "bounce"; this.overlap = new CollisionsOverlap; } load(data) { if (data === undefined) { return; } this.bounce.load(data.bounce); if (data.enable !== undefined) { this.enable = data.enable; } if (data.mode !== undefined) { this.mode = data.mode; } this.overlap.load(data.overlap); } } class SplitFactor_SplitFactor extends(null && ValueWithRandom){ constructor() { super(); this.value = 3; } } class SplitRate_SplitRate extends(null && ValueWithRandom){ constructor() { super(); this.value = { min: 4, max: 9 }; } } class Split_Split { constructor() { this.count = 1; this.factor = new SplitFactor; this.rate = new SplitRate; this.sizeOffset = true; } load(data) { if (!data) { return; } if (data.count !== undefined) { this.count = data.count; } this.factor.load(data.factor); this.rate.load(data.rate); if (data.particles !== undefined) { this.particles = deepExtend({}, data.particles); } if (data.sizeOffset !== undefined) { this.sizeOffset = data.sizeOffset; } } } class Destroy_Destroy { constructor() { this.mode = "none"; this.split = new Split; } load(data) { if (!data) { return; } if (data.mode !== undefined) { this.mode = data.mode; } this.split.load(data.split); } } class LifeDelay_LifeDelay extends(null && ValueWithRandom){ constructor() { super(); this.sync = false; } load(data) { if (!data) { return; } super.load(data); if (data.sync !== undefined) { this.sync = data.sync; } } } class LifeDuration_LifeDuration extends(null && ValueWithRandom){ constructor() { super(); this.random.minimumValue = 1e-4; this.sync = false; } load(data) { if (data === undefined) { return; } super.load(data); if (data.sync !== undefined) { this.sync = data.sync; } } } class Life_Life { constructor() { this.count = 0; this.delay = new LifeDelay; this.duration = new LifeDuration; } load(data) { if (data === undefined) { return; } if (data.count !== undefined) { this.count = data.count; } this.delay.load(data.delay); this.duration.load(data.duration); } } class Attract_Attract { constructor() { this.distance = 200; this.enable = false; this.rotate = { x: 3e3, y: 3e3 }; } get rotateX() { return this.rotate.x; } set rotateX(value) { this.rotate.x = value; } get rotateY() { return this.rotate.y; } set rotateY(value) { this.rotate.y = value; } load(data) { var _a, _b, _c, _d; if (!data) { return; } if (data.distance !== undefined) { this.distance = setRangeValue(data.distance); } if (data.enable !== undefined) { this.enable = data.enable; } const rotateX = (_b = (_a = data.rotate) === null || _a === void 0 ? void 0 : _a.x) !== null && _b !== void 0 ? _b : data.rotateX; if (rotateX !== undefined) { this.rotate.x = rotateX; } const rotateY = (_d = (_c = data.rotate) === null || _c === void 0 ? void 0 : _c.y) !== null && _d !== void 0 ? _d : data.rotateY; if (rotateY !== undefined) { this.rotate.y = rotateY; } } } class MoveAngle_MoveAngle { constructor() { this.offset = 0; this.value = 90; } load(data) { if (data === undefined) { return; } if (data.offset !== undefined) { this.offset = setRangeValue(data.offset); } if (data.value !== undefined) { this.value = setRangeValue(data.value); } } } class MoveGravity_MoveGravity { constructor() { this.acceleration = 9.81; this.enable = false; this.inverse = false; this.maxSpeed = 50; } load(data) { if (!data) { return; } if (data.acceleration !== undefined) { this.acceleration = setRangeValue(data.acceleration); } if (data.enable !== undefined) { this.enable = data.enable; } if (data.inverse !== undefined) { this.inverse = data.inverse; } if (data.maxSpeed !== undefined) { this.maxSpeed = setRangeValue(data.maxSpeed); } } } class PathDelay_PathDelay extends(null && ValueWithRandom){ constructor() { super(); } } class Path_Path { constructor() { this.clamp = true; this.delay = new PathDelay; this.enable = false; this.options = {}; } load(data) { if (data === undefined) { return; } if (data.clamp !== undefined) { this.clamp = data.clamp; } this.delay.load(data.delay); if (data.enable !== undefined) { this.enable = data.enable; } this.generator = data.generator; if (data.options) { this.options = deepExtend(this.options, data.options); } } } class Spin_Spin { constructor() { this.acceleration = 0; this.enable = false; } load(data) { if (!data) { return; } if (data.acceleration !== undefined) { this.acceleration = setRangeValue(data.acceleration); } if (data.enable !== undefined) { this.enable = data.enable; } this.position = data.position ? deepExtend({}, data.position) : undefined; } } class Move_Move { constructor() { this.angle = new MoveAngle; this.attract = new Attract; this.decay = 0; this.distance = {}; this.direction = "none"; this.drift = 0; this.enable = false; this.gravity = new MoveGravity; this.path = new Path; this.outModes = new OutModes; this.random = false; this.size = false; this.speed = 2; this.spin = new Spin; this.straight = false; this.trail = new Trail; this.vibrate = false; this.warp = false; } get collisions() { return false; } set collisions(value) {} get bounce() { return this.collisions; } set bounce(value) { this.collisions = value; } get out_mode() { return this.outMode; } set out_mode(value) { this.outMode = value; } get outMode() { return this.outModes.default; } set outMode(value) { this.outModes.default = value; } get noise() { return this.path; } set noise(value) { this.path = value; } load(data) { var _a, _b, _c; if (data === undefined) { return; } if (data.angle !== undefined) { if (typeof data.angle === "number") { this.angle.value = data.angle; } else { this.angle.load(data.angle); } } this.attract.load(data.attract); if (data.decay !== undefined) { this.decay = data.decay; } if (data.direction !== undefined) { this.direction = data.direction; } if (data.distance !== undefined) { this.distance = typeof data.distance === "number" ? { horizontal: data.distance, vertical: data.distance } : deepExtend({}, data.distance); } if (data.drift !== undefined) { this.drift = setRangeValue(data.drift); } if (data.enable !== undefined) { this.enable = data.enable; } this.gravity.load(data.gravity); const outMode = (_a = data.outMode) !== null && _a !== void 0 ? _a : data.out_mode; if (data.outModes !== undefined || outMode !== undefined) { if (typeof data.outModes === "string" || data.outModes === undefined && outMode !== undefined) { this.outModes.load({ default: (_b = data.outModes) !== null && _b !== void 0 ? _b : outMode }); } else { this.outModes.load(data.outModes); } } this.path.load((_c = data.path) !== null && _c !== void 0 ? _c : data.noise); if (data.random !== undefined) { this.random = data.random; } if (data.size !== undefined) { this.size = data.size; } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } this.spin.load(data.spin); if (data.straight !== undefined) { this.straight = data.straight; } this.trail.load(data.trail); if (data.vibrate !== undefined) { this.vibrate = data.vibrate; } if (data.warp !== undefined) { this.warp = data.warp; } } } class AnimationOptions_AnimationOptions { constructor() { this.count = 0; this.enable = false; this.speed = 1; this.sync = false; } load(data) { if (!data) { return; } if (data.count !== undefined) { this.count = setRangeValue(data.count); } if (data.enable !== undefined) { this.enable = data.enable; } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } if (data.sync !== undefined) { this.sync = data.sync; } } } class OpacityAnimation_OpacityAnimation extends(null && AnimationOptions){ constructor() { super(); this.destroy = "none"; this.enable = false; this.speed = 2; this.startValue = "random"; this.sync = false; } get opacity_min() { return this.minimumValue; } set opacity_min(value) { this.minimumValue = value; } load(data) { var _a; if (data === undefined) { return; } super.load(data); if (data.destroy !== undefined) { this.destroy = data.destroy; } if (data.enable !== undefined) { this.enable = data.enable; } this.minimumValue = (_a = data.minimumValue) !== null && _a !== void 0 ? _a : data.opacity_min; if (data.speed !== undefined) { this.speed = data.speed; } if (data.startValue !== undefined) { this.startValue = data.startValue; } if (data.sync !== undefined) { this.sync = data.sync; } } } class Opacity_Opacity extends(null && ValueWithRandom){ constructor() { super(); this.animation = new OpacityAnimation; this.random.minimumValue = .1; this.value = 1; } get anim() { return this.animation; } set anim(value) { this.animation = value; } load(data) { var _a; if (!data) { return; } super.load(data); const animation = (_a = data.animation) !== null && _a !== void 0 ? _a : data.anim; if (animation !== undefined) { this.animation.load(animation); this.value = setRangeValue(this.value, this.animation.enable ? this.animation.minimumValue : undefined); } } } class OrbitRotation_OrbitRotation extends(null && ValueWithRandom){ constructor() { super(); this.value = 45; this.random.enable = false; this.random.minimumValue = 0; } load(data) { if (data === undefined) { return; } super.load(data); } } class Orbit_Orbit { constructor() { this.animation = new AnimationOptions; this.enable = false; this.opacity = 1; this.rotation = new OrbitRotation; this.width = 1; } load(data) { if (data === undefined) { return; } this.animation.load(data.animation); this.rotation.load(data.rotation); if (data.enable !== undefined) { this.enable = data.enable; } if (data.opacity !== undefined) { this.opacity = setRangeValue(data.opacity); } if (data.width !== undefined) { this.width = setRangeValue(data.width); } if (data.radius !== undefined) { this.radius = setRangeValue(data.radius); } if (data.color !== undefined) { this.color = OptionsColor.create(this.color, data.color); } } } class Repulse_Repulse extends(null && ValueWithRandom){ constructor() { super(); this.enabled = false; this.distance = 1; this.duration = 1; this.factor = 1; this.speed = 1; } load(data) { super.load(data); if (!data) { return; } if (data.enabled !== undefined) { this.enabled = data.enabled; } if (data.distance !== undefined) { this.distance = setRangeValue(data.distance); } if (data.duration !== undefined) { this.duration = setRangeValue(data.duration); } if (data.factor !== undefined) { this.factor = setRangeValue(data.factor); } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } } } class RollLight_RollLight { constructor() { this.enable = false; this.value = 0; } load(data) { if (!data) { return; } if (data.enable !== undefined) { this.enable = data.enable; } if (data.value !== undefined) { this.value = setRangeValue(data.value); } } } class Roll_Roll { constructor() { this.darken = new RollLight; this.enable = false; this.enlighten = new RollLight; this.mode = "vertical"; this.speed = 25; } load(data) { if (!data) { return; } if (data.backColor !== undefined) { this.backColor = OptionsColor.create(this.backColor, data.backColor); } this.darken.load(data.darken); if (data.enable !== undefined) { this.enable = data.enable; } this.enlighten.load(data.enlighten); if (data.mode !== undefined) { this.mode = data.mode; } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } } } class RotateAnimation_RotateAnimation { constructor() { this.enable = false; this.speed = 0; this.sync = false; } load(data) { if (data === undefined) { return; } if (data.enable !== undefined) { this.enable = data.enable; } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } if (data.sync !== undefined) { this.sync = data.sync; } } } class Rotate_Rotate extends(null && ValueWithRandom){ constructor() { super(); this.animation = new RotateAnimation; this.direction = "clockwise"; this.path = false; this.value = 0; } load(data) { if (!data) { return; } super.load(data); if (data.direction !== undefined) { this.direction = data.direction; } this.animation.load(data.animation); if (data.path !== undefined) { this.path = data.path; } } } class Shape_Shape { constructor() { this.options = {}; this.type = "circle"; } get image() { var _a; return (_a = this.options["image"]) !== null && _a !== void 0 ? _a : this.options["images"]; } set image(value) { this.options["image"] = value; this.options["images"] = value; } get custom() { return this.options; } set custom(value) { this.options = value; } get images() { return this.image; } set images(value) { this.image = value; } get stroke() { return []; } set stroke(_value) {} get character() { var _a; return (_a = this.options["character"]) !== null && _a !== void 0 ? _a : this.options["char"]; } set character(value) { this.options["character"] = value; this.options["char"] = value; } get polygon() { var _a; return (_a = this.options["polygon"]) !== null && _a !== void 0 ? _a : this.options["star"]; } set polygon(value) { this.options["polygon"] = value; this.options["star"] = value; } load(data) { var _a, _b, _c; if (data === undefined) { return; } const options = (_a = data.options) !== null && _a !== void 0 ? _a : data.custom; if (options !== undefined) { for (const shape in options) { const item = options[shape]; if (item !== undefined) { this.options[shape] = deepExtend((_b = this.options[shape]) !== null && _b !== void 0 ? _b : {}, item); } } } this.loadShape(data.character, "character", "char", true); this.loadShape(data.polygon, "polygon", "star", false); this.loadShape((_c = data.image) !== null && _c !== void 0 ? _c : data.images, "image", "images", true); if (data.type !== undefined) { this.type = data.type; } } loadShape(item, mainKey, altKey, altOverride) { var _a, _b, _c, _d; if (item === undefined) { return; } if (item instanceof Array) { if (!(this.options[mainKey] instanceof Array)) { this.options[mainKey] = []; if (!this.options[altKey] || altOverride) { this.options[altKey] = []; } } this.options[mainKey] = deepExtend((_a = this.options[mainKey]) !== null && _a !== void 0 ? _a : [], item); if (!this.options[altKey] || altOverride) { this.options[altKey] = deepExtend((_b = this.options[altKey]) !== null && _b !== void 0 ? _b : [], item); } } else { if (this.options[mainKey] instanceof Array) { this.options[mainKey] = {}; if (!this.options[altKey] || altOverride) { this.options[altKey] = {}; } } this.options[mainKey] = deepExtend((_c = this.options[mainKey]) !== null && _c !== void 0 ? _c : {}, item); if (!this.options[altKey] || altOverride) { this.options[altKey] = deepExtend((_d = this.options[altKey]) !== null && _d !== void 0 ? _d : {}, item); } } } } class SizeAnimation_SizeAnimation extends(null && AnimationOptions){ constructor() { super(); this.destroy = "none"; this.enable = false; this.speed = 5; this.startValue = "random"; this.sync = false; } get size_min() { return this.minimumValue; } set size_min(value) { this.minimumValue = value; } load(data) { var _a; if (data === undefined) { return; } super.load(data); if (data.destroy !== undefined) { this.destroy = data.destroy; } if (data.enable !== undefined) { this.enable = data.enable; } this.minimumValue = (_a = data.minimumValue) !== null && _a !== void 0 ? _a : data.size_min; if (data.speed !== undefined) { this.speed = data.speed; } if (data.startValue !== undefined) { this.startValue = data.startValue; } if (data.sync !== undefined) { this.sync = data.sync; } } } class Size_Size extends(null && ValueWithRandom){ constructor() { super(); this.animation = new SizeAnimation; this.random.minimumValue = 1; this.value = 3; } get anim() { return this.animation; } set anim(value) { this.animation = value; } load(data) { var _a; if (!data) { return; } super.load(data); const animation = (_a = data.animation) !== null && _a !== void 0 ? _a : data.anim; if (animation !== undefined) { this.animation.load(animation); this.value = setRangeValue(this.value, this.animation.enable ? this.animation.minimumValue : undefined); } } } class Stroke_Stroke { constructor() { this.width = 0; } load(data) { if (data === undefined) { return; } if (data.color !== undefined) { this.color = AnimatableColor.create(this.color, data.color); } if (data.width !== undefined) { this.width = data.width; } if (data.opacity !== undefined) { this.opacity = data.opacity; } } } class TiltAnimation_TiltAnimation { constructor() { this.enable = false; this.speed = 0; this.sync = false; } load(data) { if (data === undefined) { return; } if (data.enable !== undefined) { this.enable = data.enable; } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } if (data.sync !== undefined) { this.sync = data.sync; } } } class Tilt_Tilt extends(null && ValueWithRandom){ constructor() { super(); this.animation = new TiltAnimation; this.direction = "clockwise"; this.enable = false; this.value = 0; } load(data) { if (!data) { return; } super.load(data); this.animation.load(data.animation); if (data.direction !== undefined) { this.direction = data.direction; } if (data.enable !== undefined) { this.enable = data.enable; } } } class TwinkleValues_TwinkleValues { constructor() { this.enable = false; this.frequency = .05; this.opacity = 1; } load(data) { if (data === undefined) { return; } if (data.color !== undefined) { this.color = OptionsColor.create(this.color, data.color); } if (data.enable !== undefined) { this.enable = data.enable; } if (data.frequency !== undefined) { this.frequency = data.frequency; } if (data.opacity !== undefined) { this.opacity = setRangeValue(data.opacity); } } } class Twinkle_Twinkle { constructor() { this.lines = new TwinkleValues; this.particles = new TwinkleValues; } load(data) { if (data === undefined) { return; } this.lines.load(data.lines); this.particles.load(data.particles); } } class Wobble_Wobble { constructor() { this.distance = 5; this.enable = false; this.speed = 50; } load(data) { if (!data) { return; } if (data.distance !== undefined) { this.distance = setRangeValue(data.distance); } if (data.enable !== undefined) { this.enable = data.enable; } if (data.speed !== undefined) { this.speed = setRangeValue(data.speed); } } } class ZIndex_ZIndex extends(null && ValueWithRandom){ constructor() { super(); this.opacityRate = 1; this.sizeRate = 1; this.velocityRate = 1; } load(data) { super.load(data); if (!data) { return; } if (data.opacityRate !== undefined) { this.opacityRate = data.opacityRate; } if (data.sizeRate !== undefined) { this.sizeRate = data.sizeRate; } if (data.velocityRate !== undefined) { this.velocityRate = data.velocityRate; } } } class ParticlesOptions_ParticlesOptions { constructor() { this.bounce = new Bounce; this.collisions = new Collisions; this.color = new AnimatableColor; this.destroy = new Destroy; this.gradient = []; this.groups = {}; this.life = new Life; this.links = new Links; this.move = new Move; this.number = new ParticlesNumber; this.opacity = new Opacity; this.orbit = new Orbit; this.reduceDuplicates = false; this.repulse = new Repulse; this.roll = new Roll; this.rotate = new Rotate; this.shadow = new Shadow; this.shape = new Shape; this.size = new Size; this.stroke = new Stroke; this.tilt = new Tilt; this.twinkle = new Twinkle; this.wobble = new Wobble; this.zIndex = new ZIndex; } get line_linked() { return this.links; } set line_linked(value) { this.links = value; } get lineLinked() { return this.links; } set lineLinked(value) { this.links = value; } load(data) { var _a, _b, _c, _d, _e, _f, _g, _h; if (data === undefined) { return; } this.bounce.load(data.bounce); this.color.load(AnimatableColor.create(this.color, data.color)); this.destroy.load(data.destroy); this.life.load(data.life); const links = (_b = (_a = data.links) !== null && _a !== void 0 ? _a : data.lineLinked) !== null && _b !== void 0 ? _b : data.line_linked; if (links !== undefined) { this.links.load(links); } if (data.groups !== undefined) { for (const group in data.groups) { const item = data.groups[group]; if (item !== undefined) { this.groups[group] = deepExtend((_c = this.groups[group]) !== null && _c !== void 0 ? _c : {}, item); } } } this.move.load(data.move); this.number.load(data.number); this.opacity.load(data.opacity); this.orbit.load(data.orbit); if (data.reduceDuplicates !== undefined) { this.reduceDuplicates = data.reduceDuplicates; } this.repulse.load(data.repulse); this.roll.load(data.roll); this.rotate.load(data.rotate); this.shape.load(data.shape); this.size.load(data.size); this.shadow.load(data.shadow); this.tilt.load(data.tilt); this.twinkle.load(data.twinkle); this.wobble.load(data.wobble); this.zIndex.load(data.zIndex); const collisions = (_e = (_d = data.move) === null || _d === void 0 ? void 0 : _d.collisions) !== null && _e !== void 0 ? _e : (_f = data.move) === null || _f === void 0 ? void 0 : _f.bounce; if (collisions !== undefined) { this.collisions.enable = collisions; } this.collisions.load(data.collisions); const strokeToLoad = (_g = data.stroke) !== null && _g !== void 0 ? _g : (_h = data.shape) === null || _h === void 0 ? void 0 : _h.stroke; if (strokeToLoad) { if (strokeToLoad instanceof Array) { this.stroke = strokeToLoad.map((s => { const tmp = new Stroke; tmp.load(s); return tmp; })); } else { if (this.stroke instanceof Array) { this.stroke = new Stroke; } this.stroke.load(strokeToLoad); } } const gradientToLoad = data.gradient; if (gradientToLoad) { if (gradientToLoad instanceof Array) { this.gradient = gradientToLoad.map((s => { const tmp = new AnimatableGradient; tmp.load(s); return tmp; })); } else { if (this.gradient instanceof Array) { this.gradient = new AnimatableGradient; } this.gradient.load(gradientToLoad); } } } } class Responsive_Responsive { constructor() { this.maxWidth = Infinity; this.options = {}; this.mode = "canvas"; } load(data) { if (!data) { return; } if (data.maxWidth !== undefined) { this.maxWidth = data.maxWidth; } if (data.mode !== undefined) { if (data.mode === "screen") { this.mode = "screen"; } else { this.mode = "canvas"; } } if (data.options !== undefined) { this.options = deepExtend({}, data.options); } } } class Theme_Theme { constructor() { this.name = ""; this.default = new ThemeDefault; } load(data) { if (data === undefined) { return; } if (data.name !== undefined) { this.name = data.name; } this.default.load(data.default); if (data.options !== undefined) { this.options = deepExtend({}, data.options); } } } var Options_classPrivateFieldSet = undefined && undefined.__classPrivateFieldSet || function(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var Options_classPrivateFieldGet = undefined && undefined.__classPrivateFieldGet || function(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _Options_instances, _Options_engine, _Options_findDefaultTheme; class Options_Options { constructor(engine) { _Options_instances.add(this); _Options_engine.set(this, void 0); Options_classPrivateFieldSet(this, _Options_engine, engine, "f"); this.autoPlay = true; this.background = new Background; this.backgroundMask = new BackgroundMask; this.fullScreen = new FullScreen; this.detectRetina = true; this.duration = 0; this.fpsLimit = 120; this.interactivity = new Interactivity; this.manualParticles = []; this.motion = new Motion; this.particles = new ParticlesOptions; this.pauseOnBlur = true; this.pauseOnOutsideViewport = true; this.responsive = []; this.style = {}; this.themes = []; this.zLayers = 100; } get fps_limit() { return this.fpsLimit; } set fps_limit(value) { this.fpsLimit = value; } get retina_detect() { return this.detectRetina; } set retina_detect(value) { this.detectRetina = value; } get backgroundMode() { return this.fullScreen; } set backgroundMode(value) { this.fullScreen.load(value); } load(data) { var _a, _b, _c, _d, _e; if (data === undefined) { return; } if (data.preset !== undefined) { if (data.preset instanceof Array) { for (const preset of data.preset) { this.importPreset(preset); } } else { this.importPreset(data.preset); } } if (data.autoPlay !== undefined) { this.autoPlay = data.autoPlay; } const detectRetina = (_a = data.detectRetina) !== null && _a !== void 0 ? _a : data.retina_detect; if (detectRetina !== undefined) { this.detectRetina = detectRetina; } if (data.duration !== undefined) { this.duration = data.duration; } const fpsLimit = (_b = data.fpsLimit) !== null && _b !== void 0 ? _b : data.fps_limit; if (fpsLimit !== undefined) { this.fpsLimit = fpsLimit; } if (data.pauseOnBlur !== undefined) { this.pauseOnBlur = data.pauseOnBlur; } if (data.pauseOnOutsideViewport !== undefined) { this.pauseOnOutsideViewport = data.pauseOnOutsideViewport; } if (data.zLayers !== undefined) { this.zLayers = data.zLayers; } this.background.load(data.background); const fullScreen = (_c = data.fullScreen) !== null && _c !== void 0 ? _c : data.backgroundMode; if (typeof fullScreen === "boolean") { this.fullScreen.enable = fullScreen; } else { this.fullScreen.load(fullScreen); } this.backgroundMask.load(data.backgroundMask); this.interactivity.load(data.interactivity); if (data.manualParticles !== undefined) { this.manualParticles = data.manualParticles.map((t => { const tmp = new ManualParticle; tmp.load(t); return tmp; })); } this.motion.load(data.motion); this.particles.load(data.particles); this.style = deepExtend(this.style, data.style); Options_classPrivateFieldGet(this, _Options_engine, "f").plugins.loadOptions(this, data); if (data.responsive !== undefined) { for (const responsive of data.responsive) { const optResponsive = new Responsive; optResponsive.load(responsive); this.responsive.push(optResponsive); } } this.responsive.sort(((a, b) => a.maxWidth - b.maxWidth)); if (data.themes !== undefined) { for (const theme of data.themes) { const optTheme = new Theme; optTheme.load(theme); this.themes.push(optTheme); } } this.defaultDarkTheme = (_d = Options_classPrivateFieldGet(this, _Options_instances, "m", _Options_findDefaultTheme).call(this, "dark")) === null || _d === void 0 ? void 0 : _d.name; this.defaultLightTheme = (_e = Options_classPrivateFieldGet(this, _Options_instances, "m", _Options_findDefaultTheme).call(this, "light")) === null || _e === void 0 ? void 0 : _e.name; } setTheme(name) { if (name) { const chosenTheme = this.themes.find((theme => theme.name === name)); if (chosenTheme) { this.load(chosenTheme.options); } } else { const mediaMatch = typeof matchMedia !== "undefined" && matchMedia("(prefers-color-scheme: dark)"), clientDarkMode = mediaMatch && mediaMatch.matches, defaultTheme = Options_classPrivateFieldGet(this, _Options_instances, "m", _Options_findDefaultTheme).call(this, clientDarkMode ? "dark" : "light"); if (defaultTheme) { this.load(defaultTheme.options); } } } setResponsive(width, pxRatio, defaultOptions) { this.load(defaultOptions); const responsiveOptions = this.responsive.find((t => t.mode === "screen" && screen ? t.maxWidth * pxRatio > screen.availWidth : t.maxWidth * pxRatio > width)); this.load(responsiveOptions === null || responsiveOptions === void 0 ? void 0 : responsiveOptions.options); return responsiveOptions === null || responsiveOptions === void 0 ? void 0 : responsiveOptions.maxWidth; } importPreset(preset) { this.load(Options_classPrivateFieldGet(this, _Options_engine, "f").plugins.getPreset(preset)); } } _Options_engine = new WeakMap, _Options_instances = new WeakSet, _Options_findDefaultTheme = function _Options_findDefaultTheme(mode) { var _a; return (_a = this.themes.find((theme => theme.default.value && theme.default.mode === mode))) !== null && _a !== void 0 ? _a : this.themes.find((theme => theme.default.value && theme.default.mode === "any")); }; var Particle_classPrivateFieldSet = undefined && undefined.__classPrivateFieldSet || function(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var Particle_classPrivateFieldGet = undefined && undefined.__classPrivateFieldGet || function(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _Particle_engine; const fixOutMode = data => { if (isInArray(data.outMode, data.checkModes) || isInArray(data.outMode, data.checkModes)) { if (data.coord > data.maxCoord - data.radius * 2) { data.setCb(-data.radius); } else if (data.coord < data.radius * 2) { data.setCb(data.radius); } } }; class Particle_Particle { constructor(engine, id, container, position, overrideOptions, group) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; this.id = id; this.container = container; this.group = group; _Particle_engine.set(this, void 0); Particle_classPrivateFieldSet(this, _Particle_engine, engine, "f"); this.fill = true; this.close = true; this.lastPathTime = 0; this.destroyed = false; this.unbreakable = false; this.splitCount = 0; this.misplaced = false; this.retina = { maxDistance: {} }; this.ignoresResizeRatio = true; const pxRatio = container.retina.pixelRatio; const mainOptions = container.actualOptions; const particlesOptions = new ParticlesOptions; particlesOptions.load(mainOptions.particles); const shapeType = particlesOptions.shape.type; const reduceDuplicates = particlesOptions.reduceDuplicates; this.shape = shapeType instanceof Array ? itemFromArray(shapeType, this.id, reduceDuplicates) : shapeType; if (overrideOptions === null || overrideOptions === void 0 ? void 0 : overrideOptions.shape) { if (overrideOptions.shape.type) { const overrideShapeType = overrideOptions.shape.type; this.shape = overrideShapeType instanceof Array ? itemFromArray(overrideShapeType, this.id, reduceDuplicates) : overrideShapeType; } const shapeOptions = new Shape; shapeOptions.load(overrideOptions.shape); if (this.shape) { this.shapeData = this.loadShapeData(shapeOptions, reduceDuplicates); } } else { this.shapeData = this.loadShapeData(particlesOptions.shape, reduceDuplicates); } if (overrideOptions !== undefined) { particlesOptions.load(overrideOptions); } if (((_a = this.shapeData) === null || _a === void 0 ? void 0 : _a.particles) !== undefined) { particlesOptions.load((_b = this.shapeData) === null || _b === void 0 ? void 0 : _b.particles); } this.fill = (_d = (_c = this.shapeData) === null || _c === void 0 ? void 0 : _c.fill) !== null && _d !== void 0 ? _d : this.fill; this.close = (_f = (_e = this.shapeData) === null || _e === void 0 ? void 0 : _e.close) !== null && _f !== void 0 ? _f : this.close; this.options = particlesOptions; this.pathDelay = getValue(this.options.move.path.delay) * 1e3; const zIndexValue = getRangeValue(this.options.zIndex.value); container.retina.initParticle(this); const sizeOptions = this.options.size, sizeRange = sizeOptions.value; this.size = { enable: sizeOptions.animation.enable, value: getValue(sizeOptions) * container.retina.pixelRatio, max: getRangeMax(sizeRange) * pxRatio, min: getRangeMin(sizeRange) * pxRatio, loops: 0, maxLoops: getRangeValue(sizeOptions.animation.count) }; const sizeAnimation = sizeOptions.animation; if (sizeAnimation.enable) { this.size.status = 0; switch (sizeAnimation.startValue) { case "min": this.size.value = this.size.min; this.size.status = 0; break; case "random": this.size.value = randomInRange(this.size) * pxRatio; this.size.status = Math.random() >= .5 ? 0 : 1; break; case "max": default: this.size.value = this.size.max; this.size.status = 1; break; } this.size.velocity = ((_g = this.retina.sizeAnimationSpeed) !== null && _g !== void 0 ? _g : container.retina.sizeAnimationSpeed) / 100 * container.retina.reduceFactor; if (!sizeAnimation.sync) { this.size.velocity *= Math.random(); } } this.direction = getParticleDirectionAngle(this.options.move.direction); this.bubble = { inRange: false }; this.initialVelocity = this.calculateVelocity(); this.velocity = this.initialVelocity.copy(); this.moveDecay = 1 - getRangeValue(this.options.move.decay); const gravityOptions = this.options.move.gravity; this.gravity = { enable: gravityOptions.enable, acceleration: getRangeValue(gravityOptions.acceleration), inverse: gravityOptions.inverse }; this.position = this.calcPosition(container, position, clamp(zIndexValue, 0, container.zLayers)); this.initialPosition = this.position.copy(); this.offset = Vector.origin; const particles = container.particles; particles.needsSort = particles.needsSort || particles.lastZIndex < this.position.z; particles.lastZIndex = this.position.z; this.zIndexFactor = this.position.z / container.zLayers; this.sides = 24; let drawer = container.drawers.get(this.shape); if (!drawer) { drawer = Particle_classPrivateFieldGet(this, _Particle_engine, "f").plugins.getShapeDrawer(this.shape); if (drawer) { container.drawers.set(this.shape, drawer); } } if (drawer === null || drawer === void 0 ? void 0 : drawer.loadShape) { drawer === null || drawer === void 0 ? void 0 : drawer.loadShape(this); } const sideCountFunc = drawer === null || drawer === void 0 ? void 0 : drawer.getSidesCount; if (sideCountFunc) { this.sides = sideCountFunc(this); } this.life = this.loadLife(); this.spawning = this.life.delay > 0; if (this.options.move.spin.enable) { const spinPos = (_h = this.options.move.spin.position) !== null && _h !== void 0 ? _h : { x: 50, y: 50 }; const spinCenter = { x: spinPos.x / 100 * container.canvas.size.width, y: spinPos.y / 100 * container.canvas.size.height }; const pos = this.getPosition(); const distance = getDistance(pos, spinCenter); this.spin = { center: spinCenter, direction: this.velocity.x >= 0 ? "clockwise" : "counter-clockwise", angle: this.velocity.angle, radius: distance, acceleration: (_j = this.retina.spinAcceleration) !== null && _j !== void 0 ? _j : getRangeValue(this.options.move.spin.acceleration) }; } this.shadowColor = colorToRgb(this.options.shadow.color); for (const updater of container.particles.updaters) { if (updater.init) { updater.init(this); } } if (drawer && drawer.particleInit) { drawer.particleInit(container, this); } for (const [, plugin] of container.plugins) { if (plugin.particleCreated) { plugin.particleCreated(this); } } } isVisible() { return !this.destroyed && !this.spawning && this.isInsideCanvas(); } isInsideCanvas() { const radius = this.getRadius(); const canvasSize = this.container.canvas.size; return this.position.x >= -radius && this.position.y >= -radius && this.position.y <= canvasSize.height + radius && this.position.x <= canvasSize.width + radius; } draw(delta) { const container = this.container; for (const [, plugin] of container.plugins) { container.canvas.drawParticlePlugin(plugin, this, delta); } container.canvas.drawParticle(this, delta); } getPosition() { return { x: this.position.x + this.offset.x, y: this.position.y + this.offset.y, z: this.position.z }; } getRadius() { var _a; return (_a = this.bubble.radius) !== null && _a !== void 0 ? _a : this.size.value; } getMass() { return this.getRadius() ** 2 * Math.PI / 2; } getFillColor() { var _a, _b; const color = (_a = this.bubble.color) !== null && _a !== void 0 ? _a : getHslFromAnimation(this.color); if (color && this.roll && (this.backColor || this.roll.alter)) { const backFactor = this.options.roll.mode === "both" ? 2 : 1, backSum = this.options.roll.mode === "horizontal" ? Math.PI / 2 : 0, rolled = Math.floor((((_b = this.roll.angle) !== null && _b !== void 0 ? _b : 0) + backSum) / (Math.PI / backFactor)) % 2; if (rolled) { if (this.backColor) { return this.backColor; } if (this.roll.alter) { return alterHsl(color, this.roll.alter.type, this.roll.alter.value); } } } return color; } getStrokeColor() { var _a, _b; return (_b = (_a = this.bubble.color) !== null && _a !== void 0 ? _a : getHslFromAnimation(this.strokeColor)) !== null && _b !== void 0 ? _b : this.getFillColor(); } destroy(override) { this.destroyed = true; this.bubble.inRange = false; if (this.unbreakable) { return; } this.destroyed = true; this.bubble.inRange = false; for (const [, plugin] of this.container.plugins) { if (plugin.particleDestroyed) { plugin.particleDestroyed(this, override); } } if (override) { return; } const destroyOptions = this.options.destroy; if (destroyOptions.mode === "split") { this.split(); } } reset() { if (this.opacity) { this.opacity.loops = 0; } this.size.loops = 0; } split() { const splitOptions = this.options.destroy.split; if (splitOptions.count >= 0 && this.splitCount++ > splitOptions.count) { return; } const rate = getRangeValue(splitOptions.rate.value); for (let i = 0; i < rate; i++) { this.container.particles.addSplitParticle(this); } } calcPosition(container, position, zIndex, tryCount = 0) { var _a, _b, _c, _d, _e, _f; for (const [, plugin] of container.plugins) { const pluginPos = plugin.particlePosition !== undefined ? plugin.particlePosition(position, this) : undefined; if (pluginPos !== undefined) { return Vector3d.create(pluginPos.x, pluginPos.y, zIndex); } } const canvasSize = container.canvas.size; const pos = Vector3d.create((_a = position === null || position === void 0 ? void 0 : position.x) !== null && _a !== void 0 ? _a : Math.random() * canvasSize.width, (_b = position === null || position === void 0 ? void 0 : position.y) !== null && _b !== void 0 ? _b : Math.random() * canvasSize.height, zIndex); const radius = this.getRadius(); const outModes = this.options.move.outModes, fixHorizontal = outMode => { fixOutMode({ outMode: outMode, checkModes: [ "bounce", "bounce-horizontal" ], coord: pos.x, maxCoord: container.canvas.size.width, setCb: value => pos.x += value, radius: radius }); }, fixVertical = outMode => { fixOutMode({ outMode: outMode, checkModes: [ "bounce", "bounce-vertical" ], coord: pos.y, maxCoord: container.canvas.size.height, setCb: value => pos.y += value, radius: radius }); }; fixHorizontal((_c = outModes.left) !== null && _c !== void 0 ? _c : outModes.default); fixHorizontal((_d = outModes.right) !== null && _d !== void 0 ? _d : outModes.default); fixVertical((_e = outModes.top) !== null && _e !== void 0 ? _e : outModes.default); fixVertical((_f = outModes.bottom) !== null && _f !== void 0 ? _f : outModes.default); if (this.checkOverlap(pos, tryCount)) { return this.calcPosition(container, undefined, zIndex, tryCount + 1); } return pos; } checkOverlap(pos, tryCount = 0) { const collisionsOptions = this.options.collisions; const radius = this.getRadius(); if (!collisionsOptions.enable) { return false; } const overlapOptions = collisionsOptions.overlap; if (overlapOptions.enable) { return false; } const retries = overlapOptions.retries; if (retries >= 0 && tryCount > retries) { throw new Error("Particle is overlapping and can't be placed"); } let overlaps = false; for (const particle of this.container.particles.array) { if (getDistance(pos, particle.position) < radius + particle.getRadius()) { overlaps = true; break; } } return overlaps; } calculateVelocity() { const baseVelocity = getParticleBaseVelocity(this.direction), res = baseVelocity.copy(), moveOptions = this.options.move, rad = Math.PI / 180 * getRangeValue(moveOptions.angle.value), radOffset = Math.PI / 180 * getRangeValue(moveOptions.angle.offset), range = { left: radOffset - rad / 2, right: radOffset + rad / 2 }; if (!moveOptions.straight) { res.angle += randomInRange(setRangeValue(range.left, range.right)); } if (moveOptions.random && typeof moveOptions.speed === "number") { res.length *= Math.random(); } return res; } loadShapeData(shapeOptions, reduceDuplicates) { const shapeData = shapeOptions.options[this.shape]; if (shapeData) { return deepExtend({}, shapeData instanceof Array ? itemFromArray(shapeData, this.id, reduceDuplicates) : shapeData); } } loadLife() { const container = this.container; const particlesOptions = this.options; const lifeOptions = particlesOptions.life; const life = { delay: container.retina.reduceFactor ? getRangeValue(lifeOptions.delay.value) * (lifeOptions.delay.sync ? 1 : Math.random()) / container.retina.reduceFactor * 1e3 : 0, delayTime: 0, duration: container.retina.reduceFactor ? getRangeValue(lifeOptions.duration.value) * (lifeOptions.duration.sync ? 1 : Math.random()) / container.retina.reduceFactor * 1e3 : 0, time: 0, count: particlesOptions.life.count }; if (life.duration <= 0) { life.duration = -1; } if (life.count <= 0) { life.count = -1; } return life; } } _Particle_engine = new WeakMap; var Particles_classPrivateFieldSet = undefined && undefined.__classPrivateFieldSet || function(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var Particles_classPrivateFieldGet = undefined && undefined.__classPrivateFieldGet || function(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _Particles_engine; class Particles_Particles { constructor(engine, container) { this.container = container; _Particles_engine.set(this, void 0); Particles_classPrivateFieldSet(this, _Particles_engine, engine, "f"); this.nextId = 0; this.array = []; this.zArray = []; this.mover = new ParticlesMover(container); this.limit = 0; this.needsSort = false; this.lastZIndex = 0; this.freqs = { links: new Map, triangles: new Map }; this.interactionManager = new InteractionManager(Particles_classPrivateFieldGet(this, _Particles_engine, "f"), container); const canvasSize = this.container.canvas.size; this.linksColors = new Map; this.quadTree = new QuadTree(new Rectangle(-canvasSize.width / 4, -canvasSize.height / 4, canvasSize.width * 3 / 2, canvasSize.height * 3 / 2), 4); this.updaters = Particles_classPrivateFieldGet(this, _Particles_engine, "f").plugins.getUpdaters(container, true); } get count() { return this.array.length; } init() { var _a; const container = this.container; const options = container.actualOptions; this.lastZIndex = 0; this.needsSort = false; this.freqs.links = new Map; this.freqs.triangles = new Map; let handled = false; this.updaters = Particles_classPrivateFieldGet(this, _Particles_engine, "f").plugins.getUpdaters(container, true); this.interactionManager.init(); for (const [, plugin] of container.plugins) { if (plugin.particlesInitialization !== undefined) { handled = plugin.particlesInitialization(); } if (handled) { break; } } this.addManualParticles(); if (!handled) { for (const group in options.particles.groups) { const groupOptions = options.particles.groups[group]; for (let i = this.count, j = 0; j < ((_a = groupOptions.number) === null || _a === void 0 ? void 0 : _a.value) && i < options.particles.number.value; i++, j++) { this.addParticle(undefined, groupOptions, group); } } for (let i = this.count; i < options.particles.number.value; i++) { this.addParticle(); } } container.pathGenerator.init(container); } async redraw() { this.clear(); this.init(); await this.draw({ value: 0, factor: 0 }); } removeAt(index, quantity = 1, group, override) { if (!(index >= 0 && index <= this.count)) { return; } let deleted = 0; for (let i = index; deleted < quantity && i < this.count; i++) { const particle = this.array[i]; if (!particle || particle.group !== group) { continue; } particle.destroy(override); this.array.splice(i--, 1); const zIdx = this.zArray.indexOf(particle); this.zArray.splice(zIdx, 1); deleted++; } } remove(particle, group, override) { this.removeAt(this.array.indexOf(particle), undefined, group, override); } async update(delta) { const container = this.container; const particlesToDelete = []; container.pathGenerator.update(); for (const [, plugin] of container.plugins) { if (plugin.update !== undefined) { plugin.update(delta); } } for (const particle of this.array) { const resizeFactor = container.canvas.resizeFactor; if (resizeFactor && !particle.ignoresResizeRatio) { particle.position.x *= resizeFactor.width; particle.position.y *= resizeFactor.height; } particle.ignoresResizeRatio = false; particle.bubble.inRange = false; for (const [, plugin] of this.container.plugins) { if (particle.destroyed) { break; } if (plugin.particleUpdate) { plugin.particleUpdate(particle, delta); } } this.mover.move(particle, delta); if (particle.destroyed) { particlesToDelete.push(particle); continue; } this.quadTree.insert(new Point(particle.getPosition(), particle)); } for (const particle of particlesToDelete) { this.remove(particle); } await this.interactionManager.externalInteract(delta); for (const particle of container.particles.array) { for (const updater of this.updaters) { updater.update(particle, delta); } if (!particle.destroyed && !particle.spawning) { await this.interactionManager.particlesInteract(particle, delta); } } delete container.canvas.resizeFactor; } async draw(delta) { const container = this.container; container.canvas.clear(); const canvasSize = this.container.canvas.size; this.quadTree = new QuadTree(new Rectangle(-canvasSize.width / 4, -canvasSize.height / 4, canvasSize.width * 3 / 2, canvasSize.height * 3 / 2), 4); await this.update(delta); if (this.needsSort) { this.zArray.sort(((a, b) => b.position.z - a.position.z || a.id - b.id)); this.lastZIndex = this.zArray[this.zArray.length - 1].position.z; this.needsSort = false; } for (const [, plugin] of container.plugins) { container.canvas.drawPlugin(plugin, delta); } for (const p of this.zArray) { p.draw(delta); } } clear() { this.array = []; this.zArray = []; } push(nb, mouse, overrideOptions, group) { this.pushing = true; for (let i = 0; i < nb; i++) { this.addParticle(mouse === null || mouse === void 0 ? void 0 : mouse.position, overrideOptions, group); } this.pushing = false; } addParticle(position, overrideOptions, group) { const container = this.container, options = container.actualOptions, limit = options.particles.number.limit * container.density; if (limit > 0) { const countToRemove = this.count + 1 - limit; if (countToRemove > 0) { this.removeQuantity(countToRemove); } } return this.pushParticle(position, overrideOptions, group); } addSplitParticle(parent) { const splitOptions = parent.options.destroy.split, options = new ParticlesOptions; options.load(parent.options); const factor = getRangeValue(splitOptions.factor.value); options.color.load({ value: { hsl: parent.getFillColor() } }); if (typeof options.size.value === "number") { options.size.value /= factor; } else { options.size.value.min /= factor; options.size.value.max /= factor; } options.load(splitOptions.particles); const offset = splitOptions.sizeOffset ? setRangeValue(-parent.size.value, parent.size.value) : 0; const position = { x: parent.position.x + randomInRange(offset), y: parent.position.y + randomInRange(offset) }; return this.pushParticle(position, options, parent.group, (particle => { if (particle.size.value < .5) { return false; } particle.velocity.length = randomInRange(setRangeValue(parent.velocity.length, particle.velocity.length)); particle.splitCount = parent.splitCount + 1; particle.unbreakable = true; setTimeout((() => { particle.unbreakable = false; }), 500); return true; })); } removeQuantity(quantity, group) { this.removeAt(0, quantity, group); } getLinkFrequency(p1, p2) { const range = setRangeValue(p1.id, p2.id), key = `${getRangeMin(range)}_${getRangeMax(range)}`; let res = this.freqs.links.get(key); if (res === undefined) { res = Math.random(); this.freqs.links.set(key, res); } return res; } getTriangleFrequency(p1, p2, p3) { let [id1, id2, id3] = [ p1.id, p2.id, p3.id ]; if (id1 > id2) { [id2, id1] = [ id1, id2 ]; } if (id2 > id3) { [id3, id2] = [ id2, id3 ]; } if (id1 > id3) { [id3, id1] = [ id1, id3 ]; } const key = `${id1}_${id2}_${id3}`; let res = this.freqs.triangles.get(key); if (res === undefined) { res = Math.random(); this.freqs.triangles.set(key, res); } return res; } addManualParticles() { const container = this.container, options = container.actualOptions; for (const particle of options.manualParticles) { const pos = particle.position ? { x: particle.position.x * container.canvas.size.width / 100, y: particle.position.y * container.canvas.size.height / 100 } : undefined; this.addParticle(pos, particle.options); } } setDensity() { const options = this.container.actualOptions; for (const group in options.particles.groups) { this.applyDensity(options.particles.groups[group], 0, group); } this.applyDensity(options.particles, options.manualParticles.length); } applyDensity(options, manualCount, group) { var _a; if (!((_a = options.number.density) === null || _a === void 0 ? void 0 : _a.enable)) { return; } const numberOptions = options.number; const densityFactor = this.initDensityFactor(numberOptions.density); const optParticlesNumber = numberOptions.value; const optParticlesLimit = numberOptions.limit > 0 ? numberOptions.limit : optParticlesNumber; const particlesNumber = Math.min(optParticlesNumber, optParticlesLimit) * densityFactor + manualCount; const particlesCount = Math.min(this.count, this.array.filter((t => t.group === group)).length); this.limit = numberOptions.limit * densityFactor; if (particlesCount < particlesNumber) { this.push(Math.abs(particlesNumber - particlesCount), undefined, options, group); } else if (particlesCount > particlesNumber) { this.removeQuantity(particlesCount - particlesNumber, group); } } initDensityFactor(densityOptions) { const container = this.container; if (!container.canvas.element || !densityOptions.enable) { return 1; } const canvas = container.canvas.element, pxRatio = container.retina.pixelRatio; return canvas.width * canvas.height / (densityOptions.factor * pxRatio ** 2 * densityOptions.area); } pushParticle(position, overrideOptions, group, initializer) { try { const particle = new Particle(Particles_classPrivateFieldGet(this, _Particles_engine, "f"), this.nextId, this.container, position, overrideOptions, group); let canAdd = true; if (initializer) { canAdd = initializer(particle); } if (!canAdd) { return; } this.array.push(particle); this.zArray.push(particle); this.nextId++; return particle; } catch (e) { console.warn(`error adding particle: ${e}`); return; } } } _Particles_engine = new WeakMap; class Retina_Retina { constructor(container) { this.container = container; } init() { const container = this.container; const options = container.actualOptions; this.pixelRatio = !options.detectRetina || isSsr() ? 1 : window.devicePixelRatio; const motionOptions = this.container.actualOptions.motion; if (motionOptions && (motionOptions.disable || motionOptions.reduce.value)) { if (isSsr() || typeof matchMedia === "undefined" || !matchMedia) { this.reduceFactor = 1; } else { const mediaQuery = matchMedia("(prefers-reduced-motion: reduce)"); if (mediaQuery) { this.handleMotionChange(mediaQuery); const handleChange = () => { this.handleMotionChange(mediaQuery); container.refresh().catch((() => {})); }; if (mediaQuery.addEventListener !== undefined) { mediaQuery.addEventListener("change", handleChange); } else if (mediaQuery.addListener !== undefined) { mediaQuery.addListener(handleChange); } } } } else { this.reduceFactor = 1; } const ratio = this.pixelRatio; if (container.canvas.element) { const element = container.canvas.element; container.canvas.size.width = element.offsetWidth * ratio; container.canvas.size.height = element.offsetHeight * ratio; } const particles = options.particles; this.attractDistance = getRangeValue(particles.move.attract.distance) * ratio; this.linksDistance = particles.links.distance * ratio; this.linksWidth = particles.links.width * ratio; this.sizeAnimationSpeed = getRangeValue(particles.size.animation.speed) * ratio; this.maxSpeed = getRangeValue(particles.move.gravity.maxSpeed) * ratio; if (particles.orbit.radius !== undefined) { this.orbitRadius = getRangeValue(particles.orbit.radius) * this.container.retina.pixelRatio; } const modes = options.interactivity.modes; this.connectModeDistance = modes.connect.distance * ratio; this.connectModeRadius = modes.connect.radius * ratio; this.grabModeDistance = modes.grab.distance * ratio; this.repulseModeDistance = modes.repulse.distance * ratio; this.bounceModeDistance = modes.bounce.distance * ratio; this.attractModeDistance = modes.attract.distance * ratio; this.slowModeRadius = modes.slow.radius * ratio; this.bubbleModeDistance = modes.bubble.distance * ratio; if (modes.bubble.size) { this.bubbleModeSize = modes.bubble.size * ratio; } } initParticle(particle) { const options = particle.options; const ratio = this.pixelRatio; const moveDistance = options.move.distance; const props = particle.retina; props.attractDistance = getRangeValue(options.move.attract.distance) * ratio; props.linksDistance = options.links.distance * ratio; props.linksWidth = options.links.width * ratio; props.moveDrift = getRangeValue(options.move.drift) * ratio; props.moveSpeed = getRangeValue(options.move.speed) * ratio; props.sizeAnimationSpeed = getRangeValue(options.size.animation.speed) * ratio; if (particle.spin) { props.spinAcceleration = getRangeValue(options.move.spin.acceleration) * ratio; } const maxDistance = props.maxDistance; maxDistance.horizontal = moveDistance.horizontal !== undefined ? moveDistance.horizontal * ratio : undefined; maxDistance.vertical = moveDistance.vertical !== undefined ? moveDistance.vertical * ratio : undefined; props.maxSpeed = getRangeValue(options.move.gravity.maxSpeed) * ratio; } handleMotionChange(mediaQuery) { const options = this.container.actualOptions; if (mediaQuery.matches) { const motion = options.motion; this.reduceFactor = motion.disable ? 0 : motion.reduce.value ? 1 / motion.reduce.factor : 1; } else { this.reduceFactor = 1; } } } var Container_classPrivateFieldSet = undefined && undefined.__classPrivateFieldSet || function(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var Container_classPrivateFieldGet = undefined && undefined.__classPrivateFieldGet || function(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _Container_engine; class Container_Container { constructor(engine, id, sourceOptions, ...presets) { this.id = id; _Container_engine.set(this, void 0); Container_classPrivateFieldSet(this, _Container_engine, engine, "f"); this.fpsLimit = 120; this.duration = 0; this.lifeTime = 0; this.firstStart = true; this.started = false; this.destroyed = false; this.paused = true; this.lastFrameTime = 0; this.zLayers = 100; this.pageHidden = false; this._sourceOptions = sourceOptions; this._initialSourceOptions = sourceOptions; this.retina = new Retina(this); this.canvas = new Canvas(this); this.particles = new Particles(Container_classPrivateFieldGet(this, _Container_engine, "f"), this); this.drawer = new FrameManager(this); this.presets = presets; this.pathGenerator = { generate: () => { const v = Vector.create(0, 0); v.length = Math.random(); v.angle = Math.random() * Math.PI * 2; return v; }, init: () => {}, update: () => {} }; this.interactivity = { mouse: { clicking: false, inside: false } }; this.bubble = {}; this.repulse = { particles: [] }; this.attract = { particles: [] }; this.plugins = new Map; this.drawers = new Map; this.density = 1; this._options = new Options(Container_classPrivateFieldGet(this, _Container_engine, "f")); this.actualOptions = new Options(Container_classPrivateFieldGet(this, _Container_engine, "f")); this.eventListeners = new EventListeners(this); if (typeof IntersectionObserver !== "undefined" && IntersectionObserver) { this.intersectionObserver = new IntersectionObserver((entries => this.intersectionManager(entries))); } } get options() { return this._options; } get sourceOptions() { return this._sourceOptions; } play(force) { const needsUpdate = this.paused || force; if (this.firstStart && !this.actualOptions.autoPlay) { this.firstStart = false; return; } if (this.paused) { this.paused = false; } if (needsUpdate) { for (const [, plugin] of this.plugins) { if (plugin.play) { plugin.play(); } } } this.draw(needsUpdate || false); } pause() { if (this.drawAnimationFrame !== undefined) { cancelAnimation()(this.drawAnimationFrame); delete this.drawAnimationFrame; } if (this.paused) { return; } for (const [, plugin] of this.plugins) { if (plugin.pause) { plugin.pause(); } } if (!this.pageHidden) { this.paused = true; } } draw(force) { let refreshTime = force; this.drawAnimationFrame = animate()((async timestamp => { if (refreshTime) { this.lastFrameTime = undefined; refreshTime = false; } await this.drawer.nextFrame(timestamp); })); } getAnimationStatus() { return !this.paused && !this.pageHidden; } setNoise(noiseOrGenerator, init, update) { this.setPath(noiseOrGenerator, init, update); } setPath(pathOrGenerator, init, update) { var _a, _b, _c; if (!pathOrGenerator) { return; } if (typeof pathOrGenerator === "function") { this.pathGenerator.generate = pathOrGenerator; if (init) { this.pathGenerator.init = init; } if (update) { this.pathGenerator.update = update; } } else { const oldGenerator = this.pathGenerator; this.pathGenerator = pathOrGenerator; (_a = this.pathGenerator).generate || (_a.generate = oldGenerator.generate); (_b = this.pathGenerator).init || (_b.init = oldGenerator.init); (_c = this.pathGenerator).update || (_c.update = oldGenerator.update); } } destroy() { this.stop(); this.canvas.destroy(); for (const [, drawer] of this.drawers) { if (drawer.destroy) { drawer.destroy(this); } } for (const key of this.drawers.keys()) { this.drawers.delete(key); } this.destroyed = true; } exportImg(callback) { this.exportImage(callback); } exportImage(callback, type, quality) { var _a; return (_a = this.canvas.element) === null || _a === void 0 ? void 0 : _a.toBlob(callback, type !== null && type !== void 0 ? type : "image/png", quality); } exportConfiguration() { return JSON.stringify(this.actualOptions, undefined, 2); } refresh() { this.stop(); return this.start(); } reset() { this._options = new Options(Container_classPrivateFieldGet(this, _Container_engine, "f")); return this.refresh(); } stop() { if (!this.started) { return; } this.firstStart = true; this.started = false; this.eventListeners.removeListeners(); this.pause(); this.particles.clear(); this.canvas.clear(); if (this.interactivity.element instanceof HTMLElement && this.intersectionObserver) { this.intersectionObserver.unobserve(this.interactivity.element); } for (const [, plugin] of this.plugins) { if (plugin.stop) { plugin.stop(); } } for (const key of this.plugins.keys()) { this.plugins.delete(key); } this.particles.linksColors = new Map; delete this.particles.grabLineColor; delete this.particles.linksColor; this._sourceOptions = this._options; } async loadTheme(name) { this.currentTheme = name; await this.refresh(); } async start() { if (this.started) { return; } await this.init(); this.started = true; this.eventListeners.addListeners(); if (this.interactivity.element instanceof HTMLElement && this.intersectionObserver) { this.intersectionObserver.observe(this.interactivity.element); } for (const [, plugin] of this.plugins) { if (plugin.startAsync !== undefined) { await plugin.startAsync(); } else if (plugin.start !== undefined) { plugin.start(); } } this.play(); } addClickHandler(callback) { const el = this.interactivity.element; if (!el) { return; } const clickOrTouchHandler = (e, pos, radius) => { if (this.destroyed) { return; } const pxRatio = this.retina.pixelRatio, posRetina = { x: pos.x * pxRatio, y: pos.y * pxRatio }, particles = this.particles.quadTree.queryCircle(posRetina, radius * pxRatio); callback(e, particles); }; const clickHandler = e => { if (this.destroyed) { return; } const mouseEvent = e; const pos = { x: mouseEvent.offsetX || mouseEvent.clientX, y: mouseEvent.offsetY || mouseEvent.clientY }; clickOrTouchHandler(e, pos, 1); }; const touchStartHandler = () => { if (this.destroyed) { return; } touched = true; touchMoved = false; }; const touchMoveHandler = () => { if (this.destroyed) { return; } touchMoved = true; }; const touchEndHandler = e => { var _a, _b, _c; if (this.destroyed) { return; } if (touched && !touchMoved) { const touchEvent = e; let lastTouch = touchEvent.touches[touchEvent.touches.length - 1]; if (!lastTouch) { lastTouch = touchEvent.changedTouches[touchEvent.changedTouches.length - 1]; if (!lastTouch) { return; } } const canvasRect = (_a = this.canvas.element) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect(); const pos = { x: lastTouch.clientX - ((_b = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.left) !== null && _b !== void 0 ? _b : 0), y: lastTouch.clientY - ((_c = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.top) !== null && _c !== void 0 ? _c : 0) }; clickOrTouchHandler(e, pos, Math.max(lastTouch.radiusX, lastTouch.radiusY)); } touched = false; touchMoved = false; }; const touchCancelHandler = () => { if (this.destroyed) { return; } touched = false; touchMoved = false; }; let touched = false; let touchMoved = false; el.addEventListener("click", clickHandler); el.addEventListener("touchstart", touchStartHandler); el.addEventListener("touchmove", touchMoveHandler); el.addEventListener("touchend", touchEndHandler); el.addEventListener("touchcancel", touchCancelHandler); } updateActualOptions() { this.actualOptions.responsive = []; const newMaxWidth = this.actualOptions.setResponsive(this.canvas.size.width, this.retina.pixelRatio, this._options); this.actualOptions.setTheme(this.currentTheme); if (this.responsiveMaxWidth != newMaxWidth) { this.responsiveMaxWidth = newMaxWidth; return true; } return false; } async init() { this._options = new Options(Container_classPrivateFieldGet(this, _Container_engine, "f")); for (const preset of this.presets) { this._options.load(Container_classPrivateFieldGet(this, _Container_engine, "f").plugins.getPreset(preset)); } const shapes = Container_classPrivateFieldGet(this, _Container_engine, "f").plugins.getSupportedShapes(); for (const type of shapes) { const drawer = Container_classPrivateFieldGet(this, _Container_engine, "f").plugins.getShapeDrawer(type); if (drawer) { this.drawers.set(type, drawer); } } this._options.load(this._initialSourceOptions); this._options.load(this._sourceOptions); this.actualOptions = new Options(Container_classPrivateFieldGet(this, _Container_engine, "f")); this.actualOptions.load(this._options); this.retina.init(); this.canvas.init(); this.updateActualOptions(); this.canvas.initBackground(); this.canvas.resize(); this.zLayers = this.actualOptions.zLayers; this.duration = getRangeValue(this.actualOptions.duration); this.lifeTime = 0; this.fpsLimit = this.actualOptions.fpsLimit > 0 ? this.actualOptions.fpsLimit : 120; const availablePlugins = Container_classPrivateFieldGet(this, _Container_engine, "f").plugins.getAvailablePlugins(this); for (const [id, plugin] of availablePlugins) { this.plugins.set(id, plugin); } for (const [, drawer] of this.drawers) { if (drawer.init) { await drawer.init(this); } } for (const [, plugin] of this.plugins) { if (plugin.init) { plugin.init(this.actualOptions); } else if (plugin.initAsync !== undefined) { await plugin.initAsync(this.actualOptions); } } const pathOptions = this.actualOptions.particles.move.path; if (pathOptions.generator) { this.setPath(Container_classPrivateFieldGet(this, _Container_engine, "f").plugins.getPathGenerator(pathOptions.generator)); } this.particles.init(); this.particles.setDensity(); for (const [, plugin] of this.plugins) { if (plugin.particlesSetup !== undefined) { plugin.particlesSetup(); } } } intersectionManager(entries) { if (!this.actualOptions.pauseOnOutsideViewport) { return; } for (const entry of entries) { if (entry.target !== this.interactivity.element) { continue; } if (entry.isIntersecting) { this.play(); } else { this.pause(); } } } } _Container_engine = new WeakMap; var Loader_classPrivateFieldSet = undefined && undefined.__classPrivateFieldSet || function(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var Loader_classPrivateFieldGet = undefined && undefined.__classPrivateFieldGet || function(receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _Loader_engine; function fetchError(statusCode) { console.error(`Error tsParticles - fetch status: ${statusCode}`); console.error("Error tsParticles - File config not found"); } class Loader { constructor(engine) { _Loader_engine.set(this, void 0); Loader_classPrivateFieldSet(this, _Loader_engine, engine, "f"); } dom() { return Loader_classPrivateFieldGet(this, _Loader_engine, "f").domArray; } domItem(index) { const dom = this.dom(); const item = dom[index]; if (item && !item.destroyed) { return item; } dom.splice(index, 1); } async loadOptions(params) { var _a, _b, _c; const tagId = (_a = params.tagId) !== null && _a !== void 0 ? _a : `tsparticles${Math.floor(Math.random() * 1e4)}`; const {options: options, index: index} = params; let domContainer = (_b = params.element) !== null && _b !== void 0 ? _b : document.getElementById(tagId); if (!domContainer) { domContainer = document.createElement("div"); domContainer.id = tagId; (_c = document.querySelector("body")) === null || _c === void 0 ? void 0 : _c.append(domContainer); } const currentOptions = options instanceof Array ? itemFromArray(options, index) : options; const dom = this.dom(); const oldIndex = dom.findIndex((v => v.id === tagId)); if (oldIndex >= 0) { const old = this.domItem(oldIndex); if (old && !old.destroyed) { old.destroy(); dom.splice(oldIndex, 1); } } let canvasEl; if (domContainer.tagName.toLowerCase() === "canvas") { canvasEl = domContainer; canvasEl.dataset[Constants.generatedAttribute] = "false"; } else { const existingCanvases = domContainer.getElementsByTagName("canvas"); if (existingCanvases.length) { canvasEl = existingCanvases[0]; canvasEl.dataset[Constants.generatedAttribute] = "false"; } else { canvasEl = document.createElement("canvas"); canvasEl.dataset[Constants.generatedAttribute] = "true"; canvasEl.style.width = "100%"; canvasEl.style.height = "100%"; domContainer.appendChild(canvasEl); } } const newItem = new Container(Loader_classPrivateFieldGet(this, _Loader_engine, "f"), tagId, currentOptions); if (oldIndex >= 0) { dom.splice(oldIndex, 0, newItem); } else { dom.push(newItem); } newItem.canvas.loadCanvas(canvasEl); await newItem.start(); return newItem; } async loadRemoteOptions(params) { const {url: jsonUrl, index: index} = params; const url = jsonUrl instanceof Array ? itemFromArray(jsonUrl, index) : jsonUrl; if (!url) { return; } const response = await fetch(url); if (!response.ok) { fetchError(response.status); return; } const data = await response.json(); return this.loadOptions({ tagId: params.tagId, element: params.element, index: index, options: data }); } load(tagId, options, index) { const params = { index: index }; if (typeof tagId === "string") { params.tagId = tagId; } else { params.options = tagId; } if (typeof options === "number") { params.index = options !== null && options !== void 0 ? options : params.index; } else { params.options = options !== null && options !== void 0 ? options : params.options; } return this.loadOptions(params); } async set(id, domContainer, options, index) { const params = { index: index }; if (typeof id === "string") { params.tagId = id; } else { params.element = id; } if (domContainer instanceof HTMLElement) { params.element = domContainer; } else { params.options = domContainer; } if (typeof options === "number") { params.index = options; } else { params.options = options !== null && options !== void 0 ? options : params.options; } return this.loadOptions(params); } async loadJSON(tagId, jsonUrl, index) { let url, id; if (typeof jsonUrl === "number" || jsonUrl === undefined) { url = tagId; } else { id = tagId; url = jsonUrl; } return this.loadRemoteOptions({ tagId: id, url: url, index: index }); } async setJSON(id, domContainer, jsonUrl, index) { let url, newId, newIndex, element; if (id instanceof HTMLElement) { element = id; url = domContainer; newIndex = jsonUrl; } else { newId = id; element = domContainer; url = jsonUrl; newIndex = index; } return this.loadRemoteOptions({ tagId: newId, url: url, index: newIndex, element: element }); } setOnClickHandler(callback) { const dom = this.dom(); if (dom.length === 0) { throw new Error("Can only set click handlers after calling tsParticles.load() or tsParticles.loadJSON()"); } for (const domItem of dom) { domItem.addClickHandler(callback); } } } _Loader_engine = new WeakMap; function NumberUtils_clamp(num, min, max) { return Math.min(Math.max(num, min), max); } function NumberUtils_mix(comp1, comp2, weight1, weight2) { return Math.floor((comp1 * weight1 + comp2 * weight2) / (weight1 + weight2)); } function NumberUtils_randomInRange(r) { const max = NumberUtils_getRangeMax(r); let min = NumberUtils_getRangeMin(r); if (max === min) { min = 0; } return Math.random() * (max - min) + min; } function NumberUtils_getRangeValue(value) { return typeof value === "number" ? value : NumberUtils_randomInRange(value); } function NumberUtils_getRangeMin(value) { return typeof value === "number" ? value : value.min; } function NumberUtils_getRangeMax(value) { return typeof value === "number" ? value : value.max; } function NumberUtils_setRangeValue(source, value) { if (source === value || value === undefined && typeof source === "number") { return source; } const min = NumberUtils_getRangeMin(source), max = NumberUtils_getRangeMax(source); return value !== undefined ? { min: Math.min(min, value), max: Math.max(max, value) } : NumberUtils_setRangeValue(min, max); } function NumberUtils_getValue(options) { const random = options.random; const {enable: enable, minimumValue: minimumValue} = typeof random === "boolean" ? { enable: random, minimumValue: 0 } : random; return enable ? NumberUtils_getRangeValue(NumberUtils_setRangeValue(options.value, minimumValue)) : NumberUtils_getRangeValue(options.value); } function NumberUtils_getDistances(pointA, pointB) { const dx = pointA.x - pointB.x; const dy = pointA.y - pointB.y; return { dx: dx, dy: dy, distance: Math.sqrt(dx * dx + dy * dy) }; } function NumberUtils_getDistance(pointA, pointB) { return NumberUtils_getDistances(pointA, pointB).distance; } function NumberUtils_getParticleDirectionAngle(direction) { if (typeof direction === "number") { return direction * Math.PI / 180; } else { switch (direction) { case "top": return -Math.PI / 2; case "top-right": return -Math.PI / 4; case "right": return 0; case "bottom-right": return Math.PI / 4; case "bottom": return Math.PI / 2; case "bottom-left": return 3 * Math.PI / 4; case "left": return Math.PI; case "top-left": return -3 * Math.PI / 4; case "none": default: return Math.random() * Math.PI * 2; } } } function NumberUtils_getParticleBaseVelocity(direction) { const baseVelocity = Vector.origin; baseVelocity.length = 1; baseVelocity.angle = direction; return baseVelocity; } function NumberUtils_collisionVelocity(v1, v2, m1, m2) { return Vector.create(v1.x * (m1 - m2) / (m1 + m2) + v2.x * 2 * m2 / (m1 + m2), v1.y); } function calcEasing(value, type) { switch (type) { case "ease-out-quad": return 1 - (1 - value) ** 2; case "ease-out-cubic": return 1 - (1 - value) ** 3; case "ease-out-quart": return 1 - (1 - value) ** 4; case "ease-out-quint": return 1 - (1 - value) ** 5; case "ease-out-expo": return value === 1 ? 1 : 1 - Math.pow(2, -10 * value); case "ease-out-sine": return Math.sin(value * Math.PI / 2); case "ease-out-back": { const c1 = 1.70158; const c3 = c1 + 1; return 1 + c3 * Math.pow(value - 1, 3) + c1 * Math.pow(value - 1, 2); } case "ease-out-circ": return Math.sqrt(1 - Math.pow(value - 1, 2)); default: return value; } } function rectSideBounce(pSide, pOtherSide, rectSide, rectOtherSide, velocity, factor) { const res = { bounced: false }; if (pOtherSide.min >= rectOtherSide.min && pOtherSide.min <= rectOtherSide.max && pOtherSide.max >= rectOtherSide.min && pOtherSide.max <= rectOtherSide.max) { if (pSide.max >= rectSide.min && pSide.max <= (rectSide.max + rectSide.min) / 2 && velocity > 0 || pSide.min <= rectSide.max && pSide.min > (rectSide.max + rectSide.min) / 2 && velocity < 0) { res.velocity = velocity * -factor; res.bounced = true; } } return res; } function checkSelector(element, selectors) { if (selectors instanceof Array) { for (const selector of selectors) { if (element.matches(selector)) { return true; } } return false; } else { return element.matches(selectors); } } function Utils_isSsr() { return typeof window === "undefined" || !window || typeof window.document === "undefined" || !window.document; } function Utils_animate() { return Utils_isSsr() ? callback => setTimeout(callback) : callback => (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || window.setTimeout)(callback); } function Utils_cancelAnimation() { return Utils_isSsr() ? handle => clearTimeout(handle) : handle => (window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.clearTimeout)(handle); } function Utils_isInArray(value, array) { return value === array || array instanceof Array && array.indexOf(value) > -1; } async function loadFont(character) { var _a, _b; try { await document.fonts.load(`${(_a = character.weight) !== null && _a !== void 0 ? _a : "400"} 36px '${(_b = character.font) !== null && _b !== void 0 ? _b : "Verdana"}'`); } catch (_c) {} } function arrayRandomIndex(array) { return Math.floor(Math.random() * array.length); } function Utils_itemFromArray(array, index, useIndex = true) { const fixedIndex = index !== undefined && useIndex ? index % array.length : arrayRandomIndex(array); return array[fixedIndex]; } function isPointInside(point, size, radius, direction) { return areBoundsInside(calculateBounds(point, radius !== null && radius !== void 0 ? radius : 0), size, direction); } function areBoundsInside(bounds, size, direction) { let inside = true; if (!direction || direction === "bottom") { inside = bounds.top < size.height; } if (inside && (!direction || direction === "left")) { inside = bounds.right > 0; } if (inside && (!direction || direction === "right")) { inside = bounds.left < size.width; } if (inside && (!direction || direction === "top")) { inside = bounds.bottom > 0; } return inside; } function calculateBounds(point, radius) { return { bottom: point.y + radius, left: point.x - radius, right: point.x + radius, top: point.y - radius }; } function Utils_deepExtend(destination, ...sources) { for (const source of sources) { if (source === undefined || source === null) { continue; } if (typeof source !== "object") { destination = source; continue; } const sourceIsArray = Array.isArray(source); if (sourceIsArray && (typeof destination !== "object" || !destination || !Array.isArray(destination))) { destination = []; } else if (!sourceIsArray && (typeof destination !== "object" || !destination || Array.isArray(destination))) { destination = {}; } for (const key in source) { if (key === "__proto__") { continue; } const sourceDict = source; const value = sourceDict[key]; const isObject = typeof value === "object"; const destDict = destination; destDict[key] = isObject && Array.isArray(value) ? value.map((v => Utils_deepExtend(destDict[key], v))) : Utils_deepExtend(destDict[key], value); } } return destination; } function isDivModeEnabled(mode, divs) { return divs instanceof Array ? !!divs.find((t => t.enable && Utils_isInArray(mode, t.mode))) : Utils_isInArray(mode, divs.mode); } function divModeExecute(mode, divs, callback) { if (divs instanceof Array) { for (const div of divs) { const divMode = div.mode; const divEnabled = div.enable; if (divEnabled && Utils_isInArray(mode, divMode)) { singleDivModeExecute(div, callback); } } } else { const divMode = divs.mode; const divEnabled = divs.enable; if (divEnabled && Utils_isInArray(mode, divMode)) { singleDivModeExecute(divs, callback); } } } function singleDivModeExecute(div, callback) { const selectors = div.selectors; if (selectors instanceof Array) { for (const selector of selectors) { callback(selector, div); } } else { callback(selectors, div); } } function divMode(divs, element) { if (!element || !divs) { return; } if (divs instanceof Array) { return divs.find((d => checkSelector(element, d.selectors))); } else if (checkSelector(element, divs.selectors)) { return divs; } } function circleBounceDataFromParticle(p) { return { position: p.getPosition(), radius: p.getRadius(), mass: p.getMass(), velocity: p.velocity, factor: Vector.create(getValue(p.options.bounce.horizontal), getValue(p.options.bounce.vertical)) }; } function circleBounce(p1, p2) { const {x: xVelocityDiff, y: yVelocityDiff} = p1.velocity.sub(p2.velocity); const [pos1, pos2] = [ p1.position, p2.position ]; const {dx: xDist, dy: yDist} = getDistances(pos2, pos1); if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) { const angle = -Math.atan2(yDist, xDist); const m1 = p1.mass; const m2 = p2.mass; const u1 = p1.velocity.rotate(angle); const u2 = p2.velocity.rotate(angle); const v1 = collisionVelocity(u1, u2, m1, m2); const v2 = collisionVelocity(u2, u1, m1, m2); const vFinal1 = v1.rotate(-angle); const vFinal2 = v2.rotate(-angle); p1.velocity.x = vFinal1.x * p1.factor.x; p1.velocity.y = vFinal1.y * p1.factor.y; p2.velocity.x = vFinal2.x * p2.factor.x; p2.velocity.y = vFinal2.y * p2.factor.y; } } function rectBounce(particle, divBounds) { const pPos = particle.getPosition(); const size = particle.getRadius(); const bounds = calculateBounds(pPos, size); const resH = rectSideBounce({ min: bounds.left, max: bounds.right }, { min: bounds.top, max: bounds.bottom }, { min: divBounds.left, max: divBounds.right }, { min: divBounds.top, max: divBounds.bottom }, particle.velocity.x, getValue(particle.options.bounce.horizontal)); if (resH.bounced) { if (resH.velocity !== undefined) { particle.velocity.x = resH.velocity; } if (resH.position !== undefined) { particle.position.x = resH.position; } } const resV = rectSideBounce({ min: bounds.top, max: bounds.bottom }, { min: bounds.left, max: bounds.right }, { min: divBounds.top, max: divBounds.bottom }, { min: divBounds.left, max: divBounds.right }, particle.velocity.y, getValue(particle.options.bounce.vertical)); if (resV.bounced) { if (resV.velocity !== undefined) { particle.velocity.y = resV.velocity; } if (resV.position !== undefined) { particle.position.y = resV.position; } } } function hue2rgb(p, q, t) { let tCalc = t; if (tCalc < 0) { tCalc += 1; } if (tCalc > 1) { tCalc -= 1; } if (tCalc < 1 / 6) { return p + (q - p) * 6 * tCalc; } if (tCalc < 1 / 2) { return q; } if (tCalc < 2 / 3) { return p + (q - p) * (2 / 3 - tCalc) * 6; } return p; } function stringToRgba(input) { if (input.startsWith("rgb")) { const regex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([\d.]+)\s*)?\)/i; const result = regex.exec(input); return result ? { a: result.length > 4 ? parseFloat(result[5]) : 1, b: parseInt(result[3], 10), g: parseInt(result[2], 10), r: parseInt(result[1], 10) } : undefined; } else if (input.startsWith("hsl")) { const regex = /hsla?\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([\d.]+)\s*)?\)/i; const result = regex.exec(input); return result ? hslaToRgba({ a: result.length > 4 ? parseFloat(result[5]) : 1, h: parseInt(result[1], 10), l: parseInt(result[3], 10), s: parseInt(result[2], 10) }) : undefined; } else if (input.startsWith("hsv")) { const regex = /hsva?\(\s*(\d+)°\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([\d.]+)\s*)?\)/i; const result = regex.exec(input); return result ? hsvaToRgba({ a: result.length > 4 ? parseFloat(result[5]) : 1, h: parseInt(result[1], 10), s: parseInt(result[2], 10), v: parseInt(result[3], 10) }) : undefined; } else { const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i; const hexFixed = input.replace(shorthandRegex, ((_m, r, g, b, a) => r + r + g + g + b + b + (a !== undefined ? a + a : ""))); const regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i; const result = regex.exec(hexFixed); return result ? { a: result[4] !== undefined ? parseInt(result[4], 16) / 255 : 1, b: parseInt(result[3], 16), g: parseInt(result[2], 16), r: parseInt(result[1], 16) } : undefined; } } function ColorUtils_colorToRgb(input, index, useIndex = true) { var _a, _b, _c; if (input === undefined) { return; } const color = typeof input === "string" ? { value: input } : input; let res; if (typeof color.value === "string") { if (color.value === Constants.randomColorValue) { res = getRandomRgbColor(); } else { res = stringToRgb(color.value); } } else { if (color.value instanceof Array) { const colorSelected = itemFromArray(color.value, index, useIndex); res = ColorUtils_colorToRgb({ value: colorSelected }); } else { const colorValue = color.value; const rgbColor = (_a = colorValue.rgb) !== null && _a !== void 0 ? _a : color.value; if (rgbColor.r !== undefined) { res = rgbColor; } else { const hslColor = (_b = colorValue.hsl) !== null && _b !== void 0 ? _b : color.value; if (hslColor.h !== undefined && hslColor.l !== undefined) { res = hslToRgb(hslColor); } else { const hsvColor = (_c = colorValue.hsv) !== null && _c !== void 0 ? _c : color.value; if (hsvColor.h !== undefined && hsvColor.v !== undefined) { res = hsvToRgb(hsvColor); } } } } } return res; } function ColorUtils_colorToHsl(color, index, useIndex = true) { const rgb = ColorUtils_colorToRgb(color, index, useIndex); return rgb !== undefined ? rgbToHsl(rgb) : undefined; } function rgbToHsl(color) { const r1 = color.r / 255; const g1 = color.g / 255; const b1 = color.b / 255; const max = Math.max(r1, g1, b1); const min = Math.min(r1, g1, b1); const res = { h: 0, l: (max + min) / 2, s: 0 }; if (max != min) { res.s = res.l < .5 ? (max - min) / (max + min) : (max - min) / (2 - max - min); res.h = r1 === max ? (g1 - b1) / (max - min) : res.h = g1 === max ? 2 + (b1 - r1) / (max - min) : 4 + (r1 - g1) / (max - min); } res.l *= 100; res.s *= 100; res.h *= 60; if (res.h < 0) { res.h += 360; } return res; } function stringToAlpha(input) { var _a; return (_a = stringToRgba(input)) === null || _a === void 0 ? void 0 : _a.a; } function stringToRgb(input) { return stringToRgba(input); } function hslToRgb(hsl) { const result = { b: 0, g: 0, r: 0 }; const hslPercent = { h: hsl.h / 360, l: hsl.l / 100, s: hsl.s / 100 }; if (hslPercent.s === 0) { result.b = hslPercent.l; result.g = hslPercent.l; result.r = hslPercent.l; } else { const q = hslPercent.l < .5 ? hslPercent.l * (1 + hslPercent.s) : hslPercent.l + hslPercent.s - hslPercent.l * hslPercent.s; const p = 2 * hslPercent.l - q; result.r = hue2rgb(p, q, hslPercent.h + 1 / 3); result.g = hue2rgb(p, q, hslPercent.h); result.b = hue2rgb(p, q, hslPercent.h - 1 / 3); } result.r = Math.floor(result.r * 255); result.g = Math.floor(result.g * 255); result.b = Math.floor(result.b * 255); return result; } function hslaToRgba(hsla) { const rgbResult = hslToRgb(hsla); return { a: hsla.a, b: rgbResult.b, g: rgbResult.g, r: rgbResult.r }; } function hslToHsv(hsl) { const l = hsl.l / 100, sl = hsl.s / 100; const v = l + sl * Math.min(l, 1 - l), sv = !v ? 0 : 2 * (1 - l / v); return { h: hsl.h, s: sv * 100, v: v * 100 }; } function hslaToHsva(hsla) { const hsvResult = hslToHsv(hsla); return { a: hsla.a, h: hsvResult.h, s: hsvResult.s, v: hsvResult.v }; } function hsvToHsl(hsv) { const v = hsv.v / 100, sv = hsv.s / 100; const l = v * (1 - sv / 2), sl = l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l); return { h: hsv.h, l: l * 100, s: sl * 100 }; } function hsvaToHsla(hsva) { const hslResult = hsvToHsl(hsva); return { a: hsva.a, h: hslResult.h, l: hslResult.l, s: hslResult.s }; } function hsvToRgb(hsv) { const result = { b: 0, g: 0, r: 0 }; const hsvPercent = { h: hsv.h / 60, s: hsv.s / 100, v: hsv.v / 100 }; const c = hsvPercent.v * hsvPercent.s, x = c * (1 - Math.abs(hsvPercent.h % 2 - 1)); let tempRgb; if (hsvPercent.h >= 0 && hsvPercent.h <= 1) { tempRgb = { r: c, g: x, b: 0 }; } else if (hsvPercent.h > 1 && hsvPercent.h <= 2) { tempRgb = { r: x, g: c, b: 0 }; } else if (hsvPercent.h > 2 && hsvPercent.h <= 3) { tempRgb = { r: 0, g: c, b: x }; } else if (hsvPercent.h > 3 && hsvPercent.h <= 4) { tempRgb = { r: 0, g: x, b: c }; } else if (hsvPercent.h > 4 && hsvPercent.h <= 5) { tempRgb = { r: x, g: 0, b: c }; } else if (hsvPercent.h > 5 && hsvPercent.h <= 6) { tempRgb = { r: c, g: 0, b: x }; } if (tempRgb) { const m = hsvPercent.v - c; result.r = Math.floor((tempRgb.r + m) * 255); result.g = Math.floor((tempRgb.g + m) * 255); result.b = Math.floor((tempRgb.b + m) * 255); } return result; } function hsvaToRgba(hsva) { const rgbResult = hsvToRgb(hsva); return { a: hsva.a, b: rgbResult.b, g: rgbResult.g, r: rgbResult.r }; } function rgbToHsv(rgb) { const rgbPercent = { r: rgb.r / 255, g: rgb.g / 255, b: rgb.b / 255 }, xMax = Math.max(rgbPercent.r, rgbPercent.g, rgbPercent.b), xMin = Math.min(rgbPercent.r, rgbPercent.g, rgbPercent.b), v = xMax, c = xMax - xMin; let h = 0; if (v === rgbPercent.r) { h = 60 * ((rgbPercent.g - rgbPercent.b) / c); } else if (v === rgbPercent.g) { h = 60 * (2 + (rgbPercent.b - rgbPercent.r) / c); } else if (v === rgbPercent.b) { h = 60 * (4 + (rgbPercent.r - rgbPercent.g) / c); } const s = !v ? 0 : c / v; return { h: h, s: s * 100, v: v * 100 }; } function rgbaToHsva(rgba) { const hsvResult = rgbToHsv(rgba); return { a: rgba.a, h: hsvResult.h, s: hsvResult.s, v: hsvResult.v }; } function getRandomRgbColor(min) { const fixedMin = min !== null && min !== void 0 ? min : 0; return { b: Math.floor(randomInRange(setRangeValue(fixedMin, 256))), g: Math.floor(randomInRange(setRangeValue(fixedMin, 256))), r: Math.floor(randomInRange(setRangeValue(fixedMin, 256))) }; } function ColorUtils_getStyleFromRgb(color, opacity) { return `rgba(${color.r}, ${color.g}, ${color.b}, ${opacity !== null && opacity !== void 0 ? opacity : 1})`; } function ColorUtils_getStyleFromHsl(color, opacity) { return `hsla(${color.h}, ${color.s}%, ${color.l}%, ${opacity !== null && opacity !== void 0 ? opacity : 1})`; } function getStyleFromHsv(color, opacity) { return ColorUtils_getStyleFromHsl(hsvToHsl(color), opacity); } function ColorUtils_colorMix(color1, color2, size1, size2) { let rgb1 = color1; let rgb2 = color2; if (rgb1.r === undefined) { rgb1 = hslToRgb(color1); } if (rgb2.r === undefined) { rgb2 = hslToRgb(color2); } return { b: mix(rgb1.b, rgb2.b, size1, size2), g: mix(rgb1.g, rgb2.g, size1, size2), r: mix(rgb1.r, rgb2.r, size1, size2) }; } function getLinkColor(p1, p2, linkColor) { var _a, _b; if (linkColor === Constants.randomColorValue) { return getRandomRgbColor(); } else if (linkColor === "mid") { const sourceColor = (_a = p1.getFillColor()) !== null && _a !== void 0 ? _a : p1.getStrokeColor(); const destColor = (_b = p2 === null || p2 === void 0 ? void 0 : p2.getFillColor()) !== null && _b !== void 0 ? _b : p2 === null || p2 === void 0 ? void 0 : p2.getStrokeColor(); if (sourceColor && destColor && p2) { return ColorUtils_colorMix(sourceColor, destColor, p1.getRadius(), p2.getRadius()); } else { const hslColor = sourceColor !== null && sourceColor !== void 0 ? sourceColor : destColor; if (hslColor) { return hslToRgb(hslColor); } } } else { return linkColor; } } function getLinkRandomColor(optColor, blink, consent) { const color = typeof optColor === "string" ? optColor : optColor.value; if (color === Constants.randomColorValue) { if (consent) { return ColorUtils_colorToRgb({ value: color }); } else if (blink) { return Constants.randomColorValue; } else { return Constants.midColorValue; } } else { return ColorUtils_colorToRgb({ value: color }); } } function ColorUtils_getHslFromAnimation(animation) { return animation !== undefined ? { h: animation.h.value, s: animation.s.value, l: animation.l.value } : undefined; } function getHslAnimationFromHsl(hsl, animationOptions, reduceFactor) { const resColor = { h: { enable: false, value: hsl.h }, s: { enable: false, value: hsl.s }, l: { enable: false, value: hsl.l } }; if (animationOptions) { setColorAnimation(resColor.h, animationOptions.h, reduceFactor); setColorAnimation(resColor.s, animationOptions.s, reduceFactor); setColorAnimation(resColor.l, animationOptions.l, reduceFactor); } return resColor; } function setColorAnimation(colorValue, colorAnimation, reduceFactor) { colorValue.enable = colorAnimation.enable; if (colorValue.enable) { colorValue.velocity = getRangeValue(colorAnimation.speed) / 100 * reduceFactor; if (colorAnimation.sync) { return; } colorValue.status = 0; colorValue.velocity *= Math.random(); if (colorValue.value) { colorValue.value *= Math.random(); } } else { colorValue.velocity = 0; } } function drawLine(context, begin, end) { context.beginPath(); context.moveTo(begin.x, begin.y); context.lineTo(end.x, end.y); context.closePath(); } function drawTriangle(context, p1, p2, p3) { context.beginPath(); context.moveTo(p1.x, p1.y); context.lineTo(p2.x, p2.y); context.lineTo(p3.x, p3.y); context.closePath(); } function CanvasUtils_paintBase(context, dimension, baseColor) { context.save(); context.fillStyle = baseColor !== null && baseColor !== void 0 ? baseColor : "rgba(0,0,0,0)"; context.fillRect(0, 0, dimension.width, dimension.height); context.restore(); } function CanvasUtils_clear(context, dimension) { context.clearRect(0, 0, dimension.width, dimension.height); } function drawLinkLine(context, width, begin, end, maxDistance, canvasSize, warp, backgroundMask, composite, colorLine, opacity, shadow) { let drawn = false; if (getDistance(begin, end) <= maxDistance) { drawLine(context, begin, end); drawn = true; } else if (warp) { let pi1; let pi2; const endNE = { x: end.x - canvasSize.width, y: end.y }; const d1 = getDistances(begin, endNE); if (d1.distance <= maxDistance) { const yi = begin.y - d1.dy / d1.dx * begin.x; pi1 = { x: 0, y: yi }; pi2 = { x: canvasSize.width, y: yi }; } else { const endSW = { x: end.x, y: end.y - canvasSize.height }; const d2 = getDistances(begin, endSW); if (d2.distance <= maxDistance) { const yi = begin.y - d2.dy / d2.dx * begin.x; const xi = -yi / (d2.dy / d2.dx); pi1 = { x: xi, y: 0 }; pi2 = { x: xi, y: canvasSize.height }; } else { const endSE = { x: end.x - canvasSize.width, y: end.y - canvasSize.height }; const d3 = getDistances(begin, endSE); if (d3.distance <= maxDistance) { const yi = begin.y - d3.dy / d3.dx * begin.x; const xi = -yi / (d3.dy / d3.dx); pi1 = { x: xi, y: yi }; pi2 = { x: pi1.x + canvasSize.width, y: pi1.y + canvasSize.height }; } } } if (pi1 && pi2) { drawLine(context, begin, pi1); drawLine(context, end, pi2); drawn = true; } } if (!drawn) { return; } context.lineWidth = width; if (backgroundMask) { context.globalCompositeOperation = composite; } context.strokeStyle = getStyleFromRgb(colorLine, opacity); if (shadow.enable) { const shadowColor = colorToRgb(shadow.color); if (shadowColor) { context.shadowBlur = shadow.blur; context.shadowColor = getStyleFromRgb(shadowColor); } } context.stroke(); } function drawLinkTriangle(context, pos1, pos2, pos3, backgroundMask, composite, colorTriangle, opacityTriangle) { drawTriangle(context, pos1, pos2, pos3); if (backgroundMask) { context.globalCompositeOperation = composite; } context.fillStyle = getStyleFromRgb(colorTriangle, opacityTriangle); context.fill(); } function CanvasUtils_drawConnectLine(context, width, lineStyle, begin, end) { context.save(); drawLine(context, begin, end); context.lineWidth = width; context.strokeStyle = lineStyle; context.stroke(); context.restore(); } function CanvasUtils_gradient(context, p1, p2, opacity) { const gradStop = Math.floor(p2.getRadius() / p1.getRadius()); const color1 = p1.getFillColor(); const color2 = p2.getFillColor(); if (!color1 || !color2) { return; } const sourcePos = p1.getPosition(); const destPos = p2.getPosition(); const midRgb = colorMix(color1, color2, p1.getRadius(), p2.getRadius()); const grad = context.createLinearGradient(sourcePos.x, sourcePos.y, destPos.x, destPos.y); grad.addColorStop(0, getStyleFromHsl(color1, opacity)); grad.addColorStop(gradStop > 1 ? 1 : gradStop, getStyleFromRgb(midRgb, opacity)); grad.addColorStop(1, getStyleFromHsl(color2, opacity)); return grad; } function CanvasUtils_drawGrabLine(context, width, begin, end, colorLine, opacity) { context.save(); drawLine(context, begin, end); context.strokeStyle = getStyleFromRgb(colorLine, opacity); context.lineWidth = width; context.stroke(); context.restore(); } function CanvasUtils_drawParticle(container, context, particle, delta, fillColorValue, strokeColorValue, backgroundMask, composite, radius, opacity, shadow, gradient) { var _a, _b, _c, _d, _e, _f; const pos = particle.getPosition(); const tiltOptions = particle.options.tilt; const rollOptions = particle.options.roll; context.save(); if (tiltOptions.enable || rollOptions.enable) { const roll = rollOptions.enable && particle.roll; const tilt = tiltOptions.enable && particle.tilt; const rollHorizontal = roll && (rollOptions.mode === "horizontal" || rollOptions.mode === "both"); const rollVertical = roll && (rollOptions.mode === "vertical" || rollOptions.mode === "both"); context.setTransform(rollHorizontal ? Math.cos(particle.roll.angle) : 1, tilt ? Math.cos(particle.tilt.value) * particle.tilt.cosDirection : 0, tilt ? Math.sin(particle.tilt.value) * particle.tilt.sinDirection : 0, rollVertical ? Math.sin(particle.roll.angle) : 1, pos.x, pos.y); } else { context.translate(pos.x, pos.y); } context.beginPath(); const angle = ((_b = (_a = particle.rotate) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 0) + (particle.options.rotate.path ? particle.velocity.angle : 0); if (angle !== 0) { context.rotate(angle); } if (backgroundMask) { context.globalCompositeOperation = composite; } const shadowColor = particle.shadowColor; if (shadow.enable && shadowColor) { context.shadowBlur = shadow.blur; context.shadowColor = getStyleFromRgb(shadowColor); context.shadowOffsetX = shadow.offset.x; context.shadowOffsetY = shadow.offset.y; } if (gradient) { const gradientAngle = gradient.angle.value; const fillGradient = gradient.type === "radial" ? context.createRadialGradient(0, 0, 0, 0, 0, radius) : context.createLinearGradient(Math.cos(gradientAngle) * -radius, Math.sin(gradientAngle) * -radius, Math.cos(gradientAngle) * radius, Math.sin(gradientAngle) * radius); for (const color of gradient.colors) { fillGradient.addColorStop(color.stop, getStyleFromHsl({ h: color.value.h.value, s: color.value.s.value, l: color.value.l.value }, (_d = (_c = color.opacity) === null || _c === void 0 ? void 0 : _c.value) !== null && _d !== void 0 ? _d : opacity)); } context.fillStyle = fillGradient; } else { if (fillColorValue) { context.fillStyle = fillColorValue; } } const stroke = particle.stroke; context.lineWidth = (_e = particle.strokeWidth) !== null && _e !== void 0 ? _e : 0; if (strokeColorValue) { context.strokeStyle = strokeColorValue; } drawShape(container, context, particle, radius, opacity, delta); if (((_f = stroke === null || stroke === void 0 ? void 0 : stroke.width) !== null && _f !== void 0 ? _f : 0) > 0) { context.stroke(); } if (particle.close) { context.closePath(); } if (particle.fill) { context.fill(); } context.restore(); context.save(); if (tiltOptions.enable && particle.tilt) { context.setTransform(1, Math.cos(particle.tilt.value) * particle.tilt.cosDirection, Math.sin(particle.tilt.value) * particle.tilt.sinDirection, 1, pos.x, pos.y); } else { context.translate(pos.x, pos.y); } if (angle !== 0) { context.rotate(angle); } if (backgroundMask) { context.globalCompositeOperation = composite; } drawShapeAfterEffect(container, context, particle, radius, opacity, delta); context.restore(); } function drawShape(container, context, particle, radius, opacity, delta) { if (!particle.shape) { return; } const drawer = container.drawers.get(particle.shape); if (!drawer) { return; } drawer.draw(context, particle, radius, opacity, delta, container.retina.pixelRatio); } function drawShapeAfterEffect(container, context, particle, radius, opacity, delta) { if (!particle.shape) { return; } const drawer = container.drawers.get(particle.shape); if (!(drawer === null || drawer === void 0 ? void 0 : drawer.afterEffect)) { return; } drawer.afterEffect(context, particle, radius, opacity, delta, container.retina.pixelRatio); } function CanvasUtils_drawPlugin(context, plugin, delta) { if (!plugin.draw) { return; } context.save(); plugin.draw(context, delta); context.restore(); } function CanvasUtils_drawParticlePlugin(context, plugin, particle, delta) { if (plugin.drawParticle !== undefined) { context.save(); plugin.drawParticle(context, particle, delta); context.restore(); } } function drawEllipse(context, particle, fillColorValue, radius, opacity, width, rotation, start, end) { const pos = particle.getPosition(); if (fillColorValue) { context.strokeStyle = getStyleFromHsl(fillColorValue, opacity); } if (width === 0) { return; } context.lineWidth = width; const rotationRadian = rotation * Math.PI / 180; context.beginPath(); context.ellipse(pos.x, pos.y, radius / 2, radius * 2, rotationRadian, start, end); context.stroke(); } function CanvasUtils_alterHsl(color, type, value) { return { h: color.h, s: color.s, l: color.l + (type === "darken" ? -1 : 1) * value }; } function checkDestroy(particle, value, minValue, maxValue) { switch (particle.options.size.animation.destroy) { case "max": if (value >= maxValue) { particle.destroy(); } break; case "min": if (value <= minValue) { particle.destroy(); } break; } } function updateSize(particle, delta) { var _a, _b, _c, _d; const sizeVelocity = ((_a = particle.size.velocity) !== null && _a !== void 0 ? _a : 0) * delta.factor; const minValue = particle.size.min; const maxValue = particle.size.max; if (particle.destroyed || !particle.size.enable || ((_b = particle.size.maxLoops) !== null && _b !== void 0 ? _b : 0) > 0 && ((_c = particle.size.loops) !== null && _c !== void 0 ? _c : 0) > ((_d = particle.size.maxLoops) !== null && _d !== void 0 ? _d : 0)) { return; } switch (particle.size.status) { case 0: if (particle.size.value >= maxValue) { particle.size.status = 1; if (!particle.size.loops) { particle.size.loops = 0; } particle.size.loops++; } else { particle.size.value += sizeVelocity; } break; case 1: if (particle.size.value <= minValue) { particle.size.status = 0; if (!particle.size.loops) { particle.size.loops = 0; } particle.size.loops++; } else { particle.size.value -= sizeVelocity; } } checkDestroy(particle, particle.size.value, minValue, maxValue); if (!particle.destroyed) { particle.size.value = NumberUtils_clamp(particle.size.value, minValue, maxValue); } } class SizeUpdater { init() {} isEnabled(particle) { var _a, _b, _c, _d; return !particle.destroyed && !particle.spawning && particle.size.enable && (((_a = particle.size.maxLoops) !== null && _a !== void 0 ? _a : 0) <= 0 || ((_b = particle.size.maxLoops) !== null && _b !== void 0 ? _b : 0) > 0 && ((_c = particle.size.loops) !== null && _c !== void 0 ? _c : 0) < ((_d = particle.size.maxLoops) !== null && _d !== void 0 ? _d : 0)); } update(particle, delta) { if (!this.isEnabled(particle)) { return; } updateSize(particle, delta); } } async function loadSizeUpdater(engine) { await engine.addParticleUpdater("size", (() => new SizeUpdater)); } return __webpack_exports__; }(); }));
/*! * pinia v2.0.11 * (c) 2022 Eduardo San Martin Morote * @license MIT */ var Pinia = (function (exports, vueDemi) { 'use strict'; /** * setActivePinia must be called to handle SSR at the top of functions like * `fetch`, `setup`, `serverPrefetch` and others */ let activePinia; /** * Sets or unsets the active pinia. Used in SSR and internally when calling * actions and getters * * @param pinia - Pinia instance */ const setActivePinia = (pinia) => (activePinia = pinia); /** * Get the currently active pinia if there is any. */ const getActivePinia = () => (vueDemi.getCurrentInstance() && vueDemi.inject(piniaSymbol)) || activePinia; const piniaSymbol = (Symbol('pinia') ); function getDevtoolsGlobalHook() { return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__; } function getTarget() { // @ts-ignore return (typeof navigator !== 'undefined' && typeof window !== 'undefined') ? window : typeof global !== 'undefined' ? global : {}; } const isProxyAvailable = typeof Proxy === 'function'; const HOOK_SETUP = 'devtools-plugin:setup'; const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set'; class ApiProxy { constructor(plugin, hook) { this.target = null; this.targetQueue = []; this.onQueue = []; this.plugin = plugin; this.hook = hook; const defaultSettings = {}; if (plugin.settings) { for (const id in plugin.settings) { const item = plugin.settings[id]; defaultSettings[id] = item.defaultValue; } } const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`; let currentSettings = Object.assign({}, defaultSettings); try { const raw = localStorage.getItem(localSettingsSaveId); const data = JSON.parse(raw); Object.assign(currentSettings, data); } catch (e) { // noop } this.fallbacks = { getSettings() { return currentSettings; }, setSettings(value) { try { localStorage.setItem(localSettingsSaveId, JSON.stringify(value)); } catch (e) { // noop } currentSettings = value; }, }; if (hook) { hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => { if (pluginId === this.plugin.id) { this.fallbacks.setSettings(value); } }); } this.proxiedOn = new Proxy({}, { get: (_target, prop) => { if (this.target) { return this.target.on[prop]; } else { return (...args) => { this.onQueue.push({ method: prop, args, }); }; } }, }); this.proxiedTarget = new Proxy({}, { get: (_target, prop) => { if (this.target) { return this.target[prop]; } else if (prop === 'on') { return this.proxiedOn; } else if (Object.keys(this.fallbacks).includes(prop)) { return (...args) => { this.targetQueue.push({ method: prop, args, resolve: () => { }, }); return this.fallbacks[prop](...args); }; } else { return (...args) => { return new Promise(resolve => { this.targetQueue.push({ method: prop, args, resolve, }); }); }; } }, }); } async setRealTarget(target) { this.target = target; for (const item of this.onQueue) { this.target.on[item.method](...item.args); } for (const item of this.targetQueue) { item.resolve(await this.target[item.method](...item.args)); } } } function setupDevtoolsPlugin(pluginDescriptor, setupFn) { const target = getTarget(); const hook = getDevtoolsGlobalHook(); const enableProxy = isProxyAvailable && pluginDescriptor.enableEarlyProxy; if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) { hook.emit(HOOK_SETUP, pluginDescriptor, setupFn); } else { const proxy = enableProxy ? new ApiProxy(pluginDescriptor, hook) : null; const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || []; list.push({ pluginDescriptor, setupFn, proxy, }); if (proxy) setupFn(proxy.proxiedTarget); } } function isPlainObject( // eslint-disable-next-line @typescript-eslint/no-explicit-any o) { return (o && typeof o === 'object' && Object.prototype.toString.call(o) === '[object Object]' && typeof o.toJSON !== 'function'); } // type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]> } // TODO: can we change these to numbers? /** * Possible types for SubscriptionCallback */ exports.MutationType = void 0; (function (MutationType) { /** * Direct mutation of the state: * * - `store.name = 'new name'` * - `store.$state.name = 'new name'` * - `store.list.push('new item')` */ MutationType["direct"] = "direct"; /** * Mutated the state with `$patch` and an object * * - `store.$patch({ name: 'newName' })` */ MutationType["patchObject"] = "patch object"; /** * Mutated the state with `$patch` and a function * * - `store.$patch(state => state.name = 'newName')` */ MutationType["patchFunction"] = "patch function"; // maybe reset? for $state = {} and $reset })(exports.MutationType || (exports.MutationType = {})); const IS_CLIENT = typeof window !== 'undefined'; /* * FileSaver.js A saveAs() FileSaver implementation. * * Originally by Eli Grey, adapted as an ESM module by Eduardo San Martin * Morote. * * License : MIT */ // The one and only way of getting global scope in all environments // https://stackoverflow.com/q/3277182/1008999 const _global = /*#__PURE__*/ (() => typeof window === 'object' && window.window === window ? window : typeof self === 'object' && self.self === self ? self : typeof global === 'object' && global.global === global ? global : typeof globalThis === 'object' ? globalThis : { HTMLElement: null })(); function bom(blob, { autoBom = false } = {}) { // prepend BOM for UTF-8 XML and text/* types (including HTML) // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF if (autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type }); } return blob; } function download(url, name, opts) { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'blob'; xhr.onload = function () { saveAs(xhr.response, name, opts); }; xhr.onerror = function () { console.error('could not download file'); }; xhr.send(); } function corsEnabled(url) { const xhr = new XMLHttpRequest(); // use sync to avoid popup blocker xhr.open('HEAD', url, false); try { xhr.send(); } catch (e) { } return xhr.status >= 200 && xhr.status <= 299; } // `a.click()` doesn't work for all browsers (#465) function click(node) { try { node.dispatchEvent(new MouseEvent('click')); } catch (e) { const evt = document.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); node.dispatchEvent(evt); } } const _navigator = typeof navigator === 'object' ? navigator : { userAgent: '' }; // Detect WebView inside a native macOS app by ruling out all browsers // We just need to check for 'Safari' because all other browsers (besides Firefox) include that too // https://www.whatismybrowser.com/guides/the-latest-user-agent/macos const isMacOSWebView = /*#__PURE__*/ (() => /Macintosh/.test(_navigator.userAgent) && /AppleWebKit/.test(_navigator.userAgent) && !/Safari/.test(_navigator.userAgent))(); const saveAs = !IS_CLIENT ? () => { } // noop : // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program typeof HTMLAnchorElement !== 'undefined' && 'download' in HTMLAnchorElement.prototype && !isMacOSWebView ? downloadSaveAs : // Use msSaveOrOpenBlob as a second approach 'msSaveOrOpenBlob' in _navigator ? msSaveAs : // Fallback to using FileReader and a popup fileSaverSaveAs; function downloadSaveAs(blob, name = 'download', opts) { const a = document.createElement('a'); a.download = name; a.rel = 'noopener'; // tabnabbing // TODO: detect chrome extensions & packaged apps // a.target = '_blank' if (typeof blob === 'string') { // Support regular links a.href = blob; if (a.origin !== location.origin) { if (corsEnabled(a.href)) { download(blob, name, opts); } else { a.target = '_blank'; click(a); } } else { click(a); } } else { // Support blobs a.href = URL.createObjectURL(blob); setTimeout(function () { URL.revokeObjectURL(a.href); }, 4e4); // 40s setTimeout(function () { click(a); }, 0); } } function msSaveAs(blob, name = 'download', opts) { if (typeof blob === 'string') { if (corsEnabled(blob)) { download(blob, name, opts); } else { const a = document.createElement('a'); a.href = blob; a.target = '_blank'; setTimeout(function () { click(a); }); } } else { // @ts-ignore: works on windows navigator.msSaveOrOpenBlob(bom(blob, opts), name); } } function fileSaverSaveAs(blob, name, opts, popup) { // Open a popup immediately do go around popup blocker // Mostly only available on user interaction and the fileReader is async so... popup = popup || open('', '_blank'); if (popup) { popup.document.title = popup.document.body.innerText = 'downloading...'; } if (typeof blob === 'string') return download(blob, name, opts); const force = blob.type === 'application/octet-stream'; const isSafari = /constructor/i.test(String(_global.HTMLElement)) || 'safari' in _global; const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent); if ((isChromeIOS || (force && isSafari) || isMacOSWebView) && typeof FileReader !== 'undefined') { // Safari doesn't allow downloading of blob URLs const reader = new FileReader(); reader.onloadend = function () { let url = reader.result; if (typeof url !== 'string') { popup = null; throw new Error('Wrong reader.result type'); } url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, 'data:attachment/file;'); if (popup) { popup.location.href = url; } else { location.assign(url); } popup = null; // reverse-tabnabbing #460 }; reader.readAsDataURL(blob); } else { const url = URL.createObjectURL(blob); if (popup) popup.location.assign(url); else location.href = url; popup = null; // reverse-tabnabbing #460 setTimeout(function () { URL.revokeObjectURL(url); }, 4e4); // 40s } } /** * Shows a toast or console.log * * @param message - message to log * @param type - different color of the tooltip */ function toastMessage(message, type) { const piniaMessage = '🍍 ' + message; if (typeof __VUE_DEVTOOLS_TOAST__ === 'function') { __VUE_DEVTOOLS_TOAST__(piniaMessage, type); } else if (type === 'error') { console.error(piniaMessage); } else if (type === 'warn') { console.warn(piniaMessage); } else { console.log(piniaMessage); } } function isPinia(o) { return '_a' in o && 'install' in o; } function checkClipboardAccess() { if (!('clipboard' in navigator)) { toastMessage(`Your browser doesn't support the Clipboard API`, 'error'); return true; } } function checkNotFocusedError(error) { if (error instanceof Error && error.message.toLowerCase().includes('document is not focused')) { toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', 'warn'); return true; } return false; } async function actionGlobalCopyState(pinia) { if (checkClipboardAccess()) return; try { await navigator.clipboard.writeText(JSON.stringify(pinia.state.value)); toastMessage('Global state copied to clipboard.'); } catch (error) { if (checkNotFocusedError(error)) return; toastMessage(`Failed to serialize the state. Check the console for more details.`, 'error'); console.error(error); } } async function actionGlobalPasteState(pinia) { if (checkClipboardAccess()) return; try { pinia.state.value = JSON.parse(await navigator.clipboard.readText()); toastMessage('Global state pasted from clipboard.'); } catch (error) { if (checkNotFocusedError(error)) return; toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, 'error'); console.error(error); } } async function actionGlobalSaveState(pinia) { try { saveAs(new Blob([JSON.stringify(pinia.state.value)], { type: 'text/plain;charset=utf-8', }), 'pinia-state.json'); } catch (error) { toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error'); console.error(error); } } let fileInput; function getFileOpener() { if (!fileInput) { fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = '.json'; } function openFile() { return new Promise((resolve, reject) => { fileInput.onchange = async () => { const files = fileInput.files; if (!files) return resolve(null); const file = files.item(0); if (!file) return resolve(null); return resolve({ text: await file.text(), file }); }; // @ts-ignore: TODO: changed from 4.3 to 4.4 fileInput.oncancel = () => resolve(null); fileInput.onerror = reject; fileInput.click(); }); } return openFile; } async function actionGlobalOpenStateFile(pinia) { try { const open = await getFileOpener(); const result = await open(); if (!result) return; const { text, file } = result; pinia.state.value = JSON.parse(text); toastMessage(`Global state imported from "${file.name}".`); } catch (error) { toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error'); console.error(error); } } function formatDisplay(display) { return { _custom: { display, }, }; } const PINIA_ROOT_LABEL = '🍍 Pinia (root)'; const PINIA_ROOT_ID = '_root'; function formatStoreForInspectorTree(store) { return isPinia(store) ? { id: PINIA_ROOT_ID, label: PINIA_ROOT_LABEL, } : { id: store.$id, label: store.$id, }; } function formatStoreForInspectorState(store) { if (isPinia(store)) { const storeNames = Array.from(store._s.keys()); const storeMap = store._s; const state = { state: storeNames.map((storeId) => ({ editable: true, key: storeId, value: store.state.value[storeId], })), getters: storeNames .filter((id) => storeMap.get(id)._getters) .map((id) => { const store = storeMap.get(id); return { editable: false, key: id, value: store._getters.reduce((getters, key) => { getters[key] = store[key]; return getters; }, {}), }; }), }; return state; } const state = { state: Object.keys(store.$state).map((key) => ({ editable: true, key, value: store.$state[key], })), }; // avoid adding empty getters if (store._getters && store._getters.length) { state.getters = store._getters.map((getterName) => ({ editable: false, key: getterName, value: store[getterName], })); } if (store._customProperties.size) { state.customProperties = Array.from(store._customProperties).map((key) => ({ editable: true, key, value: store[key], })); } return state; } function formatEventData(events) { if (!events) return {}; if (Array.isArray(events)) { // TODO: handle add and delete for arrays and objects return events.reduce((data, event) => { data.keys.push(event.key); data.operations.push(event.type); data.oldValue[event.key] = event.oldValue; data.newValue[event.key] = event.newValue; return data; }, { oldValue: {}, keys: [], operations: [], newValue: {}, }); } else { return { operation: formatDisplay(events.type), key: formatDisplay(events.key), oldValue: events.oldValue, newValue: events.newValue, }; } } function formatMutationType(type) { switch (type) { case exports.MutationType.direct: return 'mutation'; case exports.MutationType.patchFunction: return '$patch'; case exports.MutationType.patchObject: return '$patch'; default: return 'unknown'; } } // timeline can be paused when directly changing the state let isTimelineActive = true; const componentStateTypes = []; const MUTATIONS_LAYER_ID = 'pinia:mutations'; const INSPECTOR_ID = 'pinia'; /** * Gets the displayed name of a store in devtools * * @param id - id of the store * @returns a formatted string */ const getStoreType = (id) => '🍍 ' + id; /** * Add the pinia plugin without any store. Allows displaying a Pinia plugin tab * as soon as it is added to the application. * * @param app - Vue application * @param pinia - pinia instance */ function registerPiniaDevtools(app, pinia) { setupDevtoolsPlugin({ id: 'dev.esm.pinia', label: 'Pinia 🍍', logo: 'https://pinia.vuejs.org/logo.svg', packageName: 'pinia', homepage: 'https://pinia.vuejs.org', componentStateTypes, app, }, (api) => { api.addTimelineLayer({ id: MUTATIONS_LAYER_ID, label: `Pinia 🍍`, color: 0xe5df88, }); api.addInspector({ id: INSPECTOR_ID, label: 'Pinia 🍍', icon: 'storage', treeFilterPlaceholder: 'Search stores', actions: [ { icon: 'content_copy', action: () => { actionGlobalCopyState(pinia); }, tooltip: 'Serialize and copy the state', }, { icon: 'content_paste', action: async () => { await actionGlobalPasteState(pinia); api.sendInspectorTree(INSPECTOR_ID); api.sendInspectorState(INSPECTOR_ID); }, tooltip: 'Replace the state with the content of your clipboard', }, { icon: 'save', action: () => { actionGlobalSaveState(pinia); }, tooltip: 'Save the state as a JSON file', }, { icon: 'folder_open', action: async () => { await actionGlobalOpenStateFile(pinia); api.sendInspectorTree(INSPECTOR_ID); api.sendInspectorState(INSPECTOR_ID); }, tooltip: 'Import the state from a JSON file', }, ], }); api.on.inspectComponent((payload, ctx) => { const proxy = (payload.componentInstance && payload.componentInstance.proxy); if (proxy && proxy._pStores) { const piniaStores = payload.componentInstance.proxy._pStores; Object.values(piniaStores).forEach((store) => { payload.instanceData.state.push({ type: getStoreType(store.$id), key: 'state', editable: true, value: store._isOptionsAPI ? { _custom: { value: store.$state, actions: [ { icon: 'restore', tooltip: 'Reset the state of this store', action: () => store.$reset(), }, ], }, } : store.$state, }); if (store._getters && store._getters.length) { payload.instanceData.state.push({ type: getStoreType(store.$id), key: 'getters', editable: false, value: store._getters.reduce((getters, key) => { getters[key] = store[key]; return getters; }, {}), }); } }); } }); api.on.getInspectorTree((payload) => { if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { let stores = [pinia]; stores = stores.concat(Array.from(pinia._s.values())); payload.rootNodes = (payload.filter ? stores.filter((store) => '$id' in store ? store.$id .toLowerCase() .includes(payload.filter.toLowerCase()) : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase())) : stores).map(formatStoreForInspectorTree); } }); api.on.getInspectorState((payload) => { if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId); if (!inspectedStore) { // this could be the selected store restored for a different project // so it's better not to say anything here return; } if (inspectedStore) { payload.state = formatStoreForInspectorState(inspectedStore); } } }); api.on.editInspectorState((payload, ctx) => { if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId); if (!inspectedStore) { return toastMessage(`store "${payload.nodeId}" not found`, 'error'); } const { path } = payload; if (!isPinia(inspectedStore)) { // access only the state if (path.length !== 1 || !inspectedStore._customProperties.has(path[0]) || path[0] in inspectedStore.$state) { path.unshift('$state'); } } else { // Root access, we can omit the `.value` because the devtools API does it for us path.unshift('state'); } isTimelineActive = false; payload.set(inspectedStore, path, payload.state.value); isTimelineActive = true; } }); api.on.editComponentState((payload) => { if (payload.type.startsWith('🍍')) { const storeId = payload.type.replace(/^🍍\s*/, ''); const store = pinia._s.get(storeId); if (!store) { return toastMessage(`store "${storeId}" not found`, 'error'); } const { path } = payload; if (path[0] !== 'state') { return toastMessage(`Invalid path for store "${storeId}":\n${path}\nOnly state can be modified.`); } // rewrite the first entry to be able to directly set the state as // well as any other path path[0] = '$state'; isTimelineActive = false; payload.set(store, path, payload.state.value); isTimelineActive = true; } }); }); } function addStoreToDevtools(app, store) { if (!componentStateTypes.includes(getStoreType(store.$id))) { componentStateTypes.push(getStoreType(store.$id)); } setupDevtoolsPlugin({ id: 'dev.esm.pinia', label: 'Pinia 🍍', logo: 'https://pinia.vuejs.org/logo.svg', packageName: 'pinia', homepage: 'https://pinia.vuejs.org', componentStateTypes, app, settings: { // useEmojis: { // label: 'Use emojis in messages ⚡️', // type: 'boolean', // defaultValue: true, // }, }, }, (api) => { store.$onAction(({ after, onError, name, args }) => { const groupId = runningActionId++; api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), title: '🛫 ' + name, subtitle: 'start', data: { store: formatDisplay(store.$id), action: formatDisplay(name), args, }, groupId, }, }); after((result) => { activeAction = undefined; api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), title: '🛬 ' + name, subtitle: 'end', data: { store: formatDisplay(store.$id), action: formatDisplay(name), args, result, }, groupId, }, }); }); onError((error) => { activeAction = undefined; api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), logType: 'error', title: '💥 ' + name, subtitle: 'end', data: { store: formatDisplay(store.$id), action: formatDisplay(name), args, error, }, groupId, }, }); }); }, true); store._customProperties.forEach((name) => { vueDemi.watch(() => vueDemi.unref(store[name]), (newValue, oldValue) => { api.notifyComponentUpdate(); api.sendInspectorState(INSPECTOR_ID); if (isTimelineActive) { api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), title: 'Change', subtitle: name, data: { newValue, oldValue, }, groupId: activeAction, }, }); } }, { deep: true }); }); store.$subscribe(({ events, type }, state) => { api.notifyComponentUpdate(); api.sendInspectorState(INSPECTOR_ID); if (!isTimelineActive) return; // rootStore.state[store.id] = state const eventData = { time: Date.now(), title: formatMutationType(type), data: { store: formatDisplay(store.$id), ...formatEventData(events), }, groupId: activeAction, }; // reset for the next mutation activeAction = undefined; if (type === exports.MutationType.patchFunction) { eventData.subtitle = '⤵️'; } else if (type === exports.MutationType.patchObject) { eventData.subtitle = '🧩'; } else if (events && !Array.isArray(events)) { eventData.subtitle = events.type; } if (events) { eventData.data['rawEvent(s)'] = { _custom: { display: 'DebuggerEvent', type: 'object', tooltip: 'raw DebuggerEvent[]', value: events, }, }; } api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: eventData, }); }, { detached: true, flush: 'sync' }); const hotUpdate = store._hotUpdate; store._hotUpdate = vueDemi.markRaw((newStore) => { hotUpdate(newStore); api.addTimelineEvent({ layerId: MUTATIONS_LAYER_ID, event: { time: Date.now(), title: '🔥 ' + store.$id, subtitle: 'HMR update', data: { store: formatDisplay(store.$id), info: formatDisplay(`HMR update`), }, }, }); // update the devtools too api.notifyComponentUpdate(); api.sendInspectorTree(INSPECTOR_ID); api.sendInspectorState(INSPECTOR_ID); }); const { $dispose } = store; store.$dispose = () => { $dispose(); api.notifyComponentUpdate(); api.sendInspectorTree(INSPECTOR_ID); api.sendInspectorState(INSPECTOR_ID); toastMessage(`Disposed "${store.$id}" store 🗑`); }; // trigger an update so it can display new registered stores api.notifyComponentUpdate(); api.sendInspectorTree(INSPECTOR_ID); api.sendInspectorState(INSPECTOR_ID); toastMessage(`"${store.$id}" store installed 🆕`); }); } let runningActionId = 0; let activeAction; /** * Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the * context of all actions, allowing us to set `runningAction` on each access and effectively associating any state * mutation to the action. * * @param store - store to patch * @param actionNames - list of actionst to patch */ function patchActionForGrouping(store, actionNames) { // original actions of the store as they are given by pinia. We are going to override them const actions = actionNames.reduce((storeActions, actionName) => { // use toRaw to avoid tracking #541 storeActions[actionName] = vueDemi.toRaw(store)[actionName]; return storeActions; }, {}); for (const actionName in actions) { store[actionName] = function () { // setActivePinia(store._p) // the running action id is incremented in a before action hook const _actionId = runningActionId; const trackedStore = new Proxy(store, { get(...args) { activeAction = _actionId; return Reflect.get(...args); }, set(...args) { activeAction = _actionId; return Reflect.set(...args); }, }); return actions[actionName].apply(trackedStore, arguments); }; } } /** * pinia.use(devtoolsPlugin) */ function devtoolsPlugin({ app, store, options }) { // HMR module if (store.$id.startsWith('__hot:')) { return; } // detect option api vs setup api if (options.state) { store._isOptionsAPI = true; } // only wrap actions in option-defined stores as this technique relies on // wrapping the context of the action with a proxy if (typeof options.state === 'function') { patchActionForGrouping( // @ts-expect-error: can cast the store... store, Object.keys(options.actions)); const originalHotUpdate = store._hotUpdate; // Upgrade the HMR to also update the new actions vueDemi.toRaw(store)._hotUpdate = function (newStore) { originalHotUpdate.apply(this, arguments); patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions)); }; } addStoreToDevtools(app, // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric? store); } /** * Creates a Pinia instance to be used by the application */ function createPinia() { const scope = vueDemi.effectScope(true); // NOTE: here we could check the window object for a state and directly set it // if there is anything like it with Vue 3 SSR const state = scope.run(() => vueDemi.ref({})); let _p = []; // plugins added before calling app.use(pinia) let toBeInstalled = []; const pinia = vueDemi.markRaw({ install(app) { // this allows calling useStore() outside of a component setup after // installing pinia's plugin setActivePinia(pinia); if (!vueDemi.isVue2) { pinia._a = app; app.provide(piniaSymbol, pinia); app.config.globalProperties.$pinia = pinia; /* istanbul ignore else */ if (IS_CLIENT) { registerPiniaDevtools(app, pinia); } toBeInstalled.forEach((plugin) => _p.push(plugin)); toBeInstalled = []; } }, use(plugin) { if (!this._a && !vueDemi.isVue2) { toBeInstalled.push(plugin); } else { _p.push(plugin); } return this; }, _p, // it's actually undefined here // @ts-expect-error _a: null, _e: scope, _s: new Map(), state, }); // pinia devtools rely on dev only features so they cannot be forced unless // the dev build of Vue is used if (IS_CLIENT) { pinia.use(devtoolsPlugin); } return pinia; } /** * Checks if a function is a `StoreDefinition`. * * @param fn - object to test * @returns true if `fn` is a StoreDefinition */ const isUseStore = (fn) => { return typeof fn === 'function' && typeof fn.$id === 'string'; }; /** * Mutates in place `newState` with `oldState` to _hot update_ it. It will * remove any key not existing in `newState` and recursively merge plain * objects. * * @param newState - new state object to be patched * @param oldState - old state that should be used to patch newState * @returns - newState */ function patchObject(newState, oldState) { // no need to go through symbols because they cannot be serialized anyway for (const key in oldState) { const subPatch = oldState[key]; // skip the whole sub tree if (!(key in newState)) { continue; } const targetValue = newState[key]; if (isPlainObject(targetValue) && isPlainObject(subPatch) && !vueDemi.isRef(subPatch) && !vueDemi.isReactive(subPatch)) { newState[key] = patchObject(targetValue, subPatch); } else { // objects are either a bit more complex (e.g. refs) or primitives, so we // just set the whole thing if (vueDemi.isVue2) { vueDemi.set(newState, key, subPatch); } else { newState[key] = subPatch; } } } return newState; } /** * Creates an _accept_ function to pass to `import.meta.hot` in Vite applications. * * @example * ```js * const useUser = defineStore(...) * if (import.meta.hot) { * import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot)) * } * ``` * * @param initialUseStore - return of the defineStore to hot update * @param hot - `import.meta.hot` */ function acceptHMRUpdate(initialUseStore, hot) { return (newModule) => { const pinia = hot.data.pinia || initialUseStore._pinia; if (!pinia) { // this store is still not used return; } // preserve the pinia instance across loads hot.data.pinia = pinia; // console.log('got data', newStore) for (const exportName in newModule) { const useStore = newModule[exportName]; // console.log('checking for', exportName) if (isUseStore(useStore) && pinia._s.has(useStore.$id)) { // console.log('Accepting update for', useStore.$id) const id = useStore.$id; if (id !== initialUseStore.$id) { console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`); // return import.meta.hot.invalidate() return hot.invalidate(); } const existingStore = pinia._s.get(id); if (!existingStore) { console.log(`skipping hmr because store doesn't exist yet`); return; } useStore(pinia, existingStore); } } }; } const noop = () => { }; function addSubscription(subscriptions, callback, detached, onCleanup = noop) { subscriptions.push(callback); const removeSubscription = () => { const idx = subscriptions.indexOf(callback); if (idx > -1) { subscriptions.splice(idx, 1); onCleanup(); } }; if (!detached && vueDemi.getCurrentInstance()) { vueDemi.onUnmounted(removeSubscription); } return removeSubscription; } function triggerSubscriptions(subscriptions, ...args) { subscriptions.slice().forEach((callback) => { callback(...args); }); } function mergeReactiveObjects(target, patchToApply) { // no need to go through symbols because they cannot be serialized anyway for (const key in patchToApply) { const subPatch = patchToApply[key]; const targetValue = target[key]; if (isPlainObject(targetValue) && isPlainObject(subPatch) && !vueDemi.isRef(subPatch) && !vueDemi.isReactive(subPatch)) { target[key] = mergeReactiveObjects(targetValue, subPatch); } else { // @ts-expect-error: subPatch is a valid value target[key] = subPatch; } } return target; } const skipHydrateSymbol = Symbol('pinia:skipHydration') ; const skipHydrateMap = /*#__PURE__*/ new WeakMap(); function skipHydrate(obj) { return vueDemi.isVue2 ? // in @vue/composition-api, the refs are sealed so defineProperty doesn't work... /* istanbul ignore next */ skipHydrateMap.set(obj, 1) && obj : Object.defineProperty(obj, skipHydrateSymbol, {}); } function shouldHydrate(obj) { return vueDemi.isVue2 ? /* istanbul ignore next */ !skipHydrateMap.has(obj) : !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol); } const { assign } = Object; function isComputed(o) { return !!(vueDemi.isRef(o) && o.effect); } function createOptionsStore(id, options, pinia, hot) { const { state, actions, getters } = options; const initialState = pinia.state.value[id]; let store; function setup() { if (!initialState && (!hot)) { /* istanbul ignore if */ if (vueDemi.isVue2) { vueDemi.set(pinia.state.value, id, state ? state() : {}); } else { pinia.state.value[id] = state ? state() : {}; } } // avoid creating a state in pinia.state.value const localState = hot ? // use ref() to unwrap refs inside state TODO: check if this is still necessary vueDemi.toRefs(vueDemi.ref(state ? state() : {}).value) : vueDemi.toRefs(pinia.state.value[id]); return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => { computedGetters[name] = vueDemi.markRaw(vueDemi.computed(() => { setActivePinia(pinia); // it was created just before const store = pinia._s.get(id); // allow cross using stores /* istanbul ignore next */ if (vueDemi.isVue2 && !store._r) return; // @ts-expect-error // return getters![name].call(context, context) // TODO: avoid reading the getter while assigning with a global variable return getters[name].call(store, store); })); return computedGetters; }, {})); } store = createSetupStore(id, setup, options, pinia, hot); store.$reset = function $reset() { const newState = state ? state() : {}; // we use a patch to group all changes into one single subscription this.$patch(($state) => { assign($state, newState); }); }; return store; } function createSetupStore($id, setup, options = {}, pinia, hot) { let scope; const buildState = options.state; const optionsForPlugin = assign({ actions: {} }, options); /* istanbul ignore if */ if (!pinia._e.active) { throw new Error('Pinia destroyed'); } // watcher options for $subscribe const $subscribeOptions = { deep: true, // flush: 'post', }; /* istanbul ignore else */ if (!vueDemi.isVue2) { $subscribeOptions.onTrigger = (event) => { /* istanbul ignore else */ if (isListening) { debuggerEvents = event; // avoid triggering this while the store is being built and the state is being set in pinia } else if (isListening == false && !store._hotUpdating) { // let patch send all the events together later /* istanbul ignore else */ if (Array.isArray(debuggerEvents)) { debuggerEvents.push(event); } else { console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.'); } } }; } // internal state let isListening; // set to true at the end let isSyncListening; // set to true at the end let subscriptions = vueDemi.markRaw([]); let actionSubscriptions = vueDemi.markRaw([]); let debuggerEvents; const initialState = pinia.state.value[$id]; // avoid setting the state for option stores are it is set // by the setup if (!buildState && !initialState && (!hot)) { /* istanbul ignore if */ if (vueDemi.isVue2) { vueDemi.set(pinia.state.value, $id, {}); } else { pinia.state.value[$id] = {}; } } const hotState = vueDemi.ref({}); function $patch(partialStateOrMutator) { let subscriptionMutation; isListening = isSyncListening = false; // reset the debugger events since patches are sync /* istanbul ignore else */ { debuggerEvents = []; } if (typeof partialStateOrMutator === 'function') { partialStateOrMutator(pinia.state.value[$id]); subscriptionMutation = { type: exports.MutationType.patchFunction, storeId: $id, events: debuggerEvents, }; } else { mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator); subscriptionMutation = { type: exports.MutationType.patchObject, payload: partialStateOrMutator, storeId: $id, events: debuggerEvents, }; } vueDemi.nextTick().then(() => { isListening = true; }); isSyncListening = true; // because we paused the watcher, we need to manually call the subscriptions triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]); } /* istanbul ignore next */ const $reset = () => { throw new Error(`🍍: Store "${$id}" is build using the setup syntax and does not implement $reset().`); } ; function $dispose() { scope.stop(); subscriptions = []; actionSubscriptions = []; pinia._s.delete($id); } /** * Wraps an action to handle subscriptions. * * @param name - name of the action * @param action - action to wrap * @returns a wrapped action to handle subscriptions */ function wrapAction(name, action) { return function () { setActivePinia(pinia); const args = Array.from(arguments); const afterCallbackList = []; const onErrorCallbackList = []; function after(callback) { afterCallbackList.push(callback); } function onError(callback) { onErrorCallbackList.push(callback); } // @ts-expect-error triggerSubscriptions(actionSubscriptions, { args, name, store, after, onError, }); let ret; try { ret = action.apply(this && this.$id === $id ? this : store, args); // handle sync errors } catch (error) { triggerSubscriptions(onErrorCallbackList, error); throw error; } if (ret instanceof Promise) { return ret .then((value) => { triggerSubscriptions(afterCallbackList, value); return value; }) .catch((error) => { triggerSubscriptions(onErrorCallbackList, error); return Promise.reject(error); }); } // allow the afterCallback to override the return value triggerSubscriptions(afterCallbackList, ret); return ret; }; } const _hmrPayload = /*#__PURE__*/ vueDemi.markRaw({ actions: {}, getters: {}, state: [], hotState, }); const partialStore = { _p: pinia, // _s: scope, $id, $onAction: addSubscription.bind(null, actionSubscriptions), $patch, $reset, $subscribe(callback, options = {}) { const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher()); const stopWatcher = scope.run(() => vueDemi.watch(() => pinia.state.value[$id], (state) => { if (options.flush === 'sync' ? isSyncListening : isListening) { callback({ storeId: $id, type: exports.MutationType.direct, events: debuggerEvents, }, state); } }, assign({}, $subscribeOptions, options))); return removeSubscription; }, $dispose, }; /* istanbul ignore if */ if (vueDemi.isVue2) { // start as non ready partialStore._r = false; } const store = vueDemi.reactive(assign(IS_CLIENT ? // devtools custom properties { _customProperties: vueDemi.markRaw(new Set()), _hmrPayload, } : {}, partialStore // must be added later // setupStore )); // store the partial store now so the setup of stores can instantiate each other before they are finished without // creating infinite loops. pinia._s.set($id, store); // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped const setupStore = pinia._e.run(() => { scope = vueDemi.effectScope(); return scope.run(() => setup()); }); // overwrite existing actions to support $onAction for (const key in setupStore) { const prop = setupStore[key]; if ((vueDemi.isRef(prop) && !isComputed(prop)) || vueDemi.isReactive(prop)) { // mark it as a piece of state to be serialized if (hot) { vueDemi.set(hotState.value, key, vueDemi.toRef(setupStore, key)); // createOptionStore directly sets the state in pinia.state.value so we // can just skip that } else if (!buildState) { // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created if (initialState && shouldHydrate(prop)) { if (vueDemi.isRef(prop)) { prop.value = initialState[key]; } else { // probably a reactive object, lets recursively assign mergeReactiveObjects(prop, initialState[key]); } } // transfer the ref to the pinia state to keep everything in sync /* istanbul ignore if */ if (vueDemi.isVue2) { vueDemi.set(pinia.state.value[$id], key, prop); } else { pinia.state.value[$id][key] = prop; } } /* istanbul ignore else */ { _hmrPayload.state.push(key); } // action } else if (typeof prop === 'function') { // @ts-expect-error: we are overriding the function we avoid wrapping if const actionValue = hot ? prop : wrapAction(key, prop); // this a hot module replacement store because the hotUpdate method needs // to do it with the right context /* istanbul ignore if */ if (vueDemi.isVue2) { vueDemi.set(setupStore, key, actionValue); } else { // @ts-expect-error setupStore[key] = actionValue; } /* istanbul ignore else */ { _hmrPayload.actions[key] = prop; } // list actions so they can be used in plugins // @ts-expect-error optionsForPlugin.actions[key] = prop; } else { // add getters for devtools if (isComputed(prop)) { _hmrPayload.getters[key] = buildState ? // @ts-expect-error options.getters[key] : prop; if (IS_CLIENT) { const getters = // @ts-expect-error: it should be on the store setupStore._getters || (setupStore._getters = vueDemi.markRaw([])); getters.push(key); } } } } // add the state, getters, and action properties /* istanbul ignore if */ if (vueDemi.isVue2) { Object.keys(setupStore).forEach((key) => { vueDemi.set(store, key, // @ts-expect-error: valid key indexing setupStore[key]); }); } else { assign(store, setupStore); // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object. // Make `storeToRefs()` work with `reactive()` #799 assign(vueDemi.toRaw(store), setupStore); } // use this instead of a computed with setter to be able to create it anywhere // without linking the computed lifespan to wherever the store is first // created. Object.defineProperty(store, '$state', { get: () => (hot ? hotState.value : pinia.state.value[$id]), set: (state) => { /* istanbul ignore if */ if (hot) { throw new Error('cannot set hotState'); } $patch(($state) => { assign($state, state); }); }, }); // add the hotUpdate before plugins to allow them to override it /* istanbul ignore else */ { store._hotUpdate = vueDemi.markRaw((newStore) => { store._hotUpdating = true; newStore._hmrPayload.state.forEach((stateKey) => { if (stateKey in store.$state) { const newStateTarget = newStore.$state[stateKey]; const oldStateSource = store.$state[stateKey]; if (typeof newStateTarget === 'object' && isPlainObject(newStateTarget) && isPlainObject(oldStateSource)) { patchObject(newStateTarget, oldStateSource); } else { // transfer the ref newStore.$state[stateKey] = oldStateSource; } } // patch direct access properties to allow store.stateProperty to work as // store.$state.stateProperty vueDemi.set(store, stateKey, vueDemi.toRef(newStore.$state, stateKey)); }); // remove deleted state properties Object.keys(store.$state).forEach((stateKey) => { if (!(stateKey in newStore.$state)) { vueDemi.del(store, stateKey); } }); // avoid devtools logging this as a mutation isListening = false; isSyncListening = false; pinia.state.value[$id] = vueDemi.toRef(newStore._hmrPayload, 'hotState'); isSyncListening = true; vueDemi.nextTick().then(() => { isListening = true; }); for (const actionName in newStore._hmrPayload.actions) { const action = newStore[actionName]; vueDemi.set(store, actionName, wrapAction(actionName, action)); } // TODO: does this work in both setup and option store? for (const getterName in newStore._hmrPayload.getters) { const getter = newStore._hmrPayload.getters[getterName]; const getterValue = buildState ? // special handling of options api vueDemi.computed(() => { setActivePinia(pinia); return getter.call(store, store); }) : getter; vueDemi.set(store, getterName, getterValue); } // remove deleted getters Object.keys(store._hmrPayload.getters).forEach((key) => { if (!(key in newStore._hmrPayload.getters)) { vueDemi.del(store, key); } }); // remove old actions Object.keys(store._hmrPayload.actions).forEach((key) => { if (!(key in newStore._hmrPayload.actions)) { vueDemi.del(store, key); } }); // update the values used in devtools and to allow deleting new properties later on store._hmrPayload = newStore._hmrPayload; store._getters = newStore._getters; store._hotUpdating = false; }); const nonEnumerable = { writable: true, configurable: true, // avoid warning on devtools trying to display this property enumerable: false, }; if (IS_CLIENT) { ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => { Object.defineProperty(store, p, { value: store[p], ...nonEnumerable, }); }); } } /* istanbul ignore if */ if (vueDemi.isVue2) { // mark the store as ready before plugins store._r = true; } // apply all plugins pinia._p.forEach((extender) => { /* istanbul ignore else */ if (IS_CLIENT) { const extensions = scope.run(() => extender({ store, app: pinia._a, pinia, options: optionsForPlugin, })); Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key)); assign(store, extensions); } else { assign(store, scope.run(() => extender({ store, app: pinia._a, pinia, options: optionsForPlugin, }))); } }); if (store.$state && typeof store.$state === 'object' && typeof store.$state.constructor === 'function' && !store.$state.constructor.toString().includes('[native code]')) { console.warn(`[🍍]: The "state" must be a plain object. It cannot be\n` + `\tstate: () => new MyClass()\n` + `Found in store "${store.$id}".`); } // only apply hydrate to option stores with an initial state in pinia if (initialState && buildState && options.hydrate) { options.hydrate(store.$state, initialState); } isListening = true; isSyncListening = true; return store; } function defineStore( // TODO: add proper types from above idOrOptions, setup, setupOptions) { let id; let options; const isSetupStore = typeof setup === 'function'; if (typeof idOrOptions === 'string') { id = idOrOptions; // the option store setup will contain the actual options in this case options = isSetupStore ? setupOptions : setup; } else { options = idOrOptions; id = idOrOptions.id; } function useStore(pinia, hot) { const currentInstance = vueDemi.getCurrentInstance(); pinia = // in test mode, ignore the argument provided as we can always retrieve a // pinia instance with getActivePinia() (pinia) || (currentInstance && vueDemi.inject(piniaSymbol)); if (pinia) setActivePinia(pinia); if (!activePinia) { throw new Error(`[🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?\n` + `\tconst pinia = createPinia()\n` + `\tapp.use(pinia)\n` + `This will fail in production.`); } pinia = activePinia; if (!pinia._s.has(id)) { // creating the store registers it in `pinia._s` if (isSetupStore) { createSetupStore(id, setup, options, pinia); } else { createOptionsStore(id, options, pinia); } /* istanbul ignore else */ { // @ts-expect-error: not the right inferred type useStore._pinia = pinia; } } const store = pinia._s.get(id); if (hot) { const hotId = '__hot:' + id; const newStore = isSetupStore ? createSetupStore(hotId, setup, options, pinia, true) : createOptionsStore(hotId, assign({}, options), pinia, true); hot._hotUpdate(newStore); // cleanup the state properties and the store from the cache delete pinia.state.value[hotId]; pinia._s.delete(hotId); } // save stores in instances to access them devtools if (IS_CLIENT && currentInstance && currentInstance.proxy && // avoid adding stores that are just built for hot module replacement !hot) { const vm = currentInstance.proxy; const cache = '_pStores' in vm ? vm._pStores : (vm._pStores = {}); cache[id] = store; } // StoreGeneric cannot be casted towards Store return store; } useStore.$id = id; return useStore; } let mapStoreSuffix = 'Store'; /** * Changes the suffix added by `mapStores()`. Can be set to an empty string. * Defaults to `"Store"`. Make sure to extend the MapStoresCustomization * interface if you need are using TypeScript. * * @param suffix - new suffix */ function setMapStoreSuffix(suffix // could be 'Store' but that would be annoying for JS ) { mapStoreSuffix = suffix; } /** * Allows using stores without the composition API (`setup()`) by generating an * object to be spread in the `computed` field of a component. It accepts a list * of store definitions. * * @example * ```js * export default { * computed: { * // other computed properties * ...mapStores(useUserStore, useCartStore) * }, * * created() { * this.userStore // store with id "user" * this.cartStore // store with id "cart" * } * } * ``` * * @param stores - list of stores to map to an object */ function mapStores(...stores) { if (Array.isArray(stores[0])) { console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:\n` + `Replace\n` + `\tmapStores([useAuthStore, useCartStore])\n` + `with\n` + `\tmapStores(useAuthStore, useCartStore)\n` + `This will fail in production if not fixed.`); stores = stores[0]; } return stores.reduce((reduced, useStore) => { // @ts-expect-error: $id is added by defineStore reduced[useStore.$id + mapStoreSuffix] = function () { return useStore(this.$pinia); }; return reduced; }, {}); } /** * Allows using state and getters from one store without using the composition * API (`setup()`) by generating an object to be spread in the `computed` field * of a component. * * @param useStore - store to map from * @param keysOrMapper - array or object */ function mapState(useStore, keysOrMapper) { return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => { reduced[key] = function () { return useStore(this.$pinia)[key]; }; return reduced; }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => { // @ts-expect-error reduced[key] = function () { const store = useStore(this.$pinia); const storeKey = keysOrMapper[key]; // for some reason TS is unable to infer the type of storeKey to be a // function return typeof storeKey === 'function' ? storeKey.call(this, store) : store[storeKey]; }; return reduced; }, {}); } /** * Alias for `mapState()`. You should use `mapState()` instead. * @deprecated use `mapState()` instead. */ const mapGetters = mapState; /** * Allows directly using actions from your store without using the composition * API (`setup()`) by generating an object to be spread in the `methods` field * of a component. * * @param useStore - store to map from * @param keysOrMapper - array or object */ function mapActions(useStore, keysOrMapper) { return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => { // @ts-expect-error reduced[key] = function (...args) { return useStore(this.$pinia)[key](...args); }; return reduced; }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => { // @ts-expect-error reduced[key] = function (...args) { return useStore(this.$pinia)[keysOrMapper[key]](...args); }; return reduced; }, {}); } /** * Allows using state and getters from one store without using the composition * API (`setup()`) by generating an object to be spread in the `computed` field * of a component. * * @param useStore - store to map from * @param keysOrMapper - array or object */ function mapWritableState(useStore, keysOrMapper) { return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => { // @ts-ignore reduced[key] = { get() { return useStore(this.$pinia)[key]; }, set(value) { // it's easier to type it here as any return (useStore(this.$pinia)[key] = value); }, }; return reduced; }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => { // @ts-ignore reduced[key] = { get() { return useStore(this.$pinia)[keysOrMapper[key]]; }, set(value) { // it's easier to type it here as any return (useStore(this.$pinia)[keysOrMapper[key]] = value); }, }; return reduced; }, {}); } /** * Creates an object of references with all the state, getters, and plugin-added * state properties of the store. Similar to `toRefs()` but specifically * designed for Pinia stores so methods and non reactive properties are * completely ignored. * * @param store - store to extract the refs from */ function storeToRefs(store) { store = vueDemi.toRaw(store); const refs = {}; for (const key in store) { const value = store[key]; if (vueDemi.isRef(value) || vueDemi.isReactive(value)) { // @ts-expect-error: the key is state or getter refs[key] = // --- vueDemi.toRef(store, key); } } return refs; } /** * Vue 2 Plugin that must be installed for pinia to work. Note **you don't need * this plugin if you are using Nuxt.js**. Use the `buildModule` instead: * https://pinia.vuejs.org/ssr/nuxt.html. * * @example * ```js * import Vue from 'vue' * import { PiniaVuePlugin, createPinia } from 'pinia' * * Vue.use(PiniaVuePlugin) * const pinia = createPinia() * * new Vue({ * el: '#app', * // ... * pinia, * }) * ``` * * @param _Vue - `Vue` imported from 'vue'. */ const PiniaVuePlugin = function (_Vue) { // Equivalent of // app.config.globalProperties.$pinia = pinia _Vue.mixin({ beforeCreate() { const options = this.$options; if (options.pinia) { const pinia = options.pinia; // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/master/src/apis/inject.ts#L30 /* istanbul ignore else */ if (!this._provided) { const provideCache = {}; Object.defineProperty(this, '_provided', { get: () => provideCache, set: (v) => Object.assign(provideCache, v), }); } this._provided[piniaSymbol] = pinia; // propagate the pinia instance in an SSR friendly way // avoid adding it to nuxt twice /* istanbul ignore else */ if (!this.$pinia) { this.$pinia = pinia; } pinia._a = this; if (IS_CLIENT) { // this allows calling useStore() outside of a component setup after // installing pinia's plugin setActivePinia(pinia); { registerPiniaDevtools(pinia._a, pinia); } } } else if (!this.$pinia && options.parent && options.parent.$pinia) { this.$pinia = options.parent.$pinia; } }, destroyed() { delete this._pStores; }, }); }; exports.PiniaVuePlugin = PiniaVuePlugin; exports.acceptHMRUpdate = acceptHMRUpdate; exports.createPinia = createPinia; exports.defineStore = defineStore; exports.getActivePinia = getActivePinia; exports.mapActions = mapActions; exports.mapGetters = mapGetters; exports.mapState = mapState; exports.mapStores = mapStores; exports.mapWritableState = mapWritableState; exports.setActivePinia = setActivePinia; exports.setMapStoreSuffix = setMapStoreSuffix; exports.skipHydrate = skipHydrate; exports.storeToRefs = storeToRefs; Object.defineProperty(exports, '__esModule', { value: true }); return exports; })({}, VueDemi);
import{p as promiseResolve,b as bootstrapLazy}from"./index-245f2fc2.js";const patchEsm=()=>promiseResolve(),defineCustomElements=(e,i)=>"undefined"==typeof window?Promise.resolve():patchEsm().then(()=>bootstrapLazy([["ion-icon",[[1,"ion-icon",{mode:[1025],color:[1],ariaLabel:[1537,"aria-label"],ariaHidden:[513,"aria-hidden"],ios:[1],md:[1],flipRtl:[4,"flip-rtl"],name:[1],src:[1],icon:[8],size:[1],lazy:[4],sanitize:[4],svgContent:[32],isVisible:[32]}]]]],i));export{defineCustomElements};
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.TWEEN = factory()); }(this, (function () { 'use strict'; var NOW; // Include a performance.now polyfill. // In node.js, use process.hrtime. // eslint-disable-next-line // @ts-ignore if (typeof self === 'undefined' && typeof process !== 'undefined' && process.hrtime) { NOW = function () { // eslint-disable-next-line // @ts-ignore var time = process.hrtime(); // Convert [seconds, nanoseconds] to milliseconds. return time[0] * 1000 + time[1] / 1000000; }; } // In a browser, use self.performance.now if it is available. else if (typeof self !== 'undefined' && self.performance !== undefined && self.performance.now !== undefined) { // This must be bound, because directly assigning this function // leads to an invocation exception in Chrome. NOW = self.performance.now.bind(self.performance); } // Use Date.now if it is available. else if (Date.now !== undefined) { NOW = Date.now; } // Otherwise, use 'new Date().getTime()'. else { NOW = function () { return new Date().getTime(); }; } var NOW$1 = NOW; /** * Controlling groups of tweens * * Using the TWEEN singleton to manage your tweens can cause issues in large apps with many components. * In these cases, you may want to create your own smaller groups of tween */ var Group = /** @class */ (function () { function Group() { this._tweens = {}; this._tweensAddedDuringUpdate = {}; } Group.prototype.getAll = function () { var _this = this; return Object.keys(this._tweens).map(function (tweenId) { return _this._tweens[tweenId]; }); }; Group.prototype.removeAll = function () { this._tweens = {}; }; Group.prototype.add = function (tween) { this._tweens[tween.getId()] = tween; this._tweensAddedDuringUpdate[tween.getId()] = tween; }; Group.prototype.remove = function (tween) { delete this._tweens[tween.getId()]; delete this._tweensAddedDuringUpdate[tween.getId()]; }; Group.prototype.update = function (time, preserve) { var tweenIds = Object.keys(this._tweens); if (tweenIds.length === 0) { return false; } time = time !== undefined ? time : NOW$1(); // Tweens are updated in "batches". If you add a new tween during an // update, then the new tween will be updated in the next batch. // If you remove a tween during an update, it may or may not be updated. // However, if the removed tween was added during the current batch, // then it will not be updated. while (tweenIds.length > 0) { this._tweensAddedDuringUpdate = {}; for (var i = 0; i < tweenIds.length; i++) { var tween = this._tweens[tweenIds[i]]; if (tween && tween.update(time) === false && !preserve) { delete this._tweens[tweenIds[i]]; } } tweenIds = Object.keys(this._tweensAddedDuringUpdate); } return true; }; return Group; }()); /** * The Ease class provides a collection of easing functions for use with tween.js. */ var Easing = { Linear: { None: function (amount) { return amount; }, }, Quadratic: { In: function (amount) { return amount * amount; }, Out: function (amount) { return amount * (2 - amount); }, InOut: function (amount) { if ((amount *= 2) < 1) { return 0.5 * amount * amount; } return -0.5 * (--amount * (amount - 2) - 1); }, }, Cubic: { In: function (amount) { return amount * amount * amount; }, Out: function (amount) { return --amount * amount * amount + 1; }, InOut: function (amount) { if ((amount *= 2) < 1) { return 0.5 * amount * amount * amount; } return 0.5 * ((amount -= 2) * amount * amount + 2); }, }, Quartic: { In: function (amount) { return amount * amount * amount * amount; }, Out: function (amount) { return 1 - --amount * amount * amount * amount; }, InOut: function (amount) { if ((amount *= 2) < 1) { return 0.5 * amount * amount * amount * amount; } return -0.5 * ((amount -= 2) * amount * amount * amount - 2); }, }, Quintic: { In: function (amount) { return amount * amount * amount * amount * amount; }, Out: function (amount) { return --amount * amount * amount * amount * amount + 1; }, InOut: function (amount) { if ((amount *= 2) < 1) { return 0.5 * amount * amount * amount * amount * amount; } return 0.5 * ((amount -= 2) * amount * amount * amount * amount + 2); }, }, Sinusoidal: { In: function (amount) { return 1 - Math.cos((amount * Math.PI) / 2); }, Out: function (amount) { return Math.sin((amount * Math.PI) / 2); }, InOut: function (amount) { return 0.5 * (1 - Math.cos(Math.PI * amount)); }, }, Exponential: { In: function (amount) { return amount === 0 ? 0 : Math.pow(1024, amount - 1); }, Out: function (amount) { return amount === 1 ? 1 : 1 - Math.pow(2, -10 * amount); }, InOut: function (amount) { if (amount === 0) { return 0; } if (amount === 1) { return 1; } if ((amount *= 2) < 1) { return 0.5 * Math.pow(1024, amount - 1); } return 0.5 * (-Math.pow(2, -10 * (amount - 1)) + 2); }, }, Circular: { In: function (amount) { return 1 - Math.sqrt(1 - amount * amount); }, Out: function (amount) { return Math.sqrt(1 - --amount * amount); }, InOut: function (amount) { if ((amount *= 2) < 1) { return -0.5 * (Math.sqrt(1 - amount * amount) - 1); } return 0.5 * (Math.sqrt(1 - (amount -= 2) * amount) + 1); }, }, Elastic: { In: function (amount) { if (amount === 0) { return 0; } if (amount === 1) { return 1; } return -Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI); }, Out: function (amount) { if (amount === 0) { return 0; } if (amount === 1) { return 1; } return Math.pow(2, -10 * amount) * Math.sin((amount - 0.1) * 5 * Math.PI) + 1; }, InOut: function (amount) { if (amount === 0) { return 0; } if (amount === 1) { return 1; } amount *= 2; if (amount < 1) { return -0.5 * Math.pow(2, 10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI); } return 0.5 * Math.pow(2, -10 * (amount - 1)) * Math.sin((amount - 1.1) * 5 * Math.PI) + 1; }, }, Back: { In: function (amount) { var s = 1.70158; return amount * amount * ((s + 1) * amount - s); }, Out: function (amount) { var s = 1.70158; return --amount * amount * ((s + 1) * amount + s) + 1; }, InOut: function (amount) { var s = 1.70158 * 1.525; if ((amount *= 2) < 1) { return 0.5 * (amount * amount * ((s + 1) * amount - s)); } return 0.5 * ((amount -= 2) * amount * ((s + 1) * amount + s) + 2); }, }, Bounce: { In: function (amount) { return 1 - Easing.Bounce.Out(1 - amount); }, Out: function (amount) { if (amount < 1 / 2.75) { return 7.5625 * amount * amount; } else if (amount < 2 / 2.75) { return 7.5625 * (amount -= 1.5 / 2.75) * amount + 0.75; } else if (amount < 2.5 / 2.75) { return 7.5625 * (amount -= 2.25 / 2.75) * amount + 0.9375; } else { return 7.5625 * (amount -= 2.625 / 2.75) * amount + 0.984375; } }, InOut: function (amount) { if (amount < 0.5) { return Easing.Bounce.In(amount * 2) * 0.5; } return Easing.Bounce.Out(amount * 2 - 1) * 0.5 + 0.5; }, }, }; /** * */ var Interpolation = { Linear: function (v, k) { var m = v.length - 1; var f = m * k; var i = Math.floor(f); var fn = Interpolation.Utils.Linear; if (k < 0) { return fn(v[0], v[1], f); } if (k > 1) { return fn(v[m], v[m - 1], m - f); } return fn(v[i], v[i + 1 > m ? m : i + 1], f - i); }, Bezier: function (v, k) { var b = 0; var n = v.length - 1; var pw = Math.pow; var bn = Interpolation.Utils.Bernstein; for (var i = 0; i <= n; i++) { b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i); } return b; }, CatmullRom: function (v, k) { var m = v.length - 1; var f = m * k; var i = Math.floor(f); var fn = Interpolation.Utils.CatmullRom; if (v[0] === v[m]) { if (k < 0) { i = Math.floor((f = m * (1 + k))); } return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i); } else { if (k < 0) { return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]); } if (k > 1) { return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]); } return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); } }, Utils: { Linear: function (p0, p1, t) { return (p1 - p0) * t + p0; }, Bernstein: function (n, i) { var fc = Interpolation.Utils.Factorial; return fc(n) / fc(i) / fc(n - i); }, Factorial: (function () { var a = [1]; return function (n) { var s = 1; if (a[n]) { return a[n]; } for (var i = n; i > 1; i--) { s *= i; } a[n] = s; return s; }; })(), CatmullRom: function (p0, p1, p2, p3, t) { var v0 = (p2 - p0) * 0.5; var v1 = (p3 - p1) * 0.5; var t2 = t * t; var t3 = t * t2; return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; }, }, }; /** * Utils */ var Sequence = /** @class */ (function () { function Sequence() { } Sequence.nextId = function () { return Sequence._nextId++; }; Sequence._nextId = 0; return Sequence; }()); /** * Tween.js - Licensed under the MIT license * https://github.com/tweenjs/tween.js * ---------------------------------------------- * * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors. * Thank you all, you're awesome! */ var Tween = /** @class */ (function () { function Tween(_object, _group) { if (_group === void 0) { _group = TWEEN; } this._object = _object; this._group = _group; this._isPaused = false; this._pauseStart = 0; this._valuesStart = {}; this._valuesEnd = {}; this._valuesStartRepeat = {}; this._duration = 1000; this._initialRepeat = 0; this._repeat = 0; this._yoyo = false; this._isPlaying = false; this._reversed = false; this._delayTime = 0; this._startTime = 0; this._easingFunction = TWEEN.Easing.Linear.None; this._interpolationFunction = TWEEN.Interpolation.Linear; this._chainedTweens = []; this._onStartCallbackFired = false; this._id = TWEEN.nextId(); this._isChainStopped = false; } Tween.prototype.getId = function () { return this._id; }; Tween.prototype.isPlaying = function () { return this._isPlaying; }; Tween.prototype.isPaused = function () { return this._isPaused; }; Tween.prototype.to = function (properties, duration) { for (var prop in properties) { this._valuesEnd[prop] = properties[prop]; } if (duration !== undefined) { this._duration = duration; } return this; }; Tween.prototype.duration = function (d) { this._duration = d; return this; }; Tween.prototype.start = function (time) { if (this._isPlaying) { return this; } // eslint-disable-next-line // @ts-ignore FIXME? this._group.add(this); this._repeat = this._initialRepeat; if (this._reversed) { // If we were reversed (f.e. using the yoyo feature) then we need to // flip the tween direction back to forward. this._reversed = false; for (var property in this._valuesStartRepeat) { this._swapEndStartRepeatValues(property); this._valuesStart[property] = this._valuesStartRepeat[property]; } } this._isPlaying = true; this._isPaused = false; this._onStartCallbackFired = false; this._isChainStopped = false; this._startTime = time !== undefined ? (typeof time === 'string' ? TWEEN.now() + parseFloat(time) : time) : TWEEN.now(); this._startTime += this._delayTime; this._setupProperties(this._object, this._valuesStart, this._valuesEnd, this._valuesStartRepeat); return this; }; Tween.prototype._setupProperties = function (_object, _valuesStart, _valuesEnd, _valuesStartRepeat) { for (var property in _valuesEnd) { var startValue = _object[property]; var startValueIsArray = Array.isArray(startValue); var propType = startValueIsArray ? 'array' : typeof startValue; var isInterpolationList = !startValueIsArray && Array.isArray(_valuesEnd[property]); // If `to()` specifies a property that doesn't exist in the source object, // we should not set that property in the object if (propType === 'undefined' || propType === 'function') { continue; } // Check if an Array was provided as property value if (isInterpolationList) { var endValues = _valuesEnd[property]; if (endValues.length === 0) { continue; } // handle an array of relative values endValues = endValues.map(this._handleRelativeValue.bind(this, startValue)); // Create a local copy of the Array with the start value at the front _valuesEnd[property] = [startValue].concat(endValues); } // handle the deepness of the values if ((propType === 'object' || startValueIsArray) && startValue && !isInterpolationList) { _valuesStart[property] = startValueIsArray ? [] : {}; // eslint-disable-next-line for (var prop in startValue) { // eslint-disable-next-line // @ts-ignore FIXME? _valuesStart[property][prop] = startValue[prop]; } _valuesStartRepeat[property] = startValueIsArray ? [] : {}; // TODO? repeat nested values? And yoyo? And array values? // eslint-disable-next-line // @ts-ignore FIXME? this._setupProperties(startValue, _valuesStart[property], _valuesEnd[property], _valuesStartRepeat[property]); } else { // Save the starting value, but only once. if (typeof _valuesStart[property] === 'undefined') { _valuesStart[property] = startValue; } if (!startValueIsArray) { // eslint-disable-next-line // @ts-ignore FIXME? _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings } if (isInterpolationList) { // eslint-disable-next-line // @ts-ignore FIXME? _valuesStartRepeat[property] = _valuesEnd[property].slice().reverse(); } else { _valuesStartRepeat[property] = _valuesStart[property] || 0; } } } }; Tween.prototype.stop = function () { if (!this._isChainStopped) { this._isChainStopped = true; this.stopChainedTweens(); } if (!this._isPlaying) { return this; } // eslint-disable-next-line // @ts-ignore FIXME? this._group.remove(this); this._isPlaying = false; this._isPaused = false; if (this._onStopCallback) { this._onStopCallback(this._object); } return this; }; Tween.prototype.end = function () { this.update(Infinity); return this; }; Tween.prototype.pause = function (time) { if (this._isPaused || !this._isPlaying) { return this; } this._isPaused = true; this._pauseStart = time === undefined ? TWEEN.now() : time; // eslint-disable-next-line // @ts-ignore FIXME? this._group.remove(this); return this; }; Tween.prototype.resume = function (time) { if (!this._isPaused || !this._isPlaying) { return this; } this._isPaused = false; this._startTime += (time === undefined ? TWEEN.now() : time) - this._pauseStart; this._pauseStart = 0; // eslint-disable-next-line // @ts-ignore FIXME? this._group.add(this); return this; }; Tween.prototype.stopChainedTweens = function () { for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) { this._chainedTweens[i].stop(); } return this; }; Tween.prototype.group = function (group) { this._group = group; return this; }; Tween.prototype.delay = function (amount) { this._delayTime = amount; return this; }; Tween.prototype.repeat = function (times) { this._initialRepeat = times; this._repeat = times; return this; }; Tween.prototype.repeatDelay = function (amount) { this._repeatDelayTime = amount; return this; }; Tween.prototype.yoyo = function (yoyo) { this._yoyo = yoyo; return this; }; Tween.prototype.easing = function (easingFunction) { this._easingFunction = easingFunction; return this; }; Tween.prototype.interpolation = function (interpolationFunction) { this._interpolationFunction = interpolationFunction; return this; }; Tween.prototype.chain = function () { var tweens = []; for (var _i = 0; _i < arguments.length; _i++) { tweens[_i] = arguments[_i]; } this._chainedTweens = tweens; return this; }; Tween.prototype.onStart = function (callback) { this._onStartCallback = callback; return this; }; Tween.prototype.onUpdate = function (callback) { this._onUpdateCallback = callback; return this; }; Tween.prototype.onRepeat = function (callback) { this._onRepeatCallback = callback; return this; }; Tween.prototype.onComplete = function (callback) { this._onCompleteCallback = callback; return this; }; Tween.prototype.onStop = function (callback) { this._onStopCallback = callback; return this; }; Tween.prototype.update = function (time) { var property; var elapsed; var endTime = this._startTime + this._duration; if (time > endTime && !this._isPlaying) { return false; } // If the tween was already finished, if (!this.isPlaying) { this.start(time); } if (time < this._startTime) { return true; } if (this._onStartCallbackFired === false) { if (this._onStartCallback) { this._onStartCallback(this._object); } this._onStartCallbackFired = true; } elapsed = (time - this._startTime) / this._duration; elapsed = this._duration === 0 || elapsed > 1 ? 1 : elapsed; var value = this._easingFunction(elapsed); // properties transformations this._updateProperties(this._object, this._valuesStart, this._valuesEnd, value); if (this._onUpdateCallback) { this._onUpdateCallback(this._object, elapsed); } if (elapsed === 1) { if (this._repeat > 0) { if (isFinite(this._repeat)) { this._repeat--; } // Reassign starting values, restart by making startTime = now for (property in this._valuesStartRepeat) { if (!this._yoyo && typeof this._valuesEnd[property] === 'string') { this._valuesStartRepeat[property] = // eslint-disable-next-line // @ts-ignore FIXME? this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]); } if (this._yoyo) { this._swapEndStartRepeatValues(property); } this._valuesStart[property] = this._valuesStartRepeat[property]; } if (this._yoyo) { this._reversed = !this._reversed; } if (this._repeatDelayTime !== undefined) { this._startTime = time + this._repeatDelayTime; } else { this._startTime = time + this._delayTime; } if (this._onRepeatCallback) { this._onRepeatCallback(this._object); } return true; } else { if (this._onCompleteCallback) { this._onCompleteCallback(this._object); } for (var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i++) { // Make the chained tweens start exactly at the time they should, // even if the `update()` method was called way past the duration of the tween this._chainedTweens[i].start(this._startTime + this._duration); } this._isPlaying = false; return false; } } return true; }; Tween.prototype._updateProperties = function (_object, _valuesStart, _valuesEnd, value) { for (var property in _valuesEnd) { // Don't update properties that do not exist in the source object if (_valuesStart[property] === undefined) { continue; } var start = _valuesStart[property] || 0; var end = _valuesEnd[property]; var startIsArray = Array.isArray(_object[property]); var endIsArray = Array.isArray(end); var isInterpolationList = !startIsArray && endIsArray; if (isInterpolationList) { _object[property] = this._interpolationFunction(end, value); } else if (typeof end === 'object' && end) { // eslint-disable-next-line // @ts-ignore FIXME? this._updateProperties(_object[property], start, end, value); } else { // Parses relative end values with start as base (e.g.: +10, -3) end = this._handleRelativeValue(start, end); // Protect against non numeric properties. if (typeof end === 'number') { // eslint-disable-next-line // @ts-ignore FIXME? _object[property] = start + (end - start) * value; } } } }; Tween.prototype._handleRelativeValue = function (start, end) { if (typeof end !== 'string') { return end; } if (end.charAt(0) === '+' || end.charAt(0) === '-') { return start + parseFloat(end); } else { return parseFloat(end); } }; Tween.prototype._swapEndStartRepeatValues = function (property) { var tmp = this._valuesStartRepeat[property]; if (typeof this._valuesEnd[property] === 'string') { // eslint-disable-next-line // @ts-ignore FIXME? this._valuesStartRepeat[property] = this._valuesStartRepeat[property] + parseFloat(this._valuesEnd[property]); } else { this._valuesStartRepeat[property] = this._valuesEnd[property]; } this._valuesEnd[property] = tmp; }; return Tween; }()); var VERSION = '18.6.0'; /** * Tween.js - Licensed under the MIT license * https://github.com/tweenjs/tween.js * ---------------------------------------------- * * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors. * Thank you all, you're awesome! */ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /** * Controlling groups of tweens * * Using the TWEEN singleton to manage your tweens can cause issues in large apps with many components. * In these cases, you may want to create your own smaller groups of tween */ var Main = /** @class */ (function (_super) { __extends(Main, _super); function Main() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.version = VERSION; _this.now = NOW$1; _this.Group = Group; _this.Easing = Easing; _this.Interpolation = Interpolation; _this.nextId = Sequence.nextId; _this.Tween = Tween; return _this; } return Main; }(Group)); var TWEEN = new Main(); return TWEEN; })));
import"redux";import"./turn-order-b69ce3d4.js";import"immer";import"lodash.isplainobject";import"./reducer-ad5fe719.js";import"rfc6902";import"./initialize-546bf75c.js";import"./transport-0079de87.js";import"./base-13e38c3e.js";export{L as Local,S as SocketIO}from"./socketio-dc20fe9b.js";import"./master-deac3bd6.js";import"socket.io-client";
/*! * vue-i18n v8.25.1 * (c) 2021 kazuya kawaguchi * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.VueI18n = factory()); }(this, (function () { 'use strict'; /* */ /** * constants */ var numberFormatKeys = [ 'compactDisplay', 'currency', 'currencyDisplay', 'currencySign', 'localeMatcher', 'notation', 'numberingSystem', 'signDisplay', 'style', 'unit', 'unitDisplay', 'useGrouping', 'minimumIntegerDigits', 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits' ]; /** * utilities */ function warn (msg, err) { if (typeof console !== 'undefined') { console.warn('[vue-i18n] ' + msg); /* istanbul ignore if */ if (err) { console.warn(err.stack); } } } function error (msg, err) { if (typeof console !== 'undefined') { console.error('[vue-i18n] ' + msg); /* istanbul ignore if */ if (err) { console.error(err.stack); } } } var isArray = Array.isArray; function isObject (obj) { return obj !== null && typeof obj === 'object' } function isBoolean (val) { return typeof val === 'boolean' } function isString (val) { return typeof val === 'string' } var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; function isPlainObject (obj) { return toString.call(obj) === OBJECT_STRING } function isNull (val) { return val === null || val === undefined } function isFunction (val) { return typeof val === 'function' } function parseArgs () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var locale = null; var params = null; if (args.length === 1) { if (isObject(args[0]) || isArray(args[0])) { params = args[0]; } else if (typeof args[0] === 'string') { locale = args[0]; } } else if (args.length === 2) { if (typeof args[0] === 'string') { locale = args[0]; } /* istanbul ignore if */ if (isObject(args[1]) || isArray(args[1])) { params = args[1]; } } return { locale: locale, params: params } } function looseClone (obj) { return JSON.parse(JSON.stringify(obj)) } function remove (arr, item) { if (arr.delete(item)) { return arr } } function arrayFrom (arr) { var ret = []; arr.forEach(function (a) { return ret.push(a); }); return ret } function includes (arr, item) { return !!~arr.indexOf(item) } var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } function merge (target) { var arguments$1 = arguments; var output = Object(target); for (var i = 1; i < arguments.length; i++) { var source = arguments$1[i]; if (source !== undefined && source !== null) { var key = (void 0); for (key in source) { if (hasOwn(source, key)) { if (isObject(source[key])) { output[key] = merge(output[key], source[key]); } else { output[key] = source[key]; } } } } } return output } function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = isArray(a); var isArrayB = isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } /** * Sanitizes html special characters from input strings. For mitigating risk of XSS attacks. * @param rawText The raw input from the user that should be escaped. */ function escapeHtml(rawText) { return rawText .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;') } /** * Escapes html tags and special symbols from all provided params which were returned from parseArgs().params. * This method performs an in-place operation on the params object. * * @param {any} params Parameters as provided from `parseArgs().params`. * May be either an array of strings or a string->any map. * * @returns The manipulated `params` object. */ function escapeParams(params) { if(params != null) { Object.keys(params).forEach(function (key) { if(typeof(params[key]) == 'string') { params[key] = escapeHtml(params[key]); } }); } return params } /* */ function extend (Vue) { if (!Vue.prototype.hasOwnProperty('$i18n')) { // $FlowFixMe Object.defineProperty(Vue.prototype, '$i18n', { get: function get () { return this._i18n } }); } Vue.prototype.$t = function (key) { var values = [], len = arguments.length - 1; while ( len-- > 0 ) values[ len ] = arguments[ len + 1 ]; var i18n = this.$i18n; return i18n._t.apply(i18n, [ key, i18n.locale, i18n._getMessages(), this ].concat( values )) }; Vue.prototype.$tc = function (key, choice) { var values = [], len = arguments.length - 2; while ( len-- > 0 ) values[ len ] = arguments[ len + 2 ]; var i18n = this.$i18n; return i18n._tc.apply(i18n, [ key, i18n.locale, i18n._getMessages(), this, choice ].concat( values )) }; Vue.prototype.$te = function (key, locale) { var i18n = this.$i18n; return i18n._te(key, i18n.locale, i18n._getMessages(), locale) }; Vue.prototype.$d = function (value) { var ref; var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return (ref = this.$i18n).d.apply(ref, [ value ].concat( args )) }; Vue.prototype.$n = function (value) { var ref; var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; return (ref = this.$i18n).n.apply(ref, [ value ].concat( args )) }; } /* */ var mixin = { beforeCreate: function beforeCreate () { var options = this.$options; options.i18n = options.i18n || (options.__i18n ? {} : null); if (options.i18n) { if (options.i18n instanceof VueI18n) { // init locale messages via custom blocks if (options.__i18n) { try { var localeMessages = options.i18n && options.i18n.messages ? options.i18n.messages : {}; options.__i18n.forEach(function (resource) { localeMessages = merge(localeMessages, JSON.parse(resource)); }); Object.keys(localeMessages).forEach(function (locale) { options.i18n.mergeLocaleMessage(locale, localeMessages[locale]); }); } catch (e) { { error("Cannot parse locale messages via custom blocks.", e); } } } this._i18n = options.i18n; this._i18nWatcher = this._i18n.watchI18nData(); } else if (isPlainObject(options.i18n)) { var rootI18n = this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n ? this.$root.$i18n : null; // component local i18n if (rootI18n) { options.i18n.root = this.$root; options.i18n.formatter = rootI18n.formatter; options.i18n.fallbackLocale = rootI18n.fallbackLocale; options.i18n.formatFallbackMessages = rootI18n.formatFallbackMessages; options.i18n.silentTranslationWarn = rootI18n.silentTranslationWarn; options.i18n.silentFallbackWarn = rootI18n.silentFallbackWarn; options.i18n.pluralizationRules = rootI18n.pluralizationRules; options.i18n.preserveDirectiveContent = rootI18n.preserveDirectiveContent; } // init locale messages via custom blocks if (options.__i18n) { try { var localeMessages$1 = options.i18n && options.i18n.messages ? options.i18n.messages : {}; options.__i18n.forEach(function (resource) { localeMessages$1 = merge(localeMessages$1, JSON.parse(resource)); }); options.i18n.messages = localeMessages$1; } catch (e) { { warn("Cannot parse locale messages via custom blocks.", e); } } } var ref = options.i18n; var sharedMessages = ref.sharedMessages; if (sharedMessages && isPlainObject(sharedMessages)) { options.i18n.messages = merge(options.i18n.messages, sharedMessages); } this._i18n = new VueI18n(options.i18n); this._i18nWatcher = this._i18n.watchI18nData(); if (options.i18n.sync === undefined || !!options.i18n.sync) { this._localeWatcher = this.$i18n.watchLocale(); } if (rootI18n) { rootI18n.onComponentInstanceCreated(this._i18n); } } else { { warn("Cannot be interpreted 'i18n' option."); } } } else if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) { // root i18n this._i18n = this.$root.$i18n; } else if (options.parent && options.parent.$i18n && options.parent.$i18n instanceof VueI18n) { // parent i18n this._i18n = options.parent.$i18n; } }, beforeMount: function beforeMount () { var options = this.$options; options.i18n = options.i18n || (options.__i18n ? {} : null); if (options.i18n) { if (options.i18n instanceof VueI18n) { // init locale messages via custom blocks this._i18n.subscribeDataChanging(this); this._subscribing = true; } else if (isPlainObject(options.i18n)) { this._i18n.subscribeDataChanging(this); this._subscribing = true; } else { { warn("Cannot be interpreted 'i18n' option."); } } } else if (this.$root && this.$root.$i18n && this.$root.$i18n instanceof VueI18n) { this._i18n.subscribeDataChanging(this); this._subscribing = true; } else if (options.parent && options.parent.$i18n && options.parent.$i18n instanceof VueI18n) { this._i18n.subscribeDataChanging(this); this._subscribing = true; } }, mounted: function mounted () { if (this !== this.$root && this.$options.__INTLIFY_META__ && this.$el) { this.$el.setAttribute('data-intlify', this.$options.__INTLIFY_META__); } }, beforeDestroy: function beforeDestroy () { if (!this._i18n) { return } var self = this; this.$nextTick(function () { if (self._subscribing) { self._i18n.unsubscribeDataChanging(self); delete self._subscribing; } if (self._i18nWatcher) { self._i18nWatcher(); self._i18n.destroyVM(); delete self._i18nWatcher; } if (self._localeWatcher) { self._localeWatcher(); delete self._localeWatcher; } }); } }; /* */ var interpolationComponent = { name: 'i18n', functional: true, props: { tag: { type: [String, Boolean, Object], default: 'span' }, path: { type: String, required: true }, locale: { type: String }, places: { type: [Array, Object] } }, render: function render (h, ref) { var data = ref.data; var parent = ref.parent; var props = ref.props; var slots = ref.slots; var $i18n = parent.$i18n; if (!$i18n) { { warn('Cannot find VueI18n instance!'); } return } var path = props.path; var locale = props.locale; var places = props.places; var params = slots(); var children = $i18n.i( path, locale, onlyHasDefaultPlace(params) || places ? useLegacyPlaces(params.default, places) : params ); var tag = (!!props.tag && props.tag !== true) || props.tag === false ? props.tag : 'span'; return tag ? h(tag, data, children) : children } }; function onlyHasDefaultPlace (params) { var prop; for (prop in params) { if (prop !== 'default') { return false } } return Boolean(prop) } function useLegacyPlaces (children, places) { var params = places ? createParamsFromPlaces(places) : {}; if (!children) { return params } // Filter empty text nodes children = children.filter(function (child) { return child.tag || child.text.trim() !== '' }); var everyPlace = children.every(vnodeHasPlaceAttribute); if (everyPlace) { warn('`place` attribute is deprecated in next major version. Please switch to Vue slots.'); } return children.reduce( everyPlace ? assignChildPlace : assignChildIndex, params ) } function createParamsFromPlaces (places) { { warn('`places` prop is deprecated in next major version. Please switch to Vue slots.'); } return Array.isArray(places) ? places.reduce(assignChildIndex, {}) : Object.assign({}, places) } function assignChildPlace (params, child) { if (child.data && child.data.attrs && child.data.attrs.place) { params[child.data.attrs.place] = child; } return params } function assignChildIndex (params, child, index) { params[index] = child; return params } function vnodeHasPlaceAttribute (vnode) { return Boolean(vnode.data && vnode.data.attrs && vnode.data.attrs.place) } /* */ var numberComponent = { name: 'i18n-n', functional: true, props: { tag: { type: [String, Boolean, Object], default: 'span' }, value: { type: Number, required: true }, format: { type: [String, Object] }, locale: { type: String } }, render: function render (h, ref) { var props = ref.props; var parent = ref.parent; var data = ref.data; var i18n = parent.$i18n; if (!i18n) { { warn('Cannot find VueI18n instance!'); } return null } var key = null; var options = null; if (isString(props.format)) { key = props.format; } else if (isObject(props.format)) { if (props.format.key) { key = props.format.key; } // Filter out number format options only options = Object.keys(props.format).reduce(function (acc, prop) { var obj; if (includes(numberFormatKeys, prop)) { return Object.assign({}, acc, ( obj = {}, obj[prop] = props.format[prop], obj )) } return acc }, null); } var locale = props.locale || i18n.locale; var parts = i18n._ntp(props.value, locale, key, options); var values = parts.map(function (part, index) { var obj; var slot = data.scopedSlots && data.scopedSlots[part.type]; return slot ? slot(( obj = {}, obj[part.type] = part.value, obj.index = index, obj.parts = parts, obj )) : part.value }); var tag = (!!props.tag && props.tag !== true) || props.tag === false ? props.tag : 'span'; return tag ? h(tag, { attrs: data.attrs, 'class': data['class'], staticClass: data.staticClass }, values) : values } }; /* */ function bind (el, binding, vnode) { if (!assert(el, vnode)) { return } t(el, binding, vnode); } function update (el, binding, vnode, oldVNode) { if (!assert(el, vnode)) { return } var i18n = vnode.context.$i18n; if (localeEqual(el, vnode) && (looseEqual(binding.value, binding.oldValue) && looseEqual(el._localeMessage, i18n.getLocaleMessage(i18n.locale)))) { return } t(el, binding, vnode); } function unbind (el, binding, vnode, oldVNode) { var vm = vnode.context; if (!vm) { warn('Vue instance does not exists in VNode context'); return } var i18n = vnode.context.$i18n || {}; if (!binding.modifiers.preserve && !i18n.preserveDirectiveContent) { el.textContent = ''; } el._vt = undefined; delete el['_vt']; el._locale = undefined; delete el['_locale']; el._localeMessage = undefined; delete el['_localeMessage']; } function assert (el, vnode) { var vm = vnode.context; if (!vm) { warn('Vue instance does not exists in VNode context'); return false } if (!vm.$i18n) { warn('VueI18n instance does not exists in Vue instance'); return false } return true } function localeEqual (el, vnode) { var vm = vnode.context; return el._locale === vm.$i18n.locale } function t (el, binding, vnode) { var ref$1, ref$2; var value = binding.value; var ref = parseValue(value); var path = ref.path; var locale = ref.locale; var args = ref.args; var choice = ref.choice; if (!path && !locale && !args) { warn('value type not supported'); return } if (!path) { warn('`path` is required in v-t directive'); return } var vm = vnode.context; if (choice != null) { el._vt = el.textContent = (ref$1 = vm.$i18n).tc.apply(ref$1, [ path, choice ].concat( makeParams(locale, args) )); } else { el._vt = el.textContent = (ref$2 = vm.$i18n).t.apply(ref$2, [ path ].concat( makeParams(locale, args) )); } el._locale = vm.$i18n.locale; el._localeMessage = vm.$i18n.getLocaleMessage(vm.$i18n.locale); } function parseValue (value) { var path; var locale; var args; var choice; if (isString(value)) { path = value; } else if (isPlainObject(value)) { path = value.path; locale = value.locale; args = value.args; choice = value.choice; } return { path: path, locale: locale, args: args, choice: choice } } function makeParams (locale, args) { var params = []; locale && params.push(locale); if (args && (Array.isArray(args) || isPlainObject(args))) { params.push(args); } return params } var Vue; function install (_Vue) { /* istanbul ignore if */ if (install.installed && _Vue === Vue) { warn('already installed.'); return } install.installed = true; Vue = _Vue; var version = (Vue.version && Number(Vue.version.split('.')[0])) || -1; /* istanbul ignore if */ if (version < 2) { warn(("vue-i18n (" + (install.version) + ") need to use Vue 2.0 or later (Vue: " + (Vue.version) + ").")); return } extend(Vue); Vue.mixin(mixin); Vue.directive('t', { bind: bind, update: update, unbind: unbind }); Vue.component(interpolationComponent.name, interpolationComponent); Vue.component(numberComponent.name, numberComponent); // use simple mergeStrategies to prevent i18n instance lose '__proto__' var strats = Vue.config.optionMergeStrategies; strats.i18n = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; } /* */ var BaseFormatter = function BaseFormatter () { this._caches = Object.create(null); }; BaseFormatter.prototype.interpolate = function interpolate (message, values) { if (!values) { return [message] } var tokens = this._caches[message]; if (!tokens) { tokens = parse(message); this._caches[message] = tokens; } return compile(tokens, values) }; var RE_TOKEN_LIST_VALUE = /^(?:\d)+/; var RE_TOKEN_NAMED_VALUE = /^(?:\w)+/; function parse (format) { var tokens = []; var position = 0; var text = ''; while (position < format.length) { var char = format[position++]; if (char === '{') { if (text) { tokens.push({ type: 'text', value: text }); } text = ''; var sub = ''; char = format[position++]; while (char !== undefined && char !== '}') { sub += char; char = format[position++]; } var isClosed = char === '}'; var type = RE_TOKEN_LIST_VALUE.test(sub) ? 'list' : isClosed && RE_TOKEN_NAMED_VALUE.test(sub) ? 'named' : 'unknown'; tokens.push({ value: sub, type: type }); } else if (char === '%') { // when found rails i18n syntax, skip text capture if (format[(position)] !== '{') { text += char; } } else { text += char; } } text && tokens.push({ type: 'text', value: text }); return tokens } function compile (tokens, values) { var compiled = []; var index = 0; var mode = Array.isArray(values) ? 'list' : isObject(values) ? 'named' : 'unknown'; if (mode === 'unknown') { return compiled } while (index < tokens.length) { var token = tokens[index]; switch (token.type) { case 'text': compiled.push(token.value); break case 'list': compiled.push(values[parseInt(token.value, 10)]); break case 'named': if (mode === 'named') { compiled.push((values)[token.value]); } else { { warn(("Type of token '" + (token.type) + "' and format of value '" + mode + "' don't match!")); } } break case 'unknown': { warn("Detect 'unknown' type of token!"); } break } index++; } return compiled } /* */ /** * Path parser * - Inspired: * Vue.js Path parser */ // actions var APPEND = 0; var PUSH = 1; var INC_SUB_PATH_DEPTH = 2; var PUSH_SUB_PATH = 3; // states var BEFORE_PATH = 0; var IN_PATH = 1; var BEFORE_IDENT = 2; var IN_IDENT = 3; var IN_SUB_PATH = 4; var IN_SINGLE_QUOTE = 5; var IN_DOUBLE_QUOTE = 6; var AFTER_PATH = 7; var ERROR = 8; var pathStateMachine = []; pathStateMachine[BEFORE_PATH] = { 'ws': [BEFORE_PATH], 'ident': [IN_IDENT, APPEND], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[IN_PATH] = { 'ws': [IN_PATH], '.': [BEFORE_IDENT], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[BEFORE_IDENT] = { 'ws': [BEFORE_IDENT], 'ident': [IN_IDENT, APPEND], '0': [IN_IDENT, APPEND], 'number': [IN_IDENT, APPEND] }; pathStateMachine[IN_IDENT] = { 'ident': [IN_IDENT, APPEND], '0': [IN_IDENT, APPEND], 'number': [IN_IDENT, APPEND], 'ws': [IN_PATH, PUSH], '.': [BEFORE_IDENT, PUSH], '[': [IN_SUB_PATH, PUSH], 'eof': [AFTER_PATH, PUSH] }; pathStateMachine[IN_SUB_PATH] = { "'": [IN_SINGLE_QUOTE, APPEND], '"': [IN_DOUBLE_QUOTE, APPEND], '[': [IN_SUB_PATH, INC_SUB_PATH_DEPTH], ']': [IN_PATH, PUSH_SUB_PATH], 'eof': ERROR, 'else': [IN_SUB_PATH, APPEND] }; pathStateMachine[IN_SINGLE_QUOTE] = { "'": [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_SINGLE_QUOTE, APPEND] }; pathStateMachine[IN_DOUBLE_QUOTE] = { '"': [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_DOUBLE_QUOTE, APPEND] }; /** * Check if an expression is a literal value. */ var literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/; function isLiteral (exp) { return literalValueRE.test(exp) } /** * Strip quotes from a string */ function stripQuotes (str) { var a = str.charCodeAt(0); var b = str.charCodeAt(str.length - 1); return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str } /** * Determine the type of a character in a keypath. */ function getPathCharType (ch) { if (ch === undefined || ch === null) { return 'eof' } var code = ch.charCodeAt(0); switch (code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' return ch case 0x5F: // _ case 0x24: // $ case 0x2D: // - return 'ident' case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws' } return 'ident' } /** * Format a subPath, return its plain form if it is * a literal string or number. Otherwise prepend the * dynamic indicator (*). */ function formatSubPath (path) { var trimmed = path.trim(); // invalid leading 0 if (path.charAt(0) === '0' && isNaN(path)) { return false } return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed } /** * Parse a string path into an array of segments */ function parse$1 (path) { var keys = []; var index = -1; var mode = BEFORE_PATH; var subPathDepth = 0; var c; var key; var newChar; var type; var transition; var action; var typeMap; var actions = []; actions[PUSH] = function () { if (key !== undefined) { keys.push(key); key = undefined; } }; actions[APPEND] = function () { if (key === undefined) { key = newChar; } else { key += newChar; } }; actions[INC_SUB_PATH_DEPTH] = function () { actions[APPEND](); subPathDepth++; }; actions[PUSH_SUB_PATH] = function () { if (subPathDepth > 0) { subPathDepth--; mode = IN_SUB_PATH; actions[APPEND](); } else { subPathDepth = 0; if (key === undefined) { return false } key = formatSubPath(key); if (key === false) { return false } else { actions[PUSH](); } } }; function maybeUnescapeQuote () { var nextChar = path[index + 1]; if ((mode === IN_SINGLE_QUOTE && nextChar === "'") || (mode === IN_DOUBLE_QUOTE && nextChar === '"')) { index++; newChar = '\\' + nextChar; actions[APPEND](); return true } } while (mode !== null) { index++; c = path[index]; if (c === '\\' && maybeUnescapeQuote()) { continue } type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap['else'] || ERROR; if (transition === ERROR) { return // parse error } mode = transition[0]; action = actions[transition[1]]; if (action) { newChar = transition[2]; newChar = newChar === undefined ? c : newChar; if (action() === false) { return } } if (mode === AFTER_PATH) { return keys } } } var I18nPath = function I18nPath () { this._cache = Object.create(null); }; /** * External parse that check for a cache hit first */ I18nPath.prototype.parsePath = function parsePath (path) { var hit = this._cache[path]; if (!hit) { hit = parse$1(path); if (hit) { this._cache[path] = hit; } } return hit || [] }; /** * Get path value from path string */ I18nPath.prototype.getPathValue = function getPathValue (obj, path) { if (!isObject(obj)) { return null } var paths = this.parsePath(path); if (paths.length === 0) { return null } else { var length = paths.length; var last = obj; var i = 0; while (i < length) { var value = last[paths[i]]; if (value === undefined || value === null) { return null } last = value; i++; } return last } }; /* */ var htmlTagMatcher = /<\/?[\w\s="/.':;#-\/]+>/; var linkKeyMatcher = /(?:@(?:\.[a-z]+)?:(?:[\w\-_|./]+|\([\w\-_|./]+\)))/g; var linkKeyPrefixMatcher = /^@(?:\.([a-z]+))?:/; var bracketsMatcher = /[()]/g; var defaultModifiers = { 'upper': function (str) { return str.toLocaleUpperCase(); }, 'lower': function (str) { return str.toLocaleLowerCase(); }, 'capitalize': function (str) { return ("" + (str.charAt(0).toLocaleUpperCase()) + (str.substr(1))); } }; var defaultFormatter = new BaseFormatter(); var VueI18n = function VueI18n (options) { var this$1 = this; if ( options === void 0 ) options = {}; // Auto install if it is not done yet and `window` has `Vue`. // To allow users to avoid auto-installation in some cases, // this code should be placed here. See #290 /* istanbul ignore if */ if (!Vue && typeof window !== 'undefined' && window.Vue) { install(window.Vue); } var locale = options.locale || 'en-US'; var fallbackLocale = options.fallbackLocale === false ? false : options.fallbackLocale || 'en-US'; var messages = options.messages || {}; var dateTimeFormats = options.dateTimeFormats || {}; var numberFormats = options.numberFormats || {}; this._vm = null; this._formatter = options.formatter || defaultFormatter; this._modifiers = options.modifiers || {}; this._missing = options.missing || null; this._root = options.root || null; this._sync = options.sync === undefined ? true : !!options.sync; this._fallbackRoot = options.fallbackRoot === undefined ? true : !!options.fallbackRoot; this._formatFallbackMessages = options.formatFallbackMessages === undefined ? false : !!options.formatFallbackMessages; this._silentTranslationWarn = options.silentTranslationWarn === undefined ? false : options.silentTranslationWarn; this._silentFallbackWarn = options.silentFallbackWarn === undefined ? false : !!options.silentFallbackWarn; this._dateTimeFormatters = {}; this._numberFormatters = {}; this._path = new I18nPath(); this._dataListeners = new Set(); this._componentInstanceCreatedListener = options.componentInstanceCreatedListener || null; this._preserveDirectiveContent = options.preserveDirectiveContent === undefined ? false : !!options.preserveDirectiveContent; this.pluralizationRules = options.pluralizationRules || {}; this._warnHtmlInMessage = options.warnHtmlInMessage || 'off'; this._postTranslation = options.postTranslation || null; this._escapeParameterHtml = options.escapeParameterHtml || false; /** * @param choice {number} a choice index given by the input to $tc: `$tc('path.to.rule', choiceIndex)` * @param choicesLength {number} an overall amount of available choices * @returns a final choice index */ this.getChoiceIndex = function (choice, choicesLength) { var thisPrototype = Object.getPrototypeOf(this$1); if (thisPrototype && thisPrototype.getChoiceIndex) { var prototypeGetChoiceIndex = (thisPrototype.getChoiceIndex); return (prototypeGetChoiceIndex).call(this$1, choice, choicesLength) } // Default (old) getChoiceIndex implementation - english-compatible var defaultImpl = function (_choice, _choicesLength) { _choice = Math.abs(_choice); if (_choicesLength === 2) { return _choice ? _choice > 1 ? 1 : 0 : 1 } return _choice ? Math.min(_choice, 2) : 0 }; if (this$1.locale in this$1.pluralizationRules) { return this$1.pluralizationRules[this$1.locale].apply(this$1, [choice, choicesLength]) } else { return defaultImpl(choice, choicesLength) } }; this._exist = function (message, key) { if (!message || !key) { return false } if (!isNull(this$1._path.getPathValue(message, key))) { return true } // fallback for flat key if (message[key]) { return true } return false }; if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') { Object.keys(messages).forEach(function (locale) { this$1._checkLocaleMessage(locale, this$1._warnHtmlInMessage, messages[locale]); }); } this._initVM({ locale: locale, fallbackLocale: fallbackLocale, messages: messages, dateTimeFormats: dateTimeFormats, numberFormats: numberFormats }); }; var prototypeAccessors = { vm: { configurable: true },messages: { configurable: true },dateTimeFormats: { configurable: true },numberFormats: { configurable: true },availableLocales: { configurable: true },locale: { configurable: true },fallbackLocale: { configurable: true },formatFallbackMessages: { configurable: true },missing: { configurable: true },formatter: { configurable: true },silentTranslationWarn: { configurable: true },silentFallbackWarn: { configurable: true },preserveDirectiveContent: { configurable: true },warnHtmlInMessage: { configurable: true },postTranslation: { configurable: true } }; VueI18n.prototype._checkLocaleMessage = function _checkLocaleMessage (locale, level, message) { var paths = []; var fn = function (level, locale, message, paths) { if (isPlainObject(message)) { Object.keys(message).forEach(function (key) { var val = message[key]; if (isPlainObject(val)) { paths.push(key); paths.push('.'); fn(level, locale, val, paths); paths.pop(); paths.pop(); } else { paths.push(key); fn(level, locale, val, paths); paths.pop(); } }); } else if (isArray(message)) { message.forEach(function (item, index) { if (isPlainObject(item)) { paths.push(("[" + index + "]")); paths.push('.'); fn(level, locale, item, paths); paths.pop(); paths.pop(); } else { paths.push(("[" + index + "]")); fn(level, locale, item, paths); paths.pop(); } }); } else if (isString(message)) { var ret = htmlTagMatcher.test(message); if (ret) { var msg = "Detected HTML in message '" + message + "' of keypath '" + (paths.join('')) + "' at '" + locale + "'. Consider component interpolation with '<i18n>' to avoid XSS. See https://bit.ly/2ZqJzkp"; if (level === 'warn') { warn(msg); } else if (level === 'error') { error(msg); } } } }; fn(level, locale, message, paths); }; VueI18n.prototype._initVM = function _initVM (data) { var silent = Vue.config.silent; Vue.config.silent = true; this._vm = new Vue({ data: data }); Vue.config.silent = silent; }; VueI18n.prototype.destroyVM = function destroyVM () { this._vm.$destroy(); }; VueI18n.prototype.subscribeDataChanging = function subscribeDataChanging (vm) { this._dataListeners.add(vm); }; VueI18n.prototype.unsubscribeDataChanging = function unsubscribeDataChanging (vm) { remove(this._dataListeners, vm); }; VueI18n.prototype.watchI18nData = function watchI18nData () { var this$1 = this; return this._vm.$watch('$data', function () { var listeners = arrayFrom(this$1._dataListeners); var i = listeners.length; while(i--) { Vue.nextTick(function () { listeners[i] && listeners[i].$forceUpdate(); }); } }, { deep: true }) }; VueI18n.prototype.watchLocale = function watchLocale () { /* istanbul ignore if */ if (!this._sync || !this._root) { return null } var target = this._vm; return this._root.$i18n.vm.$watch('locale', function (val) { target.$set(target, 'locale', val); target.$forceUpdate(); }, { immediate: true }) }; VueI18n.prototype.onComponentInstanceCreated = function onComponentInstanceCreated (newI18n) { if (this._componentInstanceCreatedListener) { this._componentInstanceCreatedListener(newI18n, this); } }; prototypeAccessors.vm.get = function () { return this._vm }; prototypeAccessors.messages.get = function () { return looseClone(this._getMessages()) }; prototypeAccessors.dateTimeFormats.get = function () { return looseClone(this._getDateTimeFormats()) }; prototypeAccessors.numberFormats.get = function () { return looseClone(this._getNumberFormats()) }; prototypeAccessors.availableLocales.get = function () { return Object.keys(this.messages).sort() }; prototypeAccessors.locale.get = function () { return this._vm.locale }; prototypeAccessors.locale.set = function (locale) { this._vm.$set(this._vm, 'locale', locale); }; prototypeAccessors.fallbackLocale.get = function () { return this._vm.fallbackLocale }; prototypeAccessors.fallbackLocale.set = function (locale) { this._localeChainCache = {}; this._vm.$set(this._vm, 'fallbackLocale', locale); }; prototypeAccessors.formatFallbackMessages.get = function () { return this._formatFallbackMessages }; prototypeAccessors.formatFallbackMessages.set = function (fallback) { this._formatFallbackMessages = fallback; }; prototypeAccessors.missing.get = function () { return this._missing }; prototypeAccessors.missing.set = function (handler) { this._missing = handler; }; prototypeAccessors.formatter.get = function () { return this._formatter }; prototypeAccessors.formatter.set = function (formatter) { this._formatter = formatter; }; prototypeAccessors.silentTranslationWarn.get = function () { return this._silentTranslationWarn }; prototypeAccessors.silentTranslationWarn.set = function (silent) { this._silentTranslationWarn = silent; }; prototypeAccessors.silentFallbackWarn.get = function () { return this._silentFallbackWarn }; prototypeAccessors.silentFallbackWarn.set = function (silent) { this._silentFallbackWarn = silent; }; prototypeAccessors.preserveDirectiveContent.get = function () { return this._preserveDirectiveContent }; prototypeAccessors.preserveDirectiveContent.set = function (preserve) { this._preserveDirectiveContent = preserve; }; prototypeAccessors.warnHtmlInMessage.get = function () { return this._warnHtmlInMessage }; prototypeAccessors.warnHtmlInMessage.set = function (level) { var this$1 = this; var orgLevel = this._warnHtmlInMessage; this._warnHtmlInMessage = level; if (orgLevel !== level && (level === 'warn' || level === 'error')) { var messages = this._getMessages(); Object.keys(messages).forEach(function (locale) { this$1._checkLocaleMessage(locale, this$1._warnHtmlInMessage, messages[locale]); }); } }; prototypeAccessors.postTranslation.get = function () { return this._postTranslation }; prototypeAccessors.postTranslation.set = function (handler) { this._postTranslation = handler; }; VueI18n.prototype._getMessages = function _getMessages () { return this._vm.messages }; VueI18n.prototype._getDateTimeFormats = function _getDateTimeFormats () { return this._vm.dateTimeFormats }; VueI18n.prototype._getNumberFormats = function _getNumberFormats () { return this._vm.numberFormats }; VueI18n.prototype._warnDefault = function _warnDefault (locale, key, result, vm, values, interpolateMode) { if (!isNull(result)) { return result } if (this._missing) { var missingRet = this._missing.apply(null, [locale, key, vm, values]); if (isString(missingRet)) { return missingRet } } else { if (!this._isSilentTranslationWarn(key)) { warn( "Cannot translate the value of keypath '" + key + "'. " + 'Use the value of keypath as default.' ); } } if (this._formatFallbackMessages) { var parsedArgs = parseArgs.apply(void 0, values); return this._render(key, interpolateMode, parsedArgs.params, key) } else { return key } }; VueI18n.prototype._isFallbackRoot = function _isFallbackRoot (val) { return !val && !isNull(this._root) && this._fallbackRoot }; VueI18n.prototype._isSilentFallbackWarn = function _isSilentFallbackWarn (key) { return this._silentFallbackWarn instanceof RegExp ? this._silentFallbackWarn.test(key) : this._silentFallbackWarn }; VueI18n.prototype._isSilentFallback = function _isSilentFallback (locale, key) { return this._isSilentFallbackWarn(key) && (this._isFallbackRoot() || locale !== this.fallbackLocale) }; VueI18n.prototype._isSilentTranslationWarn = function _isSilentTranslationWarn (key) { return this._silentTranslationWarn instanceof RegExp ? this._silentTranslationWarn.test(key) : this._silentTranslationWarn }; VueI18n.prototype._interpolate = function _interpolate ( locale, message, key, host, interpolateMode, values, visitedLinkStack ) { if (!message) { return null } var pathRet = this._path.getPathValue(message, key); if (isArray(pathRet) || isPlainObject(pathRet)) { return pathRet } var ret; if (isNull(pathRet)) { /* istanbul ignore else */ if (isPlainObject(message)) { ret = message[key]; if (!(isString(ret) || isFunction(ret))) { if (!this._isSilentTranslationWarn(key) && !this._isSilentFallback(locale, key)) { warn(("Value of key '" + key + "' is not a string or function !")); } return null } } else { return null } } else { /* istanbul ignore else */ if (isString(pathRet) || isFunction(pathRet)) { ret = pathRet; } else { if (!this._isSilentTranslationWarn(key) && !this._isSilentFallback(locale, key)) { warn(("Value of key '" + key + "' is not a string or function!")); } return null } } // Check for the existence of links within the translated string if (isString(ret) && (ret.indexOf('@:') >= 0 || ret.indexOf('@.') >= 0)) { ret = this._link(locale, message, ret, host, 'raw', values, visitedLinkStack); } return this._render(ret, interpolateMode, values, key) }; VueI18n.prototype._link = function _link ( locale, message, str, host, interpolateMode, values, visitedLinkStack ) { var ret = str; // Match all the links within the local // We are going to replace each of // them with its translation var matches = ret.match(linkKeyMatcher); // eslint-disable-next-line no-autofix/prefer-const for (var idx in matches) { // ie compatible: filter custom array // prototype method if (!matches.hasOwnProperty(idx)) { continue } var link = matches[idx]; var linkKeyPrefixMatches = link.match(linkKeyPrefixMatcher); var linkPrefix = linkKeyPrefixMatches[0]; var formatterName = linkKeyPrefixMatches[1]; // Remove the leading @:, @.case: and the brackets var linkPlaceholder = link.replace(linkPrefix, '').replace(bracketsMatcher, ''); if (includes(visitedLinkStack, linkPlaceholder)) { { warn(("Circular reference found. \"" + link + "\" is already visited in the chain of " + (visitedLinkStack.reverse().join(' <- ')))); } return ret } visitedLinkStack.push(linkPlaceholder); // Translate the link var translated = this._interpolate( locale, message, linkPlaceholder, host, interpolateMode === 'raw' ? 'string' : interpolateMode, interpolateMode === 'raw' ? undefined : values, visitedLinkStack ); if (this._isFallbackRoot(translated)) { if (!this._isSilentTranslationWarn(linkPlaceholder)) { warn(("Fall back to translate the link placeholder '" + linkPlaceholder + "' with root locale.")); } /* istanbul ignore if */ if (!this._root) { throw Error('unexpected error') } var root = this._root.$i18n; translated = root._translate( root._getMessages(), root.locale, root.fallbackLocale, linkPlaceholder, host, interpolateMode, values ); } translated = this._warnDefault( locale, linkPlaceholder, translated, host, isArray(values) ? values : [values], interpolateMode ); if (this._modifiers.hasOwnProperty(formatterName)) { translated = this._modifiers[formatterName](translated); } else if (defaultModifiers.hasOwnProperty(formatterName)) { translated = defaultModifiers[formatterName](translated); } visitedLinkStack.pop(); // Replace the link with the translated ret = !translated ? ret : ret.replace(link, translated); } return ret }; VueI18n.prototype._createMessageContext = function _createMessageContext (values, formatter, path, interpolateMode) { var this$1 = this; var _list = isArray(values) ? values : []; var _named = isObject(values) ? values : {}; var list = function (index) { return _list[index]; }; var named = function (key) { return _named[key]; }; var messages = this._getMessages(); var locale = this.locale; return { list: list, named: named, values: values, formatter: formatter, path: path, messages: messages, locale: locale, linked: function (linkedKey) { return this$1._interpolate(locale, messages[locale] || {}, linkedKey, null, interpolateMode, undefined, [linkedKey]); } } }; VueI18n.prototype._render = function _render (message, interpolateMode, values, path) { if (isFunction(message)) { return message( this._createMessageContext(values, this._formatter || defaultFormatter, path, interpolateMode) ) } var ret = this._formatter.interpolate(message, values, path); // If the custom formatter refuses to work - apply the default one if (!ret) { ret = defaultFormatter.interpolate(message, values, path); } // if interpolateMode is **not** 'string' ('row'), // return the compiled data (e.g. ['foo', VNode, 'bar']) with formatter return interpolateMode === 'string' && !isString(ret) ? ret.join('') : ret }; VueI18n.prototype._appendItemToChain = function _appendItemToChain (chain, item, blocks) { var follow = false; if (!includes(chain, item)) { follow = true; if (item) { follow = item[item.length - 1] !== '!'; item = item.replace(/!/g, ''); chain.push(item); if (blocks && blocks[item]) { follow = blocks[item]; } } } return follow }; VueI18n.prototype._appendLocaleToChain = function _appendLocaleToChain (chain, locale, blocks) { var follow; var tokens = locale.split('-'); do { var item = tokens.join('-'); follow = this._appendItemToChain(chain, item, blocks); tokens.splice(-1, 1); } while (tokens.length && (follow === true)) return follow }; VueI18n.prototype._appendBlockToChain = function _appendBlockToChain (chain, block, blocks) { var follow = true; for (var i = 0; (i < block.length) && (isBoolean(follow)); i++) { var locale = block[i]; if (isString(locale)) { follow = this._appendLocaleToChain(chain, locale, blocks); } } return follow }; VueI18n.prototype._getLocaleChain = function _getLocaleChain (start, fallbackLocale) { if (start === '') { return [] } if (!this._localeChainCache) { this._localeChainCache = {}; } var chain = this._localeChainCache[start]; if (!chain) { if (!fallbackLocale) { fallbackLocale = this.fallbackLocale; } chain = []; // first block defined by start var block = [start]; // while any intervening block found while (isArray(block)) { block = this._appendBlockToChain( chain, block, fallbackLocale ); } // last block defined by default var defaults; if (isArray(fallbackLocale)) { defaults = fallbackLocale; } else if (isObject(fallbackLocale)) { /* $FlowFixMe */ if (fallbackLocale['default']) { defaults = fallbackLocale['default']; } else { defaults = null; } } else { defaults = fallbackLocale; } // convert defaults to array if (isString(defaults)) { block = [defaults]; } else { block = defaults; } if (block) { this._appendBlockToChain( chain, block, null ); } this._localeChainCache[start] = chain; } return chain }; VueI18n.prototype._translate = function _translate ( messages, locale, fallback, key, host, interpolateMode, args ) { var chain = this._getLocaleChain(locale, fallback); var res; for (var i = 0; i < chain.length; i++) { var step = chain[i]; res = this._interpolate(step, messages[step], key, host, interpolateMode, args, [key]); if (!isNull(res)) { if (step !== locale && "development" !== 'production' && !this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) { warn(("Fall back to translate the keypath '" + key + "' with '" + step + "' locale.")); } return res } } return null }; VueI18n.prototype._t = function _t (key, _locale, messages, host) { var ref; var values = [], len = arguments.length - 4; while ( len-- > 0 ) values[ len ] = arguments[ len + 4 ]; if (!key) { return '' } var parsedArgs = parseArgs.apply(void 0, values); if(this._escapeParameterHtml) { parsedArgs.params = escapeParams(parsedArgs.params); } var locale = parsedArgs.locale || _locale; var ret = this._translate( messages, locale, this.fallbackLocale, key, host, 'string', parsedArgs.params ); if (this._isFallbackRoot(ret)) { if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) { warn(("Fall back to translate the keypath '" + key + "' with root locale.")); } /* istanbul ignore if */ if (!this._root) { throw Error('unexpected error') } return (ref = this._root).$t.apply(ref, [ key ].concat( values )) } else { ret = this._warnDefault(locale, key, ret, host, values, 'string'); if (this._postTranslation && ret !== null && ret !== undefined) { ret = this._postTranslation(ret, key); } return ret } }; VueI18n.prototype.t = function t (key) { var ref; var values = [], len = arguments.length - 1; while ( len-- > 0 ) values[ len ] = arguments[ len + 1 ]; return (ref = this)._t.apply(ref, [ key, this.locale, this._getMessages(), null ].concat( values )) }; VueI18n.prototype._i = function _i (key, locale, messages, host, values) { var ret = this._translate(messages, locale, this.fallbackLocale, key, host, 'raw', values); if (this._isFallbackRoot(ret)) { if (!this._isSilentTranslationWarn(key)) { warn(("Fall back to interpolate the keypath '" + key + "' with root locale.")); } if (!this._root) { throw Error('unexpected error') } return this._root.$i18n.i(key, locale, values) } else { return this._warnDefault(locale, key, ret, host, [values], 'raw') } }; VueI18n.prototype.i = function i (key, locale, values) { /* istanbul ignore if */ if (!key) { return '' } if (!isString(locale)) { locale = this.locale; } return this._i(key, locale, this._getMessages(), null, values) }; VueI18n.prototype._tc = function _tc ( key, _locale, messages, host, choice ) { var ref; var values = [], len = arguments.length - 5; while ( len-- > 0 ) values[ len ] = arguments[ len + 5 ]; if (!key) { return '' } if (choice === undefined) { choice = 1; } var predefined = { 'count': choice, 'n': choice }; var parsedArgs = parseArgs.apply(void 0, values); parsedArgs.params = Object.assign(predefined, parsedArgs.params); values = parsedArgs.locale === null ? [parsedArgs.params] : [parsedArgs.locale, parsedArgs.params]; return this.fetchChoice((ref = this)._t.apply(ref, [ key, _locale, messages, host ].concat( values )), choice) }; VueI18n.prototype.fetchChoice = function fetchChoice (message, choice) { /* istanbul ignore if */ if (!message || !isString(message)) { return null } var choices = message.split('|'); choice = this.getChoiceIndex(choice, choices.length); if (!choices[choice]) { return message } return choices[choice].trim() }; VueI18n.prototype.tc = function tc (key, choice) { var ref; var values = [], len = arguments.length - 2; while ( len-- > 0 ) values[ len ] = arguments[ len + 2 ]; return (ref = this)._tc.apply(ref, [ key, this.locale, this._getMessages(), null, choice ].concat( values )) }; VueI18n.prototype._te = function _te (key, locale, messages) { var args = [], len = arguments.length - 3; while ( len-- > 0 ) args[ len ] = arguments[ len + 3 ]; var _locale = parseArgs.apply(void 0, args).locale || locale; return this._exist(messages[_locale], key) }; VueI18n.prototype.te = function te (key, locale) { return this._te(key, this.locale, this._getMessages(), locale) }; VueI18n.prototype.getLocaleMessage = function getLocaleMessage (locale) { return looseClone(this._vm.messages[locale] || {}) }; VueI18n.prototype.setLocaleMessage = function setLocaleMessage (locale, message) { if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') { this._checkLocaleMessage(locale, this._warnHtmlInMessage, message); } this._vm.$set(this._vm.messages, locale, message); }; VueI18n.prototype.mergeLocaleMessage = function mergeLocaleMessage (locale, message) { if (this._warnHtmlInMessage === 'warn' || this._warnHtmlInMessage === 'error') { this._checkLocaleMessage(locale, this._warnHtmlInMessage, message); } this._vm.$set(this._vm.messages, locale, merge( typeof this._vm.messages[locale] !== 'undefined' && Object.keys(this._vm.messages[locale]).length ? Object.assign({}, this._vm.messages[locale]) : {}, message )); }; VueI18n.prototype.getDateTimeFormat = function getDateTimeFormat (locale) { return looseClone(this._vm.dateTimeFormats[locale] || {}) }; VueI18n.prototype.setDateTimeFormat = function setDateTimeFormat (locale, format) { this._vm.$set(this._vm.dateTimeFormats, locale, format); this._clearDateTimeFormat(locale, format); }; VueI18n.prototype.mergeDateTimeFormat = function mergeDateTimeFormat (locale, format) { this._vm.$set(this._vm.dateTimeFormats, locale, merge(this._vm.dateTimeFormats[locale] || {}, format)); this._clearDateTimeFormat(locale, format); }; VueI18n.prototype._clearDateTimeFormat = function _clearDateTimeFormat (locale, format) { // eslint-disable-next-line no-autofix/prefer-const for (var key in format) { var id = locale + "__" + key; if (!this._dateTimeFormatters.hasOwnProperty(id)) { continue } delete this._dateTimeFormatters[id]; } }; VueI18n.prototype._localizeDateTime = function _localizeDateTime ( value, locale, fallback, dateTimeFormats, key ) { var _locale = locale; var formats = dateTimeFormats[_locale]; var chain = this._getLocaleChain(locale, fallback); for (var i = 0; i < chain.length; i++) { var current = _locale; var step = chain[i]; formats = dateTimeFormats[step]; _locale = step; // fallback locale if (isNull(formats) || isNull(formats[key])) { if (step !== locale && "development" !== 'production' && !this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) { warn(("Fall back to '" + step + "' datetime formats from '" + current + "' datetime formats.")); } } else { break } } if (isNull(formats) || isNull(formats[key])) { return null } else { var format = formats[key]; var id = _locale + "__" + key; var formatter = this._dateTimeFormatters[id]; if (!formatter) { formatter = this._dateTimeFormatters[id] = new Intl.DateTimeFormat(_locale, format); } return formatter.format(value) } }; VueI18n.prototype._d = function _d (value, locale, key) { /* istanbul ignore if */ if (!VueI18n.availabilities.dateTimeFormat) { warn('Cannot format a Date value due to not supported Intl.DateTimeFormat.'); return '' } if (!key) { return new Intl.DateTimeFormat(locale).format(value) } var ret = this._localizeDateTime(value, locale, this.fallbackLocale, this._getDateTimeFormats(), key); if (this._isFallbackRoot(ret)) { if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) { warn(("Fall back to datetime localization of root: key '" + key + "'.")); } /* istanbul ignore if */ if (!this._root) { throw Error('unexpected error') } return this._root.$i18n.d(value, key, locale) } else { return ret || '' } }; VueI18n.prototype.d = function d (value) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var locale = this.locale; var key = null; if (args.length === 1) { if (isString(args[0])) { key = args[0]; } else if (isObject(args[0])) { if (args[0].locale) { locale = args[0].locale; } if (args[0].key) { key = args[0].key; } } } else if (args.length === 2) { if (isString(args[0])) { key = args[0]; } if (isString(args[1])) { locale = args[1]; } } return this._d(value, locale, key) }; VueI18n.prototype.getNumberFormat = function getNumberFormat (locale) { return looseClone(this._vm.numberFormats[locale] || {}) }; VueI18n.prototype.setNumberFormat = function setNumberFormat (locale, format) { this._vm.$set(this._vm.numberFormats, locale, format); this._clearNumberFormat(locale, format); }; VueI18n.prototype.mergeNumberFormat = function mergeNumberFormat (locale, format) { this._vm.$set(this._vm.numberFormats, locale, merge(this._vm.numberFormats[locale] || {}, format)); this._clearNumberFormat(locale, format); }; VueI18n.prototype._clearNumberFormat = function _clearNumberFormat (locale, format) { // eslint-disable-next-line no-autofix/prefer-const for (var key in format) { var id = locale + "__" + key; if (!this._numberFormatters.hasOwnProperty(id)) { continue } delete this._numberFormatters[id]; } }; VueI18n.prototype._getNumberFormatter = function _getNumberFormatter ( value, locale, fallback, numberFormats, key, options ) { var _locale = locale; var formats = numberFormats[_locale]; var chain = this._getLocaleChain(locale, fallback); for (var i = 0; i < chain.length; i++) { var current = _locale; var step = chain[i]; formats = numberFormats[step]; _locale = step; // fallback locale if (isNull(formats) || isNull(formats[key])) { if (step !== locale && "development" !== 'production' && !this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) { warn(("Fall back to '" + step + "' number formats from '" + current + "' number formats.")); } } else { break } } if (isNull(formats) || isNull(formats[key])) { return null } else { var format = formats[key]; var formatter; if (options) { // If options specified - create one time number formatter formatter = new Intl.NumberFormat(_locale, Object.assign({}, format, options)); } else { var id = _locale + "__" + key; formatter = this._numberFormatters[id]; if (!formatter) { formatter = this._numberFormatters[id] = new Intl.NumberFormat(_locale, format); } } return formatter } }; VueI18n.prototype._n = function _n (value, locale, key, options) { /* istanbul ignore if */ if (!VueI18n.availabilities.numberFormat) { { warn('Cannot format a Number value due to not supported Intl.NumberFormat.'); } return '' } if (!key) { var nf = !options ? new Intl.NumberFormat(locale) : new Intl.NumberFormat(locale, options); return nf.format(value) } var formatter = this._getNumberFormatter(value, locale, this.fallbackLocale, this._getNumberFormats(), key, options); var ret = formatter && formatter.format(value); if (this._isFallbackRoot(ret)) { if (!this._isSilentTranslationWarn(key) && !this._isSilentFallbackWarn(key)) { warn(("Fall back to number localization of root: key '" + key + "'.")); } /* istanbul ignore if */ if (!this._root) { throw Error('unexpected error') } return this._root.$i18n.n(value, Object.assign({}, { key: key, locale: locale }, options)) } else { return ret || '' } }; VueI18n.prototype.n = function n (value) { var args = [], len = arguments.length - 1; while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ]; var locale = this.locale; var key = null; var options = null; if (args.length === 1) { if (isString(args[0])) { key = args[0]; } else if (isObject(args[0])) { if (args[0].locale) { locale = args[0].locale; } if (args[0].key) { key = args[0].key; } // Filter out number format options only options = Object.keys(args[0]).reduce(function (acc, key) { var obj; if (includes(numberFormatKeys, key)) { return Object.assign({}, acc, ( obj = {}, obj[key] = args[0][key], obj )) } return acc }, null); } } else if (args.length === 2) { if (isString(args[0])) { key = args[0]; } if (isString(args[1])) { locale = args[1]; } } return this._n(value, locale, key, options) }; VueI18n.prototype._ntp = function _ntp (value, locale, key, options) { /* istanbul ignore if */ if (!VueI18n.availabilities.numberFormat) { { warn('Cannot format to parts a Number value due to not supported Intl.NumberFormat.'); } return [] } if (!key) { var nf = !options ? new Intl.NumberFormat(locale) : new Intl.NumberFormat(locale, options); return nf.formatToParts(value) } var formatter = this._getNumberFormatter(value, locale, this.fallbackLocale, this._getNumberFormats(), key, options); var ret = formatter && formatter.formatToParts(value); if (this._isFallbackRoot(ret)) { if (!this._isSilentTranslationWarn(key)) { warn(("Fall back to format number to parts of root: key '" + key + "' .")); } /* istanbul ignore if */ if (!this._root) { throw Error('unexpected error') } return this._root.$i18n._ntp(value, locale, key, options) } else { return ret || [] } }; Object.defineProperties( VueI18n.prototype, prototypeAccessors ); var availabilities; // $FlowFixMe Object.defineProperty(VueI18n, 'availabilities', { get: function get () { if (!availabilities) { var intlDefined = typeof Intl !== 'undefined'; availabilities = { dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined', numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined' }; } return availabilities } }); VueI18n.install = install; VueI18n.version = '8.25.1'; return VueI18n; })));
/* * * * Exporting module * * (c) 2010-2021 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import Chart from '../Core/Chart/Chart.js'; import chartNavigationMixin from '../Mixins/Navigation.js'; import H from '../Core/Globals.js'; var doc = H.doc, isTouchDevice = H.isTouchDevice, win = H.win; import O from '../Core/Options.js'; var defaultOptions = O.defaultOptions; import palette from '../Core/Color/Palette.js'; import SVGRenderer from '../Core/Renderer/SVG/SVGRenderer.js'; import U from '../Core/Utilities.js'; var addEvent = U.addEvent, css = U.css, createElement = U.createElement, discardElement = U.discardElement, extend = U.extend, find = U.find, fireEvent = U.fireEvent, isObject = U.isObject, merge = U.merge, objectEach = U.objectEach, pick = U.pick, removeEvent = U.removeEvent, uniqueKey = U.uniqueKey; /** * Gets fired after a chart is printed through the context menu item or the * Chart.print method. * * @callback Highcharts.ExportingAfterPrintCallbackFunction * * @param {Highcharts.Chart} chart * The chart on which the event occured. * * @param {global.Event} event * The event that occured. */ /** * Gets fired before a chart is printed through the context menu item or the * Chart.print method. * * @callback Highcharts.ExportingBeforePrintCallbackFunction * * @param {Highcharts.Chart} chart * The chart on which the event occured. * * @param {global.Event} event * The event that occured. */ /** * Function to call if the offline-exporting module fails to export a chart on * the client side. * * @callback Highcharts.ExportingErrorCallbackFunction * * @param {Highcharts.ExportingOptions} options * The exporting options. * * @param {global.Error} err * The error from the module. */ /** * Definition for a menu item in the context menu. * * @interface Highcharts.ExportingMenuObject */ /** * The text for the menu item. * * @name Highcharts.ExportingMenuObject#text * @type {string|undefined} */ /** * If internationalization is required, the key to a language string. * * @name Highcharts.ExportingMenuObject#textKey * @type {string|undefined} */ /** * The click handler for the menu item. * * @name Highcharts.ExportingMenuObject#onclick * @type {Highcharts.EventCallbackFunction<Highcharts.Chart>|undefined} */ /** * Indicates a separator line instead of an item. * * @name Highcharts.ExportingMenuObject#separator * @type {boolean|undefined} */ /** * Possible MIME types for exporting. * * @typedef {"image/png"|"image/jpeg"|"application/pdf"|"image/svg+xml"} Highcharts.ExportingMimeTypeValue */ // Add language extend(defaultOptions.lang /** * @optionparent lang */ , { /** * Exporting module only. The text for the menu item to view the chart * in full screen. * * @since 8.0.1 * * @private */ viewFullscreen: 'View in full screen', /** * Exporting module only. The text for the menu item to exit the chart * from full screen. * * @since 8.0.1 * * @private */ exitFullscreen: 'Exit from full screen', /** * Exporting module only. The text for the menu item to print the chart. * * @since 3.0.1 * @requires modules/exporting * * @private */ printChart: 'Print chart', /** * Exporting module only. The text for the PNG download menu item. * * @since 2.0 * @requires modules/exporting * * @private */ downloadPNG: 'Download PNG image', /** * Exporting module only. The text for the JPEG download menu item. * * @since 2.0 * @requires modules/exporting * * @private */ downloadJPEG: 'Download JPEG image', /** * Exporting module only. The text for the PDF download menu item. * * @since 2.0 * @requires modules/exporting * * @private */ downloadPDF: 'Download PDF document', /** * Exporting module only. The text for the SVG download menu item. * * @since 2.0 * @requires modules/exporting * * @private */ downloadSVG: 'Download SVG vector image', /** * Exporting module menu. The tooltip title for the context menu holding * print and export menu items. * * @since 3.0 * @requires modules/exporting * * @private */ contextButtonTitle: 'Chart context menu' }); if (!defaultOptions.navigation) { // Buttons and menus are collected in a separate config option set called // 'navigation'. This can be extended later to add control buttons like // zoom and pan right click menus. /** * A collection of options for buttons and menus appearing in the exporting * module. * * @requires modules/exporting * @optionparent navigation */ defaultOptions.navigation = {}; } merge(true, defaultOptions.navigation, { /** * @optionparent navigation.buttonOptions * * @private */ buttonOptions: { theme: {}, /** * Whether to enable buttons. * * @sample highcharts/navigation/buttonoptions-enabled/ * Exporting module loaded but buttons disabled * * @type {boolean} * @default true * @since 2.0 * @apioption navigation.buttonOptions.enabled */ /** * The pixel size of the symbol on the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ symbolSize: 14, /** * The x position of the center of the symbol inside the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ symbolX: 12.5, /** * The y position of the center of the symbol inside the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ symbolY: 10.5, /** * Alignment for the buttons. * * @sample highcharts/navigation/buttonoptions-align/ * Center aligned * * @type {Highcharts.AlignValue} * @since 2.0 */ align: 'right', /** * The pixel spacing between buttons. * * @since 2.0 */ buttonSpacing: 3, /** * Pixel height of the buttons. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ height: 22, /** * A text string to add to the individual button. * * @sample highcharts/exporting/buttons-text/ * Full text button * @sample highcharts/exporting/buttons-text-symbol/ * Combined symbol and text * * @type {string} * @default null * @since 3.0 * @apioption navigation.buttonOptions.text */ /** * The vertical offset of the button's position relative to its * `verticalAlign`. * * @sample highcharts/navigation/buttonoptions-verticalalign/ * Buttons at lower right * * @type {number} * @default 0 * @since 2.0 * @apioption navigation.buttonOptions.y */ /** * The vertical alignment of the buttons. Can be one of `"top"`, * `"middle"` or `"bottom"`. * * @sample highcharts/navigation/buttonoptions-verticalalign/ * Buttons at lower right * * @type {Highcharts.VerticalAlignValue} * @since 2.0 */ verticalAlign: 'top', /** * The pixel width of the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ width: 24 } }); // Presentational attributes merge(true, defaultOptions.navigation /** * A collection of options for buttons and menus appearing in the exporting * module. * * @optionparent navigation */ , { /** * CSS styles for the popup menu appearing by default when the export * icon is clicked. This menu is rendered in HTML. * * @see In styled mode, the menu is styled with the `.highcharts-menu` * class. * * @sample highcharts/navigation/menustyle/ * Light gray menu background * * @type {Highcharts.CSSObject} * @default {"border": "1px solid #999999", "background": "#ffffff", "padding": "5px 0"} * @since 2.0 * * @private */ menuStyle: { /** @ignore-option */ border: "1px solid " + palette.neutralColor40, /** @ignore-option */ background: palette.backgroundColor, /** @ignore-option */ padding: '5px 0' }, /** * CSS styles for the individual items within the popup menu appearing * by default when the export icon is clicked. The menu items are * rendered in HTML. Font size defaults to `11px` on desktop and `14px` * on touch devices. * * @see In styled mode, the menu items are styled with the * `.highcharts-menu-item` class. * * @sample {highcharts} highcharts/navigation/menuitemstyle/ * Add a grey stripe to the left * * @type {Highcharts.CSSObject} * @default {"padding": "0.5em 1em", "color": "#333333", "background": "none", "fontSize": "11px/14px", "transition": "background 250ms, color 250ms"} * @since 2.0 * * @private */ menuItemStyle: { /** @ignore-option */ padding: '0.5em 1em', /** @ignore-option */ color: palette.neutralColor80, /** @ignore-option */ background: 'none', /** @ignore-option */ fontSize: isTouchDevice ? '14px' : '11px', /** @ignore-option */ transition: 'background 250ms, color 250ms' }, /** * CSS styles for the hover state of the individual items within the * popup menu appearing by default when the export icon is clicked. The * menu items are rendered in HTML. * * @see In styled mode, the menu items are styled with the * `.highcharts-menu-item` class. * * @sample highcharts/navigation/menuitemhoverstyle/ * Bold text on hover * * @type {Highcharts.CSSObject} * @default {"background": "#335cad", "color": "#ffffff"} * @since 2.0 * * @private */ menuItemHoverStyle: { /** @ignore-option */ background: palette.highlightColor80, /** @ignore-option */ color: palette.backgroundColor }, /** * A collection of options for buttons appearing in the exporting * module. * * In styled mode, the buttons are styled with the * `.highcharts-contextbutton` and `.highcharts-button-symbol` classes. * * @requires modules/exporting * * @private */ buttonOptions: { /** * Fill color for the symbol within the button. * * @sample highcharts/navigation/buttonoptions-symbolfill/ * Blue symbol stroke for one of the buttons * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @since 2.0 */ symbolFill: palette.neutralColor60, /** * The color of the symbol's stroke or line. * * @sample highcharts/navigation/buttonoptions-symbolstroke/ * Blue symbol stroke * * @type {Highcharts.ColorString} * @since 2.0 */ symbolStroke: palette.neutralColor60, /** * The pixel stroke width of the symbol on the button. * * @sample highcharts/navigation/buttonoptions-height/ * Bigger buttons * * @since 2.0 */ symbolStrokeWidth: 3, /** * A configuration object for the button theme. The object accepts * SVG properties like `stroke-width`, `stroke` and `fill`. * Tri-state button styles are supported by the `states.hover` and * `states.select` objects. * * @sample highcharts/navigation/buttonoptions-theme/ * Theming the buttons * * @requires modules/exporting * * @since 3.0 */ theme: { /** * The default fill exists only to capture hover events. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @default ${palette.backgroundColor} * @apioption navigation.buttonOptions.theme.fill */ /** * Default stroke for the buttons. * @type {Highcharts.ColorString} * @default none * @apioption navigation.buttonOptions.theme.stroke */ /** * Padding for the button. */ padding: 5 } } }); // Add the export related options /** * Options for the exporting module. For an overview on the matter, see * [the docs](https://www.highcharts.com/docs/export-module/export-module-overview). * * @requires modules/exporting * @optionparent exporting */ defaultOptions.exporting = { /** * Experimental setting to allow HTML inside the chart (added through * the `useHTML` options), directly in the exported image. This allows * you to preserve complicated HTML structures like tables or bi-directional * text in exported charts. * * Disclaimer: The HTML is rendered in a `foreignObject` tag in the * generated SVG. The official export server is based on PhantomJS, * which supports this, but other SVG clients, like Batik, does not * support it. This also applies to downloaded SVG that you want to * open in a desktop client. * * @type {boolean} * @default false * @since 4.1.8 * @apioption exporting.allowHTML */ /** * Additional chart options to be merged into the chart before exporting to * an image format. This does not apply to printing the chart via the export * menu. * * For example, a common use case is to add data labels to improve * readability of the exported chart, or to add a printer-friendly color * scheme to exported PDFs. * * @sample {highcharts} highcharts/exporting/chartoptions-data-labels/ * Added data labels * @sample {highstock} highcharts/exporting/chartoptions-data-labels/ * Added data labels * * @type {Highcharts.Options} * @apioption exporting.chartOptions */ /** * Whether to enable the exporting module. Disabling the module will * hide the context button, but API methods will still be available. * * @sample {highcharts} highcharts/exporting/enabled-false/ * Exporting module is loaded but disabled * @sample {highstock} highcharts/exporting/enabled-false/ * Exporting module is loaded but disabled * * @type {boolean} * @default true * @since 2.0 * @apioption exporting.enabled */ /** * Function to call if the offline-exporting module fails to export * a chart on the client side, and [fallbackToExportServer]( * #exporting.fallbackToExportServer) is disabled. If left undefined, an * exception is thrown instead. Receives two parameters, the exporting * options, and the error from the module. * * @see [fallbackToExportServer](#exporting.fallbackToExportServer) * * @type {Highcharts.ExportingErrorCallbackFunction} * @since 5.0.0 * @requires modules/exporting * @requires modules/offline-exporting * @apioption exporting.error */ /** * Whether or not to fall back to the export server if the offline-exporting * module is unable to export the chart on the client side. This happens for * certain browsers, and certain features (e.g. * [allowHTML](#exporting.allowHTML)), depending on the image type exporting * to. For very complex charts, it is possible that export can fail in * browsers that don't support Blob objects, due to data URL length limits. * It is recommended to define the [exporting.error](#exporting.error) * handler if disabling fallback, in order to notify users in case export * fails. * * @type {boolean} * @default true * @since 4.1.8 * @requires modules/exporting * @requires modules/offline-exporting * @apioption exporting.fallbackToExportServer */ /** * The filename, without extension, to use for the exported chart. * * @sample {highcharts} highcharts/exporting/filename/ * Custom file name * @sample {highstock} highcharts/exporting/filename/ * Custom file name * * @type {string} * @default chart * @since 2.0 * @apioption exporting.filename */ /** * An object containing additional key value data for the POST form that * sends the SVG to the export server. For example, a `target` can be set to * make sure the generated image is received in another frame, or a custom * `enctype` or `encoding` can be set. * * @type {Highcharts.HTMLAttributes} * @since 3.0.8 * @apioption exporting.formAttributes */ /** * Path where Highcharts will look for export module dependencies to * load on demand if they don't already exist on `window`. Should currently * point to location of [CanVG](https://github.com/canvg/canvg) library, * [RGBColor.js](https://github.com/canvg/canvg), * [jsPDF](https://github.com/yWorks/jsPDF) and * [svg2pdf.js](https://github.com/yWorks/svg2pdf.js), required for client * side export in certain browsers. * * @type {string} * @default https://code.highcharts.com/{version}/lib * @since 5.0.0 * @apioption exporting.libURL */ /** * Analogous to [sourceWidth](#exporting.sourceWidth). * * @type {number} * @since 3.0 * @apioption exporting.sourceHeight */ /** * The width of the original chart when exported, unless an explicit * [chart.width](#chart.width) is set, or a pixel width is set on the * container. The width exported raster image is then multiplied by * [scale](#exporting.scale). * * @sample {highcharts} highcharts/exporting/sourcewidth/ * Source size demo * @sample {highstock} highcharts/exporting/sourcewidth/ * Source size demo * @sample {highmaps} maps/exporting/sourcewidth/ * Source size demo * * @type {number} * @since 3.0 * @apioption exporting.sourceWidth */ /** * The pixel width of charts exported to PNG or JPG. As of Highcharts * 3.0, the default pixel width is a function of the [chart.width]( * #chart.width) or [exporting.sourceWidth](#exporting.sourceWidth) and the * [exporting.scale](#exporting.scale). * * @sample {highcharts} highcharts/exporting/width/ * Export to 200px wide images * @sample {highstock} highcharts/exporting/width/ * Export to 200px wide images * * @type {number} * @since 2.0 * @apioption exporting.width */ /** * Default MIME type for exporting if `chart.exportChart()` is called * without specifying a `type` option. Possible values are `image/png`, * `image/jpeg`, `application/pdf` and `image/svg+xml`. * * @type {Highcharts.ExportingMimeTypeValue} * @since 2.0 */ type: 'image/png', /** * The URL for the server module converting the SVG string to an image * format. By default this points to Highchart's free web service. * * @since 2.0 */ url: 'https://export.highcharts.com/', /** * When printing the chart from the menu item in the burger menu, if * the on-screen chart exceeds this width, it is resized. After printing * or cancelled, it is restored. The default width makes the chart * fit into typical paper format. Note that this does not affect the * chart when printing the web page as a whole. * * @since 4.2.5 */ printMaxWidth: 780, /** * Defines the scale or zoom factor for the exported image compared * to the on-screen display. While for instance a 600px wide chart * may look good on a website, it will look bad in print. The default * scale of 2 makes this chart export to a 1200px PNG or JPG. * * @see [chart.width](#chart.width) * @see [exporting.sourceWidth](#exporting.sourceWidth) * * @sample {highcharts} highcharts/exporting/scale/ * Scale demonstrated * @sample {highstock} highcharts/exporting/scale/ * Scale demonstrated * @sample {highmaps} maps/exporting/scale/ * Scale demonstrated * * @since 3.0 */ scale: 2, /** * Options for the export related buttons, print and export. In addition * to the default buttons listed here, custom buttons can be added. * See [navigation.buttonOptions](#navigation.buttonOptions) for general * options. * * @type {Highcharts.Dictionary<*>} * @requires modules/exporting */ buttons: { /** * Options for the export button. * * In styled mode, export button styles can be applied with the * `.highcharts-contextbutton` class. * * @declare Highcharts.ExportingButtonsOptionsObject * @extends navigation.buttonOptions * @requires modules/exporting */ contextButton: { /** * A click handler callback to use on the button directly instead of * the popup menu. * * @sample highcharts/exporting/buttons-contextbutton-onclick/ * Skip the menu and export the chart directly * * @type {Function} * @since 2.0 * @apioption exporting.buttons.contextButton.onclick */ /** * See [navigation.buttonOptions.symbolFill]( * #navigation.buttonOptions.symbolFill). * * @type {Highcharts.ColorString} * @default #666666 * @since 2.0 * @apioption exporting.buttons.contextButton.symbolFill */ /** * The horizontal position of the button relative to the `align` * option. * * @type {number} * @default -10 * @since 2.0 * @apioption exporting.buttons.contextButton.x */ /** * The class name of the context button. */ className: 'highcharts-contextbutton', /** * The class name of the menu appearing from the button. */ menuClassName: 'highcharts-contextmenu', /** * The symbol for the button. Points to a definition function in * the `Highcharts.Renderer.symbols` collection. The default * `exportIcon` function is part of the exporting module. Possible * values are "circle", "square", "diamond", "triangle", * "triangle-down", "menu", "menuball" or custom shape. * * @sample highcharts/exporting/buttons-contextbutton-symbol/ * Use a circle for symbol * @sample highcharts/exporting/buttons-contextbutton-symbol-custom/ * Custom shape as symbol * * @type {Highcharts.SymbolKeyValue|"exportIcon"|"menu"|"menuball"|string} * @since 2.0 */ symbol: 'menu', /** * The key to a [lang](#lang) option setting that is used for the * button's title tooltip. When the key is `contextButtonTitle`, it * refers to [lang.contextButtonTitle](#lang.contextButtonTitle) * that defaults to "Chart context menu". * * @since 6.1.4 */ titleKey: 'contextButtonTitle', /** * This option is deprecated, use * [titleKey](#exporting.buttons.contextButton.titleKey) instead. * * @deprecated * @type {string} * @apioption exporting.buttons.contextButton._titleKey */ /** * A collection of strings pointing to config options for the menu * items. The config options are defined in the * `menuItemDefinitions` option. * * By default, there is the "View in full screen" and "Print" menu * items, plus one menu item for each of the available export types. * * @sample {highcharts} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * @sample {highstock} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * @sample {highmaps} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * * @type {Array<string>} * @default ["viewFullscreen", "printChart", "separator", "downloadPNG", "downloadJPEG", "downloadPDF", "downloadSVG"] * @since 2.0 */ menuItems: [ 'viewFullscreen', 'printChart', 'separator', 'downloadPNG', 'downloadJPEG', 'downloadPDF', 'downloadSVG' ] } }, /** * An object consisting of definitions for the menu items in the context * menu. Each key value pair has a `key` that is referenced in the * [menuItems](#exporting.buttons.contextButton.menuItems) setting, * and a `value`, which is an object with the following properties: * * - **onclick:** The click handler for the menu item * * - **text:** The text for the menu item * * - **textKey:** If internationalization is required, the key to a language * string * * Custom text for the "exitFullScreen" can be set only in lang options * (it is not a separate button). * * @sample {highcharts} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * @sample {highstock} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * @sample {highmaps} highcharts/exporting/menuitemdefinitions/ * Menu item definitions * * * @type {Highcharts.Dictionary<Highcharts.ExportingMenuObject>} * @default {"viewFullscreen": {}, "printChart": {}, "separator": {}, "downloadPNG": {}, "downloadJPEG": {}, "downloadPDF": {}, "downloadSVG": {}} * @since 5.0.13 */ menuItemDefinitions: { /** * @ignore */ viewFullscreen: { textKey: 'viewFullscreen', onclick: function () { this.fullscreen.toggle(); } }, /** * @ignore */ printChart: { textKey: 'printChart', onclick: function () { this.print(); } }, /** * @ignore */ separator: { separator: true }, /** * @ignore */ downloadPNG: { textKey: 'downloadPNG', onclick: function () { this.exportChart(); } }, /** * @ignore */ downloadJPEG: { textKey: 'downloadJPEG', onclick: function () { this.exportChart({ type: 'image/jpeg' }); } }, /** * @ignore */ downloadPDF: { textKey: 'downloadPDF', onclick: function () { this.exportChart({ type: 'application/pdf' }); } }, /** * @ignore */ downloadSVG: { textKey: 'downloadSVG', onclick: function () { this.exportChart({ type: 'image/svg+xml' }); } } } }; /** * Fires after a chart is printed through the context menu item or the * `Chart.print` method. * * @sample highcharts/chart/events-beforeprint-afterprint/ * Rescale the chart to print * * @type {Highcharts.ExportingAfterPrintCallbackFunction} * @since 4.1.0 * @context Highcharts.Chart * @requires modules/exporting * @apioption chart.events.afterPrint */ /** * Fires before a chart is printed through the context menu item or * the `Chart.print` method. * * @sample highcharts/chart/events-beforeprint-afterprint/ * Rescale the chart to print * * @type {Highcharts.ExportingBeforePrintCallbackFunction} * @since 4.1.0 * @context Highcharts.Chart * @requires modules/exporting * @apioption chart.events.beforePrint */ /** * The post utility * * @private * @function Highcharts.post * @param {string} url * Post URL * @param {object} data * Post data * @param {Highcharts.Dictionary<string>} [formAttributes] * Additional attributes for the post request * @return {void} */ H.post = function (url, data, formAttributes) { // create the form var form = createElement('form', merge({ method: 'post', action: url, enctype: 'multipart/form-data' }, formAttributes), { display: 'none' }, doc.body); // add the data objectEach(data, function (val, name) { createElement('input', { type: 'hidden', name: name, value: val }, null, form); }); // submit form.submit(); // clean up discardElement(form); }; if (H.isSafari) { H.win.matchMedia('print').addListener(function (mqlEvent) { if (!H.printingChart) { return void 0; } if (mqlEvent.matches) { H.printingChart.beforePrint(); } else { H.printingChart.afterPrint(); } }); } extend(Chart.prototype, /** @lends Highcharts.Chart.prototype */ { /* eslint-disable no-invalid-this, valid-jsdoc */ /** * Exporting module only. A collection of fixes on the produced SVG to * account for expando properties, browser bugs, VML problems and other. * Returns a cleaned SVG. * * @private * @function Highcharts.Chart#sanitizeSVG * @param {string} svg * SVG code to sanitize * @param {Highcharts.Options} options * Chart options to apply * @return {string} * Sanitized SVG code * @requires modules/exporting */ sanitizeSVG: function (svg, options) { var split = svg.indexOf('</svg>') + 6, html = svg.substr(split); // Remove any HTML added to the container after the SVG (#894, #9087) svg = svg.substr(0, split); // Move HTML into a foreignObject if (options && options.exporting && options.exporting.allowHTML) { if (html) { html = '<foreignObject x="0" y="0" ' + 'width="' + options.chart.width + '" ' + 'height="' + options.chart.height + '">' + '<body xmlns="http://www.w3.org/1999/xhtml">' + // Some tags needs to be closed in xhtml (#13726) html.replace(/(<(?:img|br).*?(?=\>))>/g, '$1 />') + '</body>' + '</foreignObject>'; svg = svg.replace('</svg>', html + '</svg>'); } } svg = svg .replace(/zIndex="[^"]+"/g, '') .replace(/symbolName="[^"]+"/g, '') .replace(/jQuery[0-9]+="[^"]+"/g, '') .replace(/url\(("|&quot;)(.*?)("|&quot;)\;?\)/g, 'url($2)') .replace(/url\([^#]+#/g, 'url(#') .replace(/<svg /, '<svg xmlns:xlink="http://www.w3.org/1999/xlink" ') .replace(/ (|NS[0-9]+\:)href=/g, ' xlink:href=') // #3567 .replace(/\n/, ' ') // Batik doesn't support rgba fills and strokes (#3095) .replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g, // eslint-disable-line max-len '$1="rgb($2)" $1-opacity="$3"') // Replace HTML entities, issue #347 .replace(/&nbsp;/g, '\u00A0') // no-break space .replace(/&shy;/g, '\u00AD'); // soft hyphen // Further sanitize for oldIE if (this.ieSanitizeSVG) { svg = this.ieSanitizeSVG(svg); } return svg; }, /** * Return the unfiltered innerHTML of the chart container. Used as hook for * plugins. In styled mode, it also takes care of inlining CSS style rules. * * @see Chart#getSVG * * @function Highcharts.Chart#getChartHTML * * @returns {string} * The unfiltered SVG of the chart. * * @requires modules/exporting */ getChartHTML: function () { if (this.styledMode) { this.inlineStyles(); } return this.container.innerHTML; }, /** * Return an SVG representation of the chart. * * @sample highcharts/members/chart-getsvg/ * View the SVG from a button * * @function Highcharts.Chart#getSVG * * @param {Highcharts.Options} [chartOptions] * Additional chart options for the generated SVG representation. For * collections like `xAxis`, `yAxis` or `series`, the additional * options is either merged in to the original item of the same * `id`, or to the first item if a common id is not found. * * @return {string} * The SVG representation of the rendered chart. * * @fires Highcharts.Chart#event:getSVG * * @requires modules/exporting */ getSVG: function (chartOptions) { var chart = this, chartCopy, sandbox, svg, seriesOptions, sourceWidth, sourceHeight, cssWidth, cssHeight, // Copy the options and add extra options options = merge(chart.options, chartOptions); // Use userOptions to make the options chain in series right (#3881) options.plotOptions = merge(chart.userOptions.plotOptions, chartOptions && chartOptions.plotOptions); // ... and likewise with time, avoid that undefined time properties are // merged over legacy global time options options.time = merge(chart.userOptions.time, chartOptions && chartOptions.time); // create a sandbox where a new chart will be generated sandbox = createElement('div', null, { position: 'absolute', top: '-9999em', width: chart.chartWidth + 'px', height: chart.chartHeight + 'px' }, doc.body); // get the source size cssWidth = chart.renderTo.style.width; cssHeight = chart.renderTo.style.height; sourceWidth = options.exporting.sourceWidth || options.chart.width || (/px$/.test(cssWidth) && parseInt(cssWidth, 10)) || (options.isGantt ? 800 : 600); sourceHeight = options.exporting.sourceHeight || options.chart.height || (/px$/.test(cssHeight) && parseInt(cssHeight, 10)) || 400; // override some options extend(options.chart, { animation: false, renderTo: sandbox, forExport: true, renderer: 'SVGRenderer', width: sourceWidth, height: sourceHeight }); options.exporting.enabled = false; // hide buttons in print delete options.data; // #3004 // prepare for replicating the chart options.series = []; chart.series.forEach(function (serie) { seriesOptions = merge(serie.userOptions, { animation: false, enableMouseTracking: false, showCheckbox: false, visible: serie.visible }); // Used for the navigator series that has its own option set if (!seriesOptions.isInternal) { options.series.push(seriesOptions); } }); // Assign an internal key to ensure a one-to-one mapping (#5924) chart.axes.forEach(function (axis) { if (!axis.userOptions.internalKey) { // #6444 axis.userOptions.internalKey = uniqueKey(); } }); // generate the chart copy chartCopy = new Chart(options, chart.callback); // Axis options and series options (#2022, #3900, #5982) if (chartOptions) { ['xAxis', 'yAxis', 'series'].forEach(function (coll) { var collOptions = {}; if (chartOptions[coll]) { collOptions[coll] = chartOptions[coll]; chartCopy.update(collOptions); } }); } // Reflect axis extremes in the export (#5924) chart.axes.forEach(function (axis) { var axisCopy = find(chartCopy.axes, function (copy) { return copy.options.internalKey === axis.userOptions.internalKey; }), extremes = axis.getExtremes(), userMin = extremes.userMin, userMax = extremes.userMax; if (axisCopy && ((typeof userMin !== 'undefined' && userMin !== axisCopy.min) || (typeof userMax !== 'undefined' && userMax !== axisCopy.max))) { axisCopy.setExtremes(userMin, userMax, true, false); } }); // Get the SVG from the container's innerHTML svg = chartCopy.getChartHTML(); fireEvent(this, 'getSVG', { chartCopy: chartCopy }); svg = chart.sanitizeSVG(svg, options); // free up memory options = null; chartCopy.destroy(); discardElement(sandbox); return svg; }, /** * @private * @function Highcharts.Chart#getSVGForExport * @param {Highcharts.ExportingOptions} options * @param {Highcharts.Options} chartOptions * @return {string} * @requires modules/exporting */ getSVGForExport: function (options, chartOptions) { var chartExportingOptions = this.options.exporting; return this.getSVG(merge({ chart: { borderRadius: 0 } }, chartExportingOptions.chartOptions, chartOptions, { exporting: { sourceWidth: ((options && options.sourceWidth) || chartExportingOptions.sourceWidth), sourceHeight: ((options && options.sourceHeight) || chartExportingOptions.sourceHeight) } })); }, /** * Get the default file name used for exported charts. By default it creates * a file name based on the chart title. * * @function Highcharts.Chart#getFilename * * @return {string} A file name without extension. * * @requires modules/exporting */ getFilename: function () { var s = this.userOptions.title && this.userOptions.title.text, filename = this.options.exporting.filename; if (filename) { return filename.replace(/\//g, '-'); } if (typeof s === 'string') { filename = s .toLowerCase() .replace(/<\/?[^>]+(>|$)/g, '') // strip HTML tags .replace(/[\s_]+/g, '-') .replace(/[^a-z0-9\-]/g, '') // preserve only latin .replace(/^[\-]+/g, '') // dashes in the start .replace(/[\-]+/g, '-') // dashes in a row .substr(0, 24) .replace(/[\-]+$/g, ''); // dashes in the end; } if (!filename || filename.length < 5) { filename = 'chart'; } return filename; }, /** * Exporting module required. Submit an SVG version of the chart to a server * along with some parameters for conversion. * * @sample highcharts/members/chart-exportchart/ * Export with no options * @sample highcharts/members/chart-exportchart-filename/ * PDF type and custom filename * @sample highcharts/members/chart-exportchart-custom-background/ * Different chart background in export * @sample stock/members/chart-exportchart/ * Export with Highstock * * @function Highcharts.Chart#exportChart * * @param {Highcharts.ExportingOptions} exportingOptions * Exporting options in addition to those defined in * [exporting](https://api.highcharts.com/highcharts/exporting). * * @param {Highcharts.Options} chartOptions * Additional chart options for the exported chart. For example a * different background color can be added here, or `dataLabels` for * export only. * * @return {void} * * @requires modules/exporting */ exportChart: function (exportingOptions, chartOptions) { var svg = this.getSVGForExport(exportingOptions, chartOptions); // merge the options exportingOptions = merge(this.options.exporting, exportingOptions); // do the post H.post(exportingOptions.url, { filename: exportingOptions.filename ? exportingOptions.filename.replace(/\//g, '-') : this.getFilename(), type: exportingOptions.type, // IE8 fails to post undefined correctly, so use 0 width: exportingOptions.width || 0, scale: exportingOptions.scale, svg: svg }, exportingOptions.formAttributes); }, /** * Move the chart container(s) to another div. * * @function Highcharts#moveContainers * * @private * * @param {Highcharts.HTMLDOMElement} moveTo * Move target * @return {void} */ moveContainers: function (moveTo) { var chart = this; (chart.fixedDiv ? // When scrollablePlotArea is active (#9533) [chart.fixedDiv, chart.scrollingContainer] : [chart.container]).forEach(function (div) { moveTo.appendChild(div); }); }, /** * Prepare chart and document before printing a chart. * * @function Highcharts#beforePrint * * @private * * @return {void} * * @fires Highcharts.Chart#event:beforePrint */ beforePrint: function () { var chart = this, body = doc.body, printMaxWidth = chart.options.exporting.printMaxWidth, printReverseInfo = { childNodes: body.childNodes, origDisplay: [], resetParams: void 0 }; var handleMaxWidth; chart.isPrinting = true; chart.pointer.reset(null, 0); fireEvent(chart, 'beforePrint'); // Handle printMaxWidth handleMaxWidth = printMaxWidth && chart.chartWidth > printMaxWidth; if (handleMaxWidth) { printReverseInfo.resetParams = [ chart.options.chart.width, void 0, false ]; chart.setSize(printMaxWidth, void 0, false); } // hide all body content [].forEach.call(printReverseInfo.childNodes, function (node, i) { if (node.nodeType === 1) { printReverseInfo.origDisplay[i] = node.style.display; node.style.display = 'none'; } }); // pull out the chart chart.moveContainers(body); // Storage details for undo action after printing chart.printReverseInfo = printReverseInfo; }, /** * Clena up after printing a chart. * * @function Highcharts#afterPrint * * @private * * @param {Highcharts.Chart} chart * Chart that was (or suppose to be) printed * @return {void} * * @fires Highcharts.Chart#event:afterPrint */ afterPrint: function () { var chart = this; if (!chart.printReverseInfo) { return void 0; } var childNodes = chart.printReverseInfo.childNodes, origDisplay = chart.printReverseInfo.origDisplay, resetParams = chart.printReverseInfo.resetParams; // put the chart back in chart.moveContainers(chart.renderTo); // restore all body content [].forEach.call(childNodes, function (node, i) { if (node.nodeType === 1) { node.style.display = (origDisplay[i] || ''); } }); chart.isPrinting = false; // Reset printMaxWidth if (resetParams) { chart.setSize.apply(chart, resetParams); } delete chart.printReverseInfo; delete H.printingChart; fireEvent(chart, 'afterPrint'); }, /** * Exporting module required. Clears away other elements in the page and * prints the chart as it is displayed. By default, when the exporting * module is enabled, a context button with a drop down menu in the upper * right corner accesses this function. * * @sample highcharts/members/chart-print/ * Print from a HTML button * * @function Highcharts.Chart#print * * @return {void} * * @fires Highcharts.Chart#event:beforePrint * @fires Highcharts.Chart#event:afterPrint * * @requires modules/exporting */ print: function () { var chart = this; if (chart.isPrinting) { // block the button while in printing mode return; } H.printingChart = chart; if (!H.isSafari) { chart.beforePrint(); } // Give the browser time to draw WebGL content, an issue that randomly // appears (at least) in Chrome ~67 on the Mac (#8708). setTimeout(function () { win.focus(); // #1510 win.print(); // allow the browser to prepare before reverting if (!H.isSafari) { setTimeout(function () { chart.afterPrint(); }, 1000); } }, 1); }, /** * Display a popup menu for choosing the export type. * * @private * @function Highcharts.Chart#contextMenu * @param {string} className * An identifier for the menu. * @param {Array<string|Highcharts.ExportingMenuObject>} items * A collection with text and onclicks for the items. * @param {number} x * The x position of the opener button * @param {number} y * The y position of the opener button * @param {number} width * The width of the opener button * @param {number} height * The height of the opener button * @return {void} * @requires modules/exporting */ contextMenu: function (className, items, x, y, width, height, button) { var chart = this, navOptions = chart.options.navigation, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, cacheName = 'cache-' + className, menu = chart[cacheName], menuPadding = Math.max(width, height), // for mouse leave detection innerMenu, menuStyle; // create the menu only the first time if (!menu) { // create a HTML element above the SVG chart.exportContextMenu = chart[cacheName] = menu = createElement('div', { className: className }, { position: 'absolute', zIndex: 1000, padding: menuPadding + 'px', pointerEvents: 'auto' }, chart.fixedDiv || chart.container); innerMenu = createElement('ul', { className: 'highcharts-menu' }, { listStyle: 'none', margin: 0, padding: 0 }, menu); // Presentational CSS if (!chart.styledMode) { css(innerMenu, extend({ MozBoxShadow: '3px 3px 10px #888', WebkitBoxShadow: '3px 3px 10px #888', boxShadow: '3px 3px 10px #888' }, navOptions.menuStyle)); } // hide on mouse out menu.hideMenu = function () { css(menu, { display: 'none' }); if (button) { button.setState(0); } chart.openMenu = false; css(chart.renderTo, { overflow: 'hidden' }); // #10361 U.clearTimeout(menu.hideTimer); fireEvent(chart, 'exportMenuHidden'); }; // Hide the menu some time after mouse leave (#1357) chart.exportEvents.push(addEvent(menu, 'mouseleave', function () { menu.hideTimer = win.setTimeout(menu.hideMenu, 500); }), addEvent(menu, 'mouseenter', function () { U.clearTimeout(menu.hideTimer); }), // Hide it on clicking or touching outside the menu (#2258, // #2335, #2407) addEvent(doc, 'mouseup', function (e) { if (!chart.pointer.inClass(e.target, className)) { menu.hideMenu(); } }), addEvent(menu, 'click', function () { if (chart.openMenu) { menu.hideMenu(); } })); // create the items items.forEach(function (item) { if (typeof item === 'string') { item = chart.options.exporting .menuItemDefinitions[item]; } if (isObject(item, true)) { var element; if (item.separator) { element = createElement('hr', null, null, innerMenu); } else { // When chart initialized with the table, // wrong button text displayed, #14352. if (item.textKey === 'viewData' && chart.isDataTableVisible) { item.textKey = 'hideData'; } element = createElement('li', { className: 'highcharts-menu-item', onclick: function (e) { if (e) { // IE7 e.stopPropagation(); } menu.hideMenu(); if (item.onclick) { item.onclick .apply(chart, arguments); } } }, null, innerMenu); element.appendChild(doc.createTextNode(item.text || chart.options.lang[item.textKey])); if (!chart.styledMode) { element.onmouseover = function () { css(this, navOptions.menuItemHoverStyle); }; element.onmouseout = function () { css(this, navOptions.menuItemStyle); }; css(element, extend({ cursor: 'pointer' }, navOptions.menuItemStyle)); } } // Keep references to menu divs to be able to destroy them chart.exportDivElements.push(element); } }); // Keep references to menu and innerMenu div to be able to destroy // them chart.exportDivElements.push(innerMenu, menu); chart.exportMenuWidth = menu.offsetWidth; chart.exportMenuHeight = menu.offsetHeight; } menuStyle = { display: 'block' }; // if outside right, right align it if (x + chart.exportMenuWidth > chartWidth) { menuStyle.right = (chartWidth - x - width - menuPadding) + 'px'; } else { menuStyle.left = (x - menuPadding) + 'px'; } // if outside bottom, bottom align it if (y + height + chart.exportMenuHeight > chartHeight && button.alignOptions.verticalAlign !== 'top') { menuStyle.bottom = (chartHeight - y - menuPadding) + 'px'; } else { menuStyle.top = (y + height - menuPadding) + 'px'; } css(menu, menuStyle); css(chart.renderTo, { overflow: '' }); // #10361 chart.openMenu = true; fireEvent(chart, 'exportMenuShown'); }, /** * Add the export button to the chart, with options. * * @private * @function Highcharts.Chart#addButton * @param {Highcharts.NavigationButtonOptions} options * @return {void} * @requires modules/exporting */ addButton: function (options) { var chart = this, renderer = chart.renderer, btnOptions = merge(chart.options.navigation.buttonOptions, options), onclick = btnOptions.onclick, menuItems = btnOptions.menuItems, symbol, button, symbolSize = btnOptions.symbolSize || 12; if (!chart.btnCount) { chart.btnCount = 0; } // Keeps references to the button elements if (!chart.exportDivElements) { chart.exportDivElements = []; chart.exportSVGElements = []; } if (btnOptions.enabled === false) { return; } var attr = btnOptions.theme, states = attr.states, hover = states && states.hover, select = states && states.select, callback; if (!chart.styledMode) { attr.fill = pick(attr.fill, palette.backgroundColor); attr.stroke = pick(attr.stroke, 'none'); } delete attr.states; if (onclick) { callback = function (e) { if (e) { e.stopPropagation(); } onclick.call(chart, e); }; } else if (menuItems) { callback = function (e) { // consistent with onclick call (#3495) if (e) { e.stopPropagation(); } chart.contextMenu(button.menuClassName, menuItems, button.translateX, button.translateY, button.width, button.height, button); button.setState(2); }; } if (btnOptions.text && btnOptions.symbol) { attr.paddingLeft = pick(attr.paddingLeft, 30); } else if (!btnOptions.text) { extend(attr, { width: btnOptions.width, height: btnOptions.height, padding: 0 }); } if (!chart.styledMode) { attr['stroke-linecap'] = 'round'; attr.fill = pick(attr.fill, palette.backgroundColor); attr.stroke = pick(attr.stroke, 'none'); } button = renderer .button(btnOptions.text, 0, 0, callback, attr, hover, select) .addClass(options.className) .attr({ title: pick(chart.options.lang[btnOptions._titleKey || btnOptions.titleKey], '') }); button.menuClassName = (options.menuClassName || 'highcharts-menu-' + chart.btnCount++); if (btnOptions.symbol) { symbol = renderer .symbol(btnOptions.symbol, btnOptions.symbolX - (symbolSize / 2), btnOptions.symbolY - (symbolSize / 2), symbolSize, symbolSize // If symbol is an image, scale it (#7957) , { width: symbolSize, height: symbolSize }) .addClass('highcharts-button-symbol') .attr({ zIndex: 1 }) .add(button); if (!chart.styledMode) { symbol.attr({ stroke: btnOptions.symbolStroke, fill: btnOptions.symbolFill, 'stroke-width': btnOptions.symbolStrokeWidth || 1 }); } } button .add(chart.exportingGroup) .align(extend(btnOptions, { width: button.width, x: pick(btnOptions.x, chart.buttonOffset) // #1654 }), true, 'spacingBox'); chart.buttonOffset += ((button.width + btnOptions.buttonSpacing) * (btnOptions.align === 'right' ? -1 : 1)); chart.exportSVGElements.push(button, symbol); }, /** * Destroy the export buttons. * @private * @function Highcharts.Chart#destroyExport * @param {global.Event} [e] * @return {void} * @requires modules/exporting */ destroyExport: function (e) { var chart = e ? e.target : this, exportSVGElements = chart.exportSVGElements, exportDivElements = chart.exportDivElements, exportEvents = chart.exportEvents, cacheName; // Destroy the extra buttons added if (exportSVGElements) { exportSVGElements.forEach(function (elem, i) { // Destroy and null the svg elements if (elem) { // #1822 elem.onclick = elem.ontouchstart = null; cacheName = 'cache-' + elem.menuClassName; if (chart[cacheName]) { delete chart[cacheName]; } chart.exportSVGElements[i] = elem.destroy(); } }); exportSVGElements.length = 0; } // Destroy the exporting group if (chart.exportingGroup) { chart.exportingGroup.destroy(); delete chart.exportingGroup; } // Destroy the divs for the menu if (exportDivElements) { exportDivElements.forEach(function (elem, i) { // Remove the event handler U.clearTimeout(elem.hideTimer); // #5427 removeEvent(elem, 'mouseleave'); // Remove inline events chart.exportDivElements[i] = elem.onmouseout = elem.onmouseover = elem.ontouchstart = elem.onclick = null; // Destroy the div by moving to garbage bin discardElement(elem); }); exportDivElements.length = 0; } if (exportEvents) { exportEvents.forEach(function (unbind) { unbind(); }); exportEvents.length = 0; } } /* eslint-enable no-invalid-this, valid-jsdoc */ }); // These ones are translated to attributes rather than styles SVGRenderer.prototype.inlineToAttributes = [ 'fill', 'stroke', 'strokeLinecap', 'strokeLinejoin', 'strokeWidth', 'textAnchor', 'x', 'y' ]; // These CSS properties are not inlined. Remember camelCase. SVGRenderer.prototype.inlineBlacklist = [ /-/, /^(clipPath|cssText|d|height|width)$/, /^font$/, /[lL]ogical(Width|Height)$/, /perspective/, /TapHighlightColor/, /^transition/, /^length$/ // #7700 // /^text (border|color|cursor|height|webkitBorder)/ ]; SVGRenderer.prototype.unstyledElements = [ 'clipPath', 'defs', 'desc' ]; /** * Analyze inherited styles from stylesheets and add them inline * * @private * @function Highcharts.Chart#inlineStyles * @return {void} * * @todo: What are the border styles for text about? In general, text has a lot * of properties. * @todo: Make it work with IE9 and IE10. * * @requires modules/exporting */ Chart.prototype.inlineStyles = function () { var renderer = this.renderer, inlineToAttributes = renderer.inlineToAttributes, blacklist = renderer.inlineBlacklist, whitelist = renderer.inlineWhitelist, // For IE unstyledElements = renderer.unstyledElements, defaultStyles = {}, dummySVG, iframe, iframeDoc; // Create an iframe where we read default styles without pollution from this // body iframe = doc.createElement('iframe'); css(iframe, { width: '1px', height: '1px', visibility: 'hidden' }); doc.body.appendChild(iframe); iframeDoc = iframe.contentWindow.document; iframeDoc.open(); iframeDoc.write('<svg xmlns="http://www.w3.org/2000/svg"></svg>'); iframeDoc.close(); /** * Make hyphenated property names out of camelCase * @private * @param {string} prop * Property name in camelCase * @return {string} * Hyphenated property name */ function hyphenate(prop) { return prop.replace(/([A-Z])/g, function (a, b) { return '-' + b.toLowerCase(); }); } /** * Call this on all elements and recurse to children * @private * @param {Highcharts.HTMLDOMElement} node * Element child * @return {void} */ function recurse(node) { var styles, parentStyles, cssText = '', dummy, styleAttr, blacklisted, whitelisted, i; /** * Check computed styles and whether they are in the white/blacklist for * styles or atttributes. * @private * @param {string} val * Style value * @param {string} prop * Style property name * @return {void} */ function filterStyles(val, prop) { // Check against whitelist & blacklist blacklisted = whitelisted = false; if (whitelist) { // Styled mode in IE has a whitelist instead. // Exclude all props not in this list. i = whitelist.length; while (i-- && !whitelisted) { whitelisted = whitelist[i].test(prop); } blacklisted = !whitelisted; } // Explicitly remove empty transforms if (prop === 'transform' && val === 'none') { blacklisted = true; } i = blacklist.length; while (i-- && !blacklisted) { blacklisted = (blacklist[i].test(prop) || typeof val === 'function'); } if (!blacklisted) { // If parent node has the same style, it gets inherited, no need // to inline it. Top-level props should be diffed against parent // (#7687). if ((parentStyles[prop] !== val || node.nodeName === 'svg') && defaultStyles[node.nodeName][prop] !== val) { // Attributes if (!inlineToAttributes || inlineToAttributes.indexOf(prop) !== -1) { if (val) { node.setAttribute(hyphenate(prop), val); } // Styles } else { cssText += hyphenate(prop) + ':' + val + ';'; } } } } if (node.nodeType === 1 && unstyledElements.indexOf(node.nodeName) === -1) { styles = win.getComputedStyle(node, null); parentStyles = node.nodeName === 'svg' ? {} : win.getComputedStyle(node.parentNode, null); // Get default styles from the browser so that we don't have to add // these if (!defaultStyles[node.nodeName]) { /* if (!dummySVG) { dummySVG = doc.createElementNS(H.SVG_NS, 'svg'); dummySVG.setAttribute('version', '1.1'); doc.body.appendChild(dummySVG); } */ dummySVG = iframeDoc.getElementsByTagName('svg')[0]; dummy = iframeDoc.createElementNS(node.namespaceURI, node.nodeName); dummySVG.appendChild(dummy); // Copy, so we can remove the node defaultStyles[node.nodeName] = merge(win.getComputedStyle(dummy, null)); // Remove default fill, otherwise text disappears when exported if (node.nodeName === 'text') { delete defaultStyles.text.fill; } dummySVG.removeChild(dummy); } // Loop through all styles and add them inline if they are ok if (H.isFirefox || H.isMS) { // Some browsers put lots of styles on the prototype for (var p in styles) { // eslint-disable-line guard-for-in filterStyles(styles[p], p); } } else { objectEach(styles, filterStyles); } // Apply styles if (cssText) { styleAttr = node.getAttribute('style'); node.setAttribute('style', (styleAttr ? styleAttr + ';' : '') + cssText); } // Set default stroke width (needed at least for IE) if (node.nodeName === 'svg') { node.setAttribute('stroke-width', '1px'); } if (node.nodeName === 'text') { return; } // Recurse [].forEach.call(node.children || node.childNodes, recurse); } } /** * Remove the dummy objects used to get defaults * @private * @return {void} */ function tearDown() { dummySVG.parentNode.remove(); // Remove trash from DOM that stayed after each exporting iframe.remove(); } recurse(this.container.querySelector('svg')); tearDown(); }; H.Renderer.prototype.symbols.menu = function (x, y, width, height) { var arr = [ ['M', x, y + 2.5], ['L', x + width, y + 2.5], ['M', x, y + height / 2 + 0.5], ['L', x + width, y + height / 2 + 0.5], ['M', x, y + height - 1.5], ['L', x + width, y + height - 1.5] ]; return arr; }; H.Renderer.prototype.symbols.menuball = function (x, y, width, height) { var path = [], h = (height / 3) - 2; path = path.concat(this.circle(width - h, y, h, h), this.circle(width - h, y + h + 4, h, h), this.circle(width - h, y + 2 * (h + 4), h, h)); return path; }; /** * Add the buttons on chart load * @private * @function Highcharts.Chart#renderExporting * @return {void} * @requires modules/exporting */ Chart.prototype.renderExporting = function () { var chart = this, exportingOptions = chart.options.exporting, buttons = exportingOptions.buttons, isDirty = chart.isDirtyExporting || !chart.exportSVGElements; chart.buttonOffset = 0; if (chart.isDirtyExporting) { chart.destroyExport(); } if (isDirty && exportingOptions.enabled !== false) { chart.exportEvents = []; chart.exportingGroup = chart.exportingGroup || chart.renderer.g('exporting-group').attr({ zIndex: 3 // #4955, // #8392 }).add(); objectEach(buttons, function (button) { chart.addButton(button); }); chart.isDirtyExporting = false; } }; /* eslint-disable no-invalid-this */ // Add update methods to handle chart.update and chart.exporting.update and // chart.navigation.update. These must be added to the chart instance rather // than the Chart prototype in order to use the chart instance inside the update // function. addEvent(Chart, 'init', function () { var chart = this; /** * @private * @param {"exporting"|"navigation"} prop * Property name in option root * @param {Highcharts.ExportingOptions|Highcharts.NavigationOptions} options * Options to update * @param {boolean} [redraw=true] * Whether to redraw * @return {void} */ function update(prop, options, redraw) { chart.isDirtyExporting = true; merge(true, chart.options[prop], options); if (pick(redraw, true)) { chart.redraw(); } } chart.exporting = { update: function (options, redraw) { update('exporting', options, redraw); } }; // Register update() method for navigation. Can not be set the same way as // for exporting, because navigation options are shared with bindings which // has separate update() logic. chartNavigationMixin.addUpdate(function (options, redraw) { update('navigation', options, redraw); }, chart); }); /* eslint-enable no-invalid-this */ Chart.prototype.callbacks.push(function (chart) { chart.renderExporting(); addEvent(chart, 'redraw', chart.renderExporting); // Destroy the export elements at chart destroy addEvent(chart, 'destroy', chart.destroyExport); // Uncomment this to see a button directly below the chart, for quick // testing of export /* var button, viewImage, viewSource; if (!chart.renderer.forExport) { viewImage = function () { var div = doc.createElement('div'); div.innerHTML = chart.getSVGForExport(); chart.renderTo.parentNode.appendChild(div); }; viewSource = function () { var pre = doc.createElement('pre'); pre.innerHTML = chart.getSVGForExport() .replace(/</g, '\n&lt;') .replace(/>/g, '&gt;'); chart.renderTo.parentNode.appendChild(pre); }; viewImage(); // View SVG Image button = doc.createElement('button'); button.innerHTML = 'View SVG Image'; chart.renderTo.parentNode.appendChild(button); button.onclick = viewImage; // View SVG Source button = doc.createElement('button'); button.innerHTML = 'View SVG Source'; chart.renderTo.parentNode.appendChild(button); button.onclick = viewSource; } //*/ });
import { HandleableMiddleware } from 'quiver-component-base' import { assertConfig, componentConstructor } from 'quiver-component-base/util' const configHandlerToMiddleware = configHandler => async function(config, builder) { const newConfig = await configHandler(config) return builder(newConfig) } export class ConfigMiddleware extends HandleableMiddleware { mainHandleableMiddlewareFn() { return configHandlerToMiddleware(this.configHandlerFn()) } configHandlerFn() { throw new Error('abstract method configHandlerFn() is not implemented') } get componentType() { return 'ConfigMiddleware' } } const safeConfigMiddlewareFn = configHandler => { return async function(config) { const newConfig = await configHandler(config) || config assertConfig(newConfig) return newConfig } } export const configMiddleware = componentConstructor( ConfigMiddleware, 'configHandlerFn', safeConfigMiddlewareFn)
version https://git-lfs.github.com/spec/v1 oid sha256:1d9240cbeffe56c957891f9e3d847c636e433f843b70bc823242dbe9363c83eb size 31238
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m7.79 18-.51-7h9.46l-.51 7H7.79zM9.83 5h4.33l2.8 2.73L16.87 9H7.12l-.09-1.27L9.83 5zM22 7.46l-1.41-1.41L19 7.63l.03-.56L14.98 3H9.02L4.97 7.07l.03.5-1.59-1.56L2 7.44l3.23 3.11.7 9.45h12.14l.7-9.44L22 7.46z" }), 'TakeoutDiningOutlined'); exports.default = _default;
module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: { release: { options: { 'force': true }, src: [ 'dist/css', 'dist/fonts', 'dist/img', 'dist/js', 'dist/favicon.ico', 'dist/index.html' ] } }, copy: { main: { expand: true, cwd: 'src/', src: [ 'js/**/*.hbar', 'img/**', 'fonts/**', '*.txt', '*.html', '*.ico', '*.png' ], dest: 'dist' }, docs: { expand: true, src: [ 'README.md' ], dest: 'dist' } }, watch: { options: { atBegin: true }, all: { files: [ 'src/**', 'src/less/**/*.less', '!src/js/lib/**', 'README.md', 'Gruntfile.js' ], tasks: ['build'] } }, jsdoc: { dist : { src: [ 'src/js/**/*.js', 'dist/README.md', '!src/js/lib' ], options: { destination: 'dist/doc', template : 'node_modules/ink-docstrap/template' } } }, htmlmin: { dist: { // Target options: { // Target options removeComments: false, collapseWhitespace: true }, files: { // Dictionary of files 'dist/index.html': 'dist/index.html' } } }, cache_control: { dist: { source: 'src/index.html', options: { version: '2.0.1', links: true, scripts: true, replace: false, outputDest: 'dist/index.html' } } }, uglify: { options: { mangle: false }, min: { files: grunt.file.expandMapping(['src/js/**/*.js'], 'dist/', { rename: function(destBase, destPath) { return destBase+destPath.replace('src/js', 'js'); } }) } }, cssmin: { options: { shorthandCompacting: false, roundingPrecision: -1 }, dist: { files: { 'dist/css/main.css': ['src/css/**/*.css'] } } }, jshint: { all: [ 'Gruntfile.js', 'src/js/app/**/*.js', 'src/js/app.js' ], options: { jshintrc: '.jshintrc' } }, bootlint: { options: { stoponerror: false, relaxerror: [ 'W005' ] }, files: ['src/**/*.html'] }, csslint: { options: { csslintrc: '.csslintrc' }, lax: { src: [ 'src/css/**/*.css', '!src/css/bootstrap*' ] } } }); /** * Distribution tasks. */ grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-htmlmin'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-cssmin'); /** * Test tasks. */ grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-csslint'); grunt.loadNpmTasks('grunt-bootlint'); /** * Development task. */ grunt.loadNpmTasks('grunt-contrib-watch'); /** * */ grunt.registerTask('default', 'Default grunt task.', ['build']); grunt.registerTask('build', ['clean','copy','cache_control','cssmin','htmlmin','uglify','copy:docs','jsdoc']); grunt.registerTask('test', ['csslint','jshint','bootlint']); };
'use strict'; const chalk = require('chalk'); const EventEmitter = require('events').EventEmitter; const FlatReporter = require('lib/reporters/flat-factory/flat'); const logger = require('lib/utils').logger; const Events = require('lib/constants/events'); describe('Reporter#Flat', () => { const sandbox = sinon.sandbox.create(); let test; let emitter; const emit = (event, data) => { emitter.emit(Events.BEGIN); if (event) { emitter.emit(event, data); } emitter.emit(Events.END, {}); }; beforeEach(() => { test = { suite: {path: []}, state: {name: 'test'}, browserId: 0, retriesLeft: 1 }; const reporter = new FlatReporter(); emitter = new EventEmitter(); reporter.attachRunner(emitter); sandbox.stub(logger); }); afterEach(() => { sandbox.restore(); emitter.removeAllListeners(); }); describe('should print an error if it there is in', () => { it('result', () => { test.message = 'Error from result'; emit(Events.ERROR, test); assert.calledWith(logger.error, test.message); }); it('originalError', () => { test.originalError = {stack: 'Error from originalError'}; emit(Events.ERROR, test); assert.calledWith(logger.error, test.originalError.stack); }); }); it('should log result from stats', () => { emit(Events.END, { total: 15, updated: 1, passed: 2, failed: 3, skipped: 4, retries: 5 }); const deserealizedResult = chalk.stripColor(logger.log.firstCall.args[0]); assert.equal(deserealizedResult, 'Total: 15 Updated: 1 Passed: 2 Failed: 3 Skipped: 4 Retries: 5'); }); it('should correctly do the rendering', () => { test = { suite: {path: ['block', 'size', 'big']}, state: {name: 'hover'}, browserId: 'chrome' }; emit(Events.UPDATE_RESULT, test); const deserealizedResult = chalk .stripColor(logger.log.firstCall.args[0]) .substr(2); // remove first symbol (icon) assert.equal(deserealizedResult, 'block size big hover [chrome]'); }); });
import bluebird from "bluebird"; import {omit, difference} from "lodash"; import {makeError} from "../../shared/utils/error"; import AbstractController from "../../shared/controllers/abstract"; import MailController from "./mail"; export default class OptOutController extends AbstractController { static realm = "mail"; getByUser(request) { if (request.params._id !== request.user._id.toString()) { return bluebird.reject(makeError("access-denied", 403, {reason: "user"})); } return this.distinct("type", {user: request.params._id}) .then(types => Object.keys(MailController.types[process.env.MODULE]) .reduce((memo, type) => Object.assign(memo, { [type]: !types.includes(type) }), { _id: request.params._id }) ); } replace(request) { if (request.params._id !== request.user._id.toString()) { return bluebird.reject(makeError("access-denied", 403, {reason: "user"})); } const types = omit(request.body, "_id"); const diff = difference(Object.keys(types), Object.keys(MailController.types[process.env.MODULE])); if (diff.length) { return bluebird.reject(makeError("invalid-param", 400, {name: diff[0], reason: "unrecognized"})); } return this.remove({user: request.params._id}) .then(() => this.create(Object.keys(types) .filter(type => !types[type]) .map(type => ({ type, user: request.params._id })) )) .then(() => this.getByUser(request)); } }
import { valueConverter } from 'aurelia-framework'; import { parsePhoneNumberFromString } from 'libphonenumber-js'; import { _ as __decorate } from './_tslib.js'; import 'date-fns'; import 'kramed'; import 'numeral'; import { U as UIFormat } from './ui-format.js'; let SplitValueConverter = class SplitValueConverter { toView(object, char = ",") { return (object || "").split(new RegExp(`[${char}]`)); } }; SplitValueConverter = __decorate([ valueConverter("split") ], SplitValueConverter); let ObjectMapValueConverter = class ObjectMapValueConverter { toView(object) { if (isEmpty(object)) { return new Map(); } const map = new Map(); object.forEach((value, key) => map.set(key, value)); return map; } }; ObjectMapValueConverter = __decorate([ valueConverter("objectMap") ], ObjectMapValueConverter); let GroupValueConverter = class GroupValueConverter { toView(array, property) { return array.groupBy(property); } }; GroupValueConverter = __decorate([ valueConverter("group") ], GroupValueConverter); let SliceValueConverter = class SliceValueConverter { toView(array, end = 0) { return end === 0 ? array : array.slice(0, end); } }; SliceValueConverter = __decorate([ valueConverter("slice") ], SliceValueConverter); let FilterValueConverter = class FilterValueConverter { toView(array, value, property) { if (isEmpty(array)) { return []; } if (isEmpty(value)) { return array; } if (array instanceof Map) { const map = new Map(); array.forEach((v, k) => { k.toString().includes(value) || (property ? v[property].toString().includes(value.toString()) : v.toString().includes(value.toString())) ? map.set(k, v) : fn(); }); return map; } else { return array.filter(o => property ? o[property].toString().includes(value.toString()) : o.toString().includes(value.toString())); } } }; FilterValueConverter = __decorate([ valueConverter("filter") ], FilterValueConverter); let OrderByValueConverter = class OrderByValueConverter { toView(array, property, isAscending = true) { if (isEmpty(array)) { return []; } let up = 1; let down = -1; if (!isAscending) { up = -1; down = 1; } if (array instanceof Map) { return new Map([...array].sort((a, b) => (a[0] > b[0] ? up : down))); } return [...array].sort((a, b) => (a[property] > b[property] ? up : down)); } }; OrderByValueConverter = __decorate([ valueConverter("orderBy") ], OrderByValueConverter); let SortValueConverter = class SortValueConverter { toView(array, property, isAscending = true) { if (isEmpty(array)) { return []; } if (array instanceof Map) { return new Map([...array].sortBy("0", isAscending)); } return [...array].sortBy(property, isAscending); } }; SortValueConverter = __decorate([ valueConverter("sort") ], SortValueConverter); const getPhone = (value = "", country = "us") => { const number = parsePhoneNumberFromString(value || "", country); return number ? number : { country: "", formatNational: () => "", formatInternational: () => "" }; }; let JsonValueConverter = class JsonValueConverter { toView(value) { return JSON.stringify(value); } }; JsonValueConverter = __decorate([ valueConverter("json") ], JsonValueConverter); let MarkdownValueConverter = class MarkdownValueConverter { toView(value) { return UIFormat.toHTML(value || ""); } }; MarkdownValueConverter = __decorate([ valueConverter("md") ], MarkdownValueConverter); let PhoneValueConverter = class PhoneValueConverter { toView(value, country = "") { return getPhone(value, country).formatInternational(); } }; PhoneValueConverter = __decorate([ valueConverter("phone") ], PhoneValueConverter); let PhoneLocalValueConverter = class PhoneLocalValueConverter { toView(value, country = "us") { return getPhone(value, country).formatNational(); } }; PhoneLocalValueConverter = __decorate([ valueConverter("phoneLocal") ], PhoneLocalValueConverter); let PhoneHtmlValueConverter = class PhoneHtmlValueConverter { toView(value, country = "") { const phoneNumber = getPhone(value, country); return `<span class="ui-flag ${phoneNumber.country}"></span>&nbsp;${phoneNumber.formatInternational()}`; } }; PhoneHtmlValueConverter = __decorate([ valueConverter("phoneHtml") ], PhoneHtmlValueConverter); let PhoneLocalHtmlValueConverter = class PhoneLocalHtmlValueConverter { toView(value, country = "us") { const phoneNumber = getPhone(value, country); return `<span class="ui-flag ${phoneNumber.country}"></span>&nbsp;${phoneNumber.formatNational()}`; } }; PhoneLocalHtmlValueConverter = __decorate([ valueConverter("phoneLocalHtml") ], PhoneLocalHtmlValueConverter); let DateValueConverter = class DateValueConverter { toView(value, format) { return UIFormat.date(value, format); } }; DateValueConverter = __decorate([ valueConverter("date") ], DateValueConverter); let TimeValueConverter = class TimeValueConverter { toView(value, format) { return UIFormat.time(value, format); } }; TimeValueConverter = __decorate([ valueConverter("time") ], TimeValueConverter); let DatetimeValueConverter = class DatetimeValueConverter { toView(value, format) { return UIFormat.datetime(value, format); } }; DatetimeValueConverter = __decorate([ valueConverter("datetime") ], DatetimeValueConverter); let FromNowValueConverter = class FromNowValueConverter { toView(value) { return UIFormat.fromNow(value); } }; FromNowValueConverter = __decorate([ valueConverter("fromnow") ], FromNowValueConverter); let AgeValueConverter = class AgeValueConverter { toView(value) { return UIFormat.age(value); } }; AgeValueConverter = __decorate([ valueConverter("age") ], AgeValueConverter); let UtcValueConverter = class UtcValueConverter { toView(value) { return UIFormat.utcDate(value); } }; UtcValueConverter = __decorate([ valueConverter("utc") ], UtcValueConverter); let IsoValueConverter = class IsoValueConverter { toView(value) { return UIFormat.dateToISO(value); } }; IsoValueConverter = __decorate([ valueConverter("iso") ], IsoValueConverter); let NumberValueConverter = class NumberValueConverter { toView(value, format) { return UIFormat.number(value, format); } }; NumberValueConverter = __decorate([ valueConverter("number") ], NumberValueConverter); let CurrencyValueConverter = class CurrencyValueConverter { toView(value, symbol, format) { return UIFormat.currency(value, symbol, format); } }; CurrencyValueConverter = __decorate([ valueConverter("currency") ], CurrencyValueConverter); let PercentValueConverter = class PercentValueConverter { toView(value) { return UIFormat.percent(value); } }; PercentValueConverter = __decorate([ valueConverter("percent") ], PercentValueConverter); const ValueConverters = [ FilterValueConverter, GroupValueConverter, ObjectMapValueConverter, SliceValueConverter, SortValueConverter, SplitValueConverter, OrderByValueConverter, AgeValueConverter, CurrencyValueConverter, DateValueConverter, DatetimeValueConverter, FromNowValueConverter, JsonValueConverter, MarkdownValueConverter, NumberValueConverter, PercentValueConverter, PhoneHtmlValueConverter, PhoneLocalHtmlValueConverter, PhoneLocalValueConverter, PhoneValueConverter, TimeValueConverter, UtcValueConverter, IsoValueConverter ]; export { ValueConverters }; //# sourceMappingURL=value-converters.js.map
const a = 1212; const b = 43535; const util = require('util'); /** * @param man <human> * @param {Boolean} flag * @returns {number} */ const convertShopToClient = (man, flag) => { man.age = 34; }
const AbstractComparison = Jymfony.Component.Validator.Constraints.AbstractComparison; const Constraint = Jymfony.Component.Validator.Constraint; /** * @memberOf Jymfony.Component.Validator.Constraints */ export default class LessThan extends AbstractComparison { /** * @inheritdoc */ static getErrorName(errorCode) { if (LessThan.TOO_HIGH_ERROR === errorCode) { return 'TOO_HIGH_ERROR'; } return Constraint.getErrorName(errorCode); } /** * @inheritdoc */ __construct(options = null) { this.message = 'This value should be less than {{ compared_value }}.'; return super.__construct(options); } } Object.defineProperty(LessThan, 'TOO_HIGH_ERROR', { value: '079d7420-2d13-460c-8756-de810eeb37d2', writable: false });
// gulp-series var gulp = require("gulp"); module.exports = new function() { var self = this; this.tasks = {}; function getSeriesTaskName(index, seriesOrName) { return index+"."+(Array.isArray(seriesOrName) ? seriesOrName[index] : seriesOrName); } function runSeriesTask(series) { var tasks = self.tasks; series.forEach(function(t) { if(!tasks.hasOwnProperty(t)) throw "task " + t + " is not registered"; }); return function() { if(!series.length) throw "no series provided"; series.forEach(function(t, i) { if(i === 0) gulp.task(getSeriesTaskName(i, t), tasks[t]); else gulp.task(getSeriesTaskName(i, t), [getSeriesTaskName(i - 1, series)], tasks[t]); }); return gulp.start(getSeriesTaskName(series.length - 1, series)); }; } this.registerTasks = function(tasks) { for(var n in tasks) { if(!tasks.hasOwnProperty(n)) continue; gulp.task(n, tasks[n]); } self.tasks = tasks; }; this.registerSeries = function(name, series) { gulp.task(name, runSeriesTask(series)); }; };
consts: function() { let $I18N_0$; if (typeof ngI18nClosureMode !== "undefined" && ngI18nClosureMode) { /** * @suppress {msgDescriptions} */ const $MSG_EXTERNAL_7428861019045796010$$APP_SPEC_TS_1$ = goog.getMsg(" Count: {$startTagXhtmlSpan}5{$closeTagXhtmlSpan}", { "startTagXhtmlSpan": "\uFFFD#4\uFFFD", "closeTagXhtmlSpan": "\uFFFD/#4\uFFFD" }); $I18N_0$ = $MSG_EXTERNAL_7428861019045796010$$APP_SPEC_TS_1$; } else { $I18N_0$ = $localize ` Count: ${"\uFFFD#4\uFFFD"}:START_TAG__XHTML_SPAN:5${"\uFFFD/#4\uFFFD"}:CLOSE_TAG__XHTML_SPAN:`; } return [ ["xmlns", "http://www.w3.org/2000/svg"], ["xmlns", "http://www.w3.org/1999/xhtml"], $i18n_0$ ]; }, template: function MyComponent_Template(rf, ctx) { if (rf & 1) { $r3$.ɵɵnamespaceSVG(); $r3$.ɵɵelementStart(0, "svg", 0); $r3$.ɵɵelementStart(1, "foreignObject"); $r3$.ɵɵnamespaceHTML(); $r3$.ɵɵelementStart(2, "div", 1); $r3$.ɵɵi18nStart(3, 2); $r3$.ɵɵelement(4, "span"); $r3$.ɵɵi18nEnd(); $r3$.ɵɵelementEnd(); $r3$.ɵɵelementEnd(); $r3$.ɵɵelementEnd(); } }
(function() { var MainView, stripTags, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; stripTags = function(input, allowed) { var commentsAndPhpTags, tags; allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi; commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi; return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) { if (allowed.indexOf('<' + $1.toLowerCase() + '>') > -1) { return $0; } else { return ''; } }); }; KD.enableLogs; MainView = (function(superClass) { extend(MainView, superClass); function MainView() { MainView.__super__.constructor.apply(this, arguments); this.kite = KD.getSingleton("vmController"); this.header = new KDHeaderView({ type: "big", title: "KodioFM Holiday Radio" }); this.talksWrapper = new KDCustomHTMLView({ cssClass: "talks" }); this.talk1 = new KDCustomHTMLView({ cssClass: "talk1", partial: "<span>Why did the programmer quit his job?</span>" }); this.talk2 = new KDCustomHTMLView({ cssClass: "talk2", partial: "<span><h2>Ouch!</h2>Pines and needles!</span>" }); this.talk3 = new KDCustomHTMLView({ cssClass: "talk3", partial: "<span>Because he didn't get arrays.</span>" }); this.talk4 = new KDCustomHTMLView({ cssClass: "talk4", partial: "<span><h2>Sigh!</h2>Why do I still hangout with these guys?</span>" }); this.talksWrapper.addSubView(this.talk1); this.talksWrapper.addSubView(this.talk2); this.talksWrapper.addSubView(this.talk3); this.talksWrapper.addSubView(this.talk4); this.characters = new KDCustomHTMLView({ cssClass: "characters" }); this.char1 = new KDCustomHTMLView({ cssClass: "char1" }); this.char2 = new KDCustomHTMLView({ cssClass: "char2" }); this.char3 = new KDCustomHTMLView({ cssClass: "char3" }); this.char4 = new KDCustomHTMLView({ cssClass: "char4" }); this.characters.addSubView(this.char2); this.characters.addSubView(this.char1); this.characters.addSubView(this.char3); this.characters.addSubView(this.char4); setTimeout((function(_this) { return function() { return $(".char2").hover(function() { $(".talk1").fadeIn(500); return $(".char1").hover(function() { $(".talk2").fadeIn(500); return $(".char3").hover(function() { $(".talk3").fadeIn(500); return $(".char4").hover(function() { return $(".talk4").fadeIn(500); }); }); }); }); }; })(this), 500); this.playerWrapper = new KDCustomHTMLView({ cssClass: "playerWrapper" }); this.playerWrapper.updatePartial('<audio id="audio-player" name="audio-player" src="http://108.61.73.118:8124/;">Your browser does not support the audio element.</audio>'); this.playButton = new KDButtonView({ cssClass: "playButton fa fa-play", tooltip: { title: "Play Radio!", placement: "bottom" }, callback: (function(_this) { return function() { if (_this.playButton.hasClass("stopButton")) { _this.playButton.unsetClass("stopButton fa-stop"); _this.playButton.setClass("playButton fa-play"); _this.playerLabel.updatePartial("---"); document.getElementById('audio-player').pause(); return document.getElementById('audio-player').currentTime = 0; } else { setInterval(function() { return _this.getInfo("http://www.181.fm/station_playing/181-xtraditional.html"); }, 10000); _this.playButton.unsetClass("playButton fa-play"); _this.playButton.setClass("stopButton fa-stop"); return document.getElementById('audio-player').play(); } }; })(this) }); this.volumeMinus = new KDButtonView({ cssClass: "volumeMinus fa fa-volume-down", tooltip: { title: "Volume Down!", placement: "bottom" }, callback: (function(_this) { return function() { return document.getElementById('audio-player').volume -= 0.1; }; })(this) }); this.volumePlus = new KDButtonView({ cssClass: "volumePlus fa fa-volume-up", tooltip: { title: "Volume Up!", placement: "bottom" }, callback: (function(_this) { return function() { return document.getElementById('audio-player').volume += 0.1; }; })(this) }); this.playerWrapper.addSubView(this.playButton); this.playerWrapper.addSubView(this.volumeMinus); this.playerWrapper.addSubView(this.volumePlus); this.playerLabel = new KDCustomHTMLView({ cssClass: "playerLabel", partial: "---" }); } MainView.prototype.getInfo = function(url) { if (!url) { return; } return this.kite.run("curl -kLss " + url, (function(_this) { return function(error, data) { data = strip_tags(data); data = data.replace(/[\n\r\t]/g, ""); data = data.substr(data.indexOf("CD") + 2); data = data.trim(); return _this.playerLabel.updatePartial(data); }; })(this)); }; MainView.prototype.pistachio = function() { return "<footer>\n {{> @talksWrapper}}\n {{> @characters}}\n <section class=\"ground\">\n {{> @header}}{{> @playerWrapper}}{{> @playerLabel}}\n </section>\n</footer>"; }; appView.addSubView(new MainView({ cssClass: "wrapper snowcontainer" })); return MainView; })(JView); }).call(this);
'use strict'; const Config = require('../../../config'); const UnsupportedMethods = require('./unsupportedMethods'); const SupportedMethod = require('./supportedMethod'); module.exports = function (settings) { const exportEndpoint = {}; const path = Config.get('/apiUrlPrefix') + '/' + settings.name; const urls = settings.urls; exportEndpoint.register = function (server, options, next) { const routes = []; const createRoutes = function (url) { const params = url.params || ''; url.requests.forEach((proposedRequest) => { const supportedMethod = SupportedMethod(server, proposedRequest, settings, params, path); routes.push(supportedMethod); }); const unsupportedMethods = UnsupportedMethods(settings, params, path); routes.push(unsupportedMethods); }; urls.forEach(createRoutes); server.route(routes); next(); }; exportEndpoint.register.attributes = { name: settings.name, path, urls }; return exportEndpoint; };
/* * * Fold sections to optimize page load * * @author Robert Haritonov (http://rhr.me) * * */ define([ "jquery", "source/load-options", "sourceModules/utils", "sourceModules/browser", "sourceModules/sections", "sourceModules/innerNavigation" ], function($, options, utils, browser, sections, innerNavigation) { 'use strict'; $(function(){ //TODO: move to utils // Bulletproof localStorage check var storage; var fail; var uid; try { uid = new Date(); (storage = window.localStorage).setItem(uid, uid); fail = storage.getItem(uid) !== uid.toString(); storage.removeItem(uid); fail && (storage = false); } catch (e) { } //TODO: /move to utils var SECTION_CLASS = options.SECTION_CLASS; var L_SECTION_CLASS = $('.'+SECTION_CLASS); var OPEN_SECTION_CLASS = 'source_section__open'; var sectionsOnPage = L_SECTION_CLASS; var specName = utils.getSpecName(); //Определяем название спеки var clientConfig = {}; var RES_HIDE_SECTIONS = 'Hide all sections'; if (storage) { //Check if localstorage has required data if (typeof localStorage.getItem('LsClientConfig') === 'string') { //LocalStorage can store only strings //Using JSON for passing array through localStorage clientConfig = $.parseJSON(localStorage.getItem('LsClientConfig')); } else { try { localStorage.setItem('LsClientConfig', JSON.stringify(clientConfig)); } catch (e) { } } } //Preparing config if (typeof clientConfig[specName] !== 'object') { clientConfig[specName] = {}; clientConfig[specName].closedSections = {}; } else if (typeof clientConfig[specName].closedSections !== 'object') { clientConfig[specName].closedSections = {}; } /* Config must look like: clientConfig = { covers: { closedSections: { section1: true, section2: true } } } */ var closedSections = clientConfig[specName].closedSections; var updateConfig = function () { try { localStorage.setItem('LsClientConfig', JSON.stringify(clientConfig)); } catch (e) { } }; var openSpoiler = function ($target, config) { if ($target.is('h3')) { $target = $target.closest('.source_section'); } $target.addClass(OPEN_SECTION_CLASS); var sectionID = $target.attr('id'); var isRendered = false; closedSections["section" + sectionID] = false; if (config) { //Remember options in localStorage updateConfig(); } // TODO: remove mustache check from core if (options.pluginsOptions && options.pluginsOptions.mustache) { // Need to use absolute path to get same scope with requires from inline scripts require(['/plugins/mustache/js/mustache.js'], function(templater){ if (typeof templater.PostponedTemplates !== 'undefined') { if ($target.attr('data-rendered') === 'true') { isRendered = true; } if (!isRendered) { for (var arr in templater.PostponedTemplates[sectionID]) { if (templater.PostponedTemplates[sectionID].hasOwnProperty(arr)) { var values = templater.PostponedTemplates[sectionID][arr]; templater.insertTemplate(values[0], values[1], values[2]); } } $target.attr('data-rendered', 'true'); } } }); } }; var closeSpoiler = function (t, config) { t.removeClass(OPEN_SECTION_CLASS); var tID = t.attr('id'); closedSections["section" + tID] = true; if (config) { updateConfig(); } }; var navHash = utils.parseNavHash(); var sectionsCount = sectionsOnPage.length; for (var i = 0; i < sectionsCount; i++) { var $this = $(sectionsOnPage[i]); var tID = $this.attr('id'); //Check from local storage config if (closedSections["section" + tID]) { $this.attr('data-def-stat', 'closed'); } //Open all unclosed by confing spoilers and scroll to hash targeted section //For ie < 8 all sections closed by default if ($this.attr('data-def-stat') !== 'closed' && !(browser.msie && parseInt(browser.version, 10) < 8)) { openSpoiler($this); } } if (navHash !== '') { openSpoiler($(navHash)); } //To open sections on from inner navigation var openOnNavigation = function() { var navHash = utils.parseNavHash(); openSpoiler($(navHash)); //Close other closed by default sections for (var i = 0; i < sectionsOnPage.length; i++) { var t = $(sectionsOnPage[i]); var tID = t.attr('id'); if (t.attr('data-def-stat') === 'closed' && navHash !== '#' + tID) { closeSpoiler(t); } } if (navHash !== '') { utils.scrollToSection(navHash); } }; //If supports history API if (window.history && history.pushState && !browser.msie) { window.addEventListener('popstate', function (event) { openOnNavigation(); }); } else { $('.source_main_nav_a').on({ click: function(e) { e.preventDefault(); //Imitate hash change on click var href = $(this).attr('href'); href = href.split('#'); href = href[href.length - 1]; window.location.hash = href; openOnNavigation(); } }); } var toggleSpoiler = function (t) { if (t.hasClass(OPEN_SECTION_CLASS)) { closeSpoiler(t, true); } else { openSpoiler(t, true); } }; for(var j = 0; j < sections.getQuantity(); j++) { sections.getSections()[j].headerElement .addClass("source_section_h") .append('<a href="#" onclick="return false" class="source_section_h_expand"></a>'); } $('.source_section_h_expand').on({ click:function () { $this = $(this).closest('.source_section'); toggleSpoiler($this); } }); innerNavigation.addMenuItem(RES_HIDE_SECTIONS, function(){ for (var i = 0; i < sectionsOnPage.length; i++) { closeSpoiler($(sectionsOnPage[i]), true); } }, function(){ for (var i = 0; i < sectionsOnPage.length; i++) { openSpoiler($(sectionsOnPage[i]), true); } }); }); });
/** * @memberof moduleName * @ngdoc controller * @name XxxxController */ class SampleController { /** * Constrctor : inyección de servicios ... * @memberof ActividadesController * @function constructor * @param $scope {service} scope del controller */ constructor($scope) { 'ngInject'; this.$scope = $scope; } /** * Inicialización de las propiedades del componente */ $onInit () { this.name = "Sample" this.value = parent.value } // Fin del $onInit } // Fin del controller SampleController angular.module('moduleName') /** * Componente responsable de los datos de ... * @memberof moduleName * @ngdoc component * @name ..... */ .component("sample", { require: {parent : '^appMain'}, templateUrl : "components/sample.html", // usa controller as por defecto controller: SampleController, //controllerAs: '$ctrl', valor por defecto bindings: {} }) //Fin del componente y del objeto que lo define
(function( $ ) { $.fn.serializeFormExt = function(callback) { var form = $(this); var ret = new FormData(); var loading = 0; var xcallback = function () { if (loading > 0) setTimeout(xcallback, 250); else callback(ret); }; var reader = { file: function (fileObj) { fileObj = $(fileObj); var reader = new FileReader(); var file = fileObj[0].files[0]; loading++; reader.onload = function (e) { ret.append(fileObj.attr('name'), e.target.result); loading--; }; reader.readAsDataURL(file); }, text: function (textObj) { textObj = $(textObj); ret.append(textObj.attr('name'), textObj.val()); } }; $('input', form).each(function () { var obj = $(this); var type = obj.attr('type'); if (!type) return; type = type.toLowerCase(); if (!reader[type]) return; reader[type](obj); }); xcallback(); }; }( jQuery ));
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const msRest = require('ms-rest'); const msRestAzure = require('ms-rest-azure'); const WebResource = msRest.WebResource; /** * @summary Lists all node agent SKUs supported by the Azure Batch service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.accountListNodeAgentSkusOptions] Additional * parameters for the operation * * @param {string} [options.accountListNodeAgentSkusOptions.filter] An OData * $filter clause. For more information on constructing this filter, see * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-node-agent-skus. * * @param {number} [options.accountListNodeAgentSkusOptions.maxResults] The * maximum number of items to return in the response. A maximum of 1000 results * will be returned. * * @param {number} [options.accountListNodeAgentSkusOptions.timeout] The * maximum time that the server can spend processing the request, in seconds. * The default is 30 seconds. * * @param {uuid} [options.accountListNodeAgentSkusOptions.clientRequestId] The * caller-generated request identity, in the form of a GUID with no decoration * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. * * @param {boolean} * [options.accountListNodeAgentSkusOptions.returnClientRequestId] Whether the * server should return the client-request-id in the response. * * @param {date} [options.accountListNodeAgentSkusOptions.ocpDate] The time the * request was issued. Client libraries typically set this to the current * system clock time; set it explicitly if you are calling the REST API * directly. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link AccountListNodeAgentSkusResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _listNodeAgentSkus(options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } let accountListNodeAgentSkusOptions = (options && options.accountListNodeAgentSkusOptions !== undefined) ? options.accountListNodeAgentSkusOptions : undefined; // Validate try { if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') { throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } let filter; let maxResults; let timeout; let clientRequestId; let returnClientRequestId; let ocpDate; try { if (accountListNodeAgentSkusOptions !== null && accountListNodeAgentSkusOptions !== undefined) { filter = accountListNodeAgentSkusOptions.filter; if (filter !== null && filter !== undefined && typeof filter.valueOf() !== 'string') { throw new Error('filter must be of type string.'); } } if (accountListNodeAgentSkusOptions !== null && accountListNodeAgentSkusOptions !== undefined) { maxResults = accountListNodeAgentSkusOptions.maxResults; if (maxResults !== null && maxResults !== undefined && typeof maxResults !== 'number') { throw new Error('maxResults must be of type number.'); } } if (accountListNodeAgentSkusOptions !== null && accountListNodeAgentSkusOptions !== undefined) { timeout = accountListNodeAgentSkusOptions.timeout; if (timeout !== null && timeout !== undefined && typeof timeout !== 'number') { throw new Error('timeout must be of type number.'); } } if (accountListNodeAgentSkusOptions !== null && accountListNodeAgentSkusOptions !== undefined) { clientRequestId = accountListNodeAgentSkusOptions.clientRequestId; if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) { throw new Error('clientRequestId must be of type string and must be a valid uuid.'); } } if (accountListNodeAgentSkusOptions !== null && accountListNodeAgentSkusOptions !== undefined) { returnClientRequestId = accountListNodeAgentSkusOptions.returnClientRequestId; if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') { throw new Error('returnClientRequestId must be of type boolean.'); } } if (accountListNodeAgentSkusOptions !== null && accountListNodeAgentSkusOptions !== undefined) { ocpDate = accountListNodeAgentSkusOptions.ocpDate; if (ocpDate && !(ocpDate instanceof Date || (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) { throw new Error('ocpDate must be of type date.'); } } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'nodeagentskus'; let queryParameters = []; queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion)); if (filter !== null && filter !== undefined) { queryParameters.push('$filter=' + encodeURIComponent(filter)); } if (maxResults !== null && maxResults !== undefined) { queryParameters.push('maxresults=' + encodeURIComponent(maxResults.toString())); } if (timeout !== null && timeout !== undefined) { queryParameters.push('timeout=' + encodeURIComponent(timeout.toString())); } if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if (clientRequestId !== undefined && clientRequestId !== null) { httpRequest.headers['client-request-id'] = clientRequestId.toString(); } if (returnClientRequestId !== undefined && returnClientRequestId !== null) { httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString(); } if (ocpDate !== undefined && ocpDate !== null) { httpRequest.headers['ocp-date'] = ocpDate.toUTCString(); } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { let internalError = null; if (parsedErrorResponse.error) internalError = parsedErrorResponse.error; error.code = internalError ? internalError.code : parsedErrorResponse.code; error.message = internalError ? internalError.message : parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['BatchError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['AccountListNodeAgentSkusResult']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** * @summary Lists all node agent SKUs supported by the Azure Batch service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.accountListNodeAgentSkusNextOptions] Additional * parameters for the operation * * @param {uuid} [options.accountListNodeAgentSkusNextOptions.clientRequestId] * The caller-generated request identity, in the form of a GUID with no * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. * * @param {boolean} * [options.accountListNodeAgentSkusNextOptions.returnClientRequestId] Whether * the server should return the client-request-id in the response. * * @param {date} [options.accountListNodeAgentSkusNextOptions.ocpDate] The time * the request was issued. Client libraries typically set this to the current * system clock time; set it explicitly if you are calling the REST API * directly. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link AccountListNodeAgentSkusResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _listNodeAgentSkusNext(nextPageLink, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } let accountListNodeAgentSkusNextOptions = (options && options.accountListNodeAgentSkusNextOptions !== undefined) ? options.accountListNodeAgentSkusNextOptions : undefined; // Validate try { if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') { throw new Error('nextPageLink cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } let clientRequestId; let returnClientRequestId; let ocpDate; try { if (accountListNodeAgentSkusNextOptions !== null && accountListNodeAgentSkusNextOptions !== undefined) { clientRequestId = accountListNodeAgentSkusNextOptions.clientRequestId; if (clientRequestId !== null && clientRequestId !== undefined && !(typeof clientRequestId.valueOf() === 'string' && msRest.isValidUuid(clientRequestId))) { throw new Error('clientRequestId must be of type string and must be a valid uuid.'); } } if (accountListNodeAgentSkusNextOptions !== null && accountListNodeAgentSkusNextOptions !== undefined) { returnClientRequestId = accountListNodeAgentSkusNextOptions.returnClientRequestId; if (returnClientRequestId !== null && returnClientRequestId !== undefined && typeof returnClientRequestId !== 'boolean') { throw new Error('returnClientRequestId must be of type boolean.'); } } if (accountListNodeAgentSkusNextOptions !== null && accountListNodeAgentSkusNextOptions !== undefined) { ocpDate = accountListNodeAgentSkusNextOptions.ocpDate; if (ocpDate && !(ocpDate instanceof Date || (typeof ocpDate.valueOf() === 'string' && !isNaN(Date.parse(ocpDate))))) { throw new Error('ocpDate must be of type date.'); } } } catch (error) { return callback(error); } // Construct URL let requestUrl = '{nextLink}'; requestUrl = requestUrl.replace('{nextLink}', nextPageLink); // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; odata=minimalmetadata; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if (clientRequestId !== undefined && clientRequestId !== null) { httpRequest.headers['client-request-id'] = clientRequestId.toString(); } if (returnClientRequestId !== undefined && returnClientRequestId !== null) { httpRequest.headers['return-client-request-id'] = returnClientRequestId.toString(); } if (ocpDate !== undefined && ocpDate !== null) { httpRequest.headers['ocp-date'] = ocpDate.toUTCString(); } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { let internalError = null; if (parsedErrorResponse.error) internalError = parsedErrorResponse.error; error.code = internalError ? internalError.code : parsedErrorResponse.code; error.message = internalError ? internalError.message : parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['BatchError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['AccountListNodeAgentSkusResult']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** Class representing a Account. */ class Account { /** * Create a Account. * @param {BatchServiceClient} client Reference to the service client. */ constructor(client) { this.client = client; this._listNodeAgentSkus = _listNodeAgentSkus; this._listNodeAgentSkusNext = _listNodeAgentSkusNext; } /** * @summary Lists all node agent SKUs supported by the Azure Batch service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.accountListNodeAgentSkusOptions] Additional * parameters for the operation * * @param {string} [options.accountListNodeAgentSkusOptions.filter] An OData * $filter clause. For more information on constructing this filter, see * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-node-agent-skus. * * @param {number} [options.accountListNodeAgentSkusOptions.maxResults] The * maximum number of items to return in the response. A maximum of 1000 results * will be returned. * * @param {number} [options.accountListNodeAgentSkusOptions.timeout] The * maximum time that the server can spend processing the request, in seconds. * The default is 30 seconds. * * @param {uuid} [options.accountListNodeAgentSkusOptions.clientRequestId] The * caller-generated request identity, in the form of a GUID with no decoration * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. * * @param {boolean} * [options.accountListNodeAgentSkusOptions.returnClientRequestId] Whether the * server should return the client-request-id in the response. * * @param {date} [options.accountListNodeAgentSkusOptions.ocpDate] The time the * request was issued. Client libraries typically set this to the current * system clock time; set it explicitly if you are calling the REST API * directly. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccountListNodeAgentSkusResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listNodeAgentSkusWithHttpOperationResponse(options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listNodeAgentSkus(options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Lists all node agent SKUs supported by the Azure Batch service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.accountListNodeAgentSkusOptions] Additional * parameters for the operation * * @param {string} [options.accountListNodeAgentSkusOptions.filter] An OData * $filter clause. For more information on constructing this filter, see * https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-node-agent-skus. * * @param {number} [options.accountListNodeAgentSkusOptions.maxResults] The * maximum number of items to return in the response. A maximum of 1000 results * will be returned. * * @param {number} [options.accountListNodeAgentSkusOptions.timeout] The * maximum time that the server can spend processing the request, in seconds. * The default is 30 seconds. * * @param {uuid} [options.accountListNodeAgentSkusOptions.clientRequestId] The * caller-generated request identity, in the form of a GUID with no decoration * such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. * * @param {boolean} * [options.accountListNodeAgentSkusOptions.returnClientRequestId] Whether the * server should return the client-request-id in the response. * * @param {date} [options.accountListNodeAgentSkusOptions.ocpDate] The time the * request was issued. Client libraries typically set this to the current * system clock time; set it explicitly if you are calling the REST API * directly. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {AccountListNodeAgentSkusResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link AccountListNodeAgentSkusResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listNodeAgentSkus(options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listNodeAgentSkus(options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listNodeAgentSkus(options, optionalCallback); } } /** * @summary Lists all node agent SKUs supported by the Azure Batch service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.accountListNodeAgentSkusNextOptions] Additional * parameters for the operation * * @param {uuid} [options.accountListNodeAgentSkusNextOptions.clientRequestId] * The caller-generated request identity, in the form of a GUID with no * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. * * @param {boolean} * [options.accountListNodeAgentSkusNextOptions.returnClientRequestId] Whether * the server should return the client-request-id in the response. * * @param {date} [options.accountListNodeAgentSkusNextOptions.ocpDate] The time * the request was issued. Client libraries typically set this to the current * system clock time; set it explicitly if you are calling the REST API * directly. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<AccountListNodeAgentSkusResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listNodeAgentSkusNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listNodeAgentSkusNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * @summary Lists all node agent SKUs supported by the Azure Batch service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.accountListNodeAgentSkusNextOptions] Additional * parameters for the operation * * @param {uuid} [options.accountListNodeAgentSkusNextOptions.clientRequestId] * The caller-generated request identity, in the form of a GUID with no * decoration such as curly braces, e.g. 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. * * @param {boolean} * [options.accountListNodeAgentSkusNextOptions.returnClientRequestId] Whether * the server should return the client-request-id in the response. * * @param {date} [options.accountListNodeAgentSkusNextOptions.ocpDate] The time * the request was issued. Client libraries typically set this to the current * system clock time; set it explicitly if you are calling the REST API * directly. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {AccountListNodeAgentSkusResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link AccountListNodeAgentSkusResult} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listNodeAgentSkusNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listNodeAgentSkusNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listNodeAgentSkusNext(nextPageLink, options, optionalCallback); } } } module.exports = Account;
/** * @fileoverview Build file * @author nzakas */ /* global cat, cd, cp, echo, exec, exit, find, ls, mkdir, mv, pwd, rm, target, test*/ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ require("shelljs/make"); var checker = require("npm-license"), dateformat = require("dateformat"), fs = require("fs"), markdownlint = require("markdownlint"), nodeCLI = require("shelljs-nodecli"), os = require("os"), path = require("path"), semver = require("semver"), ejs = require("ejs"), loadPerf = require("load-perf"); //------------------------------------------------------------------------------ // Settings //------------------------------------------------------------------------------ /* * A little bit fuzzy. My computer has a first CPU speed of 3093 and the perf test * always completes in < 2000ms. However, Travis is less predictable due to * multiple different VM types. So I'm fudging this for now in the hopes that it * at least provides some sort of useful signal. */ var PERF_MULTIPLIER = 7.5e6; var OPEN_SOURCE_LICENSES = [ /MIT/, /BSD/, /Apache/, /ISC/, /WTF/, /Public Domain/ ]; //------------------------------------------------------------------------------ // Data //------------------------------------------------------------------------------ var NODE = "node ", // intentional extra space NODE_MODULES = "./node_modules/", TEMP_DIR = "./tmp/", BUILD_DIR = "./build/", DOCS_DIR = "../eslint.github.io/docs", SITE_DIR = "../eslint.github.io/", // Utilities - intentional extra space at the end of each string MOCHA = NODE_MODULES + "mocha/bin/_mocha ", ESLINT = NODE + " bin/eslint.js ", // Files MAKEFILE = "./Makefile.js", PACKAGE = "./package.json", /* eslint-disable no-use-before-define */ JS_FILES = find("lib/").filter(fileType("js")).join(" "), JSON_FILES = find("conf/").filter(fileType("json")).join(" ") + " .eslintrc", MARKDOWN_FILES_ARRAY = find("docs/").concat(ls(".")).filter(fileType("md")), TEST_FILES = find("tests/lib/").filter(fileType("js")).join(" "), /* eslint-enable no-use-before-define */ // Regex TAG_REGEX = /^(?:Fix|Update|Breaking|Docs|Build|New|Upgrade):/, ISSUE_REGEX = /\((?:fixes|refs) #\d+(?:.*(?:fixes|refs) #\d+)*\)$/, // Settings MOCHA_TIMEOUT = 4000; //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Generates a function that matches files with a particular extension. * @param {string} extension The file extension (i.e. "js") * @returns {Function} The function to pass into a filter method. * @private */ function fileType(extension) { return function(filename) { return filename.substring(filename.lastIndexOf(".") + 1) === extension; }; } /** * Returns package.json contents as a JavaScript object * @returns {Object} Contents of package.json for the project * @private */ function getPackageInfo() { return JSON.parse(fs.readFileSync(PACKAGE)); } /** * Generates a static file that includes each rule by name rather than dynamically * looking up based on directory. This is used for the browser version of ESLint. * @param {string} basedir The directory in which to look for code. * @returns {void} */ function generateRulesIndex(basedir) { var output = "module.exports = function() {\n"; output += " var rules = Object.create(null);\n"; find(basedir + "rules/").filter(fileType("js")).forEach(function(filename) { var basename = path.basename(filename, ".js"); output += " rules[\"" + basename + "\"] = require(\"./rules/" + basename + "\");\n"; }); output += "\n return rules;\n};"; output.to(basedir + "load-rules.js"); } /** * Executes a command and returns the output instead of printing it to stdout. * @param {string} cmd The command string to execute. * @returns {string} The result of the executed command. */ function execSilent(cmd) { return exec(cmd, { silent: true }).output; } /** * Generates a release blog post for eslint.org * @param {Object} releaseInfo The release metadata. * @returns {void} * @private */ function generateBlogPost(releaseInfo) { var output = ejs.render(cat("./templates/blogpost.md.ejs"), releaseInfo), now = new Date(), month = now.getMonth() + 1, day = now.getDate(), filename = "../eslint.github.io/_posts/" + now.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day) + "-eslint-" + releaseInfo.version + "-released.md"; output.to(filename); } /** * Generates a doc page with formatter result examples * @param {Object} formatterInfo Linting results from each formatter * @param {string} [prereleaseVersion] The version used for a prerelease. This * changes where the output is stored. * @returns {void} */ function generateFormatterExamples(formatterInfo, prereleaseVersion) { var output = ejs.render(cat("./templates/formatter-examples.md.ejs"), formatterInfo), filename = "../eslint.github.io/docs/user-guide/formatters/index.md", htmlFilename = "../eslint.github.io/docs/user-guide/formatters/html-formatter-example.html"; if (prereleaseVersion) { filename = filename.replace("/docs", "/docs/" + prereleaseVersion); htmlFilename = htmlFilename.replace("/docs", "/docs/" + prereleaseVersion); } output.to(filename); formatterInfo.formatterResults.html.result.to(htmlFilename); } /** * Given a semver version, determine the type of version. * @param {string} version A semver version string. * @returns {string} The type of version. * @private */ function getReleaseType(version) { if (semver.patch(version) > 0) { return "patch"; } else if (semver.minor(version) > 0) { return "minor"; } else { return "major"; } } /** * Creates a release version tag and pushes to origin. * @param {string} type The type of release to do (patch, minor, major) * @returns {void} */ function release(type) { var newVersion;/* , changes;*/ exec("git checkout master && git fetch origin && git reset --hard origin/master"); exec("npm install && npm prune"); target.test(); echo("Generating new version"); newVersion = execSilent("npm version " + type).trim(); echo("Generating changelog"); var releaseInfo = target.changelog(); // add changelog to commit exec("git add CHANGELOG.md"); exec("git commit --amend --no-edit"); // replace existing tag exec("git tag -f " + newVersion); // push all the things echo("Publishing to git"); exec("git push origin master --tags"); // now push the changelog...changes to the tag // echo("Publishing changes to github release"); // this requires a github API token in process.env.ESLINT_GITHUB_TOKEN // it will continue with an error message logged if not set // ghGot("repos/eslint/eslint/releases", { // body: JSON.stringify({ // tag_name: newVersion, // name: newVersion, // target_commitish: "master", // body: changes // }), // method: "POST", // json: true, // token: process.env.ESLINT_GITHUB_TOKEN // }, function(pubErr) { // if (pubErr) { // echo("Warning: error when publishing changes to github release: " + pubErr.message); // } echo("Publishing to npm"); getPackageInfo().files.filter(function(dirPath) { return fs.lstatSync(dirPath).isDirectory(); }).forEach(nodeCLI.exec.bind(nodeCLI, "linefix")); exec("npm publish"); exec("git reset --hard"); echo("Generating site"); target.gensite(); generateBlogPost(releaseInfo); target.publishsite(); // }); } /** * Creates a prerelease version tag and pushes to origin. * @param {string} version The prerelease version to create (i.e. 2.0.0-alpha-1). * @returns {void} */ function prerelease(version) { var newVersion;/* , changes;*/ // exec("git checkout master && git fetch origin && git reset --hard origin/master"); // exec("npm install && npm prune"); target.test(); echo("Generating new version"); newVersion = execSilent("npm version " + version).trim(); echo("Generating changelog"); var releaseInfo = target.changelog(); // add changelog to commit exec("git add CHANGELOG.md"); exec("git commit --amend --no-edit"); // replace existing tag exec("git tag -f " + newVersion); // push all the things echo("Publishing to git"); exec("git push origin master --tags"); // publish to npm echo("Publishing to npm"); getPackageInfo().files.filter(function(dirPath) { return fs.lstatSync(dirPath).isDirectory(); }).forEach(nodeCLI.exec.bind(nodeCLI, "linefix")); exec("npm publish --tag next"); exec("git reset --hard"); echo("Generating site"); target.gensite(semver.inc(version, "major")); generateBlogPost(releaseInfo); } /** * Splits a command result to separate lines. * @param {string} result The command result string. * @returns {array} The separated lines. */ function splitCommandResultToLines(result) { return result.trim().split("\n"); } /** * Gets the first commit sha of the given file. * @param {string} filePath The file path which should be checked. * @returns {string} The commit sha. */ function getFirstCommitOfFile(filePath) { var commits = execSilent("git rev-list HEAD -- " + filePath); commits = splitCommandResultToLines(commits); return commits[commits.length - 1].trim(); } /** * Gets the tag name where a given file was introduced first. * @param {string} filePath The file path to check. * @returns {string} The tag name. */ function getTagOfFirstOccurrence(filePath) { var firstCommit = getFirstCommitOfFile(filePath), tags = execSilent("git tag --contains " + firstCommit); tags = splitCommandResultToLines(tags); return tags.reduce(function(list, version) { version = semver.valid(version.trim()); if (version) { list.push(version); } return list; }, []).sort(semver.compare)[0]; } /** * Gets the version number where a given file was introduced first. * @param {string} filePath The file path to check. * @returns {string} The version number. */ function getFirstVersionOfFile(filePath) { return getTagOfFirstOccurrence(filePath); } /** * Gets the commit that deleted a file. * @param {string} filePath The path to the deleted file. * @returns {string} The commit sha. */ function getCommitDeletingFile(filePath) { var commits = execSilent("git rev-list HEAD -- " + filePath); return splitCommandResultToLines(commits)[0]; } /** * Gets the first version number where a given file is no longer present. * @param {string} filePath The path to the deleted file. * @returns {string} The version number. */ function getFirstVersionOfDeletion(filePath) { var deletionCommit = getCommitDeletingFile(filePath), tags = execSilent("git tag --contains " + deletionCommit); return splitCommandResultToLines(tags) .map(function(version) { return semver.valid(version.trim()); }) .filter(function(version) { return version; }) .sort(semver.compare)[0]; } /** * Returns the version tags * @returns {string[]} Tags * @private */ function getVersionTags() { var tags = splitCommandResultToLines(execSilent("git tag")); return tags.reduce(function(list, tag) { if (semver.valid(tag)) { list.push(tag); } return list; }, []).sort(semver.compare); } /** * Returns all the branch names * @returns {string[]} branch names * @private */ function getBranches() { var branchesRaw = splitCommandResultToLines(execSilent("git branch --list")), branches = [], branchName; for (var i = 0; i < branchesRaw.length; i++) { branchName = branchesRaw[i].replace(/^\*(.*)/, "$1").trim(); branches.push(branchName); } return branches; } /** * Lints Markdown files. * @param {array} files Array of file names to lint. * @returns {object} exec-style exit code object. * @private */ function lintMarkdown(files) { var config = { default: true, // Exclusions for deliberate/widespread violations MD001: false, // Header levels should only increment by one level at a time MD002: false, // First header should be a h1 header MD007: { // Unordered list indentation indent: 4 }, MD012: false, // Multiple consecutive blank lines MD013: false, // Line length MD014: false, // Dollar signs used before commands without showing output MD019: false, // Multiple spaces after hash on atx style header MD021: false, // Multiple spaces inside hashes on closed atx style header MD024: false, // Multiple headers with the same content MD026: false, // Trailing punctuation in header MD029: false, // Ordered list item prefix MD030: false, // Spaces after list markers MD034: false, // Bare URL used MD040: false, // Fenced code blocks should have a language specified MD041: false // First line in file should be a top level header }, result = markdownlint.sync({ files: files, config: config }), resultString = result.toString(), returnCode = resultString ? 1 : 0; if (resultString) { console.error(resultString); } return { code: returnCode }; } /** * Check if the branch name is valid * @param {string} branchName Branch name to check * @returns {boolean} true is branch exists * @private */ function hasBranch(branchName) { var branches = getBranches(); return branches.indexOf(branchName) !== -1; } /** * Gets linting results from every formatter, based on a hard-coded snippet and config * @returns {Object} Output from each formatter */ function getFormatterResults() { var CLIEngine = require("./lib/cli-engine"), chalk = require("chalk"); var formatterFiles = fs.readdirSync("./lib/formatters/"), cli = new CLIEngine({ useEslintrc: false, baseConfig: { "extends": "eslint:recommended" }, rules: { "no-else-return": 1, "indent": [1, 4], "space-unary-ops": 2, "semi": [1, "always"], "consistent-return": 2 } }), codeString = [ "function addOne(i) {", " if (i != NaN) {", " return i ++", " } else {", " return", " }", "};" ].join("\n"), rawMessages = cli.executeOnText(codeString, "fullOfProblems.js"); return formatterFiles.reduce(function(data, filename) { var fileExt = path.extname(filename), name = path.basename(filename, fileExt); if (fileExt === ".js") { data.formatterResults[name] = { result: chalk.stripColor(cli.getFormatter(name)(rawMessages.results)) }; } return data; }, { formatterResults: {} }); } //------------------------------------------------------------------------------ // Tasks //------------------------------------------------------------------------------ target.all = function() { target.test(); }; target.lint = function() { var errors = 0, makeFileCache = " ", jsCache = " ", testCache = " ", lastReturn; // using the cache locally to speed up linting process if (!process.env.TRAVIS) { makeFileCache = " --cache --cache-file .cache/makefile_cache "; jsCache = " --cache --cache-file .cache/js_cache "; testCache = " --cache --cache-file .cache/test_cache "; } echo("Validating Makefile.js"); lastReturn = exec(ESLINT + makeFileCache + MAKEFILE); if (lastReturn.code !== 0) { errors++; } echo("Validating JSON Files"); lastReturn = nodeCLI.exec("jsonlint", "-q -c", JSON_FILES); if (lastReturn.code !== 0) { errors++; } echo("Validating Markdown Files"); lastReturn = lintMarkdown(MARKDOWN_FILES_ARRAY); if (lastReturn.code !== 0) { errors++; } echo("Validating JavaScript files"); lastReturn = exec(ESLINT + jsCache + JS_FILES); if (lastReturn.code !== 0) { errors++; } echo("Validating JavaScript test files"); lastReturn = exec(ESLINT + testCache + TEST_FILES); if (lastReturn.code !== 0) { errors++; } if (errors) { exit(1); } }; target.test = function() { target.lint(); target.checkRuleFiles(); var errors = 0, lastReturn; // exec(ISTANBUL + " cover " + MOCHA + "-- -c " + TEST_FILES); lastReturn = nodeCLI.exec("istanbul", "cover", MOCHA, "-- -R progress -t " + MOCHA_TIMEOUT, "-c", TEST_FILES); if (lastReturn.code !== 0) { errors++; } // exec(ISTANBUL + "check-coverage --statement 99 --branch 98 --function 99 --lines 99"); lastReturn = nodeCLI.exec("istanbul", "check-coverage", "--statement 99 --branch 98 --function 99 --lines 99"); if (lastReturn.code !== 0) { errors++; } target.browserify(); lastReturn = nodeCLI.exec("mocha-phantomjs", "-R dot", "tests/tests.htm"); if (lastReturn.code !== 0) { errors++; } if (errors) { exit(1); } target.checkLicenses(); }; target.docs = function() { echo("Generating documentation"); nodeCLI.exec("jsdoc", "-d jsdoc lib"); echo("Documentation has been output to /jsdoc"); }; target.gensite = function(prereleaseVersion) { echo("Generating eslint.org"); var docFiles = [ "/rules/", "/user-guide/command-line-interface.md", "/user-guide/configuring.md", "/developer-guide/code-path-analysis.md", "/developer-guide/nodejs-api.md", "/developer-guide/working-with-plugins.md", "/developer-guide/working-with-rules.md" ]; // append version if (prereleaseVersion) { docFiles = docFiles.map(function(docFile) { return "/" + prereleaseVersion + docFile; }); } // 1. create temp and build directory if (!test("-d", TEMP_DIR)) { mkdir(TEMP_DIR); } // 2. remove old files from the site docFiles.forEach(function(filePath) { var fullPath = path.join(DOCS_DIR, filePath), htmlFullPath = fullPath.replace(".md", ".html"); if (test("-f", fullPath)) { rm("-r", fullPath); if (filePath.indexOf(".md") >= 0 && test("-f", htmlFullPath)) { rm("-r", htmlFullPath); } } }); // 3. Copy docs folder to a temporary directory cp("-rf", "docs/*", TEMP_DIR); var versions = test("-f", "./versions.json") ? JSON.parse(cat("./versions.json")) : {}; if (!versions.added) { versions = { added: versions, removed: {} }; } // 4. Loop through all files in temporary directory find(TEMP_DIR).forEach(function(filename) { if (test("-f", filename) && path.extname(filename) === ".md") { var rulesUrl = "https://github.com/eslint/eslint/tree/master/lib/rules/"; var docsUrl = "https://github.com/eslint/eslint/tree/master/docs/rules/"; var text = cat(filename); var baseName = path.basename(filename); var sourceBaseName = path.basename(filename, ".md") + ".js"; var sourcePath = path.join("lib/rules", sourceBaseName); var ruleName = path.basename(filename, ".md"); // 5. Prepend page title and layout variables at the top of rules if (path.dirname(filename).indexOf("rules") >= 0) { text = "---\ntitle: " + (ruleName === "README" ? "List of available rules" : "Rule " + ruleName) + "\nlayout: doc\n---\n<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->\n" + text; } else { text = "---\ntitle: Documentation\nlayout: doc\n---\n<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->\n" + text; } // 6. Remove .md extension for links and change README to empty string text = text.replace(/\.md(.*?\))/g, ")").replace("README.html", ""); // 7. Check if there's a trailing white line at the end of the file, if there isn't one, add it if (!/\n$/.test(text)) { text = text + "\n"; } // 8. Append first version of ESLint rule was added at. if (filename.indexOf("rules/") !== -1 && baseName !== "README.md") { var added, removed; if (!versions.added[baseName]) { versions.added[baseName] = getFirstVersionOfFile(sourcePath); } added = versions.added[baseName]; if (!versions.removed[baseName] && !fs.existsSync(sourcePath)) { versions.removed[baseName] = getFirstVersionOfDeletion(sourcePath); } removed = versions.removed[baseName]; text += "\n## Version\n\n"; text += removed ? "This rule was introduced in ESLint " + added + " and removed in " + removed + ".\n" : "This rule was introduced in ESLint " + added + ".\n"; text += "\n## Resources\n\n"; if (!removed) { text += "* [Rule source](" + rulesUrl + sourceBaseName + ")\n"; } text += "* [Documentation source](" + docsUrl + baseName + ")\n"; } // 9. Update content of the file with changes text.to(filename.replace("README.md", "index.md")); } }); JSON.stringify(versions).to("./versions.json"); // 10. Copy temorary directory to site's docs folder var outputDir = DOCS_DIR; if (prereleaseVersion) { outputDir += "/" + prereleaseVersion; } cp("-rf", TEMP_DIR + "*", outputDir); // 11. Delete temporary directory rm("-r", TEMP_DIR); // 12. Update demos, but only for non-prereleases if (!prereleaseVersion) { cp("-f", "build/eslint.js", SITE_DIR + "js/app/eslint.js"); cp("-f", "conf/eslint.json", SITE_DIR + "js/app/eslint.json"); } // 13. Create Example Formatter Output Page generateFormatterExamples(getFormatterResults()); }; target.publishsite = function() { var currentDir = pwd(); cd(SITE_DIR); exec("git add -A ."); exec("git commit -m \"Autogenerated new docs and demo at " + dateformat(new Date()) + "\""); exec("git fetch origin && git rebase origin/master"); exec("git push origin master"); cd(currentDir); }; target.browserify = function() { // 1. create temp and build directory if (!test("-d", TEMP_DIR)) { mkdir(TEMP_DIR); } if (!test("-d", BUILD_DIR)) { mkdir(BUILD_DIR); } // 2. copy files into temp directory cp("-r", "lib/*", TEMP_DIR); // 3. delete the load-rules.js file rm(TEMP_DIR + "load-rules.js"); // 4. create new load-rule.js with hardcoded requires generateRulesIndex(TEMP_DIR); // 5. browserify the temp directory nodeCLI.exec("browserify", "-x espree", TEMP_DIR + "eslint.js", "-o", BUILD_DIR + "eslint.js", "-s eslint"); // 6. Browserify espree nodeCLI.exec("browserify", "-r espree", "-o", TEMP_DIR + "espree.js"); // 7. Concatenate the two files together cat(TEMP_DIR + "espree.js", BUILD_DIR + "eslint.js").to(BUILD_DIR + "eslint.js"); // 8. remove temp directory rm("-r", TEMP_DIR); }; target.changelog = function() { // get most recent two tags var tags = getVersionTags(), rangeTags = tags.slice(tags.length - 2), now = new Date(), timestamp = dateformat(now, "mmmm d, yyyy"), releaseInfo = { releaseType: getReleaseType(rangeTags[1]), version: rangeTags[1] }; // output header (rangeTags[1] + " - " + timestamp + "\n").to("CHANGELOG.tmp"); // get log statements var logs = execSilent("git log --no-merges --pretty=format:\"* %s (%an)\" " + rangeTags.join("..")).split(/\n/g); logs.shift(); // get rid of version commit logs.forEach(function(log) { var tag = log.substring(2, log.indexOf(":")).toLowerCase(); if (!releaseInfo["changelog_" + tag]) { releaseInfo["changelog_" + tag] = []; } releaseInfo["changelog_" + tag].push(log); }); var output = logs.join("\n"); // and join it into a string releaseInfo.raw = output; logs.push(""); // to create empty lines logs.unshift(""); // output log statements logs.join("\n").toEnd("CHANGELOG.tmp"); // switch-o change-o cat("CHANGELOG.tmp", "CHANGELOG.md").to("CHANGELOG.md.tmp"); rm("CHANGELOG.tmp"); rm("CHANGELOG.md"); mv("CHANGELOG.md.tmp", "CHANGELOG.md"); return releaseInfo; }; target.checkRuleFiles = function() { echo("Validating rules"); var eslintConf = require("./conf/eslint.json").rules; var ruleFiles = find("lib/rules/").filter(fileType("js")), rulesIndexText = cat("docs/rules/README.md"), errors = 0; ruleFiles.forEach(function(filename) { var basename = path.basename(filename, ".js"); var docFilename = "docs/rules/" + basename + ".md"; var indexLine = new RegExp("\\* \\[" + basename + "\\].*").exec(rulesIndexText); indexLine = indexLine ? indexLine[0] : ""; /** * Check if basename is present in eslint conf * @returns {boolean} true if present * @private */ function isInConfig() { return eslintConf.hasOwnProperty(basename); } /** * Check if rule is off in eslint conf * @returns {boolean} true if off * @private */ function isOffInConfig() { var rule = eslintConf[basename]; return rule === 0 || (rule && rule[0] === 0); } /** * Check if rule is on in eslint conf * @returns {boolean} true if on * @private */ function isOnInConfig() { return !isOffInConfig(); } /** * Check if rule is not recommended by eslint * @returns {boolean} true if not recommended * @private */ function isNotRecommended() { return indexLine.indexOf("(recommended)") === -1; } /** * Check if rule is recommended by eslint * @returns {boolean} true if recommended * @private */ function isRecommended() { return !isNotRecommended(); } /** * Check if id is present in title * @param {string} id id to check for * @returns {boolean} true if present * @private */ function hasIdInTitle(id) { var docText = cat(docFilename); var idInTitleRegExp = new RegExp("^# (.*?) \\(" + id + "\\)"); return idInTitleRegExp.test(docText); } // check for docs if (!test("-f", docFilename)) { console.error("Missing documentation for rule %s", basename); errors++; } else { // check for entry in docs index if (rulesIndexText.indexOf("(" + basename + ".md)") === -1) { console.error("Missing link to documentation for rule %s in index", basename); errors++; } // check for proper doc format if (!hasIdInTitle(basename)) { console.error("Missing id in the doc page's title of rule %s", basename); errors++; } } // check for default configuration if (!isInConfig()) { console.error("Missing default setting for %s in eslint.json", basename); errors++; } // check that rule is not recommended in docs but off in default config if (isRecommended() && isOffInConfig()) { console.error("Rule documentation says that %s is recommended, but it is disabled in eslint.json.", basename); errors++; } // check that rule is not on in default config but not recommended if (isOnInConfig("default") && isNotRecommended("default")) { console.error("Missing '(recommended)' for rule %s in index", basename); errors++; } // check for tests if (!test("-f", "tests/lib/rules/" + basename + ".js")) { console.error("Missing tests for rule %s", basename); errors++; } }); if (errors) { exit(1); } }; target.checkLicenses = function() { /** * Check if a dependency is eligible to be used by us * @param {object} dependency dependency to check * @returns {boolean} true if we have permission * @private */ function isPermissible(dependency) { var licenses = dependency.licenses; if (Array.isArray(licenses)) { return licenses.some(function(license) { return isPermissible({ name: dependency.name, licenses: license }); }); } return OPEN_SOURCE_LICENSES.some(function(license) { return license.test(licenses); }); } echo("Validating licenses"); checker.init({ start: __dirname }, function(deps) { var impermissible = Object.keys(deps).map(function(dependency) { return { name: dependency, licenses: deps[dependency].licenses }; }).filter(function(dependency) { return !isPermissible(dependency); }); if (impermissible.length) { impermissible.forEach(function(dependency) { console.error("%s license for %s is impermissible.", dependency.licenses, dependency.name ); }); exit(1); } }); }; target.checkGitCommit = function() { var commitMsgs, failed; if (hasBranch("master")) { commitMsgs = splitCommandResultToLines(execSilent("git log HEAD --not master --format=format:%s --no-merges")); } else { commitMsgs = [execSilent("git log -1 --format=format:%s --no-merges")]; } echo("Validating Commit Message"); // No commit since master should not cause test to fail if (commitMsgs[0] === "") { return; } // Check for more than one commit if (commitMsgs.length > 1) { echo(" - More than one commit found, please squash."); failed = true; } // Only check non-release messages if (!semver.valid(commitMsgs[0]) && !/^Revert /.test(commitMsgs[0])) { if (commitMsgs[0].slice(0, commitMsgs[0].indexOf("\n")).length > 72) { echo(" - First line of commit message must not exceed 72 characters"); failed = true; } // Check for tag at start of message if (!TAG_REGEX.test(commitMsgs[0])) { echo([" - Commit summary must start with one of:", " 'Fix:'", " 'Update:'", " 'Breaking:'", " 'Docs:'", " 'Build:'", " 'New:'", " 'Upgrade:'", " Please refer to the contribution guidelines for more details."].join("\n")); failed = true; } // Check for an issue reference at end (unless it's a documentation commit) if (!/^Docs:/.test(commitMsgs[0])) { if (!ISSUE_REGEX.test(commitMsgs[0])) { echo([" - Commit summary must end with with one of:", " '(fixes #1234)'", " '(refs #1234)'", " Where '1234' is the issue being addressed.", " Please refer to the contribution guidelines for more details."].join("\n")); failed = true; } } } if (failed) { exit(1); } }; /** * Calculates the time for each run for performance * @param {string} cmd cmd * @param {int} runs Total number of runs to do * @param {int} runNumber Current run number * @param {int[]} results Collection results from each run * @param {function} cb Function to call when everything is done * @returns {int[]} calls the cb with all the results * @private */ function time(cmd, runs, runNumber, results, cb) { var start = process.hrtime(); exec(cmd, { silent: true }, function() { var diff = process.hrtime(start), actual = (diff[0] * 1e3 + diff[1] / 1e6); // ms results.push(actual); echo("Performance Run #" + runNumber + ": %dms", actual); if (runs > 1) { return time(cmd, runs - 1, runNumber + 1, results, cb); } else { return cb(results); } }); } /** * Run the load performance for eslint * @returns {void} * @private */ function loadPerformance() { var results = []; for (var cnt = 0; cnt < 5; cnt++) { var loadPerfData = loadPerf({ checkDependencies: false }); echo("Load performance Run #" + (cnt + 1) + ": %dms", loadPerfData.loadTime); results.push(loadPerfData.loadTime); } results.sort(function(a, b) { return a - b; }); var median = results[~~(results.length / 2)]; echo("\nLoad Performance median : %dms", median); } target.perf = function() { var cpuSpeed = os.cpus()[0].speed, max = PERF_MULTIPLIER / cpuSpeed, cmd = ESLINT + "--no-ignore ./tests/performance/jshint.js"; echo("CPU Speed is %d with multiplier %d", cpuSpeed, PERF_MULTIPLIER); time(cmd, 5, 1, [], function(results) { results.sort(function(a, b) { return a - b; }); var median = results[~~(results.length / 2)]; if (median > max) { echo("Performance budget exceeded: %dms (limit: %dms)", median, max); } else { echo("Performance budget ok: %dms (limit: %dms)", median, max); } echo("\n"); loadPerformance(); }); }; target.patch = function() { release("patch"); }; target.minor = function() { release("minor"); }; target.major = function() { release("major"); }; target.prerelease = function(version) { prerelease(version); };
// flow-typed signature: 113e0d46b29531ba54c76e52e6d30bfb // flow-typed version: <<STUB>>/nyc_v^15.1.0/flow_v0.143.1 /** * This is an autogenerated libdef stub for: * * 'nyc' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'nyc' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'nyc/bin/nyc' { declare module.exports: any; } declare module 'nyc/bin/wrap' { declare module.exports: any; } declare module 'nyc/lib/commands/check-coverage' { declare module.exports: any; } declare module 'nyc/lib/commands/helpers' { declare module.exports: any; } declare module 'nyc/lib/commands/instrument' { declare module.exports: any; } declare module 'nyc/lib/commands/merge' { declare module.exports: any; } declare module 'nyc/lib/commands/report' { declare module.exports: any; } declare module 'nyc/lib/config-util' { declare module.exports: any; } declare module 'nyc/lib/fs-promises' { declare module.exports: any; } declare module 'nyc/lib/hash' { declare module.exports: any; } declare module 'nyc/lib/instrumenters/istanbul' { declare module.exports: any; } declare module 'nyc/lib/instrumenters/noop' { declare module.exports: any; } declare module 'nyc/lib/process-args' { declare module.exports: any; } declare module 'nyc/lib/register-env' { declare module.exports: any; } declare module 'nyc/lib/source-maps' { declare module.exports: any; } declare module 'nyc/lib/wrap' { declare module.exports: any; } // Filename aliases declare module 'nyc/bin/nyc.js' { declare module.exports: $Exports<'nyc/bin/nyc'>; } declare module 'nyc/bin/wrap.js' { declare module.exports: $Exports<'nyc/bin/wrap'>; } declare module 'nyc/index' { declare module.exports: $Exports<'nyc'>; } declare module 'nyc/index.js' { declare module.exports: $Exports<'nyc'>; } declare module 'nyc/lib/commands/check-coverage.js' { declare module.exports: $Exports<'nyc/lib/commands/check-coverage'>; } declare module 'nyc/lib/commands/helpers.js' { declare module.exports: $Exports<'nyc/lib/commands/helpers'>; } declare module 'nyc/lib/commands/instrument.js' { declare module.exports: $Exports<'nyc/lib/commands/instrument'>; } declare module 'nyc/lib/commands/merge.js' { declare module.exports: $Exports<'nyc/lib/commands/merge'>; } declare module 'nyc/lib/commands/report.js' { declare module.exports: $Exports<'nyc/lib/commands/report'>; } declare module 'nyc/lib/config-util.js' { declare module.exports: $Exports<'nyc/lib/config-util'>; } declare module 'nyc/lib/fs-promises.js' { declare module.exports: $Exports<'nyc/lib/fs-promises'>; } declare module 'nyc/lib/hash.js' { declare module.exports: $Exports<'nyc/lib/hash'>; } declare module 'nyc/lib/instrumenters/istanbul.js' { declare module.exports: $Exports<'nyc/lib/instrumenters/istanbul'>; } declare module 'nyc/lib/instrumenters/noop.js' { declare module.exports: $Exports<'nyc/lib/instrumenters/noop'>; } declare module 'nyc/lib/process-args.js' { declare module.exports: $Exports<'nyc/lib/process-args'>; } declare module 'nyc/lib/register-env.js' { declare module.exports: $Exports<'nyc/lib/register-env'>; } declare module 'nyc/lib/source-maps.js' { declare module.exports: $Exports<'nyc/lib/source-maps'>; } declare module 'nyc/lib/wrap.js' { declare module.exports: $Exports<'nyc/lib/wrap'>; }
{ bounceBack: true, spinTo: ['side-1', 'side-2', …, or 'side-6'], spinToX: [number from 0 to 360], spinToY: [number from 0 to 360], spinToZ: [number from 0 to 360] }
import { AppRegistry, } from 'react-native'; import Routes from './src/routes'; AppRegistry.registerComponent('RNBoilerplate', () => Routes);
import * as through from 'through2'; import * as es from 'event-stream'; import path from 'path'; import gutil from 'gulp-util'; import config from './../config'; import notifier from 'node-notifier'; export default (param = '') => { let message = `${param}`; let stream = es.through( function write(data) { gutil.log(gutil.colors.yellow(message)); notifier.notify({ 'title': config.info, 'message': message, 'wait': false }); this.emit('data', data); }, function end () { this.emit('end'); } ); return stream; };
var GlobalSystem = window.System; require("./utils_test"); require("./crawl_test"); require("./normalize_test"); require("./import_test"); require("./load_test"); require("./locate_test"); var makeIframe = function(src){ var iframe = document.createElement('iframe'); window.removeMyself = function(){ delete window.removeMyself; document.body.removeChild(iframe); QUnit.start(); }; document.body.appendChild(iframe); iframe.src = src; }; QUnit.module("system-npm plugin"); asyncTest("utils.moduleName.create and utils.moduleName.parse", function(){ GlobalSystem['import']("npm-utils") .then(function(utils){ var parsed = utils.moduleName.parse("abc/foo/def","bar"); equal(parsed.modulePath, "foo/def", "is absolute"); parsed = utils.moduleName.parse("abc#./foo/def","bar"); equal(parsed.modulePath, "./foo/def", "is relative"); var res = utils.moduleName.create(parsed); equal(res,"abc#foo/def", "set back to absolute"); }).then(QUnit.start); }); asyncTest("crawl.getDependencyMap", function(){ GlobalSystem['import']("npm-crawl") .then(function(crawl){ var deps = crawl.getDependencyMap({}, { dependencies: {"bower": "1.2.3", "can": "2.2.2"} }); deepEqual(deps, { "can": {name: "can", version: "2.2.2"}}); }).then(QUnit.start); }); asyncTest("Loads globals", function(){ GlobalSystem["import"]("jquery").then(function($){ ok($.fn.jquery, "jQuery loaded"); }).then(start, start); }); asyncTest("meta", function(){ GlobalSystem["import"]("~/test/meta").then(function(meta){ equal(meta,"123", "got 123"); }).then(start); }); asyncTest("module names that start with @", function(){ GlobalSystem.paths["@foo"] = "test/foo.js"; GlobalSystem["import"]("@foo").then(function(foo){ equal(foo,"bar", "got 123"); }).then(start); }); asyncTest("jquery-ui", function(){ GlobalSystem.paths["@foo"] = "test/foo.js"; Promise.all([ GlobalSystem["import"]("jquery"), GlobalSystem["import"]("jquery-ui/draggable") ]).then(function(mods){ var $ = mods[0]; ok($.fn.draggable); }).then(start, start); }); asyncTest("import self", function(){ GlobalSystem.globalBrowser = { "steal-npm": "steal-npm" }; Promise.all([ GlobalSystem["import"]("steal-npm"), GlobalSystem["import"]("steal-npm/test/meta") ]).then(function(mods){ equal(mods[0], "example-main", "example-main"); equal(mods[1], "123", "steal-npm/test/meta"); }).then(start); }); asyncTest("modules using process.env", function(){ GlobalSystem.env = "development"; GlobalSystem["delete"]("package.json!npm"); delete window.process; GlobalSystem["import"]("package.json!npm").then(function() { return GlobalSystem["import"]("test/env"); }).then(function(env){ equal(env, "development", "loaded the env"); }).then(start); }); asyncTest("Reuse existing npmContext.pkgInfo", function(){ GlobalSystem.npmContext.pkgInfo = [{ name: "reuse-test", version: "1.0.0", fileUrl: GlobalSystem.baseURL }]; GlobalSystem["delete"]("package.json!npm"); GlobalSystem["import"]("package.json!npm").then(function(){ var pkgInfo = GlobalSystem.npmContext.pkgInfo; var pkg = pkgInfo[pkgInfo.length - 1]; equal(pkg.name, "reuse-test", "package was reused"); }).then(start); }); asyncTest("Support cloned loader", function(){ var origDefault = GlobalSystem.npmPaths.__default; GlobalSystem.npmPaths.__default = { fileUrl: origDefault.fileUrl, main: origDefault.main, name: origDefault.name, version: origDefault.version, resolutions: {} }; GlobalSystem.normalize(origDefault.name) .then(function(normalizedName) { return GlobalSystem.locate({ name: normalizedName }); }) .then(function(path) { ok(path); }) .then(start); }); asyncTest("module names", function(){ makeIframe("not_relative_main/dev.html"); }); asyncTest("main does not include .js in map", function(){ makeIframe("map_main/dev.html"); }); asyncTest("ignoreBrowser", function(){ makeIframe("ignore_browser/dev.html"); }); asyncTest("directories.lib", function(){ makeIframe("directories_lib/dev.html"); }); asyncTest("github ranges as requested versions are matched", function(){ makeIframe("git_ranges/dev.html"); }); asyncTest("works with packages that have multiple versions of the same dependency", function(){ makeIframe("mult_dep/dev.html"); }); asyncTest("works when System.map and System.paths are provided", function(){ makeIframe("map_paths/dev.html"); }); asyncTest("browser config pointing to an alt main", function(){ makeIframe("browser/dev.html"); }); asyncTest("browser config to ignore a module", function(){ makeIframe("browser-false/dev.html"); }); asyncTest("configDependencies combined from loader and pkg.system", function(){ makeIframe("config_deps/dev.html"); }); asyncTest("Converting name of git versions works", function(){ makeIframe("git_config/dev.html"); }); asyncTest("contextual maps work", function(){ makeIframe("contextual_map/dev.html"); }); asyncTest("configDependencies can override config with systemConfig export", function(){ makeIframe("ext_config/dev.html"); }); asyncTest("transform the JSON with jsonOptions", function(){ makeIframe("json-options/dev.html"); }); QUnit.module("npmDependencies"); asyncTest("are used exclusively if npmIgnore is not provided", function(){ makeIframe("npm_deps_only/dev.html"); }); asyncTest("override npmIgnore when npmIgnore is provided", function(){ makeIframe("npm_deps_override/dev.html"); }); asyncTest("ignores devDependencies when no npmDependencies is provided", function(){ makeIframe("npm_deps_devignore/dev.html"); }); asyncTest("npmIgnore a single module works", function(){ makeIframe("npm_deps_ignore/dev.html"); }); asyncTest("use paths configured, including wildcards, for modules when provided", function(){ makeIframe("paths_config/dev.html"); }); asyncTest("scoped packages work", function(){ makeIframe("scoped/dev.html"); }); asyncTest("works with npm 3's flat file structure", function(){ makeIframe("npm3/dev.html"); }); asyncTest("works with child packages with version ranges", function(){ makeIframe("parent/dev.html"); }); asyncTest("With npm3 traversal starts by going to the mosted nested position", function(){ makeIframe("nested_back/dev.html"); }); asyncTest("peerDependencies are matched against parent that has a matching version", function(){ makeIframe("peer_deps/dev.html"); }); asyncTest("Able to load dependencies using /index convention", function(){ makeIframe("folder_index/dev.html"); }); asyncTest("load in a webworker", function(){ makeIframe("worker/dev.html"); }); asyncTest("works with steal-conditional", function() { makeIframe("conditionals/index.html"); }); asyncTest("works if only system.main is defined", function() { makeIframe("only-system-main/dev.html"); }); QUnit.start();
/* * Utils for working with getting values out of nodes aggregations (different * information about nodes because of data changing after node restart) */ import { last, sortBy, get } from 'lodash'; // Get the key from the aggregation with the latest timestamp export function getLatestAggKey(buckets) { return last(sortBy(buckets, (b => get(b, 'max_timestamp.value')))).key; } /* Get the last attributes from the aggregation * Or undefined, if no attributes were set * NOTE: this is lazy because attributes are not sorted. We expect the * attributes to not change across node restarts */ export function getNodeAttribute(buckets) { // nothing in the bucket, set to undefined if (buckets.length === 0) return; // boolean-ish string return last(buckets).key_as_string; }
const execWrapPath = require.resolve('./exec-wrap') , os = require('os') , path = require('path') , fs = require('fs') , assert = require('assert') , xtend = require('xtend') , after = require('after') function fix (exercise) { var dataPath = path.join(os.tmpDir(), '~workshopper.wraptmp.' + process.pid) var submissionPath = dataPath + '-submission' var solutionPath = dataPath + '-solution' exercise.wrapData = {} exercise.wrapMods = [] exercise.addVerifySetup(function setup (callback) { this.solutionArgs.unshift('$execwrap$solution') // flag if solution this.solutionArgs.unshift('$execwrap$' + this.solution) // original main cmd this.solutionArgs.unshift('$execwrap$' + solutionPath) // path to context data this.solutionArgs.unshift('$execwrap$' + JSON.stringify(exercise.wrapMods)) // list of mods to load this.solution = execWrapPath this.submissionArgs.unshift('$execwrap$submission') // flag if submission this.submissionArgs.unshift('$execwrap$' + this.submission) // original main cmd this.submissionArgs.unshift('$execwrap$' + submissionPath) // path to context data this.submissionArgs.unshift('$execwrap$' + JSON.stringify(exercise.wrapMods)) // list of mods to load this.submission = execWrapPath var wrapData = JSON.stringify(exercise.wrapData) var files = [ submissionPath , solutionPath ] var done = after(files.length, function(err) { if (err) return callback(new Error('Error writing execwrap data: ' + (err.message || err), err)) callback() }) files.forEach(function (path) { fs.writeFile(path, wrapData, 'utf8', done) }) }) exercise.addVerifyProcessor(function (callback) { // sync... yes.. unfortunately, otherwise we'll have timing problems fs.readFile(submissionPath, 'utf8', function (err, data) { if (err) return callback(new Error('Error reading execwrap data: ' + (err.message || err), err)) exercise.wrapData = JSON.parse(data) fs.unlink(submissionPath, function () { callback(null, true) // pass, nothing to fail here }) }) }) // convenience exercise.wrapModule = function (mod) { exercise.wrapMods.push(mod) } // convenience exercise.wrapSet = function (k, v) { if (typeof k == 'string') exercise.wrapData[k] = v else if (typeof k == 'object') exercise.wrapData = xtend(exercise.wrapData, k) } // convenience exercise.wrapGet = function (k) { return exercise.wrapData[k] } } function wrappedexec (exercise) { if (typeof exercise.wrapInject != 'function' || typeof exercise.wrapSet != 'function') fix(exercise) return exercise } module.exports = wrappedexec
define(function(require) { 'use strict'; var WidgetPickerFilterView; var _ = require('underscore'); var BaseView = require('oroui/js/app/views/base/view'); WidgetPickerFilterView = BaseView.extend({ template: require('tpl!oroui/templates/widget-picker/widget-picker-filter-view.html'), autoRender: true, events: { 'keyup [data-role="widget-picker-search"]': 'onSearch', 'change [data-role="widget-picker-search"]': 'onSearch', 'paste [data-role="widget-picker-search"]': 'onSearch', 'mouseup [data-role="widget-picker-search"]': 'onSearch' }, /** * @inheritDoc */ initialize: function(options) { this.onSearch = _.debounce(this.onSearch, 100); WidgetPickerFilterView.__super__.initialize.apply(this, arguments); }, /** * * @param {Event} e */ onSearch: function(e) { this.model.set('search', e.currentTarget.value); } }); return WidgetPickerFilterView; });