code
stringlengths
2
1.05M
var booksApp = angular.module("booksApp", []); booksApp.controller("MainCtrl", function($scope, Models) { $scope.books = Models.books(); $scope.levels = Models.levels(); $scope.selectedBook = null; $scope.selectBook = function(book) { $scope.selectedBook = book; }; $scope.createBook = function() { $scope.books.push({ title: "This is a new book", description: "...", level: "???" }); }; }); booksApp.factory("Models", function() { var books = function() { return [ { title: "Backbone c'est de la balle", description: "tutorial bb", level: "très bon" }, { title: "React ça dépote", description: "se perfectionner avec React", level: "bon" }, { title: "J'apprends Angular", description: "from scratch", level: "débutant" } ]; }; var levels = function() { return [ "très bon", "bon", "débutant" ]; }; return { books: books, levels: levels } });
const mapStyle = [ { featureType: "administrative", elementType: "all", stylers: [ { saturation: "-100", }, ], }, { featureType: "administrative", elementType: "geometry", stylers: [{ visibility: "off" }], }, { featureType: "administrative.country", elementType: "geometry.stroke", stylers: [{ visibility: "on" }], }, { featureType: "administrative.province", elementType: "geometry.stroke", stylers: [{ visibility: "on" }], }, { featureType: "administrative.locality", elementType: "geometry.stroke", stylers: [{ visibility: "on" }], }, { featureType: "administrative.neighborhood", elementType: "geometry.stroke", stylers: [{ visibility: "on" }], }, { featureType: "administrative.land_parcel", elementType: "geometry.stroke", stylers: [{ visibility: "on" }], }, { featureType: "administrative.province", elementType: "all", stylers: [{ visibility: "off" }], }, { featureType: "landscape", elementType: "all", stylers: [ { saturation: -100, }, { lightness: 65, }, { visibility: "on", }, ], }, { featureType: "poi", elementType: "all", stylers: [ { saturation: -100, }, { lightness: "50", }, { visibility: "simplified", }, ], }, { featureType: "road", elementType: "all", stylers: [ { saturation: "-100", }, ], }, { featureType: "road.highway", elementType: "all", stylers: [ { visibility: "simplified", }, ], }, { featureType: "road.arterial", elementType: "all", stylers: [ { lightness: "30", }, ], }, { featureType: "road.local", elementType: "all", stylers: [ { lightness: "40", }, ], }, { featureType: "transit", elementType: "all", stylers: [ { saturation: -100, }, { visibility: "simplified", }, ], }, { featureType: "water", elementType: "geometry", stylers: [ { hue: "#C3CACB", }, { lightness: -25, }, { saturation: -92, }, ], }, { featureType: "water", elementType: "geometry.fill", stylers: [ { lightness: "40", }, { color: "#C3CACB;", }, ], }, { featureType: "water", elementType: "labels", stylers: [ { lightness: -25, }, { saturation: -100, }, ], }, ]; export default mapStyle;
import Ember from 'ember'; export default Ember.Route.extend({ setupController: function(controller, model){ controller.set('query', controller.get('search')); controller.set('displaySearchTips', false); } });
var util = require('util'); should = require('should'), JSUS = require('./../jsus').JSUS; var qId; var foo = 1; var foo2 = 2; var q; describe('QUEUE', function(){ before(function() { q = JSUS.getQueue(); }); it('#getQueue() should get a new Queue object', function() { ('object' === typeof q).should.be.true; }); it('the queue should block callback to be executed if non-ready (1/2)', function() { q.add('aa'); q.add('bb'); q.onReady(function() { foo = foo + 1; }); foo.should.be.eql(1); }); it('the queue should wait until it is completely free', function(){ q.remove('bb'); foo.should.be.eql(1); }); it('the queue should block callback to be executed if non-ready (2/2)', function(){ q.onReady(function() { foo2 = foo2 + 1; }) foo.should.be.eql(1); foo2.should.be.eql(2); }); it('the queue should assign automatically an id', function(){ qId = q.add(); ('string' === typeof qId).should.be.true; }); it('clearing the queue should happen when all items are removed', function(){ q.remove('aa'); q.remove(qId); foo.should.be.eql(2); foo2.should.be.eql(3); }); });
"use strict"; var setup = require("./setup"); var db = require("../index"); var expect = require("chai").expect; var DbUtil = require("./db-util"); var util = require("./util"); var conti = require("conti"); var m = require("./model"); function initDb(done){ this.timeout(10000); util.withConnect(function(conn, done){ util.initTables(conn, ["shinryoukoui_master_arch", "iyakuhin_master_arch", "tokuteikizai_master_arch", "visit_gazou_label"], ["visit_conduct", "visit_conduct_shinryou", "visit_conduct_drug", "visit_conduct_kizai"], done); }, done); } describe("Testing safely delete conduct", function(){ var conn; beforeEach(initDb); beforeEach(function(done){ setup.connect(function(err, conn_){ if( err ){ done(err); return; } conn = conn_; done(); }) }); afterEach(function(done){ setup.release(conn, done); }); afterEach(initDb); var valid_from = "2016-04-01"; var at = "2016-06-26 21:35:21"; var valid_upto = "2018-03-31"; var valid_upto_no_limit = "0000-00-00"; it("empty", function(done){ var conduct = m.conduct(); conti.exec([ function(done){ conduct.save(conn, done); }, function(done){ db.safelyDeleteConduct(conn, conduct.data.id, done); } ], done); }); it("with label", function(done){ var conduct = m.conduct(); var conductId; conti.exec([ function(done){ conduct.save(conn, done); }, function(done){ conductId = conduct.data.id; var label = m.gazouLabel({ visit_conduct_id: conductId }); label.save(conn, done); }, function(done){ db.safelyDeleteConduct(conn, conductId, function(err){ expect(err).ok; done(); }) } ], done); }); it("with shinryou", function(done){ var conduct = m.conduct(); var conductId; conti.exec([ function(done){ conduct.save(conn, done); }, function(done){ conductId = conduct.data.id; var shinryou = m.conductShinryou({ visit_conduct_id: conductId }); shinryou.save(conn, done); }, function(done){ db.safelyDeleteConduct(conn, conductId, function(err){ expect(err).ok; done(); }) } ], done); }); it("with drug", function(done){ var conduct = m.conduct(); var conductId; conti.exec([ function(done){ conduct.save(conn, done); }, function(done){ conductId = conduct.data.id; var drug = m.conductDrug({ visit_conduct_id: conductId }); drug.save(conn, done); }, function(done){ db.safelyDeleteConduct(conn, conductId, function(err){ expect(err).ok; done(); }) } ], done); }); it("with kizai", function(done){ var conduct = m.conduct(); var conductId; conti.exec([ function(done){ conduct.save(conn, done); }, function(done){ conductId = conduct.data.id; var kizai = m.conductKizai({ visit_conduct_id: conductId }); kizai.save(conn, done); }, function(done){ db.safelyDeleteConduct(conn, conductId, function(err){ expect(err).ok; done(); }) } ], done); }); })
// Pages service used to communicate Pages REST endpoints (function () { 'use strict'; angular .module('pages') .factory('PagesService', PagesService); PagesService.$inject = ['$resource']; function PagesService($resource) { return $resource('/api/pages/:pageId', { pageId: '@_id' }, { update: { method: 'PUT' }, query: { method: 'GET', isArray: true }, getBySlug: { method: 'GET', url: '/api/pages/slugged/:slug' }, getForMenu: { method: 'GET', url: '/api/pages/onmenu', isArray: true }, getEvents: { method: 'GET', url: '/api/pages/events', isArray: true } }); } }());
var async = require('async'); var _ = require('lodash'); function removePollResult (args, done) { var seneca = this; var plugin = args.role; var ENTITY_NS = ('cd/polls_results'); var resultId = args.resultId; seneca.make$(ENTITY_NS).remove$({id: resultId}, done); } module.exports = removePollResult;
var Collector = require("./lib/collector"); var Subscriber = require("./lib/subscriber"); var logger = require("./helper/logger"); module.exports = { Collector: Collector, Subscriber: Subscriber, logger: logger };
/* A simple drawing application for touch devices. Loïc Fontaine - http://github.com/lfont - MIT Licensed */ define({ "root": { "xx-xx": "Default", "en-us": "English", "fr-fr": "Français" }, "fr-fr": true });
'use strict'; /* Directives */ app.directive('appVersion', ['version', function (version) { return function (scope, elm, attrs) { elm.text(version); }; }]);
var search = module.exports = function(arr, value, min, max) { if (arr.length === 0) return -1; // Defaults if (!min) min = 0; if (!max) max = arr.length - 1; var index = min + Math.floor((max - min) / 2); var val = arr[index]; if (val == value) return index; if (max - min == 0) return -1; if (val < value) return search(arr, value, min, index - 1); if (val > value) return search(arr, value, index + 1, max); };
$(function() { return alert('Page loaded'); });
let Verify = require('./Verify'); class Api { /** * Create a new API instance. * * @param {Mix} Mix */ constructor(Mix) { this.Mix = Mix; } /** * Register the Webpack entry/output paths. * * @param {string|Array} entry * @param {string} output */ js(entry, output) { global.entry.addScript(entry, output); return this; }; /** * Declare support for the React framework. */ react(entry, output) { this.Mix.react = true; Verify.dependency( 'babel-preset-react', 'npm install babel-preset-react --save-dev' ); this.js(entry, output); return this; }; /** * Register vendor libs that should be extracted. * This helps drastically with long-term caching. * * @param {Array} libs * @param {string} output */ extract(libs, output) { global.entry.addVendor(libs, output); return this; }; /** * Register libraries to automatically "autoload" when * the appropriate variable is references in js * * @param {object} libs */ autoload(libs) { let aliases = {}; Object.keys(libs).forEach(library => { [].concat(libs[library]).forEach(alias => { aliases[alias] = library; }); }); this.Mix.autoload = aliases; return this; }; /** * Enable Browsersync support for the project. * * @param {object} config */ browserSync(config = {}) { if (typeof config === 'string') { config = { proxy: config }; } this.Mix.browserSync = config; return this; }; /** * Register Sass compilation. * * @param {string} src * @param {string} output * @param {object} pluginOptions */ sass(src, output, pluginOptions = {}) { return this.preprocess( 'Sass', src, output, pluginOptions ); }; /** * Register standalone-Sass compilation that will not run through Webpack. * * @param {string} src * @param {string} output * @param {object} pluginOptions */ standaloneSass(src, output, pluginOptions = {}) { let Preprocessor = require('./Preprocessors/StandaloneSass'); this.Mix.standaloneSass = new Preprocessor(src, output, pluginOptions); return this; }; /** * Register Less compilation. * * @param {string} src * @param {string} output * @param {object} pluginOptions */ less(src, output, pluginOptions = {}) { return this.preprocess( 'Less', src, output, pluginOptions ); }; /** * Register Stylus compilation. * * @param {string} src * @param {string} output * @param {object} pluginOptions */ stylus(src, output, pluginOptions = {}) { Verify.dependency( 'stylus-loader', 'npm install stylus-loader stylus --save-dev' ); return this.preprocess( 'Stylus', src, output, pluginOptions ); }; /** * Register a generic CSS preprocessor. * * @param {string} type * @param {string} src * @param {string} output * @param {object} pluginOptions */ preprocess(type, src, output, pluginOptions) { Verify.preprocessor(type, src, output); global.entry.addStylesheet(src, output); let Preprocessor = require('./Preprocessors/' + type); this.Mix.preprocessors = (this.Mix.preprocessors || []).concat( new Preprocessor(src, output, pluginOptions) ); return this; }; /** * Combine a collection of files. * * @param {string|Array} src * @param {string} output */ combine(src, output) { this.Mix.concat.add({ src, output }); return this; }; /** * Alias for this.Mix.combine(). * * @param {string|Array} src * @param {string} output */ scripts(src, output) { return this.combine(src, output); }; /** * Alias for this.Mix.combine(). * * @param {string|Array} src * @param {string} output */ styles(src, output) { return this.combine(src, output); }; /** * Identical to this.Mix.combine(), but includes Babel compilation. * * @param {string|Array} src * @param {string} output */ babel(src, output) { this.Mix.concat.add({ src, output, babel: true }); return this; }; /** * Copy one or more files to a new location. * * @param {string} from * @param {string} to * @param {boolean} flatten */ copy(from, to, flatten = true) { this.Mix.copy = this.Mix.copy || []; [].concat(from).forEach(src => { this.Mix.copy.push({ from: src, to: global.Paths.root(to), flatten: flatten }); }); return this; }; /** * Copy an entire directory to a new location. * * @param {string} from * @param {string} to */ copyDirectory(from, to) { return this.copy(from, to, false); }; /** * Minify the provided file. * * @param {string|Array} src */ minify(src) { let output = src.replace(/\.([a-z]{2,})$/i, '.min.$1'); this.Mix.concat.add({ src, output }); return this; }; /** * Enable sourcemap support. */ sourceMaps() { global.options.sourcemaps = (this.Mix.inProduction ? false : '#inline-source-map'); return this; }; /** * Enable compiled file versioning. * * @param {string|Array} files */ version(files = []) { global.options.versioning = true; this.Mix.version = [].concat(files); return this; }; /** * Disable all OS notifications. */ disableNotifications() { global.options.notifications = false; return this; }; /** * Set the path to your public folder. * * @param {string} path */ setPublicPath(path) { global.options.publicPath = this.Mix.publicPath = new File(path) .parsePath() .pathWithoutExt; return this; }; /** * Set prefix for generated asset paths * * @param {string} path */ setResourceRoot(path) { global.options.resourceRoot = path; return this; }; /** * Merge custom config with the provided webpack.config file. * * @param {object} config */ webpackConfig(config) { this.Mix.webpackConfig = config; return this; } /** * Set Mix-specific options. * * @param {object} options */ options(options) { if (options.purifyCss) { options.purifyCss = require('./PurifyPaths').build(options.purifyCss); Verify.dependency( 'purifycss-webpack', 'npm install purifycss-webpack --save-dev', true // abortOnComplete ); } global.options.merge(options); return this; }; /** * Register a Webpack build event handler. * * @param {Function} callback */ then(callback) { global.events.listen('build', callback); return this; } } module.exports = Api;
var SymbolDraw = require('../../chart/helper/SymbolDraw'); var zrUtil = require('zrender/lib/core/util'); var numberUtil = require('../../util/number'); var List = require('../../data/List'); var markerHelper = require('./markerHelper'); function updateMarkerLayout(mpData, seriesModel, api) { var coordSys = seriesModel.coordinateSystem; mpData.each(function (idx) { var itemModel = mpData.getItemModel(idx); var point; var xPx = numberUtil.parsePercent(itemModel.get('x'), api.getWidth()); var yPx = numberUtil.parsePercent(itemModel.get('y'), api.getHeight()); if (!isNaN(xPx) && !isNaN(yPx)) { point = [xPx, yPx]; } // Chart like bar may have there own marker positioning logic else if (seriesModel.getMarkerPosition) { // Use the getMarkerPoisition point = seriesModel.getMarkerPosition( mpData.getValues(mpData.dimensions, idx) ); } else if (coordSys) { var x = mpData.get(coordSys.dimensions[0], idx); var y = mpData.get(coordSys.dimensions[1], idx); point = coordSys.dataToPoint([x, y]); } // Use x, y if has any if (!isNaN(xPx)) { point[0] = xPx; } if (!isNaN(yPx)) { point[1] = yPx; } mpData.setItemLayout(idx, point); }); } require('./MarkerView').extend({ type: 'markPoint', updateLayout: function (markPointModel, ecModel, api) { ecModel.eachSeries(function (seriesModel) { var mpModel = seriesModel.markPointModel; if (mpModel) { updateMarkerLayout(mpModel.getData(), seriesModel, api); this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel); } }, this); }, renderSeries: function (seriesModel, mpModel, ecModel, api) { var coordSys = seriesModel.coordinateSystem; var seriesId = seriesModel.id; var seriesData = seriesModel.getData(); var symbolDrawMap = this.markerGroupMap; var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw()); var mpData = createList(coordSys, seriesModel, mpModel); // FIXME mpModel.setData(mpData); updateMarkerLayout(mpModel.getData(), seriesModel, api); mpData.each(function (idx) { var itemModel = mpData.getItemModel(idx); var symbolSize = itemModel.getShallow('symbolSize'); if (typeof symbolSize === 'function') { // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据? symbolSize = symbolSize( mpModel.getRawValue(idx), mpModel.getDataParams(idx) ); } mpData.setItemVisual(idx, { symbolSize: symbolSize, color: itemModel.get('itemStyle.normal.color') || seriesData.getVisual('color'), symbol: itemModel.getShallow('symbol') }); }); // TODO Text are wrong symbolDraw.updateData(mpData); this.group.add(symbolDraw.group); // Set host model for tooltip // FIXME mpData.eachItemGraphicEl(function (el) { el.traverse(function (child) { child.dataModel = mpModel; }); }); symbolDraw.__keep = true; symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent'); } }); /** * @inner * @param {module:echarts/coord/*} [coordSys] * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Model} mpModel */ function createList(coordSys, seriesModel, mpModel) { var coordDimsInfos; if (coordSys) { coordDimsInfos = zrUtil.map(coordSys && coordSys.dimensions, function (coordDim) { var info = seriesModel.getData().getDimensionInfo( seriesModel.coordDimToDataDim(coordDim)[0] ) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys info.name = coordDim; return info; }); } else { coordDimsInfos =[{ name: 'value', type: 'float' }]; } var mpData = new List(coordDimsInfos, mpModel); var dataOpt = zrUtil.map(mpModel.get('data'), zrUtil.curry( markerHelper.dataTransform, seriesModel )); if (coordSys) { dataOpt = zrUtil.filter( dataOpt, zrUtil.curry(markerHelper.dataFilter, coordSys) ); } mpData.initData(dataOpt, null, coordSys ? markerHelper.dimValueGetter : function (item) { return item.value; } ); return mpData; }
// Copyright 2018-2021, University of Colorado Boulder /** * Checkbox for the quadratic term, y = ax^2 * * @author Chris Malley (PixelZoom, Inc.) */ import merge from '../../../../phet-core/js/merge.js'; import MathSymbols from '../../../../scenery-phet/js/MathSymbols.js'; import GQColors from '../../common/GQColors.js'; import GQSymbols from '../../common/GQSymbols.js'; import GQCheckbox from '../../common/view/GQCheckbox.js'; import graphingQuadratics from '../../graphingQuadratics.js'; class QuadraticTermCheckbox extends GQCheckbox { /** * @param {BooleanProperty} quadraticTermVisibleProperty * @param {Object} [options] */ constructor( quadraticTermVisibleProperty, options ) { options = merge( { textFill: GQColors.QUADRATIC_TERM, // phet-io phetioDocumentation: 'checkbox that makes the quadratic term (y = ax^2) visible on the graph' }, options ); // y = ax^2 const text = `${GQSymbols.y} ${MathSymbols.EQUAL_TO} ${GQSymbols.a}${GQSymbols.xSquared}`; super( text, quadraticTermVisibleProperty, options ); } } graphingQuadratics.register( 'QuadraticTermCheckbox', QuadraticTermCheckbox ); export default QuadraticTermCheckbox;
var files = [ [ "example", "dir_cfafba98a580ce4b62f8a6fa96d7cbb0.html", "dir_cfafba98a580ce4b62f8a6fa96d7cbb0" ], [ "inc", "dir_bfccd401955b95cf8c75461437045ac0.html", "dir_bfccd401955b95cf8c75461437045ac0" ], [ "src", "dir_68267d1309a1af8e8297ef4c3efbcdba.html", "dir_68267d1309a1af8e8297ef4c3efbcdba" ] ];
(function(angular) { 'use strict'; angular.module('httpu.urlbuilder', []) .factory('huURLBuilderInterceptor', huURLBuilderInterceptor) .factory('huURLBuilderFactory', huURLBuilderFactory); huURLBuilderInterceptor.$inject = ['$injector', '$q']; function huURLBuilderInterceptor($injector, $q) { //the property to add to the config var KEY = '__huURLBuilder'; return { request: requestInterceptor, response: responseInterceptor, responseError: responseErrorInterceptor }; ////////////////////////// function requestInterceptor(config) { if (!config.buildUrl) { return config; } //Get the serialization service or func var buildUrl = angular.isString(config.buildUrl) ? $injector.get(config.buildUrl) : config.buildUrl; //Save the original config for restoring later config[KEY] = { url: config.url, params: config.params }; config.url = buildUrl(config.url, config.params); config.params = null; return config; } function responseInterceptor(response) { return restoreOriginal(response); } function responseErrorInterceptor(rejection) { return $q.reject(restoreOriginal(rejection)); } /** * Restores params an url from the original config * * @private * @param {Object} res The response/rejection object * @returns {Object} The response/rejection object */ function restoreOriginal(res) { if (!res || !res.config || !res.config[KEY]) { return res; } res.config.url = res.config[KEY].url; res.config.params = res.config[KEY].params; delete res.config[KEY]; return res; } } huURLBuilderFactory.$inject = ['$window']; function huURLBuilderFactory($window) { return paramsSerializer; ////////////////////////////// /** * From Angular * Please guys! export this! */ function encodeUriQuery(val) { return $window.encodeURIComponent(val) .replace(/%40/gi, '@') .replace(/%3A/gi, ':') .replace(/%24/g, '$') .replace(/%2C/gi, ',') .replace(/%20/g, '+'); } /** * Default serializer * Stringifies the parameters values, with any order * * @param {Object} params The parameters object * @param {Function} cb The callback(key, value) function to call when done * serializing a parameter */ function toStringEncode(params, cb) { angular.forEach(params, function iterator(value, key) { cb(key, '' + value); }); } function paramsSerializer(serializer) { serializer = serializer || toStringEncode; return function buildUrl(url, params) { if (!params) { return url; } var parts = []; serializer(params, function addKeyValue(key, value) { parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(value)); }); if (parts.length > 0) { url += ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&'); } return url; }; } } })(window.angular);
#! /usr/bin/env node 'use strict'; var cc = require('./lib/utils'); var join = require('path').join; var deepExtend = require('deep-extend'); var etc = '/etc'; var win = process.platform === "win32"; var home = win ? process.env.USERPROFILE : process.env.HOME; module.exports = function (name, defaults, argv, parse) { if ('string' !== typeof name) throw new Error('rc(name): name *must* be string'); if (!argv) argv = require('minimist')(process.argv.slice(2)); defaults = ('string' === typeof defaults ? cc.json(defaults) : defaults) || {}; parse = parse || cc.parse; var env = cc.env(name + '_'); var configs = [defaults]; var configFiles = []; function addConfigFile(file) { if (configFiles.indexOf(file) >= 0) return; var fileConfig = cc.file(file); if (fileConfig) { configs.push(parse(fileConfig)); configFiles.push(file); } } // which files do we look at? if (!win) [join(etc, name, 'config'), join(etc, name + 'rc')].forEach(addConfigFile); if (home) [join(home, '.config', name, 'config'), join(home, '.config', name), join(home, '.' + name, 'config'), join(home, '.' + name + 'rc')].forEach(addConfigFile); addConfigFile(cc.find('.' + name + 'rc')); if (env.config) addConfigFile(env.config); if (argv.config) addConfigFile(argv.config); return deepExtend.apply(null, configs.concat([env, argv, configFiles.length ? { configs: configFiles, config: configFiles[configFiles.length - 1] } : null])); }; if (!module.parent) { console.log(JSON.stringify(module.exports(process.argv[2]), false, 2)); } //# sourceMappingURL=rc-compiled.js.map
Meteor.startup(() => { var roles = _.pluck(Roles.getAllRoles().fetch(), 'name'); if (roles.indexOf('livechat-agent') === -1) { Roles.createRole('livechat-agent'); } if (roles.indexOf('livechat-manager') === -1) { Roles.createRole('livechat-manager'); } if (RocketChat.models && RocketChat.models.Permissions) { RocketChat.models.Permissions.createOrUpdate('view-l-room', ['livechat-agent', 'livechat-manager']); RocketChat.models.Permissions.createOrUpdate('view-livechat-manager', ['livechat-manager']); } });
/** * This file describes type definitions, purely used for autocompletion and intellisense * * @typedef {{ * startingYear: string, * numberOfYears: string, * currency: string, * currencyMagnitude: string, * numberOfDecimals: string, * startingCapital: string, * * VATRate: string, * corporateTaxRate: string, * incomeTax: string, * SSCEmployer: string, * SSCEmployee: string, * * interestPayableOnOverdraft: string, * interestPayableOnLoans: string, * interestReceivableOnCredit: string, * * daysInStockOfInventory: string, * daysAccountsReceivablesOutstanding: string, * daysPrepaymentOfExpenditure: string, * daysAccrualOfIncome: string, * daysAccountsPayableOutstanding: string, * daysAccrualOfCost: string, * daysDeferredIncome: string, * monthsVATPaidAfter: string, * monthsCorporateTaxPaidAfter: string, * monthsIncomeTaxPaidAfter: string, * monthsSSCPaidAfter: string, * * holidayProvision: string, * monthOfHolidayPayment: string * }} Parameters * * @typedef {{type: 'constant', value: string, change: string}} PriceTypeConstant * @typedef {{type: 'manual', value: string, change: string}} PriceTypeManual * @typedef {{type: 'revenue', percentage: string}} PriceTypeRevenue * @typedef {{type: 'investment', value: string, depreciationPeriod: string}} PriceTypeInvestment * @typedef {{type: 'salary', value: string, change: string}} PriceTypeSalary * * @typedef { * PriceTypeConstant | * PriceTypeManual | * PriceTypeRevenue | * PriceTypeInvestment | * PriceTypeSalary * } Price * * @typedef {{ * id: string, * section: string, * group: string, * label: string, * price: ?Price, * quantities: ?Object<string, string>, * deleted: ?boolean, * custom: boolean, * bmcGroup: ?string, * bmcId: ?string, * bmcChecked: ?boolean * bmcCheckedManually: ?boolean * }} Category * * @typedef {{value: boolean, isDefault: boolean}} Option * @typedef {{id: string, value: string}} TextItem * * @typedef {{ * expenses: {values: Object.<string, Option>, other: Array.<TextItem>}, * activities: {values: Object.<string, Option>, other: Array.<TextItem>}, * contacts: {values: Object.<string, Option>, other: Array.<TextItem>}, * channels: {values: Object.<string, Option>, other: Array.<TextItem>}, * partnerships: {values: Object.<string, Option>, other: Array.<TextItem>}, * investments: {values: Object.<string, Option>, other: Array.<TextItem>}, * customerSegments: {values: Object.<string, Option>, other: Array.<TextItem>}, * costStructure: Object.<string, {categoryId: string, groupId: string, index: string}> * }} BMC * * @typedef {{ * description: { * type: string, * products: Array.<TextItem>, * customers: Array.<TextItem>, * uniqueSellingPoint: string * }, * parameters: Parameters, * categories: Array.<Category>, * financing: { * investmentsInParticipations: Object<string, string> * equityContributions: Object<string, string> * bankLoansCapitalCalls: Object<string, string> * bankLoansRedemptionInstallments: Object<string, string> * otherSourcesOfFinance: Object<string, string> * }, * initialBalance: { * tangiblesAndIntangibles: string | number, * financialFixedAssets: string | number, * deferredTaxAssets: string | number, * * goodsInStock: string | number, * tradeReceivables: string | number, * prepayments: string | number, * accruedIncome: string | number, * receivableVAT: string | number, * * agio: string | number, * reserves: string | number, * profitAndLoss: string | number, * * bankLoans: string | number, * otherLongTermInterestBearingDebt: string | number, * * tradeCreditors: string | number, * accruals: string | number, * deferredIncome: string | number, * payableVAT: string | number, * payableCorporateTax: string | number, * payableIncomeTax: string | number, * payableSSC: string | number, * provisionHolidayPayment: string | number, * }, * bmc: BMC * }} Scenario * **/
const sanitizeHtml = require('sanitize-html'); const Chat = require('./../rtm-client'); const ChatModels = require('./../models/chats'); // Controller to send messages from client to slack api const chatController = { sendMessageToSlack(req, res) { // Will need to get user slack token at some point console.log('request arrived to sendMessageToSlack. req.body: ', req.body); const message = req.body.message; // const message = 'Should accept req.body.message in sendMessageToSlack'; Chat.sendMessage(message, 'C2KE7FVV3', (err, msg) => { // What does this call back get as the msg object? err? msg.text = 'Updated!'; res.status(200).send(msg); }); }, sendMessagesToClient(req, res) { // Maybe have Slack --> client handled in rtm-client.js? // Should this emit something and pass value to socket.io? // Or use HTML5 push api? }, sendMessageToDatabase(socket, data) { // sanitize the message before saving! console.log('chat.controller sendMessageToDatabase data: ', data); // const chatMessage = new ChatModels.ChatMessage(data); // console.log('sanitized html version: ', sanitized); const query = { room_id: data.room_id }; const update = { $push: { messages: { user_id: data.user_id, text: sanitizeHtml(data.text), timestamp: data.timestamp } } }; const options = { new: true, upsert: true }; const callback = (err, result) => { const mostRecent = result.messages[result.messages.length - 1]; console.log('Most recent message to be broadcast: ', mostRecent); socket.broadcast.emit('incoming chat message', mostRecent); }; ChatModels.ChatRoom.findOneAndUpdate(query, update, options, callback); }, loadChatRoomFromDatabase(socket, room) { // console.log('loadMessagesFromDatabase called'); const query = { room_id: room }; ChatModels.ChatRoom.find(query, (err, data) => { // console.log('chatRoom from db results: ', data); if (data[0] === undefined) { return; } socket.emit('chat room archive', data[0].messages); }); } }; module.exports = chatController;
// ==UserScript== // @grant unsafeWindow // @grant GM_xmlhttpRequest // @grant GM_openInTab // @grant GM_registerMenuCommand // @grant GM_getValue // @grant GM_setValue // @grant GM_setClipboard // @grant GM_info // @run-at document-start // @name:en Bypass Wait, Code & Login on Websites // @name 跳过网站等待、验证码及登录 // @name:zh-CN 跳过网站等待、验证码及登录 // @name:zh-TW 繞過站點等待、識別碼及登錄 // @description 移除各类网站验证码、登录、倒计时及更多! // @description:zh-CN 移除各类网站验证码、登录、倒计时及更多! // @description:zh-TW 移除各類站點識別碼、登錄、倒計時及更多! // @description:en Remove verify code, login requirement, counting down... and more! // @copyright 2014+, Yulei, Mod by Jixun. //// Based on [Crack Url Wait Code Login] By Yulei // 骑牛的会请求不存在的 jquery.map 文件,改用官网的 // @require https://code.jquery.com/jquery-2.1.4.min.js /// CryptoJS 相关库 // @require https://cdn.bootcss.com/crypto-js/3.1.2/components/core-min.js // @require https://cdn.bootcss.com/crypto-js/3.1.2/components/enc-base64-min.js // @require https://cdn.bootcss.com/crypto-js/3.1.2/components/md5-min.js // @require https://greasyfork.org/scripts/6696/code/CryptoJS-ByteArray.js /// 非同步枚举 // @require https://greasyfork.org/scripts/3588-interval-looper/code/Interval-Looper.js /// 兼容 GM 1.x, 2.x // @require https://greasyfork.org/scripts/2599/code/gm2-port-v104.js /// Aria2 RPC // @require https://greasyfork.org/scripts/5672/code/Aria2-RPC-build-9.js // @author Jixun.Moe<Yellow Yoshi> // @namespace http://jixun.org/ // @version 3.0.436 // 全局匹配 // @include * // 扔掉百度的广告框架页面 // @exclude http://pos.baidu.com/* // 扔掉谷歌 // @exclude http://gmail.com/* // @exclude http://.google.tld/* // @exclude http://*.gmail.com/* // @exclude http://*.google.tld/* // ==/UserScript== (function () { // 初始化 var createElement = document.createElement.bind (document); var H = { scriptName: 'CUWCL4C', scriptHome: 'https://greasyfork.org/zh-CN/scripts/2600', reportUrl: 'https://greasyfork.org/forum/post/discussion?Discussion/ScriptID=2600', isFrame: (function () { try { return unsafeWindow.top != unsafeWindow.self; } catch (e) { return true; } })(), version: GM_info.script.version, currentUrl: location.href.split ('#')[0], lowerHost: location.hostname.toLowerCase(), directHost: location.hostname.match(/\w+\.?\w+?$/)[0].toLowerCase(), defaultDlIcon: 'jx_dl', defaultDlClass: '.jx_dl', nop: function () {}, merge: function (parent) { if (arguments.length < 2) return parent || {}; var args = arguments; for (var i = 1; i < arguments.length; i++) { if (arguments[i]) { Object.keys (arguments[i]).forEach (function (key) { parent[key] = args[i][key]; }); } } return parent; }, extract: function (foo) { return foo.toString().match(/\/\*([\s\S]+)\*\//)[1].replace(/\s*--.+/g, ''); }, sFormat: function (sourceStr) { var args = arguments, argLen = args.length; if (argLen <= 1) return sourceStr; // 无效或无参数 for (var i = argLen; i--; ) sourceStr = sourceStr.replace (new RegExp('%' + i + '([^\\d]|$)','g'), args[i]); return sourceStr; }, sprintf: function (sourceStr) { var args = arguments, argLen = args.length; if (argLen <= 1) return sourceStr; // 无效或无参数 for (var i = 1; i < argLen; i++) sourceStr = sourceStr.replace (/%[sd]/i, args[i]); return sourceStr; }, beginWith: function (str, what) { return str.indexOf (what) == 0; }, contains: function (str, what) { return str.indexOf (what) != -1; }, addDownload: function (url, file) { if (H.config.dUriType == 2) { H.addToAria(url, file); } else { GM_openInTab (H.uri(url, file), true); } }, uri: function (url, filename, ref) { switch (H.config.dUriType) { case 1: return 'cuwcl4c://|1|' + [ url, filename.toString().replace(/['"\/\\:|]/g, '_'), (ref || location.href).toString().replace(/#.*/, '') ].join('|'); case 2: // 如果脚本没有手动绑定 Aria 连接 // 此处进行全局连接接管 if (!H.hasAriaCapture) H.captureAria (); return 'aria2://|' + [ url, filename.toString().replace(/['"\/\\:|]/g, '_'), (ref || location.href).toString().replace(/#.*/, '') ].join('|'); default: return url; } }, setupAria: function (bForceNew) { if (bForceNew || !H.aria) { H.aria2 = new Aria2({ auth: { type: H.config.dAria_auth, user: H.config.sAria_user, pass: H.config.sAria_pass }, host: H.config.sAria_host, port: H.config.dAria_port }); } return H.aria2; }, addToAria: function (url, filename, referer, cookie, headers) { var ariaParam = { out: filename, referer: referer || location.href, dir: H.config.sAria_dir, 'user-agent': navigator.userAgent, header: headers || [] }; if (cookie === true) cookie = document.cookie; if (cookie) ariaParam.header.push ('Cookie: ' + cookie); H.aria2.addUri ([url], ariaParam, H.nop, function (r) { var sErrorMsg; if (r.error) { sErrorMsg = H.sprintf ('错误代码 %s: %s', r.error.code, r.error.message); } else { sErrorMsg = '与 Aria2 后台通信失败, 服务未开启?'; } alert (H.sprintf('[%s] 提交任务发生错误!\n\n%s', H.scriptName, sErrorMsg)); }); }, captureAria: function (el) { if (H.config.dUriType !== 2) return ; H.hasAriaCapture = true; H.setupAria (); $(el || document).click(function (e) { var linkEl = e.target; if (linkEl && linkEl.tagName == 'A' && H.beginWith(linkEl.href, 'aria2://|')) { e.stopPropagation (); e.preventDefault (); var link = linkEl.href.split('|'); H.addToAria(link[1], decodeURIComponent(link[2]), link[3], linkEl.classList.contains('aria-cookie')); } }); }, buildAriaParam: function (opts) { if (opts.cookie) { opts.header = opts.header || []; opts.header.push ('Cookie: ' + (opts.cookie || document.cookie)); delete opts.cookie; } return H.merge ({ referer: location.href, dir: H.config.sAria_dir, 'user-agent': navigator.userAgent }, opts); }, batchDownload: function (fCallback, ref, arrDownloads) { H.setupAria (); return H.aria2.batchAddUri.apply ( // this H.aria2, // fCallback, file1, file2, ... [ fCallback ].concat ( arrDownloads.map (function (arg) { arg.options = H.buildAriaParam (H.merge({ referer: ref }, arg.options)); return arg; }) ) ); } }; H.merge (H, { _log: console.log.bind (console), _inf: console.info.bind (console), _war: console.warn.bind (console), _err: console.error.bind (console), log: function (_prefix, msg) { var args = [].slice.call(arguments, 1); if (typeof msg == 'string') { // TODO: Simplify this? H._log.apply (0, [].concat.apply ([_prefix + msg], args.slice(1))); } else { H._log.apply (0, [].concat.apply([_prefix], args)); } }.bind (H, H.sprintf ('[%s][日志] ', H.scriptName)), info: function (_prefix, msg) { var args = [].slice.call(arguments, 1); if (typeof msg == 'string') { // TODO: Simplify this? H._inf.apply (0, [].concat.apply ([_prefix + msg], args.slice(1))); } else { H._inf.apply (0, [].concat.apply([_prefix], args)); } }.bind (H, H.sprintf ('[%s][信息] ', H.scriptName)), error: function (_prefix, msg) { var args = [].slice.call(arguments, 1).concat ('\n\n错误追踪' + new Error().stack); if (typeof msg == 'string') { H._err.apply (0, [].concat.apply ([_prefix + msg], args.slice(1))); } else { H._err.apply (0, [].concat.apply([_prefix], args)); } }.bind (H, H.sprintf ('[%s][错误] ', H.scriptName)), warn: function (_prefix, msg) { var args = [].slice.call(arguments, 1); if (typeof msg == 'string') { // TODO: Simplify this? H._inf.apply (0, [].concat.apply ([_prefix + msg], args.slice(1))); } else { H._inf.apply (0, [].concat.apply([_prefix], args)); } }.bind (H, H.sprintf ('[%s][警告] ', H.scriptName)) }); H.config = H.merge ({ bDiaplayLog: true, dUriType: 0, dAria_auth: 0, sAria_user: '', sAria_pass: '', sAria_host: '127.0.0.1', dAria_port: 6800, sAria_dir: 'D:\\Download\\', bUseCustomRules: false, sCustomRule: '' }, (function (conf) { if (!conf) return {}; try { return JSON.parse (conf); } catch (e) { H.info ('配置文件 [%s] 无效, 现在使用空白配置.', conf); return {}; } })(GM_getValue (H.scriptName))); // 2014.11.30: 不显示日志 if (!H.config.bDiaplayLog || H.isFrame) { // 屏蔽日志函数 ['log', 'info'].map(function (fooName) { H['_' + fooName.slice(0, 3)] = H[fooName] = H.nop; }); } H.merge (H, { hookRequire: function (namespace, foo, callback) { // The first one is `this`, so not going to be used. var args = [].slice.call (arguments, 2); args[0] = null; var hookReq = createElement ('script'); hookReq.textContent = ';(' + function (namespace, foo, custom) { var $ns, $foo; Object.defineProperty (window, namespace, { get: function () { return $ns; }, set: function (n) { $ns = n; $foo = n[foo]; Object.defineProperty ($ns, foo, { get: function () { return function () { var ret = custom.apply (0, [].concat.apply([$ns, $foo.bind ($ns)], arguments)); if (ret) return ret; return $foo.apply ($ns, arguments); }; }, set: function (fnNew) { $foo = fnNew; } }); } }); } + ')("' + namespace + '", "' + foo + '", Function.bind.apply (' + callback + ', ' + JSON.stringify (args) + '));'; document.head.appendChild (hookReq); return hookReq; }, hookDefine: function (fooName, callback) { // The first one is `this`, so not going to be used. var args = [].slice.call (arguments, 1); args[0] = null; var hookDef = createElement ('script'); hookDef.textContent = ';(' + function (fooName, custom) { var $define; Object.defineProperty (window, fooName, { get: function () { return function () { var ret = custom.apply (0, [].concat.apply([$define], arguments)); if (ret) return ret; return $define.apply (window, arguments); }; }, set: function (n) { $define = n; } }); } + ')("' + namespace + '", "' + foo + '", Function.bind.apply (' + callback + ', ' + JSON.stringify (args) + '));'; document.head.appendChild (hookDef); return hookDef; }, base64Decode: function (str) { return CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(str)); }, getFlashVars: function (ele) { // jQuery element fix. if (!ele) return {}; if (ele.jquery) ele = ele[0]; // Check if is a flash object if (ele.type.indexOf('flash') == -1) return {}; for(var flashObject, flashVars = {}, i = ele.childNodes.length; i--;) if (ele.childNodes[i].name == 'flashvars') { flashObject = ele.childNodes[i]; break; } if (flashObject) { flashObject.value.replace(/&amp;/g, '&').replace(/([\s\S]+?)=([\s\S]+?)(&|$)/g, function (n, key, value) { // 利用正则的批量替换功能抓取数据 ^^ flashVars [key] = decodeURIComponent(value); }); } return flashVars; }, getFirstKey: function (obj) { return Object.keys(obj)[0]; }, getFirstValue: function (obj) { try { return obj[H.getFirstKey(obj)]; } catch (e) { return null; } }, getLinkExt: function (url) { return url.match(/.+\/(?:[^.]+(\..+?))(?:\?|$)/)[1]; }, getLinkExtFromQuery: function (url) { if (H.contains(url, '?')) { var parts = link3.slice(link3.indexOf('?') + 1).replace(/[^=]+?=(.+?(&|$))/g, '$1').split('&'); for (var i = parts.length, exts; i--; ) { if (exts = parts[i].match(/\.(?:[a-z0-9]{2,9})/)) { return exts[0]; } } } return H.getLinkExt (url); }, parseQueryString: function (rawUrl) { var urlParams = (H.contains (rawUrl, '?') ? rawUrl.slice (rawUrl.indexOf('?') + 1) : rawUrl).split('&'); var ret = {}; for (var i = 0, queryStr, posEqual; i < urlParams.length; i++) { queryStr = urlParams[i].toString(); posEqual = queryStr.indexOf('='); if (posEqual == -1) continue; ret[decodeURIComponent(queryStr.slice (0, posEqual))] = decodeURIComponent(queryStr.slice (posEqual + 1)); } return ret; }, wordpressAudio: function () { H.log('WordPress Audio 插件通用代码 启动'); var fixEmbed = function (obj) { if (obj.tagName != 'OBJECT' || obj.hasAttribute(H.scriptName)) return; var songObj = H.getFlashVars(obj); var songAddr = H.base64Decode(songObj.soundFile); $('<a>').html('下载「' + songObj.titles + '」<br>') .attr ({ href: H.uri (songAddr, songObj.titles + songAddr.slice(-4)), target: '_blank' }).insertBefore (obj); obj.setAttribute (H.scriptName, '^^'); }; new MutationObserver (function (eve) { for (var i=0; i<eve.length; i++) if (eve[i].target.className == 'audioplayer_container' && eve[i].addedNodes.length) fixEmbed(eve[i].addedNodes[0]); }).observe ($('.post > .entry')[0], { childList: true, subtree: true }); // Firefox fix.. = = $('object[id^="audioplayer_"]').each(function () { fixEmbed(this); }); H.log('WordPress Audio 插件通用代码 结束'); }, waitUntil: function (checkCond, fCallback, nTimeOut, nTimeInterval) { if (typeof fCallback != 'function') // Required. return ; if ('string' == typeof checkCond && checkCond.indexOf ('.') !== -1) { checkCond = checkCond.split ('.'); } if (checkCond instanceof Array) { checkCond = function (vars) { for (var i = 0, r = unsafeWindow; i < vars.length; i++) { r = r[vars[i]]; if (!r) return ; } return true; }.bind (null, checkCond.slice()); }; var timer = setInterval(function () { if ('function' == typeof checkCond) { try { if (!checkCond()) return; } catch (e) { // Not ready yet. return ; } } else if ('string' == typeof checkCond) { if (typeof (unsafeWindow[checkCond]) == 'undefined') return ; } clearInterval(timer); try { fCallback.call(this); } catch (e) { H.error ('[H.waitUntil] Callback for %s had an error: %s', H.version, e.message); } }, nTimeInterval || 150); // 如果 nTimeOut 的传入值为 true, 则无限制等待. if (nTimeOut !== true) { setTimeout (function () { // Timeout clearInterval(timer); }, nTimeOut || 10000); } }, makeFineCss: function (name, param) { var ret = {}; ret[name] = param; ['moz', 'webkit'].forEach (function (e) { ret['-' + e + '-' + name] = param; }); return ret; }, makeDelayCss: function (transitionText) { return H.makeFineCss('transition', transitionText || 'all .2s'); }, makeRotateCss: function (deg) { return H.makeFineCss('transform', 'rotate(' + (deg || 180) + 'deg)'); }, createNumPad: function (maxLen, targetInput, finishCallback, codeResetCallback) { if (!codeResetCallback) codeResetCallback = eFunc; var table = createElement('table'), rcde = $(targetInput)[0]; $(table).css({ 'background-color': '#ffcc99', 'position': 'relative', 'bottom': '164px', 'left': '170px' }); for (var i = 0; i < 4; i++) { var tr = createElement('tr'); for (var j = 0; j < 3; j++) { var td = createElement('td'); td.innerHTML = $(td).attr('k', '123456789C0←'[i * 3 + j]).attr('k'); tr.appendChild(td); } table.appendChild(tr); } $(table).find('td').click(function () { var val = rcde.value, len = val.length, key = $(this).attr('k') || ''; $(rcde).focus(); switch (key) { case '←': rcde.value = val.slice(0, -1); break; case 'C': rcde.value = ''; codeResetCallback (); break; default: rcde.value += key; len ++; if (len >= maxLen) { if (finishCallback(rcde.value)) { $(table).hide(); } else { codeResetCallback(); rcde.value = ''; } } break; } }).css({ font: 'bold 25px Tahoma', color: 'red', cursor: 'pointer', verticalAlign: ' middle', textAlign: ' center', border: '1px solid #DDDDDD', padding: '6px', width: '40px', height: '40px' }); return table; }, reDirWithRef: function (targetUrl) { if (!targetUrl) return ; H.info ('Redirect to %s...', targetUrl); var link = $('<a>') .attr('href', targetUrl) .text('正在跳转 [' + targetUrl + '], 请稍后.. ') .prependTo(document.body) .css ({fontSize: 12, color: 'inherit'}); link[0].click(); return true; }, // 网盘地址自动导向 [基于 phpDisk 的网盘] phpDiskAutoRedir: function (fCallback){ if (!fCallback) { fCallback = document.body ? H.reDirWithRef : function (p) { H.waitUntil('document.body', H.reDirWithRef.bind(null, p)); }; } var rCheckPath = /\/(file)?(file|view)([\/.\-_].*)/; // Because location.xx = xx does not pass the refer, so we're going to make a dummy form. if (rCheckPath.test (location.pathname)) { fCallback (location.pathname.replace (rCheckPath, '/$1down$3')); } else if (H.beginWith(location.pathname, '/viewfile')) { fCallback (location.pathname.replace('/viewfile', '/download')); } else { return false; } return true; }, // 插入样式表 injectStyle: function () { var styleBlock = (this && this.tagName == 'STYLE') ? this : createElement('style'); styleBlock.textContent += [].join.call(arguments, '\n'); document.head.appendChild(styleBlock); return styleBlock; }, // 强制隐藏/显示某些元素 forceHide: function () { return H.injectStyle.call (this, [].slice.call(arguments).join (', ') + '{ display: none !important }' ); }, forceShow: function () { return H.injectStyle.call (this, [].slice.call(arguments).join (', ') + '{ display: block !important }' ); }, // 强制隐藏框架 forceHideFrames: function (){ return forceHide('iframe, frameset, frame'); }, // 通用 jPlayer 注入 jPlayerPatcher: function (callback, namespace) { // 默认为 jPlayer if (!namespace) namespace = 'jPlayer'; H.info ('等候 jPlayer 就绪 ..'); H.waitUntil('$.' + namespace + '.prototype.setMedia', function () { H.info ('开始绑定函数 ..'); unsafeOverwriteFunctionSafeProxy ({ setMedia: function (newMedia) { H.info ('歌曲数据: ', newMedia); callback (newMedia); throw new ErrorUnsafeSuccess(); } }, unsafeWindow.$[namespace].prototype, '.$.' + namespace + '.prototype'); H.info ('绑定完毕, enjoy~'); }); }, fixStyleOrder: function (elStyle) { $('head').append (elStyle); } }); // 简单屏蔽广告 unsafeWindow.antiadsv2 = 0; unsafeDefineFunction ('CNZZ_AD_BATCH', function () {}); // 空白函数, 适合腾空页面函数。 var eFunc = function () {}, tFunc = function () { return true; }, fFunc = function () { return false; }; var $_GET = H.parseQueryString (H.currentUrl); H.log ('脚本开始执行。'); H.log ('域名: %s; 完整地址: %s; 请求参数: %s', H.directHost, H.currentUrl, JSON.stringify ($_GET)); H.log ('脚本版本 [ %s ] , 如果发现脚本问题请提交到 [ %s ] 谢谢。', H.version, H.reportUrl); var sites = [ /* Compiled from AA.config.js */ { id: 'internal.config', name: '脚本配置页面', host: ['localhost', 'jixunmoe.github.io'], path: ['/conf/', '/cuwcl4c/config/'], onStart: function () { unsafeWindow.rScriptVersion = H.version; unsafeWindow.rScriptConfig = JSON.stringify (H.config); H.info (H.config); var _c = confirm; document.addEventListener ('SaveConfig', function (e) { try { var config = JSON.stringify (JSON.parse (e.detail)); if (_c (H.sprintf ('确定储存设定至 %s?', H.scriptName))) GM_setValue (H.scriptName, config); } catch (e) { alert ('解析设定值出错!'); } }); }, onBody: function () { H.captureAria(document.body); } } , /* Compiled from dl.119g.js */ { id: 'dl.119g', name: '119g 网盘', host: ['d.119g.com'], noSubHost: true, onStart: function () { if (H.beginWith (location.pathname, '/f/') && !H.contains (location.pathname, '_bak')) { location.pathname = location.pathname.replace(/(_.+)?\./, '_bak.'); } } }, /* Compiled from dl.7958.js */ { id: 'dl.7958', name: '千军万马网盘系列', host: ['7958.com', 'qjwm.com'], hide: [ '#downtc', '[id^="cpro_"]', '.download_alert', '#inputyzm', '#house', '#uptown', 'a[href$="money.html"]', 'a[href$="reg.html"]' ], show: ['#downtc2', '.new_down'], onBody: function () { if (H.contains (location.pathname, 'down_')) { location.pathname = location.pathname.replace('_', 'load_'); } H.waitUntil('authad', function () { unsafeDefineFunction ('authad', tFunc); }); } }, /* Compiled from dl.9pan.js */ { id: 'dl.9pan', name: '9盘', host: 'www.9pan.net', onStart: function () { if ( /\/\d/.test ( location.pathname ) ) { location.pathname = location.pathname.replace ('/', '/down-'); } } }, /* Compiled from dl.baidu.js */ { id: 'dl.baidu', name: '百度盘免下载管家', host: ['yun.baidu.com', 'pan.baidu.com'], onBody: function () { H.waitUntil ('require', function () { unsafeExec (function () { var service = require ('common:widget/commonService/commonService.js'); service.getWidgets ('common:widget/downloadManager/service/downloadCommonUtil.js', function (util) { util.isPlatformWindows = function () { return false; }; }); }); }); } }, /* Compiled from dl.bx0635.js */ { id: 'dl.bx0635', name: '暴雪盘', hide: '#b2>:not(#down_box), .tit + div, .clear+div, .logo_r', host: 'bx0635.com', onStart: function () { unsafeWindow.open = null; } }, /* Compiled from dl.colafile.js */ { id: 'dl.colafile', name: '可乐盘', host: 'colafile.com', hide: [ '.table_right', '#down_link3', '.tui', '.ad1 > .ad1 > *:not(.downbox)', // 计时下载页的广告 '.hotrec-ele', '.viewshare-copy-outer' ], genDigit: function () { return Math.ceil(Math.random() * 255); }, genValidIp: function () { return [0,0,0,0].map(this.genDigit).join('.'); }, onBody: function () { var file_id = location.pathname.match(/\d+/)[0]; $.ajax({ url: '/ajax.php?action=downaddress&file_id=' + file_id, headers: { 'X-Forwarded-For': this.genValidIp() }, dataType: 'text' }).success (function (r) { var $dl = r.match (/downloadFile\("(.+?)"/)[1].replace('/dl.php', '/td.php'); var linkText = H.sprintf('%s 专用下载', H.scriptName); // 新版 $('<a>').addClass ('new-dbtn') .attr ('href', $dl) .append ($('<em>').addClass ('icon-download')) .append ($('<b>').text (linkText)) .appendTo ($('.slide-header-funcs')); // 旧版 $('<a>').addClass ('button btn-green') .attr ('href', $dl) .append ($('<i>').addClass ('icon')) .append (linkText) .appendTo ($('#down_verify_box > li')) .css ({ width: 300, margin: '2em 0' }); }); } }, /* Compiled from dl.ctdisk.js */ { id: 'dl.ctdisk', name: '城通网盘系列', host: [ '400gb.com', 'ctdisk.com', 'pipipan.com', 'bego.cc', 'ctfile.com', 't00y.com' ], path: '/file/', hide: ['.captcha', '.kk_xshow', 'div.span6:first-child', '#top > .alert'], onBody: function () { // Fix Anti-ABP as it doesn't check the code. H.waitUntil ('guestviewchkform', function () { unsafeExec(function () { window.guestviewchkform = function (form) { return form.randcode && form.randcode.value.length == 4; }; }); }); var keyForm = document.user_form; var $kf = $(keyForm); try { keyForm.hash_key.value = H.base64Decode(keyForm.hash_info.value); } catch (e) { H.info ('缺失或无效的 hash_key 属性值, 跳过…'); } $kf.attr('action', $kf.attr('action').replace(/(V)\d/i, '$12')); $('.captcha_right').css('float', 'left'); /* 城通现在的验证码是混合数字、字母 $('#vfcode:first').parent() .append(H.createNumPad(4, $('#randcode')[0], function () { $kf.submit(); return true; })); */ $('#page_content') .attr('id', '^_^') .val('cproIframeu12581302|httpubmcmmbaidustaticcomcpromediasmallpng'); H.log ('城通就绪.'); } }, /* Compiled from dl.dlkoo.js */ { id: 'dl.dlkoo', name: '大连生活网', example: 'http://www.dlkoo.com/down/6/2011/222686754.html', host: ['dlkoo.com'], path: '/down/downfile.asp', onStart: function () { document.write = null; Object.defineProperty(unsafeWindow, 'navigator', { set: function () {}, get: function () { return null; } }); }, onBody: function () { var firstEl = document.body.children[0]; if (!firstEl) firstEl = document.body; var firstTxt = firstEl.textContent; if (H.beginWith(firstTxt, '防盗链提示') || H.beginWith(firstTxt, '验证码')) { H.reDirWithRef(location.href); return ; } else if (H.beginWith(firstTxt, '防刷新')) { firstEl.style.whiteSpace = 'pre'; firstEl.textContent += '\n\n请稍后, 5秒后自动刷新…'; setTimeout(H.reDirWithRef, 5500, location.href); return ; } var btnDl = document.getElementById('btsubmit'); if (btnDl) { btnDl.id = null; btnDl.value = '开始下载'; btnDl.disabled = false; var fakeBtn = document.createElement('input'); fakeBtn.id = 'btsubmit'; $(fakeBtn).hide().appendTo('body'); } } }, /* Compiled from dl.howfile.js */ { id: 'dl.howfile', name: '好盘', host: 'howfile.com', hide: ['#floatdiv div', '.row1_right'], css : '#floatdiv { top: 150px; z-index: 99999; display: block !important; }' }, /* Compiled from dl.lepan.cc.js */ { id: 'cc.lepan', name: '乐盘自动下载地址', host: ['www.lepan.cc', 'www.sx566.com'], noSubHost: true, show: '#down_box', hide: ['.widget-box', 'a[href="vip.php"]'], onStart: function () { // 破坏广告 Object.defineProperty(unsafeWindow, 'google', { set: function () { }, get: function () { throw new Error(); } }); H.rule.exec('phpdisk.z', 'onStart'); }, onBody: function () { $('#down_box .widget-box').removeClass('widget-box'); } }, /* Compiled from dl.rayfile.js */ { id: 'dl.rayfile', name: '飞速网', host: 'rayfile.com', hide: ['div.left'], onBody: function () { if (unsafeWindow.vkey) { location.pathname += unsafeWindow.vkey; } else { unsafeWindow.filesize = 100; unsafeWindow.showDownload (); unsafeWindow.showDownload = eFunc; $('#downloadlink').addClass('btn_downNow_zh-cn'); $('#vodlink').addClass('btn_downTools_zh-cn'); } } }, /* Compiled from dl.sudupan.js */ { id: 'dl.sudupan', name: '速度盘', host: ['sudupan.com'], show: ['#sdpxzlj', '#sdpxzlj > td'], onStart: function () { if (H.beginWith(location.pathname, '/down_')) { location.pathname = location.pathname.replace ('/down_', '/sdp/xiazai_'); } } }, /* Compiled from dl.vdisk.js */ { id: 'dl.vdisk', name: '威盘', host: ['vdisk.cn'], hide: ['#loadingbox', '#yanzhengbox', '#yzmbox', '#getbox > .btn:first-child'], show: ['#btnbox'] }, /* Compiled from dl.yimuhe.js */ { id: 'dl.yimuhe', name: '一木禾网盘', host: 'yimuhe.com', hide: ['#loading', '.ggao', '.kuan'], show: ['#yzm'], onStart: function () { H.phpDiskAutoRedir(); }, onBody: function () { if (H.beginWith ( location.pathname, '/n_dd.php' )) { H.reDirWithRef($('#downs').attr('href')); return ; } var dlContainer = document.getElementById ('download'); if (!dlContainer) return ; // 当下载框的 style 属性被更改后, 模拟下载按钮单击. var mo = new MutationObserver (function () { $('a', dlContainer)[1].click(); }); mo.observe (dlContainer, { attributes: true }); $('#yzm>form') .append(H.createNumPad(4, '#code', function () { document.yzcode.Submit.click(); return true; }, function () { $('#vcode_img')[0].click(); })); } }, /* Compiled from fm.douban.js */ { id: 'fm.douban', name: '豆瓣电台', host: 'douban.fm', noSubHost: true, css: /* Resource: fm.douban.dl.css */ H.extract(function () { /* a#jx_douban_dl { background: #9DD6C5; padding: 3px 5px; color: #fff } a#jx_douban_dl:hover { margin-left: 5px; padding-left: 10px; background: #BAE2D6; } div#jx_douban_dl_wrap { float: right; margin-top: -230px; margin-right: -32px; font-weight: bold; font-family: 'Microsoft JHengHei UI', '微软雅黑', serif-sans; } */}), // 参考代码 豆藤, USO: 49911 onBody: function () { var linkDownload = $('<a>').css(H.makeDelayCss()) .attr ('target', '_blank') .attr ('id', 'jx_douban_dl') .text ('下载'); $('<div>') .attr ('id', 'jx_douban_dl_wrap') .append(linkDownload) .insertAfter('.player-wrap'); $('a#jx_douban_dl').hover( function() { var filename = $(this).attr('title').slice(4)+'.mp3'; filename = filename.replace(/\:/g,' -'); filename = filename.replace(/\\|\/|\*|\?|\"|\<|\>|\|/g, ''); GM_setClipboard(filename); }); H.log ('等待豆瓣电台加载 ..'); H.waitUntil('extStatusHandler', function () { H.log ('绑定函数 ..'); unsafeOverwriteFunctionSafeProxy ({ extStatusHandler: function (jsonSongObj) { var songObj = JSON.parse(jsonSongObj); if ('start' == songObj.type && songObj.song) { linkDownload .attr('href', H.uri (songObj.song.url, songObj.song.title + songObj.song.url.slice(-4))) .attr('title', '下载: ' + songObj.song.title); H.info ('%s => %s', songObj.song.title, songObj.song.url); } throw new ErrorUnsafeSuccess (); } }); H.log ('函数绑定完毕, Enjoy~'); }); } } , /* Compiled from fm.jing.js */ { id: 'fm.jing', name: 'Jing.fm', host: 'jing.fm', noSubHost: true, onStart: function () { this.dlBox = $('<a>').css({ position: 'absolute', right: 0, zIndex: 9 }).attr('target', '_blank').text('下载'); H.jPlayerPatcher (function (songObj) { this.dlBox .attr ( 'href', H.getFirstValue (songObj).replace(/\?.+/, '') ) .attr ( 'title', $('#mscPlr > .tit').text () ); }.bind (this)); H.waitUntil ('Player.load', function () { unsafeOverwriteFunctionSafeProxy ({ load: function () { setTimeout (function () { document.dispatchEvent ( new CustomEvent ('jx_jing_fm_player_loaded') ); }, 100); throw new ErrorUnsafeSuccess(); } }, unsafeWindow.Player, '.Player'); }); document.addEventListener ('jx_jing_fm_player_loaded', function () { H.info ('Jing.fm 播放器加载完毕'); this.dlBox.appendTo($('#mscPlr')); }.bind (this), false); } }, /* Compiled from fm.moe.js */ { id: 'fm.moe', name: '萌电台 [moe.fm]', host: 'moe.fm', noSubHost: true, hide: ['#promotion_ls'], onBody: function () { H.waitUntil('playerInitUI', function () { // 登录破解 unsafeWindow.is_login = true; var dlLink = $('<a>').addClass('player-button left').css(H.makeRotateCss(90)).css({ 'width': '26px', 'background-position': '-19px -96px' }).insertAfter ($('div.player-button.button-volume').first()); unsafeOverwriteFunctionSafeProxy ({ playerInitUI: function (songObj) { dlLink.attr('href', songObj.completeUrl).attr('title', '单击下载: ' + songObj.title); throw new ErrorUnsafeSuccess(); } }); }); } }, /* Compiled from fm.qq.js */ { id: 'fm.qq', name: 'QQ 电台下载解析', host: 'fm.qq.com', noSubHost: true, onBody: function () { H.log ('Waiting for fmQQ...'); H.waitUntil('$.qPlayer.player.playUrl', function () { H.log ('fmQQ Hook start!'); // CreateDLButton var dlLink = $('<a>').css(H.makeRotateCss(90)).css({ 'background-position': '-24px -73px' }); $('.btn_del').after(dlLink); document.addEventListener (H.scriptName, function (e) { var songObj = e.detail; dlLink .attr('href', H.uri(songObj.songurl, songObj.msong + '.mp3')) .attr('title', '下载: ' + songObj.msong); }, false); unsafeExec (function () { var _playurl = window.$.qPlayer.player.playUrl.bind(window.$.qPlayer.player); var _updateUrl = function () { document.dispatchEvent ( new CustomEvent (H.scriptName, {detail: $.qPlayer.playList.getSongInfoObj() }) ); } window.$.qPlayer.player.playUrl = function () { _updateUrl (); return _playurl.apply (0, arguments); }; _updateUrl (); }); H.log ('fmQQ Hook finish!'); }); } }, /* Compiled from music.163.coffee */ ({ /* 网易音乐下载解析 By Jixun 尝试使用 Coffee Script 写 */ id: 'music.163', name: '网易音乐下载解析', host: 'music.163.com', noSubHost: true, noFrame: false, dl_icon: true, css: /* Resource: com.163.music.dl.css */ H.extract(function () { /* .m-pbar, .m-pbar .barbg { width: calc( 455px - 2.5em ); } .m-playbar .play { width: calc( 570px - 2.5em ); } .m-playbar .oper { width: initial; } .jx_dl:hover { color: white; } -- 底部单曲下载 .m-playbar .oper .jx_dl { text-indent: 0; font-size: 1.5em; margin: 13px 2px 0 0; float: left; color: #ccc; text-shadow: 1px 1px 2px black, 0 0 1em black, 0 0 0.2em #aaa; } .jx_dl:hover { color: white; } -- 播放列表下载 .m-playbar .listhdc .jx_dl.addall { left: 306px; line-height: 1em; -- 多一个 px, 对齐文字 top: 13px; } .m-playbar .listhdc .line.jx_dl_line { left: 385px; } */}), onStart: function() { this.regPlayer(); return unsafeExec(function() { var fakePlatForm; fakePlatForm = navigator.platform + "--Fake-mac"; Object.defineProperty(navigator, "platform", { get: function() { return fakePlatForm; }, set: function() { return null; } }); return window.GRestrictive = false; }); }, _doRemoval: function() { return H.waitUntil('nm.x', (function(_this) { return function() { var hook1, hook2; hook1 = _this.searchFunction(unsafeWindow.nej.e, 'nej.e', '.dataset;if'); hook2 = _this.searchFunction(unsafeWindow.nm.x, 'nm.x', '.copyrightId=='); return H.waitUntil('nm.x.' + hook2, function() { return unsafeExec(function(bIsFrame, hook1, hook2) { var _bK; _bK = nej.e[hook1]; nej.e[hook1] = function(z, name) { if (name === 'copyright' || name === 'resCopyright') { return 1; } return _bK.apply(this, arguments); }; return nm.x[hook2] = function() { return false; }; }, H.isFrame, hook1, hook2); }, 7000, 500); }; })(this)); }, searchFunction: function(base, name, key) { var baseName, fn, fnStr; for (baseName in base) { fn = base[baseName]; if (fn && typeof fn === 'function') { fnStr = String(fn); if (fnStr.indexOf(key) !== -1) { H.info('Search %s, found: %s.%s', key, name, baseName); return baseName; } } } H.info('Search %s, found nothing.', key); return null; }, regPlayer: function() { return document.addEventListener(H.scriptName, (function(_this) { return function(e) { var songObj; songObj = e.detail; return _this.linkDownload.attr({ href: H.uri(_this.getUri(JSON.parse(songObj.song)), "" + songObj.name + " [" + songObj.artist + "].mp3"), title: '下载: ' + songObj.name }); }; })(this)); }, hookPlayer: function() { H.waitUntil('nm.m.f', (function(_this) { return function() { var baseName, clsFn, playerHooks, protoName, _ref; playerHooks = null; _ref = unsafeWindow.nm.m.f; for (baseName in _ref) { clsFn = _ref[baseName]; protoName = _this.searchFunction(clsFn.prototype, "nm.m.f." + baseName, '<em>00:00</em>'); if (protoName) { playerHooks = [baseName, protoName]; break; } } unsafeExec(function(scriptName, playerHooks) { var _bakPlayerUpdateUI; _bakPlayerUpdateUI = nm.m.f[playerHooks[0]].prototype[playerHooks[1]]; nm.m.f[playerHooks[0]].prototype[playerHooks[1]] = function(songObj) { var eveSongObj; eveSongObj = { artist: songObj.artists.map(function(artist) { return artist.name; }).join('、'), name: songObj.name, song: JSON.stringify(songObj) }; document.dispatchEvent(new CustomEvent(scriptName, { detail: eveSongObj })); return _bakPlayerUpdateUI.apply(this, arguments); }; }, H.scriptName, playerHooks); }; })(this)); }, hookPlayerFm: function() { return H.waitUntil('nm.m.fO', (function(_this) { return function() { var hook; hook = _this.searchFunction(unsafeWindow.nm.m.fO.prototype, 'nm.x', '.mp3Url,true'); _this.linkDownload = $('<a>').prependTo('.opts.f-cb>.f-fr').addClass('icon icon-next').html('&nbsp;').css('transform', 'rotate(90deg)'); unsafeExec(function(scriptName, hook) { var _bakPlaySong; _bakPlaySong = nm.m.fO.prototype[hook]; nm.m.fO.prototype[hook] = function(songObj) { var eveSongObj; eveSongObj = { artist: songObj.artists.map(function(artist) { return artist.name; }).join('、'), name: songObj.name, song: JSON.stringify(songObj) }; document.dispatchEvent(new CustomEvent(scriptName, { detail: eveSongObj })); return _bakPlaySong.apply(this, arguments); }; }, H.scriptName, hook); }; })(this)); }, onBody: function() { this._doRemoval(); if (H.isFrame) { return; } this.linkDownload = $('<a>').addClass(H.defaultDlIcon).appendTo($('.m-playbar .oper')).attr({ title: '播放音乐, 即刻解析' }).click(function(e) { e.stopPropagation(); }); this.linkDownloadAll = $('<a>').addClass(H.defaultDlIcon).addClass('addall').text('全部下载').attr({ title: '下载列表里的所有歌曲' }).click((function(_this) { return function(e) { e.stopPropagation(); (function(trackQueue, aria2) { var i, track, _ref; _ref = JSON.parse(trackQueue); for (i in _ref) { track = _ref[i]; aria2.add(Aria2.fn.addUri, [_this.getUri(track)], H.buildAriaParam({ out: "" + i + ". " + track.name + " [" + (track.artists.map(function(artist) { return artist.name; }).join('、')) + "].mp3" })); } aria2.send(true); })(localStorage['track-queue'], new Aria2.BATCH(H.aria2, function() { return H.info(arguments); })); }; })(this)); if (H.config.dUriType === 2) { H.captureAria(this.linkDownload); } else { this.linkDownloadAll.addClass('jx_hide'); } H.waitUntil(function() { return $('.listhdc > .addall').length; }, (function(_this) { return function() { _this.linkDownloadAll.insertBefore($('.m-playbar .listhdc .addall')).after($('<a>').addClass('line jx_dl_line')); }; })(this), true, 500); if (location.pathname === '/demo/fm') { return this.hookPlayerFm(); } else { return this.hookPlayer(); } }, dfsHash: (function() { var strToKeyCodes; strToKeyCodes = function(str) { return Array.prototype.slice.call(String(str).split('')).map(function(e) { return e.charCodeAt(); }); }; return function(dfsid) { var fids, key; key = [51, 103, 111, 56, 38, 36, 56, 42, 51, 42, 51, 104, 48, 107, 40, 50, 41, 50]; fids = strToKeyCodes(dfsid).map(function(fid, i) { return (fid ^ key[i % key.length]) & 0xFF; }); return CryptoJS.MD5(CryptoJS.lib.ByteArray(fids)).toString(CryptoJS.enc.Base64).replace(/\//g, "_").replace(/\+/g, "-"); }; })(), getUri: function(song) { var dsfId, randServer; dsfId = (song.hMusic || song.mMusic || song.lMusic).dfsId; randServer = Math.floor(Math.random() * 2) + 1; return "http://m" + randServer + ".music.126.net/" + (this.dfsHash(dsfId)) + "/" + dsfId + ".mp3"; } }), /* Compiled from music.1ting.js */ { id: 'music.1ting', name: '一听音乐', host: ['www.1ting.com'], noSubHost: true, path: ['/player/', '/album_'], onBody: function () { this.dlBtn = $('.songact a.down') .text ('直接下载') .removeAttr('onclick'); H.waitUntil ('yiting.player.entity.src', function () { unsafeExec (function () { var playTrigger = function () { // dlBtn.attr('href', window.yiting.player.entity.src); document.dispatchEvent ( new CustomEvent (H.scriptName) ); }; window.yiting.player.hook('play', playTrigger); playTrigger (); }); }); document.addEventListener (H.scriptName, this.eventHandler.bind (this), false); this.eventHandler (); }, eventHandler: function () { var songTitle = $('.song .songtitle > a').text (); this.dlBtn.attr ({ href: H.uri (unsafeWindow.yiting.player.entity.src, songTitle + '.mp3'), title: '下载: ' + songTitle }); } }, /* Compiled from music.565656.js */ { id: 'music.565656', name: '565656 音乐', host: 'www.565656.com', noSubHost: true, path: ['/plus/player.ashx', '/ting/'], onStart: function () { H.jPlayerPatcher (function (songObj) { var songAddr = songObj.mp3 || songObj.m4a; $('.play-info-otheropt > a:last') .attr('href', H.uri (songAddr, songObj.songname + songObj.m4a.slice(-4))) .find('span').text('下载: ' + songObj.songname + ' - ' + songObj.singername); }); } }, /* Compiled from music.5sing.js */ { id: 'music.5sing', name: '5sing 下载解析', host: ['5sing.com', '5sing.kugou.com'], onStart: function () { if (H.beginWith(location.pathname, '/fm/')) { // e.g. http://5sing.kugou.com/fm/m/ this._fmHook (); } }, onBody: function () { if (H.contains(location.pathname, '/down/')) { this._dlPage (); return ; } // 旧版单曲播放页面 H.waitUntil ('pageOptions.ticket', function () { var songObj = JSON.parse(H.base64Decode(unsafeWindow.pageOptions.ticket)); $('.func_icon3>a').attr ({ href: H.uri(songObj.file, songObj.songName + '.mp3'), title: '单击下载: ' + songObj.songName, }).html('<b/>直链下载'); $('#play').css ({ top: 'initial' }); $('.song_play').css ({ marginTop: '1em' }); $('.rt2').hide(); $('#report').parent().hide(); }); // 新版单曲播放页面 H.waitUntil ('globals.ticket', function () { var songObj = JSON.parse(H.base64Decode(unsafeWindow.globals.ticket)); $('.view_info>ul:last>li:first').replaceWith($('<li>').append ( $('<a>').text('点我下载').attr({ href: H.uri(songObj.file, songObj.songName + '.mp3'), title: '单击下载: ' + songObj.songName, target: '_blank' }).css ('color', '#F87877') )); }); }, _dlPage: function () { var $dl = $('<p>').prependTo ($('.sing_view')).text('正在解析音乐地址…'); $.get($('.main > h1 > a').attr('href')).success (function (res) { var songAddress = res.match(/"ticket"\s*:\s*\"(.+?)"/); if (songAddress) { var songObj = JSON.parse(H.base64Decode(songAddress[1])); songAddress = H.uri(songObj.file, songObj.songName + '.mp3'); } else if (songAddress = res.match(/,\s*file\s*:\s*\"(.+?)"/)) { // 来源请求 songAddress = songAddress[1]; } else { $dl .text ('* 下载解析失败,请访问歌曲页解析。') .css ('color', 'red'); return ; } $dl.text('解析完毕: ').append ($('<a>').attr({ href: songAddress, target: '_blank' }).text('点我下载')); }).error (function () { $dl .text ('* 网络错误,请稍候重试或访问歌曲页解析。') .css ('color', 'red'); }); }, _fmHook: function () { if (this.fmHooked) return ; this.fmHooked = true; H.hookDefine ('define', function (scriptName, _define, moduleName, requires, fCallback) { if ('player/single' === moduleName) { return _define (moduleName, requires, function (require, exports, module) { var ret = fCallback.call (null, require, exports, module); var $wsp = module.exports; var MediaElement = $wsp.mediaElement; $wsp.mediaElement = function (playerBoxId, options) { options.stats.enable = false; var mPlayer = new MediaElement (playerBoxId, options); var _play = mPlayer.play; mPlayer.play = function (songObj) { document.dispatchEvent ( new CustomEvent (scriptName, {detail: songObj}) ); return _play.call (mPlayer, songObj); }; return mPlayer; }; return ret; }); } }, H.scriptName); document.addEventListener (H.scriptName, function (e) { var songObj = e.detail; setTimeout (function () { $('.jp-download').attr ({ href: H.uri(songObj.file, songObj.songName + '.mp3'), title: '下载: ' + songObj.songName }); }, 1); }, false); }, }, /* Compiled from music.9ku.js */ { id: 'music.9ku', name: '9酷音乐', host: 'www.9ku.com', noSubHost: true, hide: ['#LR2', '#LR3', '#seegc', '.dongDown'], path: ['/play/', '/play.htm'], onStart: function () { this.dlLink = $('<a>') .attr ('target', '_blank') .attr ('title', '正在抓取歌曲数据 ..') .text ('下载'); H.jPlayerPatcher (function (songObj) { var songUrl = songObj.mp3 || songObj.m4a, songName = $('#play_musicname').text(); this.dlLink .attr ('href', H.uri (songUrl, songName + songUrl.slice(-4))) .attr ('title', '下载: ' + songName); }.bind (this)); }, onBody: function () { $('.ringDown').css ({ float: 'none', display: 'block', textAlign: 'center' }).html (this.dlLink); } }, /* Compiled from music.baidu.js */ { id: 'music.baidu', name: '百度音乐', host: 'music.baidu.com', noSubHost: true, path: /^\/song\/\d+\/download/, hide: '.foreign-tip', _setText: function (text) { if (text[0] == '+') { this.btnDownload.title.append(text.slice(1)); } else { this.btnDownload.title.text(text); } }, _setLink: function (url) { this.btnDownload.btn.attr('href', url); }, _btn: function (text, outerIcon, innerIcon) { var btn = $('<a><span class="inner"><i class="icon btn-icon-' + innerIcon + '">') .addClass('btn btn-' + outerIcon + ' actived') .attr('target', '_blank') .attr('href', '#') .appendTo(this.p); return ({ btn: btn, title: $('<span>').appendTo($('.inner', btn)).text(text) }); }, _initDl: function (e) { this.downloadInfo = JSON.parse(e.detail).downloadInfo; }, onStart: function () { document.addEventListener (H.scriptName, this._initDl.bind (this), false); unsafeExec(function (scriptName) { // 屏蔽广告写出 document.write = (function write(){}).bind(0); window.ting = {}; var origInitDownload; Object.defineProperty(window.ting, 'initDownload', { get: function () { return function (initOpts) { document.dispatchEvent (new CustomEvent (scriptName, {detail: JSON.stringify (initOpts)})); return origInitDownload.apply(this, arguments); }; }, set: function (idl) { origInitDownload = idl; } }); }, H.scriptName); }, onBody: function () { var self = this; this.parser = H.rule.get ('music.baidu.play'); if (!this.parser) { H.error ('Required rule `music.baidu.play` missing, please re-install this script.'); return ; } // 度娘的按钮前面插入我们的 var operDiv = $('.operation').prepend('<div class="clearfix">'); this.p = $('<p>').prependTo(operDiv).css('margin-bottom', '2em'); // 添加按钮 this.btnDownload = this._btn('请选择音质', 'h', 'download-small'); // this.btnExport = this._btn('导出地址', 'b', 'download-small'); this.btnDownload.btn.click(this._clickDl.bind(this)); $('.down-radio').change(function () { self.changeBitrate($(this)); }).filter(':checked').change(); }, _clickDl: function (e) { if (this.btnDownload.btn.data ('do-nothing')) return ; e.preventDefault(); var self = this; var $el = this.$el; var sid = $el.data('sid'), rate = $el.data('rate'), fmt = $el.data('format'); self._setText ('+ (开始解析)'); var fn = H.sprintf('%s [%s].%s', this.downloadInfo.song_title, this.downloadInfo.singer_name, fmt); this.parser._addFav (sid, function (errInfo) { var bNeedRmFav = errInfo.code === 22000; self.parser._getRealUrl (self.parser._buildUrl(sid, rate, fmt), function (url) { H.addDownload(url, fn); self._setLink (H.uri (url, fn)); self._setText ('+ (解析完毕)'); self.btnDownload.btn.data('parse-' + rate, [url, fn]); if (bNeedRmFav) self.parser._rmFav (sid); self.btnDownload.btn.data ('do-nothing', true); }); }); }, changeBitrate: function ($el) { this.$el = $el; this._setText (H.sprintf('下载 (%skbps, %s 格式)', $el.data('rate'), $el.data('format'))); var dataUrl = this.btnDownload.btn.data ('parse-' + $el.data('rate')); this.btnDownload.btn.data ('do-nothing', !!dataUrl); if (dataUrl) { this._setLink (dataUrl); this._setText ('+ (已解析)'); } } }, /* Compiled from music.baidu.play.js */ { id: 'music.baidu.play', name: '百度音乐盒', host: 'play.baidu.com', path: '/', show: '#floatBtn>.lossless', // jQuery 的 width 计算在火狐下会包括样式表, 即使元素已经不在 body 里… css: '.column4{width:0 !important}', // 单曲解析只有这些 qualities: 'auto_1 mp3_320+_1 mp3_320_1'.split(' '), /** * @private * 初始化事件绑定 */ initEvents: function () { this.isAria = H.config.dUriType == 2; // Batch download queue H.setupAria (); this.$q = new IntervalLoop([], this._batch.bind(this), 300); this.$q.loop(); // 准备接收数据 document.addEventListener (H.scriptName + '-BATCH', this._batchDownload.bind (this), false); if (!this.isAria) { H.warn ('批量下载仅支援 Aria2 模式!'); } document.addEventListener (H.scriptName, this._recvEvent.bind (this), false); }, /** * 错误数据 * @type {Object} */ ERROR: { '22232': { text: H.extract(function () {/* 请挂上*大陆*马甲, 因其它地区访问被屏蔽. 如果您会使用相关插件, 请加入下述地址至规则: http://music.baidu.com/data/user/collect?* 您可以按下 Ctrl+C 拷贝该消息. 相关阅读: https://github.com/JixunMoe/cuwcl4c/wiki/配合大陆代理实现访问解除封锁 */}), level: 'error', alert: true }, '22322': { text: '已经在收藏列表, 不移除.', level: 'info' }, '22331': { text: '云端收藏已满, 请先腾出位置!', level: 'warn', alert: true }, '22000': { text: '因下载解析而添加至收藏, 解析后移除链接.', level: 'info' } }, /** * 提取错误信息 * @param {Integer} errCode 错误代码 * @return {Object} 错误信息详细 */ error: function (errCode) { var errInfo = this.ERROR[errCode.toString()] || { text: '未知错误: ' + errCode, alert: true, level: 'warn' }; errInfo.code = parseInt(errCode, 10); H[errInfo.level](errInfo.text); if (errInfo.alert) alert( errInfo.text ); return errInfo; }, /** * @private * 拦截播放器下载事件 */ hookPlayerDownload: function () { var that = this; // fmPlayerView 是最后一个 H.waitUntil ('fmPlayerView', function () { that.$dlBtn = $('.main-panel .download > a'); unsafeExec(function (scriptName, hookBatch) { // 黄金 VIP var oldSetVip = HQ.model.setVipInfo; HQ.model.setVipInfo = function ( isVip, z ) { if (!isVip) { isVip = true; } return oldSetVip.call (this, isVip, z); }; HQ.model.isGold = function () { return true; }; HQ.model.setVipInfo (); var bakExtractUserInfo = UserModel.prototype._getUserInfo; UserModel.prototype._getUserInfo = function () { var r = bakExtractUserInfo.apply(this, arguments); if (!r.vip) { r.vip = { cloud: { service_level: 'gold' } }; } r.isShowSourceIcon = false; return r; }; // 屏蔽日志发送, 刷屏好烦 logCtrl.sendLog = function () {}; var instFloatBtn = listView.tip.data("ui-floatButton"); var oldMusicDownload = listView.download; listView.download = function (songIndex, isFlac) { // 批量下载, 但是不是 Aria 模式则放弃 if (!hookBatch && songIndex.length > 1) { return oldMusicDownload.apply(this, arguments); } var songData = instFloatBtn.listElem.reelList("option", "data").filter(function (e, i) { return -1 !== songIndex.indexOf(i) }).map (function (e) { return { songName: e.songName, artistName: e.artistName, songId: e.songId, isFlac: !!isFlac, isFav: !!e.hasCollected }; }); document.dispatchEvent (new CustomEvent (scriptName + '-BATCH', { detail: JSON.stringify(songData) })); }; (function () { // 取消下载按钮点击 this.$title.find('.download').off('click'); // 绑定播放事件 this.listCtrl.on('change:songLink', function (z, songData) { document.dispatchEvent (new CustomEvent (scriptName, {detail: JSON.stringify (songData)})); }); }).call (window.songInfoView); }, H.scriptName, this.isAria); }); }, /** * @private * document-start 回调 */ onStart: function () { this.initEvents (); this.hookPlayerDownload (); }, /** * 提交 Post 请求 * @param {Request} req 请求对象, 参见 GM_xmlhttpRequest * @return {Object} xmlhttpRequest 对象 */ post: function (req) { req.method = 'POST'; req.headers = req.headers || {}; req.headers.Referer = req.headers.Referer || 'http://music.baidu.com/'; req.headers['Content-Type'] = 'application/x-www-form-urlencoded'; req.data = $.param(req.data); return GM_xmlhttpRequest(req); }, /** * @private * 播放器下方的下载事件接管 * @param {Event} e 事件 */ _recvEvent: function (e) { var songData = JSON.parse (e.detail); for (var i = 3/* this.qualities.length */, song; !song && i--; ) song = songData.links[this.qualities[i]]; // 获取歌曲失败 if (!song || !song.songLink) { H.warn ('解析下载地址失败, 可能百度更新了获取方式.'); return ; } this.$dlBtn.attr ({ title: song.songName, href: H.uri(song.songLink, H.sprintf('%s [%s].%s', songData.songName, songData.artistName, song.format)) }); }, /** * 随机数 * @return {String} 随机数 */ _rnd: function () { return Math.random().toString().slice(2); }, /** * 解析百度返回的不规则数据 * @param {Response} r GM_xmlhttpRequest.onload 回调的参数 1 * @return {Object} 相关数据 */ _parseRaw: function (r) { return JSON.parse(r.responseText.replace(/\s/g, '')); }, /** * 解析百度返回的不规则数据的 data 节点 * @param {Response} r GM_xmlhttpRequest.onload 回调的参数 1 * @return {Object} 相关数据 */ _parse: function (r) { return this._parseRaw(r).data; }, /** * 取歌曲是否在收藏里面, 是的话则能直接解析 * @param {Integer} songId 曲目 ID * @param {Function} cbDone 回调, 1 参数, Boolean 是否在收藏夹 * @return {Boolean} [description] */ _isFav: function (songId, cbDone) { var self = this; GM_xmlhttpRequest ({ method: 'GET', url: H.sprintf('http://music.baidu.com/data/user/isCollect?type=song&ids=%s&r=%s', songId, this._rnd()), onload: function (r) { cbDone(!!self._parse(r).isCollect); } }); }, /** * 加入收藏夹 * @param {Integer} songId 曲目 ID * @param {Function} cbDone 回调错误信息 */ _addFav: function (songId, cbDone) { var self = this; this.post({ url: 'http://music.baidu.com/data/user/collect?r=' + this._rnd(), data: { ids: songId, type: 'song', pay_type: 0 }, onload: function (r) { cbDone(self.error(self._parseRaw(r).errorCode)); } }); }, /** * 移除收藏夹 * @param {Integer} songId 曲目 ID * @param {Function} cbDone 回调错误信息 */ _rmFav: function (songId, cbDone) { var self = this; this.post({ url: 'http://music.baidu.com/data/user/deleteCollection?r=' + this._rnd(), data: { ids: songId, type: 'song', pay_type: 0 }, onload: function (r) { cbDone(self.error(self._parseRaw(r).errorCode)); } }); }, /** * 直接获取曲目信息, 请确保用户有权限直接解析或在收藏夹内. * @param {Integer} songId 曲目 ID * @param {Function} cbSong 回调 */ _getSongInfoDirect: function (songId, cbSong) { var self = this; GM_xmlhttpRequest ({ method: 'GET', url: 'http://yinyueyun.baidu.com/data/cloud/download?songIds=' + songId, onload: function (r) { cbSong(self._parse(r).data); } }); }, /** * 获取曲目信息 * @param {Integer} songId 曲目 ID * @param {Function} cbSong 回调 */ _getSongInfo: function (songId, cbSong) { var self = this; this._addFav(songId, function (errInfo) { if (errInfo.level == 'error') { H.error('添加收藏夹出错, 取消操作.'); return ; } var isFav = errInfo.code === 22000; var qRemoveFav = $.Deferred(); qRemoveFav.done(isFav ? H.nop : function () { H.info ('移除为解析而临时添加的歌曲… %s', songId); self._rmFav(songId); }); self._getSongInfoDirect(songId, function (r) { cbSong(r, qRemoveFav.resolve.bind(qRemoveFav)); }); }); }, /** * 根据基本信息构建下载地址 * @param {Integer} songId 曲目 ID * @param {Integer} songRate 码率, 单位为 kbps * @param {String} musicFormat 音乐文件格式 * @return {String} 构建的文件地址, 需要 Cookie */ _buildUrl: function (songId, songRate, musicFormat) { return H.sprintf( 'http://yinyueyun.baidu.com/data/cloud/downloadsongfile?songIds=%s&rate=%s&format=%s', songId, songRate, musicFormat ); }, /** * 构建无需附加数据的下载地址 * @param {String} url 会跳转的地址 * @param {Function} cbUrl 回调, 1 参数, String 真实地址 */ _getRealUrl: function (url, cbUrl) { GM_xmlhttpRequest ({ method: 'GET', url: url, headers: { Range: 'bytes=0-1' }, onload: function (r) { cbUrl (r.finalUrl); } }); }, /** * 选择最高码率 * @param {Object} dl 带有码率数据的对象 * @return {Object} 最高的码率对象 */ _getBestQuality: function (dl) { var qu = Object.keys(dl).sort(function (a, b) { if (!dl[a]) return dl[b] ? -1 : 0; if (!dl[b]) return 1; return dl[a].rate - dl[b].rate; }).pop(); return dl[qu]; }, _renameUrl: function (oldUrl, file) { // /12345/xxx.mp3?yyy -> /12345/file.mp3?yyy return oldUrl.replace(/(\/\d+\/).+\?/, '$1' + file + '?'); }, /** * @private * 批量下载处理的回调函数 * @param {Function} next 回调, 当前项目处理完毕后调用 * @param {Object} objSong 曲目信息 */ _batch: function (next, objSong) { var self = this; // 检查是否需要临时加入收藏夹 var getSongInfoType = objSong.isFav ? '_getSongInfoDirect' : '_getSongInfo'; this[getSongInfoType] (objSong.songId, function (dl, cbRemoveFav) { // 除非选择下无损 否则不采用无损 if (!objSong.isFlac && dl.flac) delete dl.flac; var songDl = self._getBestQuality(dl); var file = H.sprintf('%s [%s].%s', objSong.songName, objSong.artistName, songDl.format); self._getRealUrl (self._buildUrl(objSong.songId, songDl.rate, songDl.format), function (url) { // 移除临时用的收藏夹, 不占位 if (cbRemoveFav) cbRemoveFav (); H.addDownload (self._renameUrl(url, file), file); next (); }); }); }, /** * @private * 批量下载事件接管函数 * @param {Event} e 事件 */ _batchDownload: function (e) { var arrSongs = JSON.parse (e.detail); var $q = this.$q; $q.add.apply($q, arrSongs); } }, /* Compiled from music.baidu.yinyueyun.js */ { id: 'music.baidu.yinyueyun', name: '音乐云下载', host: 'yinyueyun.baidu.com', noSubHost: true, path: '/', onStart: function () { H.waitUntil('userModel.set', function () { unsafeExec(function (scriptName, hookBatch) { var bakUserSetInfo = userModel.set; userModel.set = function (key, val, opts) { if (key === 'userInfo' && val) { val.vip = val.golden = true; } return bakUserSetInfo.apply(userModel, arguments); }; // Force update user data via hook userModel.set('userInfo', userModel.get('userInfo')); }); }); } }, /* Compiled from music.djcc.js */ { id: 'music.djcc', name: 'DJCC 舞曲', host: ['www.djcc.com'/* , 'www.dj.cc' */], noSubHost: true, path: ['/dj/', '/play.php'], missingDomain5: 'http://down.djcc.com/music/', onStart: function () { H.waitUntil ('$.post', function () { console.info ('执行 VIP 破解 (play.php 页面无效) ..'); unsafeExec (function (scriptHome, scriptName) { console.info (scriptHome); var _post = $.post; $.post = function (addr, cb) { if (addr == '/ajax.php?ajax=userinfo') { return _post.call (window.$, addr, function (s) { if (s == '') s = [1, scriptName, 0, scriptHome, 0, 0, 99999999, 99999999, 0, 0, 2, '尊贵的 ' + scriptName + ' 用户', '9年'].join('*wrf*'); cb (s); }); } return _post.apply (window.$, arguments); }; return function () {}; }, H.scriptHome, H.scriptName); }); // 播放器劫持 H.waitUntil ('jwplayer.api', function () { unsafeExec (function () { var _sp = window.jwplayer.api.selectPlayer; window.jwplayer.api.selectPlayer = function (sel) { var mPlayer = _sp (sel); var _setup = mPlayer.setup; mPlayer.setup = function (options) { console.info ('setup', options); var _opl = options.events.onPlaylistItem; options.events.onPlaylistItem = function (eventPlaylistChange) { document.dispatchEvent ( new CustomEvent (H.scriptName, {detail: JSON.stringify (mPlayer.getPlaylistItem ())}) ); return _opl.apply (this, arguments); }; return _setup.apply (mPlayer, arguments); }; return mPlayer; }; }); }); this.dlLink1 = $('<a>').text ('试听下载').attr ('target', '_blank'); this.dlLink2 = $('<a>').text ('高清下载').attr ('target', '_blank'); // 下载数据解析 document.addEventListener (H.scriptName, function (e) { var songObj = JSON.parse (e.detail); if (H.beginWith (songObj.file, wrfJw.Player.domain[0])) songObj.file = songObj.file.slice (wrfJw.Player.domain[0].length); this.dlLink1.attr ('href', H.uri (wrfJw.Player.domain[0] + songObj.file , songObj.title + '.mp3')); this.dlLink2.attr ('href', H.uri (missingDomain5 + (songObj.file2 || songObj.file), songObj.title + '.高清.mp3')); H.info (songObj); }.bind(this), false); }, onBody: function () { $('#listtabs') .append (this.dlLink1) .append (this.dlLink2) .css ('height', 'initial') .css ('min-height', '160'); } }, /* Compiled from music.djkk.js */ { id: 'music.djkk', name: 'DJ 嗨嗨', host: 'www.djkk.com', noSubHost: true, css: /* Resource: com.djkk.dl.css */ H.extract(function () { /* #jx_dl_wrapper { float: right; margin-right: 1.5em; } #jx_dl_wrapper > a { transition: color .4s; color: #aaa; } #jx_dl_wrapper > a:hover { color: #fff; text-decoration: none; } */}), onStart: function () { this.dlHolder = $('<div id="jx_dl_wrapper">'); this.dlLink = $('<a>').text('下载').appendTo (this.dlHolder); H.jPlayerPatcher (function (songObj) { var songAddr = songObj.mp3 || songObj.m4a; var songTitle = songObj.title || $('#playTitle .jp-title').text().replace(/.+:/, ''); this.dlLink .attr ('href', H.uri(songAddr, songTitle + songAddr.slice(-4)) ) .attr ('title', '下载: ' + songTitle); }.bind (this)); }, onBody: function () { this.dlHolder.appendTo ($('.main-panel')); } }, /* Compiled from music.djye.js */ { id: 'music.djye', name: 'DJ 爷爷网', host: 'www.djye.com', noSubHost: true, path: '/Player/', css : /* Resource: com.djye.dl.css */ H.extract(function () { /* #jx_dl_btn { margin-top: 7px; float: right; } #jx_dl_btn > a { transition: color .4s; color: black; } #jx_dl_btn > a:hover { color: #444; } */}), toMp3: function (song) { return song.replace(/[a-z]*\./, 'mp3.').replace(/m4a$/, 'mp3?type=down'); }, onStart: function () { this.linkHolder = $('<p id="jx_dl_btn">'); this.linkM4A = $('<a>').appendTo (this.linkHolder).text ('试听音质'); this.linkHolder.append (' | '); this.linkMP3 = $('<a>').appendTo (this.linkHolder).text ('MP3') .attr ('title', '请注意: 该链接可能因为服务器配置更新导致无法下载'); H.jPlayerPatcher (function (songObj) { var songLink = songObj.m4a.replace(/\?.*/, ''); var songTitle = $('#play_title').text (); this.linkM4A.attr('href', H.uri (songLink, songTitle + '.m4a')); this.linkMP3.attr('href', H.uri (this.toMp3(songLink), songTitle + '.mp3')); }.bind (this)); }, onBody: function () { this.linkHolder .appendTo ($('.playerMain-03')) .prev().css('padding-left', 25); } }, /* Compiled from music.duole.js */ { id: 'music.duole', name: '多乐音乐', host: 'www.duole.com', noSubHost: true, onBody: function () { var btnPrevSong = $('#player_right .last'), btnDownload = btnPrevSong.clone(); $('#player_right').animate({ 'width': '+=32' }, 500); var songInfo = $('a.music_info').css({ 'cursor': 'text' }).removeAttr('href'); var mo = new MutationObserver (function () { if (songInfo[0].hasAttribute('href')) songInfo.removeAttr ('href'); }.bind (this)); mo.observe (songInfo[0], { attributes: true }); btnDownload.insertBefore(btnPrevSong.prev()).removeClass('last').css({ 'width': '0', 'display': 'inline', 'background-position': '-150px -104px' }).css(H.makeRotateCss(90)).animate({ 'width': '+=32' }, 500).attr('target', '_blank'); var oldPlayNew = unsafeWindow.duolePlayer.playNew; var randomId; unsafeOverwriteFunctionSafeProxy ({ playNew: (function (t, n) { document.dispatchEvent ( new CustomEvent (H.scriptName, {detail: JSON.stringify ({ mp3: t, info: this.curMusic })}) ); throw new ErrorUnsafeSuccess (); }).bind(unsafeWindow.duolePlayer) }, unsafeWindow.duolePlayer, '.duolePlayer'); document.addEventListener (H.scriptName, function (e) { var songObj = JSON.parse (e.detail), songInfo = songObj.info; btnDownload.attr({ href: H.uri (songObj.mp3, songInfo.song_name + ' [' + songInfo.album_name + '] - ' + songInfo.singer_name + '.mp3'), title: '单击下载: ' + songInfo.song_name }); }, false); } }, /* Compiled from music.duomi.ear.js */ { id: 'music.duomi.ear', name: '邻居的耳朵', host: 'ear.duomi.com', noSubHost: true, onBody: function () { H.wordpressAudio (); } }, /* Compiled from music.oyinyue.js */ { id: 'music.oyinyue', name: '噢音乐下载解析', host: 'oyinyue.com', onBody: function () { if (H.beginWith (location.pathname, '/Down.aspx')) { this.downPage (); return ; } H.waitUntil ('player.setUrl', function () { unsafeOverwriteFunctionSafeProxy ({ setUrl: function (songUrl) { $('.func_icon4 > a').attr({ 'href': songUrl, 'target': '_blank' }).html('<b/>直链下载'); throw new ErrorUnsafeSuccess (); } }, unsafeWindow.player, '.player') }); }, downPage: function () { var $dl = $('<p>').prependTo ($('.sing_view')).text('正在解析音乐地址…'); this.fetch ($_GET.id, function (songUrl) { $dl.text('解析完毕: ').append ($('<a>').attr({ href: songUrl, target: '_blank' }).text('点我下载')); }, function () { $dl.text ('* 下载解析失败,请访问歌曲页解析。') .css ('color', 'red'); }); }, fetch: function (songId, successCallback, failCallback) { $.ajax ({ url: '/load/loadsong.ashx', method: 'POST', data: { songid: songId, id: 3 }, dataType: 'text' }).success (function (url) { if (url && url != '0') { successCallback (url); } else { failCallback (); } }).error (function () { failCallback (); }); } }, /* Compiled from music.qq.iplimit.js */ { id: 'music.qq.iplimit', name: 'QQ 音乐、电台海外访问限制解除', host: ['y.qq.com', 'fm.qq.com'], onBody: function () { H.info ('等候海外访问限制模组加载…'); H.waitUntil ('MUSIC.widget.main.IP_limit.isLimit', function () { H.info ('海外访问限制解除.'); unsafeOverwriteFunction ({ // 解除「QQ音乐暂时不能对您所在的国家或地区提供服务」限制 isLimit: function () {} }, unsafeWindow.MUSIC.widget.main.IP_limit, '.MUSIC.widget.main.IP_limit'); }); } }, /* Compiled from music.qq.y.js */ { id: 'music.qq.y', name: 'QQ 音乐下载解析', host: ['y.qq.com', 'soso.music.qq.com'], noSubHost: true, css: /* Resource: com.qq.y.dl.css */ H.extract(function () { /* @media screen { .m_player .bar_op { left: 208px; width: 310px; } .jx_dl_bt { transform: rotate(90deg); } .jx_dl_bt > a { width: 100%; height: 100%; display: block; outline: 0 !important; } } */}), onBody: function () { if (H.config.dUriType == 1) { H.warn ( '%s\n%s', '当前版本的协议尚未支援 Cookie 输入, 回滚至连接版', '如果您确实需要自动填入用户名, 请改用 Aria2 版' ); H.config.dUriType = 0; } var styleToFix = this.styleBlock; H.waitUntil ('MUSIC.module.webPlayer.interFace.getSongUrl', function () { H.fixStyleOrder (styleToFix); var dlBtn = $('<a>') .addClass('aria-cookie') .attr('title', '播放音乐, 即刻下载') .appendTo ( $('<strong>') .addClass ('next_bt jx_dl_bt') .insertAfter ('.next_bt') ); unsafeExec (function (scriptName) { var oldGetSong = window.MUSIC.module.webPlayer.interFace.getSongUrl; window.MUSIC.module.webPlayer.interFace.getSongUrl = function (songObj, cb) { document.dispatchEvent ( new CustomEvent (scriptName, {detail: { host: 'http://stream' + (parseInt(songObj.mstream) + 10) + '.qqmusic.qq.com/', path: "M800" + songObj.mmid + ".mp3", name: songObj.msong + '[' + songObj.msinger + ']' } }) ); return oldGetSong.apply (this, arguments); }; }, H.scriptName); document.addEventListener (H.scriptName, function (e) { var songObj = e.detail; dlBtn.attr ({ href: H.uri (songObj.host + songObj.path, songObj.name + '.mp3'), title: '下载: ' + songObj.name }); }, false); }, 7000, 500); H.waitUntil ('MUSIC.widget.trackServ.formatMusic', function () { unsafeExec(function () { var _formatMusic = MUSIC.widget.trackServ.formatMusic; MUSIC.widget.trackServ.formatMusic = function () { var _music = _formatMusic.apply(this, arguments); _music.mstatus = parseInt(_music.mstatus) || 1; _music.msize = _music.msize || 1; _music.minterval = _music.minterval || 1; if (_music.msongurl) { var _pre; if (_music.size320) { _pre = 'M800'; } else if (_music.size128) { _pre = 'M500'; } if (_pre) { _music.msongurl = 'http://stream' + (parseInt(_music.mstream) + 10) + '.qqmusic.qq.com/' + _pre + _music.mmid + '.mp3'; } } return _music; }; var getVip = g_user.getVipInfo; g_user.getVipInfo = function (successCb, failCb) { return g_user.getVipInfo (function (info) { if (1 != info.vip) info.vip = 1; if (successCb) successCb (info); }, failCb); }; }); }, 7000, 500); } }, /* Compiled from music.songtaste.js */ { id: 'music.songtaste', name: 'SongTaste 下载解析', host: ['songtaste.com'], onBody: function () { var path = location.pathname; if (H.beginWith (path, '/album/') || H.beginWith (path, '/music/')) { this.album (); } else if (H.beginWith (path, '/song/')) { this.single (); } else if (H.beginWith (path, '/playmusic.php')) { this.playlist (); } }, album: function () { H.log ('ST :: 专辑页面调整'); var btn_playAll = $($('.song_fun_btn').children()[1]); var btn_noPopPlay = btn_playAll.clone().attr({ 'value': '当前窗口播放', 'onclick': '' }).insertAfter (btn_playAll); btn_noPopPlay.click(function () { var ids = [].filter.call (unsafeWindow.chkArray, function (e) { return e.checked; }).map (function (e) { return e.value; }).join(','); if (!ids) { ids = [].map.call(unsafeWindow.chkArray, function (e) { return e.value; }).join (','); } location.href = '/playmusic.php?song_id=' + ids; }); }, single: function () { var args = $("#playicon a").attr('href').replace(/\s/g, '').replace(/"/g, "'").split("'"); var sURL = args [05], sType = args [11], sHead = args [13], songId = args [15], sLength = args [16].match (/\d{2,}/)[0]; var q = $.Deferred(); q.then (function (songUrl) { H.log ('ST :: 解析音乐地址 :: %s', songUrl); var songName = $('.mid_tit').text(); $('a#custom_1').attr({ 'href': H.uri(songUrl, songName + songUrl.slice(-4)), 'title': '下载: ' + songName }).text('直接下载'); }); if (H.contains(sURL, 'rayfile')) { q.resolve (sHead + sURL + unsafeWindow.GetSongType(sType)); } else { $.ajax({ type: 'POST', url: '/time.php', cache: true, data: 'str=' + sURL + '&sid=' + songId + '&t=' + sLength, dataType: 'text', }).success(function (r) { q.resolve (r); }); } }, playlist: function () { // 下载解析 - Hook 更换歌曲的函数,避免重复读取歌曲 + 不需要多次请求服务器不容易掉线。 H.log ('ST :: 列表模式解析'); var pDownload = $('#left_music_div > .p_fun > a:last') .text('直接下载') .attr('target', '_blank'); unsafeOverwriteFunctionSafeProxy ({ changeSong: function (name, url, isLogoShown) { // 2013.03.19 & 2013.04.09 修正: // 已经删除的歌曲自动跳到下一曲 if ( 0 == name.trim().length ) { unsafeWindow.pu.doPlayNext(2); return; } H.log ('请求歌曲 :: %s :: %s', name, url); pDownload.attr({ 'href': H.uri(url, name + url.slice(-4)), 'title': '下载: ' + name }); document.title = 'ST - ' + name; // 转接给原函数 throw new ErrorUnsafeSuccess(); }, delSongDiv: function (songid, isbox) { H.log ('删除歌曲 :: ' + songid.toString()); $('#' + songid).hide(); var new_songlist = []; for (var i = 0; i < unsafeWindow.arr_ids.length; i++) { if (unsafeWindow.arr_ids[i] == songid) { if (songid == unsafeWindow.cur_sid) unsafeWindow.pu.doPlayNext(1); unsafeWindow.arr_ids[i] = 0; } } } }); // 2013.03.19 添加: // 重建播放列表地址 $('p.p_list_txt').append($('<a>').text('重建播放列表').click(function () { location.search = '?song_id=' + unsafeWindow.arr_ids.join(','); }).css('cursor', 'pointer')); H.log ('ST :: 等待网页加载...'); H.waitUntil ('pu.doPlayNext', function () { H.log ('ST :: 官方播放器删除功能修正启动'); unsafeOverwriteFunctionSafeProxy ({ doPlayNext: function (t) { var now, avl, i; for (i = 0; i < unsafeWindow.arr_ids.length; i++) { if (unsafeWindow.arr_ids[i] == unsafeWindow.cur_sid) { now = i; break; } } // 寻找下一首未删除的歌曲。 // * 2013.01.29 修正 // 1. 上一首查找失败的情况下会滚回到当前音乐的错误。 // 2. 如果没有可听歌曲情况下无限循环的错误。 now = Math.abs((now || 0) + t); avl = 0; // 检查是否有歌曲剩余 for (i = 0; i < unsafeWindow.arr_ids.length; i++) { if (unsafeWindow.arr_ids[i]) { avl++; } } if (avl === 0) { alert('歌都被删光了还听啥...'); return; } // 寻找空位 while (true) { if (unsafeWindow.arr_ids[now]) { H.log ('切换歌曲 :: ' + now.toString()); unsafeWindow.pu.utils(now); unsafeWindow.cur_sid = unsafeWindow.arr_ids[now]; unsafeWindow.playSongRight(); return; } now += t >= 0 ? 1 : -1; if (unsafeWindow.arr_ids.length <= now) { now = 0; } if (now < 0) { now = unsafeWindow.arr_ids.length; } } } }, unsafeWindow.pu, '.pu'); }); } }, /* Compiled from music.xiami.js */ { id: 'music.xiami', name: '虾米音乐', host: 'www.xiami.com', noSubHost: true, dl_icon: true, css: /* Resource: com.xiami.fm.css */ H.extract(function () { /* -- xiami FM player css .jx_dl { position: absolute; color: #ddd; right: 99px; width: 18px; height: 18px; font-size: 18px; transition: color .3s; } .jx_dl:hover { color: #aaa; } */}), onStart: function () { var that = this; H.hookRequire ('SEIYA', 'download', function (scriptName, _SEIYA, _download, songId) { document.dispatchEvent (new CustomEvent (scriptName + '-dlById', { detail: songId })); return true; }, H.scriptName); H.waitUntil ('KISSY.use', function () { unsafeExec (function (scriptName) { window.KISSY.use ('page/mods/player', function (_KISSY, mPlayer) { var _setMusicInfo = mPlayer.prototype.setMusicInfo; mPlayer.prototype.setMusicInfo = function (songObj) { this.isVIP = true; document.dispatchEvent (new CustomEvent (scriptName + '-dlByObj', { detail: JSON.parse (songObj) })); return _setMusicInfo.apply (this, arguments); }; }); }, H.scriptName); }); document.addEventListener (H.scriptName + '-dlById', function (e) { that.fetch (e.detail, function (songObj) { GM_openInTab ( H.uri (songObj.src, songObj.title + '[' + songObj.artist + ']' + '.mp3'), false ); }); }, false); that.dlBtn = $('<a>') .addClass (H.defaultDlIcon) .attr('title', '等待获取音乐信息…'); document.addEventListener (H.scriptName + '-dlByObj', function (e) { var songObj = e.detail; that.dlBtn .attr ('href', H.uri (that.decrypt ( songObj.url ), songObj.song + '[' + songObj.artist + ']' + '.mp3')) .attr ('title', '下载: ' + songObj.song + ' [by ' + songObj.artist + ']'); }, false); }, onBody: function () { H.waitUntil (function () { return $('#J_trackFav').length; }, function () { this.dlBtn.insertBefore ($('#J_trackFav')); }.bind (this)); }, fetch: function (songId, callback) { if (!callback || !callback.call) return ; var that = this; $.ajax({ type: 'GET', url: '/song/playlist/id/' + songId + '/object_name/default/object_id/0', cache: true, dataType: 'xml' }).success (function (xmlDoc) { var songObj = {}; [].forEach.call (xmlDoc.getElementsByTagName ('track')[0].children, function (e) { // console.log ('%s => %s', e.tagName, e.textContent); songObj[e.tagName] = e.textContent; }); songObj.src = that.decrypt (songObj.location); callback ( songObj ); }); }, decrypt: function (encryptedAddress) { var spliter = parseInt(encryptedAddress[0]), link = encryptedAddress.slice(1), remainder = link.length % spliter, tmp = 0, ret = '', arr = []; for (var i = 0; i < spliter; i++) { arr.push ((remainder > i ? 1 : 0) + (link.length - remainder) / spliter); } for (i = 0; i < arr[1]; i++, tmp = 0) { for (var j = 0; j < spliter; j++) { ret += link[tmp + i]; tmp += arr[j]; } } return unescape(ret.substr(0, link.length)).replace(/\^/g, '0').replace(/\+/g, ' '); } }, /* Compiled from music.yinyuetai.js */ { id: 'music.yinyuetai', name: '音悦台下载解析', host: ['yinyuetai.com'], _linkHolder: null, onBody: function () { if (H.beginWith (location.pathname, '/video/')) { this._linkHolder = $('<span>').css ({ color: 'white', fontSize: 'small', marginLeft: '1.5em' }).appendTo ($('.vchart, .pl_title').first()); this.fetch(location.pathname.match(/\d+/)); } else { H.waitUntil (function () { return $('.J_video_info').length; }, this.procListPage.bind (this)); } }, procListPage: function () { H.info ('就绪.'); var mo = new MutationObserver (function () { H.info ('MV 已更新, 抓取新的下载地址..'); this._linkHolder = $('<p>').prependTo ('.J_mv_content'); this.fetch($('.J_video_info > a').attr('href').match (/\d+/)); }.bind (this)); mo.observe (document.querySelector('.J_video_info'), { childList: true }); }, fetch: function (videoId) { var that = this; GM_xmlhttpRequest ({ method: 'GET', url: 'http://www.yinyuetai.com/insite/get-video-info?json=true&videoId=' + videoId, onload: function (u) { try { var r = JSON.parse (u.responseText); } catch (e) { that._linkHolder.text('解析失败:数据格式错误。'); return ; } if (r.error) { that._linkHolder.text('解析失败:' + r.message); return ; } H.info ('解析完毕, 加入下载地址..'); that.addDownload (r.videoInfo.coreVideoInfo); }, onerror: function (r) { that._linkHolder.text('很抱歉, 解析下载地址失败..'); } }); }, addDownload: function (videoInfo) { this._linkHolder.text('下载: '); var rawLinks = videoInfo.videoUrlModels; for (var i = rawLinks.length; i--; ) { $('<a>').text(rawLinks[i].QualityLevelName) // TODO fix the name .attr('href', H.uri( rawLinks[i].videoUrl, H.sprintf('%s [%s][%s]%s', videoInfo.videoName, videoInfo.artistName, rawLinks[i].QualityLevelName, H.getLinkExt(rawLinks[i].videoUrl)) )) .attr('title', '下载: ' + videoInfo.videoName).appendTo(this._linkHolder) .addClass ('c_cf9'); this._linkHolder.append(' | '); } this._linkHolder.append(H.sprintf ('提供: %s %s ', H.scriptName, H.version)); } }, /* Compiled from phpdisk.a.js */ { id: 'phpdisk.a', name: '通用 phpDisk.a 网盘规则', // 相关规则: 跳转 /file-xxx -> /download.php?id=xxx&key=xxx host: [ '79pan.com', '7mv.cc', 'pan.52zz.org', '258pan.com', 'huimeiku.com', 'wpan.cc' ], hide: ['#code_box', '#down_box2', '#codefrm', '.ad', '[class^="banner"]'], show: '#down_box', onStart: function () { unsafeOverwriteFunctionSafeProxy ({ open: tFunc }); }, onBody: function () { H.waitUntil ('down_file_link', function () { // 避免地址被覆盖 unsafeWindow.update_sec = null; // 强制显示地址 unsafeWindow.down_file_link (); // 强制显示下载地址 if (unsafeWindow.show_down_url) unsafeWindow.show_down_url ('down_a1'); var jumpUrl = $('#down_link').find('a').attr('href'); // 然后跳过去 if (jumpUrl) { H.reDirWithRef (jumpUrl); } else { alert (H.sprintf('[%s]: 应用 %s 失败:\n找不到跳转地址.', H.scriptName, this.name)); } }); } }, /* Compiled from phpdisk.z.js */ { id: 'phpdisk.z', name: '通用 phpDisk.z 网盘规则', // 规则: 直接跳转 /file-xxx -> /down-xxx // 并隐藏 down_box2, 显示 down_box host: [ 'azpan.com', 'gxdisk.com', '2kuai.com', '1wp.me', '77pan.cc', 'vvpan.com', 'fmdisk.com', 'bx0635.com', '10pan.cc' ], hide: [ // azpan, gxdisk '.Downpagebox', '.talk_show', '.banner_2', '.w_305', // 2kuai.com '.ad', '#vcode', '#tui', '.dcode', '#down_box2', '#dl_tips', '.nal', '.scbar_hot_td', '#incode' ], show: [ // 2kuai.com '#down_box', '#dl_addr' ], onStart: function () { unsafeDefineFunction ('down_process', tFunc); H.phpDiskAutoRedir (); } } ]; if (H.config.bUseCustomRules) { try { [].splice.apply (sites, [0, 0].concat(eval (H.sprintf('[%s\n]', H.config.sCustomRule)))); } catch (e) { H.info ('解析自定义规则时发生错误: %s', e.message); } } var handleSite = (function () { // 扩展规则函数 H.rule = { checkPath: function (path, rule) { if (rule instanceof Array) { if (rule.length == 0) return false; for (var i = rule.length; i--; ) { if (this.checkPath(path, rule[i])) return true; } return false; } return ( // Function (rule.call && rule(path)) // String || (typeof rule == 'string' && H.beginWith (path, rule)) // Regex match || (rule instanceof RegExp && rule.test (path)) // Failed to match anything :< || false ); }, check: function (site, eve) { for (var i = 5; i--; ) { if (typeof eve == 'string') { eve = site[eve]; } else { break; } } if (typeof eve == 'string') { H.error ('Repetitive ' + event + ' handler (' + eve + '), skip ..'); eve = null; return ; } // Make this to an array. if (typeof site.host == 'string') site.host = [ site.host ]; // Should have at least one site setup. if (!site.host.length) { H.error ('RULE: key `host` is missing!'); return ; } // 检查域名 var hostMatch; if (!H.contains (site.host, H.lowerHost)) { // 是否检查子域名? if (site.noSubHost) return ; host = H.lowerHost; while (hostMatch = host.match (/^.+?\.(.+)/)) { if (H.contains (site.host, host = hostMatch[1])) { break; } } // No matching host name if (!hostMatch) return; } // 检查路径 if (site.path && !this.checkPath(location.pathname, site.path)) { return ; } return true; }, run: function (site, event) { if (!site || !event) return ; var eve = site[event]; if (site._styleApplied) // 修正 CSS 可能被覆盖的错误 H.fixStyleOrder (site.styleBlock); if (!site._styleApplied) { site._styleApplied = true; H.log ('应用 [%s] 的样式表…', site.name || '无名'); var styleBlock = H.injectStyle (); if (typeof site.hide == 'string') H.forceHide.call (styleBlock, site.hide); else if (site.hide && site.hide.length) H.forceHide.apply (styleBlock, site.hide); if (typeof site.show == 'string') H.forceShow.call (styleBlock, site.show); else if (site.show && site.show.length) H.forceShow.apply (styleBlock, site.show); // 自定义 css 注入 if (typeof site.css == 'string') H.injectStyle.call (styleBlock, site.css); else if (site.css && site.css.length) H.injectStyle.apply (styleBlock, site.css); // 下载按钮 if (site.dl_icon) { if (site.dl_icon.map) { site.dl_icon = site.dl_icon.join ('::before, '); } else if (typeof site.dl_icon != 'string') { site.dl_icon = H.defaultDlClass; } H.injectStyle.call (styleBlock, H.sprintf(/* Resource: AA.dl_btn.css */ H.extract(function () { /* @font-face { font-family: ccc; src: url(https://cdn.bootcss.com/font-awesome/4.2.0/fonts/fontawesome-webfont.woff) format('woff'); font-weight: normal; font-style: normal; } %s::before { font-family: ccc; content: "\f019"; padding-right: .5em; } .jx_hide { display: none; } */}), site.dl_icon)); } site.styleBlock = styleBlock; } if (!eve) return ; H.info ('执行规则: %s<ID: %s>[事件: %s]', site.name || '<未知>', site.id || '未知', event); return eve.call (site); }, /** * get rule by ID * @param {String} id Rule id * @return {Rule} Rule Object */ get: function (id) { return sites.filter(function (site) { return site.id == id; }).pop(); }, exec: function (id, event) { return this.run(this.get(id), event); } }; return function (event) { for (var i = sites.length; i--; ) { if (H.isFrame && sites[i].noFrame) continue; if (H.rule.check(sites[i], event) && H.rule.run(sites[i], event)) return true; } }; })(); try { GM_registerMenuCommand (H.sprintf('配置 %s[%s]', H.scriptName, H.version), function () { GM_openInTab('https://jixunmoe.github.io/cuwcl4c/config/', false); }); H.log ('onStart 准备阶段 :: 开始'); handleSite ('onStart'); H.log ('onStart 准备阶段 :: 结束'); document.addEventListener ('DOMContentLoaded', function () { H.log ('onBody 阶段 :: 开始'); handleSite ('onBody'); H.log ('onBody 阶段 :: 结束'); }, false); } catch (e) { if (e.isExit) { H.log.apply ( 0, [].concat.apply ( ['脚本退出, 错误信息'], e.message ) ); } else { H.error ('请务必将下述错误追踪代码提交至 %s\n\n%s', H.reportUrl, e.message); } } }) ();
// @flow import { css } from 'styled-components'; import { hover } from '../../utils/hover'; import { sassRgba } from '../../utils/sassRgba'; export function buttonOutlineVariant( color: string, colorHover: string = '#fff' ) { return css` color: ${color}; background-color: transparent; background-image: none; border-color: ${color}; ${hover(css` color: ${colorHover}; background-color: ${color}; border-color: ${color}; `)}; &:focus, &.focus { box-shadow: 0 0 0 3px ${sassRgba(color, 0.5)}; } &.disabled, &:disabled { color: ${color}; background-color: transparent; } &:active, &.active, .show > &.dropdown-toggle { color: ${colorHover}; background-color: ${color}; border-color: ${color}; } `; } export default buttonOutlineVariant;
//>>excludeStart("norequireExclude", pragmas.norequireExclude); require(['debuggify.logger', 'transports/console']); //>>excludeEnd("norequireExclude");
'use strict'; describe('Controller: AppCtrl', function () { // load the controller's module beforeEach(module('fraudGuiApp')); var MainCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCtrl = $controller('MainCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
/** * Copyright (C) 2012 Jonathan Scott * 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. */ /** * Environment setups */ module.exports = function(app, express){ app.configure(function() { app.use(express.logger()); }); app.configure('development', function() { app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function() { app.use(express.errorHandler()); }); };
function FieldAuditor(opts){ var self = this; //Form that has inputs to track in it; will also be where the tracking inputs will be appended self.formName = opts["formName"]; if (!self.formName) { throw "FieldAuditor: formName option must be specified"; } //Selector to determine what types of inputs to track self.inputSelector = opts["inputSelector"] || "input[type='text'], input[type='checkbox'], input[type='radio'], select, textarea"; //This is what the input(s) will be named that track changes self.changesName = opts["changesName"] || "changes[]"; self.form = $(self.formName); self.affectedElements = self.form.find(self.inputSelector); self.affectedElements.each(function(){ $(this).attr('data-original', $(this).val()); }); self.affectedElements.on("change", function(){ var changeId = $(this).attr("id") + "_change"; $(changeId).remove(); var changeVal = JSON.stringify({ "old_value" : $(this).attr("data-original"), "new_value" : $(this).val(), "name" : $(this).attr("name") }); self.form.append("<input name='" + self.changesName + "' type='hidden' id='" + changeId + "' value='" + changeVal + "'>"); }); }
import React, { Component, PropTypes } from 'react'; import parsePath from 'history/lib/parsePath'; import Location from '../../core/Location'; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } class Link extends Component { static propTypes = { to: PropTypes.string.isRequired, query: PropTypes.object, state: PropTypes.object, onClick: PropTypes.func, }; static handleClick = (event) => { let allowTransition = true; let clickResult; if (this.props && this.props.onClick) { clickResult = this.props.onClick(event); } if (isModifiedEvent(event) || !isLeftClickEvent(event)) { return; } if (clickResult === false || event.defaultPrevented === true) { allowTransition = false; } // bootstrap navbar-collapse if ($('.navbar-collapse')) $('.navbar-collapse').collapse('hide'); event.preventDefault(); if (allowTransition) { const link = event.currentTarget; if (this.props && this.props.to) { Location.push({ ...(parsePath(this.props.to)), state: this.props && this.props.state || null, }); } else { Location.push({ pathname: link.pathname, search: link.search, state: this.props && this.props.state || null, }); } } }; render() { const { to, query, ...props } = this.props; return <a href={Location.createHref(to, query)} onClick={Link.handleClick.bind(this)} {...props} />; } } export default Link;
"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: "M19 9h-1V4H8v5h-.78C6.67 8.39 5.89 8 5 8c-1.66 0-3 1.34-3 3v7c0 1.66 1.34 3 3 3 .89 0 1.67-.39 2.22-1H22v-8c0-1.66-1.34-3-3-3zM6 18c0 .55-.45 1-1 1s-1-.45-1-1v-7c0-.55.45-1 1-1s1 .45 1 1v7zm4-12h6v3h-6V6zm10 12H8v-7h11c.55 0 1 .45 1 1v6z" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "15", cy: "13", r: "1" }, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "18", cy: "13", r: "1" }, "2"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "15", cy: "16", r: "1" }, "3"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", { cx: "18", cy: "16", r: "1" }, "4"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M9 12h4v5H9z" }, "5")], 'FaxOutlined'); exports.default = _default;
/*global console*/ var AutoCompleteView = require('../ampersand-autocomplete-view'); var FormView = require('ampersand-form-view'); var Model = require('ampersand-state').extend({ props: { mbid: 'string', name: 'string', listeners: 'string' }, derived: { id: function() { return this.name; } } }); var Collection = require('ampersand-rest-collection').extend({ model: Model, url: 'http://ws.audioscrobbler.com/2.0/?method=artist.search&api_key=cef6d600c717ecadfbe965380c9bac8b&format=json', parse: function(response, options) { if (response.results) { return response.results.artistmatches.artist; } } }); /* var collection = new Collection([ { id: 'red', title: 'Red' }, { id: 'yellow', title: 'Yellow' }, { id: 'blue', title: 'Blue' }, { id: 'rat', title: 'Rat' } ]); */ var BaseView = FormView.extend({ fields: function () { return [ new AutoCompleteView({ name: 'autocomplete', parent: this, options: new Collection(), queryKey: 'artist', idAttribute: 'name', textAttribute: 'name', placeHolder: 'Please choose one', minKeywordLength: 3, maxResults: 10 }) ]; } }); document.addEventListener('DOMContentLoaded', function () { var baseView = new BaseView({el: document.body }); baseView.on('all', function (name, field) { console.log('Got event', name, field.value, field.valid); }); baseView.render(); });
/** * Fable Settings - Zookeeper Add-on * * @license MIT * * @author Jason Hillier <jason@hillier.us> * @module Fable Settings Zookeeper */ var libZookeeper = require('node-zookeeper-client'); var libAsync = require('async'); var libDeasync = require('deasync'); var CONNECTION_TIMEOUT = 1500; var FableSettingsZookeeper = function() { var tmpFableSettingsZookeeper = ( { // Connect to a zookeeper server, handle connection timeout _connectToServer: function(pServer, fCallback) { var client = libZookeeper.createClient(pServer); var tmpConnected = false; setTimeout(function() { if (!tmpConnected) { client.close(); return fCallback('Timeout trying to connect!'); } }, CONNECTION_TIMEOUT); client.once('connected', function() { tmpConnected = true; return fCallback(null, client); }); client.connect(); }, storeSettingsToServer: function(pServer, pKey, pSettings, fCallback) { tmpFableSettingsZookeeper._connectToServer(pServer, function(err, client) { if (err) return fCallback(err); client.exists(pKey, function(err, stat) { if (err) return fCallback(err); var tmpSettingsData = JSON.stringify(pSettings); if (stat) { client.setData(pKey, new Buffer(tmpSettingsData), fCallback); } else { client.mkdirp(pKey, function(err, path) { if (err) return fCallback(err); client.setData(pKey, new Buffer(tmpSettingsData), fCallback); }); } }); }); }, // Connect to zookeeper, load data for key on server loadSettingsFromServer: function(pServer, pKey, fCallback) { tmpFableSettingsZookeeper._connectToServer(pServer, function(err, client) { if (err) return fCallback(err); //console.log('connected to zookeeper'); client.getData(pKey, function(err, data, stat) { if (err) return fCallback(err); var tmpErr = null; var tmpData = null; try { tmpData = JSON.parse(data.toString('utf8')); } catch (ex) { tmpErr = ex; } return fCallback(tmpErr, tmpData); }); }); }, // Connect to zookeeper ensemble (failover to each server in list), perform action for key in url // e.g. zk://10.20.30.10:2181,10.20.30.11:2181/testdemo _executeMethodForUrl: function(pUrl, fMethod, fCallback) { var matches = pUrl.match(/zk:\/\/([^\/]+)\/([^:]+)/); var servers = matches[1]; var key = '/' + matches[2]; var serverList = servers.split(','); //try each server in list until we get data var tmpLastError = null; libAsync.eachSeries(serverList, function(pServer, fNext) { fMethod(pServer, key, function(err, data) { if (err) { tmpLastError = err; } return fNext(data); }); }, function complete(data) { if (data) { return fCallback(null, data); } else { return fCallback(tmpLastError); } }); }, loadSettingsFromUrl: function(pUrl, fCallback) { return tmpFableSettingsZookeeper._executeMethodForUrl(pUrl, tmpFableSettingsZookeeper.loadSettingsFromServer, fCallback); }, storeSettingsToUrl: function(pUrl, pSettings, fCallback) { return tmpFableSettingsZookeeper._executeMethodForUrl( pUrl, function(pServer, pKey, fNext) { return tmpFableSettingsZookeeper.storeSettingsToServer(pServer, pKey, pSettings, fNext); }, fCallback); }, // Connect and load data from zookeeper synchronously loadSettingsFromUrlSync: function(pUrl) { var tmpErr = null; var tmpData = null; tmpFableSettingsZookeeper.loadSettingsFromUrl(pUrl, function(err, data) { tmpErr = err; tmpData = data; }); libDeasync.loopWhile(function() { return !tmpErr && !tmpData}); if (tmpErr) { console.error('Zookeeper client error:', tmpErr); return null; } else { return tmpData; } } }); return tmpFableSettingsZookeeper; }; module.exports = FableSettingsZookeeper();
/** * xdata公共接口 * @author levin * @version 1.0.0 * @module OXAPI * @class OXAPI.XData * @static */ (function($){ var p={},pub={},today = new Date(), maxDateRange = 62,//最大时间范围 maxDateCountPerTime = 10;//单次服务器请求的时间范围 /* * 获取日期字符串 * @method OXAPI.XData.getDateTimeStr * @param {Date} dObj Date instance * @param {Object} cfg formatting configuration * @example OXAPI.XData.getDateTimeStr(new Date(),{len:10}) */ pub.getDateTimeStr=function(dObj,cfg){ cfg=cfg||{}; cfg.len=cfg.len||19; cfg.dayDiff=cfg.dayDiff||0; if(cfg.dayDiff!==0){ dObj.setDate(dObj.getDate()+cfg.dayDiff); }; var o =[dObj.getFullYear()+'-',(dObj.getMonth()+1)], format = function(i){ return (i<10?('0'+i):i); }; o[1]=format(o[1])+'-'; o.push(format(dObj.getDate())); if(cfg.ignoreHMS){ o.push(" 00:00:00"); }else{ o.push(' '); tempObj = dObj.getHours(); o.push(format(dObj.getHours())+':'); o.push(format(dObj.getMinutes())+':'); o.push(format(dObj.getSeconds())); } return o.join('').substr(0,cfg.len); }; p.clickstream = { query : function(_type,_params,_cbk){ var jqXHR=$.ajax({ type: "POST", url: 'http://statistic.yixun.com/json.php?mod=stat&act='+_type, data: _params, dataType: 'json' }).fail(function(jqXHR1,txtStatus,err){ _cbk(_type+':'+err); }).done(function(data,txtStatus,jqXHR1){ _cbk(null,data); }); return jqXHR; }, getRangeClickData : function(_params,cbk){ _params = $.extend({},{ uid:"6775494", start_date:pub.getDateTimeStr(today,{ignoreHMS:true}), end_date:pub.getDateTimeStr(today), date_type:"today", page_id:"1000", warehouse_id:"1", areasInfo:"S0001_1001", page_tag_ids:"-1", sumByDate:1 },_params||{}); return this.query('DragClickData',_params,cbk); } }; //ytag module p.ytag = { isLoading:false, hasAjaxError:false, jqXHR:null, data:{}, _getDataByDates:function(params0,cbk,maxDateCountPerTime){ maxDateCountPerTime = maxDateCountPerTime ||5; if(params0.dates.length==0){ cbk(null,this.data[params0.dateKey]); return; }; var tagids = params0.tagids, dateKey = params0.dateKey, dates1 = params0.dates.splice(0,maxDateCountPerTime), sdate = pub.getDateTimeStr(dates1[0]), edate = pub.getDateTimeStr(dates1[dates1.length-1]), _params = { page_id:params0.pid, warehouse_id:params0.wsid, areasInfo:params0.areaid, date_type:'custom', start_date:sdate, end_date:edate, page_tag_ids:tagids.join(',') }, me = this, tempItem,tempDate; this.jqXHR=p.clickstream.getRangeClickData(_params,function(err,d){ err = err || ( (d&&d.status)?null:'DragClickData Request Error:'+ (d?d.errmsg:'') ); if (err){ me.hasAjaxError=true; cbk(err); return; } for(var c in d.data.data){ tempItem = d.data.data[c]; tempDate = new Date(c); tempDate = new Date(tempDate.getFullYear(),tempDate.getMonth(),tempDate.getDate()); tempItem.t = tempDate.getTime(); tempItem.click_trans_rate = (parseFloat(tempItem.click_trans_rate)||0); me.data[dateKey].push(tempItem); }; //递归 me._getDataByDates(params0,cbk,maxDateCountPerTime); }); }, loadData:function(params0,cbk){ var dates = [], dateRange1 = null; len = params0.dateArr.length; for(var i=0;i<len;i++){ dateRange1 = this._validateDateRange(params0.dateArr[i].sdate,params0.dateArr[i].edate) if (!dateRange1) { cbk('Parameter Error!Check your sdate & edate!'); return; }; dates.push(dateRange1); }; params0.dates = dates; var me = this; //reset data this.data={}; this._loadDateRangeData(params0,function(err,d){ cbk(err,d); }); }, //校验开始时间和结束时间 _validateDateRange:function(sdate,edate){ if(sdate==''||edate==''){ return false; }; var tempDate = null; sdate = new Date(sdate); edate = new Date(edate); if(sdate>edate){ tempDate = sdate; sdate=edate; edate=tempDate; }; //结束日期往后推一天 //Note:new Date('2013-10-01')和new Date(2013,9,1)是不等的哦,前者多了8个小时 edate.setDate(edate.getDate()+1); return ({sdate:sdate,edate:edate,id:(sdate.getTime()+'-'+edate.getTime())}); }, _loadDateRangeData:function(params0,cbk){ if(params0.dates.length===0){ cbk(null,this.data); return; }; var dateRangeObj = params0.dates.splice(0,1)[0]; if(this.isLoading&&this.jqXHR&& this.jqXHR.readyState != 4){ this.jqXHR.abort(); this.isLoading=false; } var me = this, sdate = dateRangeObj.sdate, edate = dateRangeObj.edate, dateKey = dateRangeObj.id, dates=[]; while(sdate<edate){ dates.push(new Date(sdate.getFullYear(),sdate.getMonth(),sdate.getDate())); sdate.setDate(sdate.getDate()+1); };//while if(dates.length>maxDateRange){ cbk("Date Range Overflow! The Max Date range is "+maxDateRange); return; } this.isLoading=true; this.hasAjaxError=false; this.data[dateKey]=[]; //从服务器取数据 //采用按maxDateCountPerTime天分割轮询查询的方式,提升查询性能 this._getDataByDates({ tagids:params0.tagids, pid:params0.pid,//pageid wsid:params0.wsid,//warehouse id areaid:params0.areaid, dates:dates, dateKey:dateKey },function(err,d){ me.isLoading=false; me.jqXHR=null; if(err){ cbk('Ajax Server Error:'+err.toString()); return; } me._loadDateRangeData(params0,cbk); },maxDateCountPerTime); } }; /* * 获取ytag数据 * @method OXAPI.XData.getYTagsData * @param {Object} params0 request parameters * @param {Function} cbk callback function cbk(err,data) * @example OXAPI.XData.getYTagsData({ tagids:['10001','10002'], pid:'1000',//pageid wsid:'1',//warehouse id areaid:'S0001_1001', dateArr:[{//支持同时查询多个时间段 sdate:'2013-10-01', edate:'2013-10-30' }] },function(err,d){ console.log('err',err); console.log('data',d); }) */ pub.getYTagsData = function(params0,cbk){ p.ytag.loadData(params0,cbk); }; window['OXAPI']=window['OXAPI']||{}; OXAPI.XData = pub; })(jQuery);
Ember.FEATURES["ember-testing-lazy-routing"] = true; App = Ember.Application.create({ rootElement: '#qunit-fixture' }); App.Router.map(function() { this.route('welcome'); }); App.setupForTesting(); module("Routing", { setup: function() { App.reset(); App.injectTestHelpers(); }, teardown: function() { window.analytics = null; } }); test("should not do anything when there is no analytics reference present", function() { visit("/"); visit("/welcome"); andThen(function() { ok(!window.analytics); }); }); test("should not do anything if window.analytics is not an object", function() { window.analytics = 1; visit("/"); visit("/welcome"); andThen(function() { ok(window.analytics); }); }); test("should trigger when a route changes", function() { var counter = 0; window.analytics = { page: function() { counter = counter + 1; } }; visit("/"); andThen(function() { equal(counter, 1); }); visit("/welcome"); andThen(function() { equal(counter, 2); }); }); test("should send the current url to segmentio", function() { window.analytics = { page: function(title) { equal(title, "/welcome"); } }; visit("/welcome"); });
/// AMPjs Javascript Library /// The MIT License (MIT) /// author Yoshihito Fujiwara /// source https://bitbucket.org/yoshihitofujiwara/ampjs /// Copyright (c) 2014 Yoshihito Fujiwara (function(root, AMP){ // 'use strict'; /*---------------------------------------------------------------------- @constructor ----------------------------------------------------------------------*/ /** * <h4>イベント</h4> * <p>イベントクラスの継承して使用出来ます<br> * メディエーターとしても使用すことも可能です<br> * <a href="../../demo/AMP.Events.html">DEMO</a></p> * * * @class AMP.Events * @extends AMP.BASE_CLASS * @constructor * @example * var events = new AMP.Events(); * * // on<br> * events.on('change', function(){...});<br> * events.on('change.type', typeCall);<br> * * // off<br> * events.off('change');<br> * events.off('change', funcName);<br> * events.off();<br> * * // tigger<br> * events.tigger('change');<br> * events.tigger('change.type'); */ function Events(){ /** * <h4>イベントリスナーを連想配列で格納します</h4> * * @private * @property _listeners * @type {Object} * @example * _listeners = { * attr : eventObj.attr, <br> * func : listener, <br> * context : context <br> * } */ this._listeners = {}; } // 基底クラスを継承 AMP.inherits(Events, AMP.BASE_CLASS); // prototype var p = Events.prototype; /*-------------------------------------------------------------------------- @property --------------------------------------------------------------------------*/ /** * <h4>バージョン情報</h4> * * @static * @property VERSION * @type {String} */ Events.VERSION = '2.0.2'; /** * <h4>クラス名</h4> * * @property className * @type {String} */ p.className = 'Events'; /*-------------------------------------------------------------------------- @method --------------------------------------------------------------------------*/ /** * <h4>イベント登録</h4> * <p>イベント名に属性名を付与するも可能</p> * * @method on * @param {String} type イベントタイプ * @param {Function} listener イベントリスナー * @param {Object} context コンテキスト * @return {Events} */ p.on = function(type, listener, context){ this._addEvent(type, listener, context); return this; }; /** * <h4>1度だけ実行するイベント登録</h4> * * @method onece * @param {String} type イベントタイプ * @param {Function} listener イベントリスナー * @param {Object} context コンテキスト * @return {Events} */ p.onece = function(type, listener, context){ var self = this; self.on(type, function(){ self.off(type); listener.apply(self, arguments); }, context); return this; }; /** * <h4>イベント削除</h4> * * @method off * @param {String} type イベントタイプ * @param {Function} listener イベントリスナー * @return {Events} */ p.off = function(type, listener){ this._removeEvent(type, listener); return this; }; /** * <h4>イベント追加</h4> * * @private * @method _addEvent * @param {String} type イベントタイプ * @param {Function} listener コールバック関数 * @param {Object} context コンテキスト * @return {Void} */ p._addEvent = function(type, listener, context){ var self = this, events = type.split(' '); // listenerが関数かチェック if(AMP.isFunction(listener)){ AMP.each(events, function(item){ var eventObj = self._getEventNameMap(item); self._listeners[eventObj.type] = self._listeners[eventObj.type] || []; self._listeners[eventObj.type].push({ attr : eventObj.attr, func : listener, context: context }); }); } }; /** * <h4>イベント削除</h4> * FIXME: 内部処理最適化予定 * * @private * @method _removeEvent * @param {String} type イベントタイプ * @param {Function} listener コールバック関数 * @return {Void} */ p._removeEvent = function(type, listener){ var self = this, events = type ? type.split(' ') : [], ary = null, listeners; listener = AMP.getFunctionName(listener); AMP.each(events, function(event){ var eventObj = self._getEventNameMap(event); // イベント属性指定がある場合 if(eventObj && eventObj.attr && self._listeners[eventObj.type]){ listeners = self._listeners[eventObj.type]; AMP.each(listeners, function(item){ if(item.attr !== eventObj.attr){ if(listener){ if(listener !== AMP.getFunctionName(item.func)){ ary = ary || []; ary.push(item); } } else { ary = ary || []; ary.push(item); } } }); self._listeners[eventObj.type] = ary; // イベントタイプ指定ある場合 } else if(eventObj){ if(listener){ listeners = self._listeners[eventObj.type]; AMP.each(listeners, function(item){ if(listener !== AMP.getFunctionName(item.func)){ ary = ary || []; ary.push(item); } }); } self._listeners[eventObj.type] = ary; // イベント全て削除 } else { self._listeners = null; self._listeners = {}; } }); }; /** * <h4>イベント名、イベント属性を連想配列にして返す</h4> * * @private * @method _getEventNameMap * @param {String} type イベントタイプ * @return {Object} */ p._getEventNameMap = function(type){ var events = type.split('.'); return { type: events[0], attr: events[1] }; }; /** * <h4>登録イベントがあるか判定します</h4> * * @method hasEvent * @param {String} type イベントタイプ * @return {Boolean} */ p.hasEvent = function(type){ var flag = false, events = this._getEventNameMap(type), listeners = this._listeners[events.type]; // イベントリスナーの有無 if(listeners){ // 属性指定がある場合 if(events.attr){ AMP.each(listeners, function(item){ if(item.attr === events.attr){ flag = true; return false; } }); } else { flag = true; } } return flag; }; /** * <h4>イベント発行</h4> * <p>第二引数以降に値を渡すとcallbackに引数として渡します</p> * * @method trigger * @param {String} type イベントタイプ * @return {Events} */ p.trigger = function(type){ var self = this, events = this._getEventNameMap(type), listeners = this._listeners[events.type], args = AMP.argsToArray(arguments, 1); if(listeners){ AMP.each(listeners, function(item){ if(!events.attr || item.attr === events.attr){ item.func.apply(item.context, args); } }); } return self; }; /*-------------------------------------------------------------------------- export --------------------------------------------------------------------------*/ AMP.Events = Events; }(window, AMP));
(function() { var ACCESSOR, CoffeeScript, Module, REPL_PROMPT, REPL_PROMPT_CONTINUATION, SIMPLEVAR, Script, autocomplete, backlog, completeAttribute, completeVariable, enableColours, error, getCompletions, inspect, readline, repl, run, stdin, stdout; CoffeeScript = require('./coffee-script'); readline = require('readline'); inspect = require('util').inspect; Script = require('vm').Script; Module = require('module'); REPL_PROMPT = 'coffee> '; REPL_PROMPT_CONTINUATION = '......> '; enableColours = false; if (process.platform !== 'win32') { enableColours = !process.env.NODE_DISABLE_COLORS; } stdin = process.openStdin(); stdout = process.stdout; error = function(err) { return stdout.write((err.stack || err.toString()) + '\n'); }; backlog = ''; run = function(buffer) { var code, returnValue, _; if (!buffer.toString().trim() && !backlog) { repl.prompt(); return; } code = backlog += buffer; if (code[code.length - 1] === '\\') { backlog = "" + backlog.slice(0, -1) + "\n"; repl.setPrompt(REPL_PROMPT_CONTINUATION); repl.prompt(); return; } repl.setPrompt(REPL_PROMPT); backlog = ''; try { _ = global._; returnValue = CoffeeScript.eval("_=(" + code + "\n)", { filename: 'repl', modulename: 'repl' }); if (returnValue === void 0) { global._ = _; } else { process.stdout.write(inspect(returnValue, false, 2, enableColours) + '\n'); } } catch (err) { error(err); } return repl.prompt(); }; ACCESSOR = /\s*([\w\.]+)(?:\.(\w*))$/; SIMPLEVAR = /\s*(\w*)$/i; autocomplete = function(text) { return completeAttribute(text) || completeVariable(text) || [[], text]; }; completeAttribute = function(text) { var all, completions, match, obj, prefix, val; if (match = text.match(ACCESSOR)) { all = match[0], obj = match[1], prefix = match[2]; try { val = Script.runInThisContext(obj); } catch (error) { return; } completions = getCompletions(prefix, Object.getOwnPropertyNames(val)); return [completions, prefix]; } }; completeVariable = function(text) { var completions, free, keywords, possibilities, r, vars, _ref; free = (_ref = text.match(SIMPLEVAR)) != null ? _ref[1] : void 0; if (free != null) { vars = Script.runInThisContext('Object.getOwnPropertyNames(this)'); keywords = (function() { var _i, _len, _ref2, _results; _ref2 = CoffeeScript.RESERVED; _results = []; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { r = _ref2[_i]; if (r.slice(0, 2) !== '__') _results.push(r); } return _results; })(); possibilities = vars.concat(keywords); completions = getCompletions(free, possibilities); return [completions, free]; } }; getCompletions = function(prefix, candidates) { var el, _i, _len, _results; _results = []; for (_i = 0, _len = candidates.length; _i < _len; _i++) { el = candidates[_i]; if (el.indexOf(prefix) === 0) _results.push(el); } return _results; }; process.on('uncaughtException', error); if (readline.createInterface.length < 3) { repl = readline.createInterface(stdin, autocomplete); stdin.on('data', function(buffer) { return repl.write(buffer); }); } else { repl = readline.createInterface(stdin, stdout, autocomplete); } repl.on('attemptClose', function() { if (backlog) { backlog = ''; process.stdout.write('\n'); repl.setPrompt(REPL_PROMPT); return repl.prompt(); } else { return repl.close(); } }); repl.on('close', function() { process.stdout.write('\n'); return stdin.destroy(); }); repl.on('line', run); repl.setPrompt(REPL_PROMPT); repl.prompt(); }).call(this);
import React from 'react' import { observer } from 'mobx-react' import styles from './DrawerLabel.css' const DrawerLabel = ({ name, value, edittable }) => ( <div class={styles.root}> <div class={styles.name}>{name}</div> <div class={styles.value}>{value}</div> </div> ) export default observer(DrawerLabel)
var appSettings = require('../settings/app.json'); module.exports = { options: { dest: appSettings.dir.dist }, html: <% if(this.includeJade) { %> appSettings.dir.dist + '/index.html' <% } else { %> appSettings.dir.app + '/index.html' <% } %> };
import React from 'react'; export default () => fn(survey => { return <div />; });
/** * Created by llan on 2017/5/15. */ (function ($) { $('#my-slider').sliderPro({ width: '100%', height: 500, autoplay: true, buttons: false, arrows: true }); })(jQuery);
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("specialchar","nl",{euro:"Euro-teken",lsquo:"Linker enkel aanhalingsteken",rsquo:"Rechter enkel aanhalingsteken",ldquo:"Linker dubbel aanhalingsteken",rdquo:"Rechter dubbel aanhalingsteken",ndash:"En dash",mdash:"Em dash",iexcl:"Omgekeerd uitroepteken",cent:"Cent-teken",pound:"Pond-teken",curren:"Valuta-teken",yen:"Yen-teken",brvbar:"Gebroken streep",sect:"Paragraaf-teken",uml:"Trema",copy:"Copyright-teken",ordf:"Vrouwelijk ordinaal",laquo:"Linker guillemet",not:"Ongelijk-teken", reg:"Geregistreerd handelsmerk-teken",macr:"Macron",deg:"Graden-teken",sup2:"Superscript twee",sup3:"Superscript drie",acute:"Accent aigu",micro:"Micro-teken",para:"Alinea-teken",middot:"Halfhoge punt",cedil:"Cedille",sup1:"Superscript een",ordm:"Mannelijk ordinaal",raquo:"Rechter guillemet",frac14:"Breuk kwart",frac12:"Breuk half",frac34:"Breuk driekwart",iquest:"Omgekeerd vraagteken",Agrave:"Latijnse hoofdletter A met een accent grave",Aacute:"Latijnse hoofdletter A met een accent aigu",Acirc:"Latijnse hoofdletter A met een circonflexe", Atilde:"Latijnse hoofdletter A met een tilde",Auml:"Latijnse hoofdletter A met een trema",Aring:"Latijnse hoofdletter A met een corona",AElig:"Latijnse hoofdletter Æ",Ccedil:"Latijnse hoofdletter C met een cedille",Egrave:"Latijnse hoofdletter E met een accent grave",Eacute:"Latijnse hoofdletter E met een accent aigu",Ecirc:"Latijnse hoofdletter E met een circonflexe",Euml:"Latijnse hoofdletter E met een trema",Igrave:"Latijnse hoofdletter I met een accent grave",Iacute:"Latijnse hoofdletter I met een accent aigu", Icirc:"Latijnse hoofdletter I met een circonflexe",Iuml:"Latijnse hoofdletter I met een trema",ETH:"Latijnse hoofdletter Eth",Ntilde:"Latijnse hoofdletter N met een tilde",Ograve:"Latijnse hoofdletter O met een accent grave",Oacute:"Latijnse hoofdletter O met een accent aigu",Ocirc:"Latijnse hoofdletter O met een circonflexe",Otilde:"Latijnse hoofdletter O met een tilde",Ouml:"Latijnse hoofdletter O met een trema",times:"Maal-teken",Oslash:"Latijnse hoofdletter O met een schuine streep",Ugrave:"Latijnse hoofdletter U met een accent grave", Uacute:"Latijnse hoofdletter U met een accent aigu",Ucirc:"Latijnse hoofdletter U met een circonflexe",Uuml:"Latijnse hoofdletter U met een trema",Yacute:"Latijnse hoofdletter Y met een accent aigu",THORN:"Latijnse hoofdletter Thorn",szlig:"Latijnse kleine ringel-s",agrave:"Latijnse kleine letter a met een accent grave",aacute:"Latijnse kleine letter a met een accent aigu",acirc:"Latijnse kleine letter a met een circonflexe",atilde:"Latijnse kleine letter a met een tilde",auml:"Latijnse kleine letter a met een trema", aring:"Latijnse kleine letter a met een corona",aelig:"Latijnse kleine letter æ",ccedil:"Latijnse kleine letter c met een cedille",egrave:"Latijnse kleine letter e met een accent grave",eacute:"Latijnse kleine letter e met een accent aigu",ecirc:"Latijnse kleine letter e met een circonflexe",euml:"Latijnse kleine letter e met een trema",igrave:"Latijnse kleine letter i met een accent grave",iacute:"Latijnse kleine letter i met een accent aigu",icirc:"Latijnse kleine letter i met een circonflexe", iuml:"Latijnse kleine letter i met een trema",eth:"Latijnse kleine letter eth",ntilde:"Latijnse kleine letter n met een tilde",ograve:"Latijnse kleine letter o met een accent grave",oacute:"Latijnse kleine letter o met een accent aigu",ocirc:"Latijnse kleine letter o met een circonflexe",otilde:"Latijnse kleine letter o met een tilde",ouml:"Latijnse kleine letter o met een trema",divide:"Deel-teken",oslash:"Latijnse kleine letter o met een schuine streep",ugrave:"Latijnse kleine letter u met een accent grave", uacute:"Latijnse kleine letter u met een accent aigu",ucirc:"Latijnse kleine letter u met een circonflexe",uuml:"Latijnse kleine letter u met een trema",yacute:"Latijnse kleine letter y met een accent aigu",thorn:"Latijnse kleine letter thorn",yuml:"Latijnse kleine letter y met een trema",OElig:"Latijnse hoofdletter Œ",oelig:"Latijnse kleine letter œ",372:"Latijnse hoofdletter W met een circonflexe",374:"Latijnse hoofdletter Y met een circonflexe",373:"Latijnse kleine letter w met een circonflexe", 375:"Latijnse kleine letter y met een circonflexe",sbquo:"Lage enkele aanhalingsteken",8219:"Hoge omgekeerde enkele aanhalingsteken",bdquo:"Lage dubbele aanhalingsteken",hellip:"Beletselteken",trade:"Trademark-teken",9658:"Zwarte driehoek naar rechts",bull:"Bullet",rarr:"Pijl naar rechts",rArr:"Dubbele pijl naar rechts",hArr:"Dubbele pijl naar links",diams:"Zwart ruitje",asymp:"Benaderingsteken"});
'use strict'; // MODULES // var betaincinv = require( 'compute-betaincinv/lib/ibeta_inv_imp.js' ); // QUANTILE // /** * FUNCTION: quantile( p, d1, d2 ) * Evaluates the quantile function for a F distribution with numerator degrees of freedom `d1` and denominator degrees of freedom `d2` at a probability `p`. * * @param {Number} p - input value * @param {Number} d1 - numerator degrees of freedom * @param {Number} d2 - denominator degrees of freedom * @returns {Number} evaluated quantile function */ function quantile( p, d1, d2 ) { var bVal, x1, x2; if ( p !== p || p < 0 || p > 1 ) { return NaN; } bVal = betaincinv( d1 / 2, d2 / 2, p, 1 - p ); x1 = bVal[ 0 ]; x2 = bVal[ 1 ]; return d2 * x1 / ( d1 * x2 ); } // end FUNCTION quantile() // EXPORTS // module.exports = quantile;
var PhotoStore = require('./photo'); var FilterStore = require('./filter'); var stores = { PhotoStore: new PhotoStore(), FilterStore: new FilterStore(), }; module.exports = stores;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ru_RU = require('gregorian-calendar-format/lib/locale/ru_RU'); var _ru_RU2 = _interopRequireDefault(_ru_RU); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { today: 'Сегодня', now: 'Сейчас', ok: 'Ok', clear: 'Очистить', month: 'Месяц', year: 'Год', monthSelect: 'Выберите месяц', yearSelect: 'Выберите год', decadeSelect: 'Выберите десятилетие', yearFormat: 'yyyy', dateFormat: 'd-M-yyyy', monthFormat: 'MMMM', monthBeforeYear: true, previousMonth: 'Предыдущий месяц (PageUp)', nextMonth: 'Следующий месяц (PageDown)', previousYear: 'Предыдущий год (Control + left)', nextYear: 'Следующий год (Control + right)', previousDecade: 'Предыдущее десятилетие', nextDecade: 'Следущее десятилетие', previousCentury: 'Предыдущий век', nextCentury: 'Следующий век', format: _ru_RU2.default }; module.exports = exports['default'];
jQuery(document).ready(function ($) { var options = { $AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false $AutoPlaySteps: 1, //[Optional] Steps to go for each navigation request (this options applys only when slideshow disabled), the default value is 1 $AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000 $PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1 $ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false $SlideDuration: 500, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500 $MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20 //$SlideWidth: 600, //[Optional] Width of every slide in pixels, default value is width of 'slides' container //$SlideHeight: 300, //[Optional] Height of every slide in pixels, default value is height of 'slides' container $SlideSpacing: 5, //[Optional] Space between each slide in pixels, default value is 0 $DisplayPieces: 1, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1 $ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0. $UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc). $PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1 $DragOrientation: 3, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0) $ThumbnailNavigatorOptions: { $Class: $JssorThumbnailNavigator$, //[Required] Class to create thumbnail navigator instance $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always $ActionMode: 1, //[Optional] 0 None, 1 act by click, 2 act by mouse hover, 3 both, default value is 1 $AutoCenter: 3, //[Optional] Auto center thumbnail items in the thumbnail navigator container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 3 $Lanes: 1, //[Optional] Specify lanes to arrange thumbnails, default value is 1 $SpacingX: 1, //[Optional] Horizontal space between each thumbnail in pixel, default value is 0 $SpacingY: 0, //[Optional] Vertical space between each thumbnail in pixel, default value is 0 $DisplayPieces: 5, //[Optional] Number of pieces to display, default value is 1 $ParkingPosition: 0, //[Optional] The offset position to park thumbnail $Orientation: 1, //[Optional] Orientation to arrange thumbnails, 1 horizental, 2 vertical, default value is 1 $DisableDrag: true //[Optional] Disable drag or not, default value is false } }; var jssor_slider1 = new $JssorSlider$("slider1_container", options); //responsive code begin //you can remove responsive code if you don't want the slider scales while window resizes function ScaleSlider() { var parentWidth = jssor_slider1.$Elmt.parentNode.clientWidth; if (parentWidth) { var sliderWidth = parentWidth; //keep the slider width no more than 600 sliderWidth = Math.min(sliderWidth, 600); jssor_slider1.$ScaleWidth(sliderWidth); } else window.setTimeout(ScaleSlider, 30); } ScaleSlider(); $(window).bind("load", ScaleSlider); $(window).bind("resize", ScaleSlider); $(window).bind("orientationchange", ScaleSlider); //responsive code end });
// Regular expression that matches all symbols in the `Nl` category as per Unicode v8.0.0: /[\u16EE-\u16F0\u2160-\u2182\u2185-\u2188\u3007\u3021-\u3029\u3038-\u303A\uA6E6-\uA6EF]|\uD809[\uDC00-\uDC6E]|\uD800[\uDD40-\uDD74\uDF41\uDF4A\uDFD1-\uDFD5]/;
/* 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.webgl.WebglFilterTypes", null, function(objectFunctions, staticFunctions, ClassReference) { //console.log("dbm.constants.webgl.WebglFilterTypes"); var WebglFilterTypes = dbm.importClass("dbm.constants.webgl.WebglFilterTypes"); staticFunctions.NEAREST = 0x2600; staticFunctions.LINEAR = 0x2601; staticFunctions.NEAREST_MIPMAP_NEAREST = 0x2700; staticFunctions.LINEAR_MIPMAP_NEAREST = 0x2701; staticFunctions.NEAREST_MIPMAP_LINEAR = 0x2702; staticFunctions.LINEAR_MIPMAP_LINEAR = 0x2703; });
var $ = require('jquery'), analytics = require('ga-browser')(), tether = require('tether'), bootstrap = require('bootstrap'), UAParser = require('ua-parser-js'), autocomplete = require('jquery-autocomplete') var config = require('./config.js'); var exists = function(tag) { return $(tag).length > 0 } var makeFundraiserBody = function(data, limit) { var html = '<tr><th>Name</th><th>Amount</th></tr>'; limit = limit ? Math.min(data.length, limit) : data.length; for (var i = 0; i < limit; i++) { html += '<tr>'; html += '<td><a href="' + data[i].link + '">' + data[i].name + '</a></td>'; html += '<td>' + data[i].amount + '</td>'; html += '</tr>'; } return html; } $(function() { // GA tracking analytics('create', config.gaTrackingId, 'auto') analytics('send', 'pageview') var parser = new UAParser(), result = parser.getResult(), os = result.os.name, linkBase = 'http://maps.google.com?q='; if(os === 'iOS') { linkBase = 'maps:q='; } else if(os === 'Windows Phone' || os === 'Windows Mobile') { linkBase = 'maps:'; } var linkFull = linkBase + '701%20Ocean%20St,%20Santa%20Cruz,%20CA'; if(os=='RIM Tablet OS' || os=='BlackBerry') { linkFull = "javascript:blackberry.launch.newMap({'address':{'address1':'701 Ocean St','city':'Santa Cruz','country':'USA','stateProvince':'CA'}});"; } $('#map-link').attr('href', linkFull); if(exists('#top-individual-fundraisers')) { $.get('ws/top_fundraisers.php', function(data) { $('#top-individual-fundraisers').html(makeFundraiserBody(data.individuals, 5)); $('#top-team-fundraisers').html(makeFundraiserBody(data.teams, 5)); }); } if(exists('#fundraiser-search')) { $('#fundraiser-search').autocomplete({ source:[{ minLength: 3, url:'ws/fundraiser_search.php?q=%QUERY%', type:'remote' }], valueKey: 'name', titleKey: 'name' }).on('selected.xdsoft', function(e, datum){ window.location = datum.link; }); } })
/** * Open Payments Cloud Application API * Open Payments Cloud API * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient')); } else { // Browser globals (root is window) if (!root.OpenPaymentsCloudApplicationApi) { root.OpenPaymentsCloudApplicationApi = {}; } root.OpenPaymentsCloudApplicationApi.TransferProfile = factory(root.OpenPaymentsCloudApplicationApi.ApiClient); } }(this, function(ApiClient) { 'use strict'; /** * The TransferProfile model module. * @module model/TransferProfile * @version 1.1.0 */ /** * Constructs a new <code>TransferProfile</code>. * @alias module:model/TransferProfile * @class * @param programmeId {String} * @param id {String} * @param name {String} * @param creationTimestamp {String} */ var exports = function(programmeId, id, name, creationTimestamp) { var _this = this; _this['programmeId'] = programmeId; _this['id'] = id; _this['name'] = name; _this['creationTimestamp'] = creationTimestamp; }; /** * Constructs a <code>TransferProfile</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/TransferProfile} obj Optional instance to populate. * @return {module:model/TransferProfile} The populated <code>TransferProfile</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('programmeId')) { obj['programmeId'] = ApiClient.convertToType(data['programmeId'], 'String'); } if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'String'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); } if (data.hasOwnProperty('active')) { obj['active'] = ApiClient.convertToType(data['active'], 'Boolean'); } if (data.hasOwnProperty('tags')) { obj['tags'] = ApiClient.convertToType(data['tags'], ['String']); } if (data.hasOwnProperty('actions')) { obj['actions'] = ApiClient.convertToType(data['actions'], ['String']); } if (data.hasOwnProperty('creationTimestamp')) { obj['creationTimestamp'] = ApiClient.convertToType(data['creationTimestamp'], 'String'); } } return obj; } /** * @member {String} programmeId */ exports.prototype['programmeId'] = undefined; /** * @member {String} id */ exports.prototype['id'] = undefined; /** * @member {String} name */ exports.prototype['name'] = undefined; /** * The type of this profile, referring to the key of one of the types defined by the programme in its payment model. * @member {String} type */ exports.prototype['type'] = undefined; /** * @member {Boolean} active */ exports.prototype['active'] = undefined; /** * A set of labels that can be used by the application to group profiles together. * @member {Array.<String>} tags */ exports.prototype['tags'] = undefined; /** * The actions that can be performed on this particular resource instance. * @member {Array.<module:model/TransferProfile.ActionsEnum>} actions */ exports.prototype['actions'] = undefined; /** * @member {String} creationTimestamp */ exports.prototype['creationTimestamp'] = undefined; /** * Allowed values for the <code>actions</code> property. * @enum {String} * @readonly */ exports.ActionsEnum = { /** * value: "UPDATE" * @const */ "UPDATE": "UPDATE", /** * value: "ACTIVATE" * @const */ "ACTIVATE": "ACTIVATE", /** * value: "DEACTIVATE" * @const */ "DEACTIVATE": "DEACTIVATE" }; return exports; }));
export const breakpoints = { sm: 576, md: 786, lg: 992, xl: 1200, }; export const media = (key) => { return (style) => `@media (max-width: ${breakpoints[key]}px) { ${style} }`; };
/** * Application core * * exposes Module, Page and Widget. * * TODO: Provide pub/sub functionality * **/ requirejs.config({ baseUrl: '/', paths: { 'jquery': 'js/dependencies/jquery', 'underscore': 'js/dependencies/underscore', 'backbone': 'js/dependencies/backbone', 'bootstrap': 'js/dependencies/bootstrap', 'core': 'js/core' }, shim: { backbone: { deps: ['jquery', 'underscore'], exports: 'Backbone' } }, config: {}, packages: [{}] }); define([ 'js/module', 'js/page', 'js/widget' ], function( Module, Page, Widget ) { return { Module: Module, Page: Page, Widget: Widget }; });
Intranet.controller('PersonalOfficeChatController',['$http', '$scope', '$paginator', function($http, $scope, $paginator) { container = $('#conversation'); messageContainer = $('#write-message'); $scope.officesIdArray = DATA_ID.officesid; $scope.paginator = $paginator; $scope.postsPerPage = 10; $scope.paginator.postsPerPage = $scope.postsPerPage; $scope.posts = []; $scope.members = []; $scope.message = ''; $scope.editingPost = null; $scope.lastDate = null; $scope.avatarURL = JSON_URLS_FOR_PERSONAL_PAGE.avatar; $scope.postsOfficeGetURL = JSON_URLS_FOR_PERSONAL_PAGE.postsOffice; $scope.postOfficeAddURL = JSON_URLS_FOR_PERSONAL_PAGE.post_addOffice; $scope.membersOfficeURL = JSON_URLS_FOR_PERSONAL_PAGE.membersOffice; $scope.postsOfficeNewURL = JSON_URLS_FOR_PERSONAL_PAGE.posts_newOffice; $scope.postsOfficeCountURL = JSON_URLS_FOR_PERSONAL_PAGE.post_countOffice; $scope.posts = []; $scope.members = []; $scope.message = ''; $scope.editingPost = null; $scope.lastDate = null; $scope.$watch('paginator.curPageId', function(){ var offset = $scope.paginator.postsPerPage*($scope.paginator.curPageId - 1); var limit = $scope.paginator.postsPerPage; getOfficesPosts(offset, limit, $scope.officesIdArray); }); $scope.pressEnter = function(e) { if ((e.shiftKey == false) && ( e.keyCode == 13 )) { e.preventDefault(); $scope.sendPostOffice(); } } $scope.init = function (count ) { $scope.count = count; } function updatePosts(posts) { var editedMessages = _.filter(posts, function(p){return p.edited;}); if (editedMessages.length == posts.length) { _.map(posts, function(post){ _.map($scope.posts, function(p, i){ if (p.id == post.id) $scope.posts[i] = post; }); }); return true; } return false; } function getOfficesPosts(offset, limit) { var url = $scope.postsOfficeGetURL.replace('0', $scope.count); $http({ method: "GET", url: url, params: {offset: offset, limit: limit}}) .success(function(response){ if (response.result) { $scope.posts = response.result.reverse(); } if (response.result.length>0) { $scope.lastDate = (_.last($scope.posts)).posted.date; } container.animate({ scrollTop: container.height()+1900 },1000); }) } function getMembersForOffices() { _.map($scope.officesIdArray, function (officeId) { var url = $scope.membersOfficeURL.replace('0', $scope.count); $http({ method: "GET", url: url }) .success(function(response){ if (response.result) $scope.members = response.result; }) }) } function getPostsCountForOffice(callback) { var url = $scope.postsOfficeCountURL.replace('0', $scope.count); $http({ method: "GET", url: url }) .success(function(response){ if (response.result) callback(response.result); }) } function getNewPostsForOffice() { var url = $scope.postsOfficeNewURL.replace('0',$scope.count); if ($scope.paginator.curPageId == 1) { $http({ method: "GET", url: url, params: {last_posted: $scope.lastDate}}) .success(function(response){ if ((response.result) && (response.result.length > 0)) { var onlyUpdated = updatePosts(response.result); if (onlyUpdated == false) { getPostsCountForOffice(function(postsCount){ $scope.paginator.init(postsCount, $scope.postsPerPage); var offset = $scope.paginator.postsPerPage*($scope.paginator.curPageId - 1); var limit = $scope.paginator.postsPerPage; getOfficesPosts(offset, limit); getMembersForOffices(); }); } } }) } setInterval(getNewPostsForOffice, 3000); } $scope.editPost = function(post) { if ((!$scope.isEditable(post)) || ($scope.editingPost != null)) return; $scope.editingPost = post; messageContainer.val(post.message); } Date.minutesBetween = function( date1, date2 ) { var one_minute=1000*60; var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); var difference_ms = date2_ms - date1_ms; return Math.ceil(difference_ms/one_minute); } Date.milisecondsBetween = function( date1, date2 ) { var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); var difference_ms = date2_ms - date1_ms; return difference_ms; } Date.inMyString = function(date) { return date.getFullYear()+"-"+date.getMonth()+1+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(); } $scope.isEditable = function(post) { var postedTime = new Date(Date.parse(post.posted.date)); var now = new Date(); var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000); var minutesAgo = Date.minutesBetween(postedTime, utc); return (minutesAgo <= 5 && post.userid == $scope.userid); } $scope.sendPostOffice = function() { var post = { entityid: $scope.count, userid: window.USER.id, message: $scope.message, posted: new Date() } if ($scope.editingPost) post.postid = $scope.editingPost.id; var url = $scope.postOfficeAddURL.replace('0', $scope.count); $http({ method: "POST", url: url, data: post }) .success(function(response){ if (response.result) { // maybe need to request for posts and init paginator!!! if ($scope.editingPost == null) { $scope.posts.push(response.result); container.animate({ scrollTop: container.height()+1900 },1000); } else { _.map($scope.posts, function(p, i){ if (p.id == response.result.id) $scope.posts[i] = response.result; }); } } $scope.editingPost = null; $scope.message = ""; messageContainer.val(""); messageContainer.focus(); getMembersForOffices(); }) } $scope.changePostsPerPageOffice = function(){ getPostsCountForOffice(function(postsCount){ $scope.paginator.init(postsCount, $scope.postsPerPage); var offset = $scope.paginator.postsPerPage*($scope.paginator.curPageId - 1); var limit = $scope.paginator.postsPerPage; getOfficesPosts(offset, limit); }); } function startChat() { //console.log('start'); getMembersForOffices(); getPostsCountForOffice(function(postsCount){ $scope.paginator.init(postsCount, 100); }); setInterval(getNewPostsForOffice, 3000); } startChat(); }]); Intranet.controller('PersonalTopicChatController',['$http', '$scope', '$paginator', function($http, $scope, $paginator) { container = $('#conversation'); messageContainer = $('#write-message'); $scope.paginator = $paginator; $scope.postsPerPage = 10; $scope.paginator.postsPerPage = $scope.postsPerPage; $scope.posts = []; $scope.members = []; $scope.message = ''; $scope.editingPost = null; $scope.lastDate = null; $scope.avatarURL = JSON_URLS_FOR_PERSONAL_PAGE.avatar; $scope.postsTopicGetURL = JSON_URLS_FOR_PERSONAL_PAGE.postsTopic; $scope.postTopicAddURL = JSON_URLS_FOR_PERSONAL_PAGE.post_addTopic; $scope.membersTopicURL = JSON_URLS_FOR_PERSONAL_PAGE.membersTopic; $scope.postsTopicNewURL = JSON_URLS_FOR_PERSONAL_PAGE.posts_newTopic; $scope.postsTopicCountURL = JSON_URLS_FOR_PERSONAL_PAGE.post_countTopic; $scope.posts = []; $scope.members = []; $scope.message = ''; $scope.editingPost = null; $scope.lastDate = null; $scope.$watch('paginator.curPageId', function(){ var offset = $scope.paginator.postsPerPage*($scope.paginator.curPageId - 1); var limit = $scope.paginator.postsPerPage; getTopicsPosts(offset, limit, $scope.topicsArray); }); $scope.pressEnter = function(e) { if ((e.shiftKey == false) && ( e.keyCode == 13 )) { e.preventDefault(); $scope.sendPostTopic(); } } $scope.init = function (topicId ) { //console.log('Topic',topicId); $scope.topicId = topicId; } function updatePosts(posts) { var editedMessages = _.filter(posts, function(p){return p.edited;}); if (editedMessages.length == posts.length) { _.map(posts, function(post){ _.map($scope.posts, function(p, i){ if (p.id == post.id) $scope.posts[i] = post; }); }); return true; } return false; } function getTopicsPosts(offset, limit) { var url = $scope.postsTopicGetURL.replace('0', $scope.topicId); $http({ method: "GET", url: url, params: {offset: offset, limit: limit}}) .success(function(response){ //console.log("posts: ",response.result); if (response.result) { $scope.posts = response.result.reverse(); } if (response.result.length>0) { $scope.lastDate = (_.last($scope.posts)).posted.date; } container.animate({ scrollTop: container.height()+1900 },1000); }) } function getMembersForTopics() { var url = $scope.membersTopicURL.replace('0', $scope.topicId); $http({ method: "GET", url: url }) .success(function(response){ //console.log("members: ", response.result); if (response.result) $scope.members = response.result; }) } function getPostsCountForTopic(callback) { var url = $scope.postsTopicCountURL.replace('0', $scope.topicId); $http({ method: "GET", url: url }) .success(function(response){ //console.log("posts count: ", response.result); if (response.result) callback(response.result); }) } function getNewPostsForTopic(f) { if ($scope.paginator.curPageId == 1) { $http({ method: "GET", url: $scope.postsTopicNewURL.replace('0', $scope.topicId), params: {last_posted: $scope.lastDate}}) .success(function(response){ //console.log("new posts: ", response.result); if ((response.result) && (response.result.length > 0)) { var onlyUpdated = updatePosts(response.result); if (onlyUpdated == false) { getNewPostsForTopic(function(postsCount){ $scope.paginator.init(postsCount, $scope.postsPerPage); var offset = $scope.paginator.postsPerPage*($scope.paginator.curPageId - 1); var limit = $scope.paginator.postsPerPage; getPostsForTopics(offset, limit); getMembersForTopics(); }); } } }) } setInterval(getNewPostsForTopic, 3000); } $scope.editPost = function(post) { if ((!$scope.isEditable(post)) || ($scope.editingPost != null)) return; //console.log(post); $scope.editingPost = post; messageContainer.val(post.message); } Date.minutesBetween = function( date1, date2 ) { var one_minute=1000*60; var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); var difference_ms = date2_ms - date1_ms; return Math.ceil(difference_ms/one_minute); } Date.milisecondsBetween = function( date1, date2 ) { var date1_ms = date1.getTime(); var date2_ms = date2.getTime(); var difference_ms = date2_ms - date1_ms; return difference_ms; } Date.inMyString = function(date) { return date.getFullYear()+"-"+date.getMonth()+1+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(); } $scope.isEditable = function(post) { var postedTime = new Date(Date.parse(post.posted.date)); var now = new Date(); var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000); var minutesAgo = Date.minutesBetween(postedTime, utc); return (minutesAgo <= 5 && post.userid == $scope.userid); } $scope.sendPostTopic = function() { var post = { entityid: $scope.topicId, userid: window.USER.id, message: $scope.message, posted: new Date() } if ($scope.editingPost) post.postid = $scope.editingPost.id; var url = $scope.postTopicAddURL.replace('0', $scope.topicId); $http({ method: "POST", url: url, data: post }) .success(function(response){ //console.log("Created post: ", response.result); if (response.result) { // maybe need to request for posts and init paginator!!! if ($scope.editingPost == null) { $scope.posts.push(response.result); container.animate({ scrollTop: container.height()+1900 },1000); } else { _.map($scope.posts, function(p, i){ if (p.id == response.result.id) $scope.posts[i] = response.result; }); } } $scope.editingPost = null; $scope.message = ""; messageContainer.val(""); messageContainer.focus(); getMembersForTopic(); }) } $scope.changePostsPerPageTopic = function(){ getPostsCountForTopic(function(postsCount){ $scope.paginator.init(postsCount, $scope.postsPerPage); var offset = $scope.paginator.postsPerPage*($scope.paginator.curPageId - 1); var limit = $scope.paginator.postsPerPage; getTopicPosts(offset, limit); }); } function startChatTopic() { //console.log('chat topic started'); getMembersForTopics(); getPostsCountForTopic(function(postsCount){ $scope.paginator.init(postsCount, $scope.postsPerPage); }); setInterval(getNewPostsForTopic, 3000); } getMembersForTopics(); getPostsCountForTopic(function(postsCount){ $scope.paginator.init(postsCount, $scope.postsPerPage); }); }]);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var index_1 = require("../index"); /** * Property in entity can be marked as Embedded, and on persist all columns from the embedded are mapped to the * single table of the entity where Embedded is used. And on hydration all columns which supposed to be in the * embedded will be mapped to it from the single table. * * Array option works only in monogodb. * * @deprecated use @Column(type => EmbeddedModel) instead */ function Embedded(typeFunction, options) { return function (object, propertyName) { var reflectMetadataType = Reflect && Reflect.getMetadata ? Reflect.getMetadata("design:type", object, propertyName) : undefined; var isArray = reflectMetadataType === Array || (options && options.array === true) ? true : false; var args = { target: object.constructor, propertyName: propertyName, isArray: isArray, prefix: options && options.prefix !== undefined ? options.prefix : undefined, type: typeFunction }; index_1.getMetadataArgsStorage().embeddeds.push(args); }; } exports.Embedded = Embedded; //# sourceMappingURL=Embedded.js.map
import React,{ Component } from 'react'; export default class Options extends Component { constructor(props) { super(props); this.state = { datas: this.props.datas, } this.editor = null; this.editorBody = null; this.editorHtml = null; } componentDidMount() { console.log('componentDidMount'); this.initCkeditor(); } deleteOption(event) { this.editorHtml = null; this.props.deleteOption(event.currentTarget.attributes["data-option-id"].value); } onChangeChecked(event) { this.updateInputValue(this.editor.getData()); //fix ie 11,check befor blur; this.props.changeOptionChecked(event.currentTarget.attributes["data-option-id"].value,this.props.datas.checked); } initCkeditor(dataSourceUi) { if(!this.editor) { this.editor = CKEDITOR.replace(this.props.datas.optionId, { toolbar: 'Minimal', filebrowserImageUploadUrl:this.props.imageUploadUrl, height: 120 }); let self = this; this.editor.on("instanceReady", function () { self.editorBody = $('#' + [self.props.datas.optionId]).parent().find('iframe').contents().find('body'); //setData两个问题:1、引发事件失效 2、死循环触发; }); this.editor.on('change',function(){ console.log('change'+self.editor.getData()); setTimeout(function(){ self.updateInputValue(self.editor.getData()); },100) }); this.editor.on('blur', () => { //fix ie 11 中文输入 console.log('blur'+ self.editor.getData()); setTimeout(function(){ self.updateInputValue(self.editor.getData()); },100) }); }else { this.editor.setData(datas.inputValue); } } updateInputValue(inputValue) { console.log(inputValue); this.editorHtml = inputValue; this.props.updateInputValue(this.props.datas.optionId,inputValue); } render() { let showDanger = this.props.isValidator && this.props.datas.inputValue.length <= 0; let type = 'checkbox'; if(this.props.isRadio) { type= 'radio'; } if(this.editorBody && this.editorHtml != this.props.datas.inputValue) { this.editorBody.html(this.props.datas.inputValue); } return ( <div className="form-group"> <div className="col-sm-2 control-label"> <label className="choice-label control-label-required">{this.props.datas.optionLabel}</label> </div> <div className="col-sm-8 controls"> <textarea className="form-control datas-input col-md-8" id={this.props.datas.optionId} defaultValue={this.props.datas.inputValue} name='choices[]' value={this.props.datas.inputValue} data-image-upload-url={this.props.imageUploadUrl} data-image-download-url={this.props.imageDownloadUrl}></textarea> <div className="mtm"> <label> <input type={type} name='answer[]' data-option-id={this.props.datas.optionId} value={this.props.index} checked={this.props.datas.checked} className="answer-checkbox" onChange = {(event)=>this.onChangeChecked(event)}/>正确答案 </label> </div> <p className={showDanger ? 'color-danger' : 'hidden'}>请输入选项内容</p> </div> <div className="col-sm-2"> <a className="btn btn-default btn-sm" data-option-id={ this.props.datas.optionId } onClick={(event)=>this.deleteOption(event)} href="javascript:;"><i className="glyphicon glyphicon-trash"></i></a> </div> </div> ) } }
'use strict'; (function (window, document, videojs) { /** * Cookie access functions. * From: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie */ var cookies = { getItem: function (sKey) { if (!sKey) { return null; } return decodeURIComponent( document.cookie.replace( new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace( /[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1") ) || null; }, setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; } var sExpires = ""; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; break; case String: sExpires = "; expires=" + vEnd; break; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : ""); return true; }, removeItem: function(sKey, sPath, sDomain) { if (!this.hasItem(sKey)) { return false; } document.cookie = encodeURIComponent(sKey) + "=;" + " expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : ""); return true; }, hasItem: function (sKey) { if (!sKey) { return false; } return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace( /[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }, }, /** * Local storage functionality. */ localStorage = { available: function() { try { window.localStorage.setItem('fishingForLocalStorage', 'itsHere'); window.localStorage.removeItem('fishingForLocalStorage'); return true; } catch(e) { return false; } }, getItem: function(key) { return window.localStorage.getItem(key); }, setItem: function(key, value) { return window.localStorage.setItem(key, value); }, removeItem: function(key) { return window.localStorage.removeItem(key); } }, /** * Storage chooser, will use localstorage if available, otherwise use cookies. */ storage = { getItem: function (key) { return localStorage.available() ? localStorage.getItem(key) : cookies.getItem(key); }, setItem: function (key, value) { localStorage.available() ? localStorage.setItem(key, value) : cookies.setItem(key, value, Infinity, '/'); return value; }, removeItem: function (key) { localStorage.available() ? localStorage.removeItem(key) : cookies.removeItem(key); } }, /** * Object extend function. */ extend = function(obj) { var arg, i, k; for (i = 1; i < arguments.length; i++) { arg = arguments[i]; for (k in arg) { if (arg.hasOwnProperty(k)) { obj[k] = arg[k]; } } } return obj; }, /** * Default settings for this plugin. */ defaults = { namespace: 'autoplay-toggle', // namespace for cookie/localstorage }, /** * Autoplay toggle plugin setup. */ autoplayToggle = function (options) { var player = this, settings = extend({}, defaults, options || {}), key = settings.namespace + '-autoplay'; // add new button to player var autoplayBtn = document.createElement('div'); autoplayBtn.className = 'vjs-autoplay-toggle-button vjs-menu-button vjs-control'; autoplayBtn.innerHTML = '<div>' + '<span class="vjs-control-text">' + '自动播放:<br>' + '<span class="autoplay-toggle autoplay-toggle-active autoplay-on">开</span>' + '&nbsp;/&nbsp;' + '<span class="autoplay-toggle autoplay-off">关</span>' + '</span>' + '</div>'; player.controlBar.el().appendChild(autoplayBtn); // retrieve autoplay from storage and highlight the correct toggle option in *all* video players var autoplayToggleButton = function (activate) { // set cookie once activate ? storage.removeItem(key) : storage.setItem(key, 'no'); // get all videos and toggle all their autoplays var videos = document.querySelectorAll('.video-js'); for (var i = 0; i < videos.length; i++) { // check that this video has a toggle button var toggleBtnSelector = videos[i].querySelectorAll('.vjs-autoplay-toggle-button'); if (toggleBtnSelector.length > 0) { var toggleBtn = toggleBtnSelector[0], toggleOn = toggleBtn.querySelectorAll('.autoplay-on')[0], toggleOff = toggleBtn.querySelectorAll('.autoplay-off')[0]; if (activate) { // toggle this on toggleOn.className = 'autoplay-toggle autoplay-toggle-active autoplay-on'; toggleOff.className = 'autoplay-toggle autoplay-off'; } else { // toggle this off toggleOn.className = 'autoplay-toggle autoplay-on'; toggleOff.className = 'autoplay-toggle autoplay-toggle-active autoplay-off'; } } } }; var turnOn = !storage.getItem(key); console.log('turnOn', turnOn); player.me || (player.me = {}); // change player behavior based on toggle if (!turnOn) { // this could be autoplaying, make sure to stop it and ensure player's autoplay is false player.me.autoplay = false; player.autoplay(false); player.pause(); } else if (turnOn) { // we want this to autoplay player.me.autoplay = true; setTimeout(function () { player.tech_.play(); }, 0) } // initialize autoplay toggle autoplayToggleButton(turnOn); // set up toggle click autoplayBtn.onclick = function () { // check if key in storage and do the opposite of that to toggle var toggle = !!storage.getItem(key); autoplayToggleButton(toggle); }; // return player to allow this plugin to be chained return player; }; // set this thing up as a vjs plugin videojs.plugin('autoplayToggle', autoplayToggle); // alternative function for retrieving autoplay value from storage for situations where other plugins // are interfering with this plugin videojs.autoplaySettingFromStorage = function (options) { var settings = extend({}, defaults, options || {}), key = settings.namespace + '-autoplay'; // negate what's in storage since only "don't autoplay" is stored return !storage.getItem(key); }; })(window, document, videojs);
var _ = require('lodash'); var norma = require('norma'); var jsonic = require('jsonic'); // string args override object args module.exports = function parse_pattern(instance,args,normaspec,fixed) { args = norma('{strargs:s? objargs:o? moreobjargs:o? '+(normaspec||'')+'}', args) try { return _.extend( args, { pattern: _.extend( {}, // Precedence of arguments in add,act is left-to-right args.moreobjargs ? args.moreobjargs : {}, args.objargs ? args.objargs : {}, args.strargs ? jsonic( args.strargs ) : {}, fixed || {} ) }) } catch( e ) { var col = 1==e.line?e.column-1:e.column throw error('add_string_pattern_syntax',{ argstr: args, syntax: e.message, line: e.line, col: col }) } }
export class TaskGroupServiceClient { static beforeRemove(context) { var groupId = context.currentData()._id; var taskInGroup = Tasks.find({groupId: groupId}).fetch(); var taskCount = taskInGroup.length; bootbox.confirm({ title: "You are about to delete a task group, are you sure ?", message: "The " + taskCount + " tasks linked to this group will not be deleted.", buttons: { cancel: { label: '<i class="fa fa-times"></i> Cancel' }, confirm: { label: '<i class="fa fa-check"></i> Confirm' } }, callback: _.bind(function (result) { if (result) { Router.go("/task-groups"); this.remove(); } }, context) } ); } }
define([ 'vue', 'text!components/headerLogo/headerLogo.tpl', 'jquery', 'common/directive/setStyle', 'common/directive/setParentStyle', 'common/directive/setChildStyle' ],function(vue,tpl,$){ var component = vue.extend({ components : { }, template : tpl, data : function(){ return { id : '', headerLogo : '', active : false }; }, computed : { style : function(){ var style = {}; $.each(this.headerLogo.data.style,function(i,n){ style[n.key] = n.value; }); return style; }, col : function(){ var cols = this.headerLogo.data.col.value; return parseInt(cols); }, row : function(){ var rows = this.headerLogo.data.row.value; return parseInt(rows); }, headerLogoImg : function(){ var headerLogoImg = this.headerLogo.data.headerLogoImg; return headerLogoImg; }, headerLogoRemark : function(){ var headerLogoRemark = this.headerLogo.data.headerLogoRemark; return headerLogoRemark; }, headerLogoLink : function(){ var headerLogoLink = this.headerLogo.data.headerLogoLink; return headerLogoLink; }, logo : function(){ var logo = this.headerLogo.data.logo.value; return parseInt(logo); } }, methods : { addClassActive : function($event){ var $target = $($event.target); $target.addClass('active'); }, removeClassActive : function($event){ var $target = $($event.target); $target.removeClass('active'); }, operateEdit : function($event){ $event.preventDefault(); $event.stopPropagation(); var $target = $($event.target), id = $target.closest('.m-oparate').data('oparate'); this.$dispatch('editComponent',id); }, operateDelete : function($event){ $event.preventDefault(); $event.stopPropagation(); var _removeId = $($event.target).closest('.m-oparate').data('oparate'), _setStyleId = $($event.target).closest('table').data('id'); $($event.target).closest('.m-oparate').siblings('table').remove().end().remove(); this.$dispatch('refleshStyle',{ removeId : _removeId, setStyleId : _setStyleId }); } }, events : { } }); return component; });
$( document ).ready(function() { $('.agency-tooltip').tooltip() } );
'use strict' const _ = require('lodash') const util = require('../util') const crypto = require('tendermint-crypto') /** * Transactions component * @see {@link https://monax.io/docs/documentation/db/latest/specifications/api/#broadcast-tx} * @type {ErisDB.Transactions} */ module.exports = class Transactions { constructor (eris) { this._eris = eris } /** * Sign helper for transactions * @param {Object} tx * @param {String} privKey private key in hex format * @return {Promise} */ sign (tx, privKey) { if (!_.isObject(tx)) return Promise.reject(new Error('Transaction is required parameter')) if (!util.isPrivKey(privKey)) return Promise.reject(new Error('PrivKey is required parameter')) try { const PrivKeyEd25519 = crypto.PrivKeyEd25519 const key = new PrivKeyEd25519(new Buffer(privKey, 'hex')) return Promise.resolve(key.signString(JSON.stringify(tx)).toJSON()) } catch (err) { return Promise.reject(err) } } /** * Will wait for transaction will be validated * @param {Object} tx CallTx object * @param {Object} result broadcastTx result * @return {Promise} */ _waitForConfirmation (tx, result) { const checkEvents = (subId, step = 0) => { return new Promise((resolve, reject) => { setTimeout(() => { this._eris .events .eventPoll(subId) .then((events) => { step++ if (!_.isArray(events) || !events.length) { // No need to check after 50 steps if (step >= 50) return reject(new Error('Transaction was not confirmed')) else return checkEvents(subId, step) } for (let i = 0; i < events.length; i++) { if (events[i].tx_id == result.tx_hash && _.isObject(events[i].call_data)) return resolve(events[i]) // handle error if (events[i].tx_id == result.tx_hash && events[i].exception.length > 0) return reject(new Error(events[i].exception)) } }) .catch(reject) }, 500) }) } let subId return this._eris .events .eventSubscribe(`Acc/${result.contract_addr}/Call`) .then((newSubId) => { subId = newSubId return checkEvents(subId) }) .then((data) => { // unsubscribe return this._eris .events .eventUnsubscribe(subId) .then((result) => { return data }) }) .catch((err) => { //unsubscribe return this._eris .events .eventUnsubscribe(subId) .then(() => { return Promise.reject(err) }) .catch(() => { return Promise.reject(err) }) }) } /** * System will try to set all missing fields for given tx * - Use the other parameters to create a CallTx object * - Sign the transaction. * - Broadcast the transaction * - Wait until the transaction is fully processed * * @param {Object} tx * @param {String} privKey * @return {Promise} */ sendTransaction (tx, privKey) { if (!tx || !util.isCallTx(tx)) return Promise.reject(new Error('Transaction is required parameter')) if (!privKey || !util.isPrivKey(privKey)) return Promise.reject(new Error('PrivKey is required parameter')) let chainId let account return this._eris .blockchain .getChainId() .then((currentChainId) => { chainId = currentChainId return this._eris .accounts .getAccount(tx.input.address) }) .then((loadedAccount) => { account = loadedAccount if (!tx.address) tx.address = '' if (!tx.input.sequence) tx.input.sequence = (account && account.sequence) ? account.sequence + 1 : 1 if (!tx.fee) tx.fee = 0 if (!tx.gas_limit) tx.gas_limit = 100000 if (!tx.input.amount) tx.input.amount = 10 // Sign transaction const txForSigning = { chain_id: chainId, tx: [ 2, { address: tx.address, data: tx.data, fee: tx.fee, gas_limit: tx.gas_limit, input: { address: tx.input.address, amount: tx.input.amount, sequence: tx.input.sequence } } ] } return this.sign(txForSigning, privKey) }) .then((signed) => { tx.input.signature = signed tx.input.pub_key = account.pub_key return this.broadcastTx(tx) }) .then((info) => { if (!info.tx_hash) return Promise.reject(new Error('No tx_hash received')) return this._waitForConfirmation(tx, info) }) } /** * Broadcast a given (signed) transaction to the node. * It will be added to the tx pool if there are no issues, and if it is * accepted by all validators it will eventually be committed to a block. * WARNING: BroadcastTx will not be useful until we add a client-side signing solution. * @param {Object} tx * @return {Promise} */ broadcastTx (tx) { if (!_.isObject(tx)) return Promise.reject(new Error('Transaction is required parameter')) return this._eris.request .call('broadcastTx', tx) } /** * Get list of unconfirmed transactions * @return {Promise} */ getUnconfirmedTxs () { return this._eris.request .call('getUnconfirmedTxs') .then((data) => { if (!data || !data.txs) return Promise.reject(new Error('Wrong response received from RPC')) return data.txs }) } /** * Call a given (contract) account to execute its code with the given in-data. * @param {String} address * @param {String} data * @return {Promise} */ call (address, data) { if (!address || !util.isAddress(address)) return Promise.reject(new Error('Address is required parameter')) if (!data || !util.isHex(data)) return Promise.reject(new Error('Data is required parameter')) return this._eris.request .call('call', { address: address, data: data }) } /** * Pass contract code and tx data to the node and have it executed in the virtual machine. * This is mostly a dev feature. * @param {String} address * @param {String} data * @return {Promise} */ callCode (address, data) { if (!address || !util.isAddress(address)) return Promise.reject(new Error('Address is required parameter')) if (!data || !util.isHex(data)) return Promise.reject(new Error('Data is required parameter')) return this._eris.request .call('callCode', { address: address, data: data }) } }
var utils = require('./init'); var expect = require('chai').expect; var SMTCTag = require('../../models/tag'); var Report = require('../../models/report'); var async = require('async'); var id1; var id2; function createTags(done) { SMTCTag.create([ { name: 'Not so important tag' }, { name: 'Very important tag' } ], function(err, tags) { id1 = tags[0]._id.toString(); id2 = tags[1]._id.toString(); done(); }); } function createReports(done) { Report.create([ { smtcTags: [ id1 ] }, { smtcTags: [ id1 ] }, { smtcTags: [ id2 ] }, { smtcTags: [ id2 ] }, { smtcTags: [ id2 ] } ], done); } function removeTag(done) { SMTCTag.findOne({ _id: id1 }, function(err, tag) { tag.remove(done); }); } describe('Deleting a tag that has associated reports', function() { before(function(done) { async.series([createTags, createReports, removeTag], done); }); it('should remove the tag', function(done) { SMTCTag.find({ _id: id1 }, function(err, tags) { if (err) return done(err); expect(tags.length).to.equal(0); done(); }); }); it('should not remove the other tag', function(done) { SMTCTag.find({ _id: id2 }, function(err, tags) { if (err) return done(err); expect(tags.length).to.equal(1); done(); }); }); it('should not affect other reports', function(done) { Report.find({ smtcTags: id2 }, function(err, reports) { if (err) return done(err); expect(reports.length).to.equal(3); done(); }); }); it('should remove reference to the tags in the right reports', function(done) { Report.find({ smtcTags: id1 }, function(err, reports) { if (err) return done(err); expect(reports.length).to.equal(0); done(); }); }); after(utils.wipeModels([Report, SMTCTag])); after(utils.expectModelsEmpty); });
app.directive('project', function(){ return { restrict: 'E', scope: { proj: '=' }, templateUrl: 'js/directives/project.html' } });
// Generated on 2014-12-13 using generator-angularfire 0.8.2-7 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Configurable paths for the application var appConfig = { app: require('./bower.json').appPath || 'app', dist: 'dist' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings yeoman: appConfig, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, js: { files: ['./scripts/{,*/}*.js'], tasks: ['newer:jshint:all'], options: { livereload: '<%= connect.options.livereload %>' } }, jsTest: { files: ['test/spec/{,*/}*.js'], tasks: ['newer:jshint:test', 'karma'] }, styles: { files: ['./styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ './{,*/}*.html', '.tmp/styles/{,*/}*.css', './images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] } }, // The actual grunt server settings connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, middleware: function (connect) { return [ connect.static('.tmp'), connect().use( '/bower_components', connect.static('./bower_components') ), connect.static(appConfig.app) ]; } } }, test: { options: { port: 9001, middleware: function (connect) { return [ connect.static('.tmp'), connect.static('test'), connect().use( '/bower_components', connect.static('./bower_components') ), connect.static(appConfig.app) ]; } } }, heroku: { options: { open: false, hostname: '0.0.0.0', livereload: false, port: (process.env.PORT || 9002), keepalive: true, middleware: function (connect) { return [ connect.static('.tmp'), connect().use( '/bower_components', connect.static('./bower_components') ), connect.static(appConfig.app) ]; } } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: { src: [ 'Gruntfile.js', './scripts/{,*/}*.js' ] }, test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/spec/{,*/}*.js'] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/{,*/}*', '!<%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the app wiredep: { app: { src: ['./index.html'], ignorePath: /\.\.\// } }, // Renames files for browser caching purposes filerev: { dist: { src: [ '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= yeoman.dist %>/styles/fonts/*' ] } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: './index.html', options: { dest: '<%= yeoman.dist %>', flow: { html: { steps: { js: ['concat', 'uglifyjs'], css: ['cssmin'] }, post: {} } } } }, // Performs rewrites based on filerev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'], options: { assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images'] } }, // The following *-min tasks will produce minified files in the dist folder // By default, your `index.html`'s <!-- Usemin block --> will take care of // minification. These next options are pre-configured if you do not wish // to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= yeoman.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css' // ] // } // } // }, // uglify: { // dist: { // files: { // '<%= yeoman.dist %>/scripts/scripts.js': [ // '<%= yeoman.dist %>/scripts/scripts.js' // ] // } // } // }, // concat: { // dist: {} // }, imagemin: { dist: { files: [{ expand: true, cwd: './images', src: '{,*/}*.{png,jpg,jpeg,gif}', dest: '<%= yeoman.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: './images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseWhitespace: true, conservativeCollapse: true, collapseBooleanAttributes: true, removeCommentsFromCDATA: true, removeOptionalTags: true }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', src: ['*.html', 'views/{,*/}*.html'], dest: '<%= yeoman.dist %>' }] } }, // ng-annotate tries to make the code safe for minification automatically // by using the Angular long form for dependency injection. ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: '*.js', dest: '.tmp/concat/scripts' }] } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '.', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', '*.html', 'views/{,*/}*.html', 'images/{,*/}*.{webp}', 'fonts/*' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }, { expand: true, cwd: 'bower_components/bootstrap/dist', src: 'fonts/*', dest: '<%= yeoman.dist %>' }] }, styles: { expand: true, cwd: './styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Run some tasks in parallel to speed up the build process concurrent: { server: [ 'copy:styles' ], test: [ 'copy:styles' ], dist: [ 'copy:styles', 'imagemin', 'svgmin' ] }, // Test settings karma: { unit: { configFile: 'test/karma.conf.js', singleRun: true } } }); grunt.registerTask('serve', 'Compile then start a connect web server', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve:' + target]); }); grunt.registerTask('test', [ 'clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma' ]); grunt.registerTask('build', [ 'clean:dist', 'wiredep', 'useminPrepare', 'concurrent:dist', 'autoprefixer', // 'concat', 'ngAnnotate', 'copy:dist', 'cdnify', // 'cssmin', // 'uglify', 'filerev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); };
import React, { Component, PropTypes } from 'react'; import Button from './Button.js'; import { yellow600 } from 'material-ui/styles/colors'; class FinishButton extends Component { render() { return ( <Button name="exit_to_app" color={yellow600} onClick={() => this.props.onClick()} /> ); } } FinishButton.propTypes = { onClick: PropTypes.func.isRequired }; export default FinishButton;
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Moves the given element to the bottom of the array. * The array is modified in-place. * * @function Phaser.Utils.Array.SendToBack * @since 3.4.0 * * @param {array} array - The array. * @param {*} item - The element to move. * * @return {*} The element that was moved. */ var SendToBack = function (array, item) { var currentIndex = array.indexOf(item); if (currentIndex !== -1 && currentIndex > 0) { array.splice(currentIndex, 1); array.unshift(item); } return item; }; module.exports = SendToBack;
define(['jquery'], function($) { "use strict"; function save(id, value) { var deferred = $.ajax({ type: "POST", url: 'save/' + id, dataType: 'json', contentType: 'application/json', data: value, processData: false, }); return deferred; } var exports = Object.freeze({ save: save }); return exports; })
var fs = require('fs'); var readable = fs.createReadStream('./cat.js'); readable.pipe(process.stdout);
module.exports = function(grunt) { 'use strict'; var sources = [ 'src/js/ext/*.js', 'src/js/guide.js', 'src/js/guide-optionable.js', 'src/js/guide-extension.js', 'src/js/guide-tour.js', 'src/js/guide-spot.js', 'src/js/extensions/*.js' ], readPkg = function() { return grunt.file.readJSON('package.json'); }; // Project configuration. grunt.initConfig({ pkg: readPkg(), bumpup: 'package.json', watch: { scripts: { files: [ 'src/js/**/*.js' ], tasks: [ 'build' ] }, docs: { files: [ 'src/js/**/*.js', 'docs/guides/**/*.md', 'docs/*', '.jsduck' ], tasks: [ 'docs' ] }, css: { files: [ 'src/css/**/*.less' ], tasks: [ 'less', 'docs' ] } }, jasmine : { src: sources, options : { // timeout: 10000, outfile: '_SpecRunner.html', keepRunner: true, version: '1.3.1', styles: 'dist/guide.css', helpers: 'spec/helpers/**/*.js', vendor: 'src/vendor/**/*.js', specs : 'spec/unit/**/*.js' } }, jshint: { all: [ 'src/js/**/*.js' ], options: { jshintrc: '.jshintrc' } }, jsvalidate: { files: ['src/js/**/*.js' ] }, concat: { options: { separator: '\n\n' }, dist: { options: { // banner: '<%= meta.banner %>' }, src: sources, dest: 'dist/guide.js' } }, uglify: { options: { warnings: true, mangle: { except: [ 'jQuery', '_' ] }, output: { beautify: false }, compress: { sequences: true, dead_code: true, loops: true, unused: true, if_return: true, join_vars: true, global_defs: { "GJS_DEBUG": false } } }, dist: { files: { 'dist/guide.min.js': [ 'dist/guide.js' ] } } }, // uglify tagrelease: { file: 'package.json', commit: true, message: 'Release %version%', prefix: 'v', annotate: false }, less: { options: { strictImports: true, report: 'gzip' }, development: { options: { paths: [ "src/css" ], }, files: { "dist/guide.css": "src/css/gjs.less" } }, production: { options: { paths: [ "src/css" ], compress: true }, files: { "dist/guide.min.css": "src/css/gjs.less" } } }, jsduck: { main: { src: [ 'src/js' ], dest: 'docs/api', options: { 'title': 'Guide.js API Reference', 'categories': '.jsduck', 'color': true, 'tags': [ 'docs/jsduck_tags/async_tag' ], 'warnings': [], 'external': [ 'XMLHttpRequest', 'jQuery', '$', '_' ], 'images': 'docs/images', 'eg-iframe': 'docs/gjs-iframe.html', 'guides': 'docs/guides.json', 'head-html': 'docs/head.html' } } }, 'string-replace': { version: { files: { 'src/js/guide.js': [ 'src/js/guide.js' ] }, options: { replacements: [{ pattern: /([g|G])uide\.VERSION\s*=\s*\'.*\';/, replacement: "$1uide.VERSION = '<%= grunt.config.get('pkg.version') %>';" }] } }, debug_flags: { files: { 'dist/guide.js': [ 'dist/guide.js' ] }, options: { replacements: [{ pattern: /debug:(\s*)true/, replacement: "debug:$1false" }] } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-bumpup'); grunt.loadNpmTasks('grunt-tagrelease'); grunt.loadNpmTasks('grunt-jsvalidate'); grunt.loadNpmTasks('grunt-jsduck'); grunt.loadNpmTasks('grunt-string-replace'); grunt.registerTask('test', [ 'jsvalidate', 'jshint', 'jasmine' ]); grunt.registerTask('build', [ 'test', 'concat', 'string-replace:debug_flags', 'uglify', 'test', 'less' ]); grunt.registerTask('docs', [ 'jsduck', 'docs_assets' ]); grunt.registerTask('default', ['test']); grunt.registerTask('updatePkg', function () { grunt.config.set('pkg', readPkg()); }); grunt.registerTask('docs_assets', function () { grunt.file.copy('dist/guide.min.js', 'docs/js/guide.min.js'); grunt.file.copy('src/vendor/jquery-1.10.2.js', 'docs/js/jquery-1.10.2.js'); grunt.file.copy('src/vendor/lodash.js', 'docs/js/lodash.js'); grunt.file.copy('dist/guide.min.css', 'docs/css/guide.min.css'); }); // Release alias task grunt.registerTask('release', function (type) { grunt.task.run('test'); grunt.task.run('bumpup:' + ( type || 'patch' )); grunt.task.run('updatePkg'); grunt.task.run('string-replace:version') grunt.task.run('build'); grunt.task.run('tagrelease'); }); };
(function() { 'use strict'; angular.module('bidit') .factory('ItemService', function() { return [{ id: "#13434234", title: "item 1", description: "Lenovo 8GB i7", price: 260, remaining: "32h:5m:4s" }, { id: "#23434234", title: "item 2", description: "Lenovo 4GB i5", price: 300, remaining: "32h:5m:4s" }, { id: "#33434234", title: "item 3", description: "HP 16GB i7", price: 80, remaining: "32h:5m:4s" }, { id: "#43434234", title: "item 4", description: "Mac 8GB i7", price: 120, remaining: "32h:5m:4s" }]; }); })();
import React from "react" import { graphql } from "gatsby" export default ({ data }) => { if (!data?.allTest?.nodes) { throw new Error("Wrong data: " + JSON.stringify(data)) } return <div>{JSON.stringify(data)}</div> } export const query = graphql` query($fooBarArray: [String!], $sort: TestSortInput, $count: Boolean!) { allTest( filter: { fooBar: { nin: $fooBarArray } } sort: $sort limit: 100 ) { nodes { nodeNum text } totalCount @include(if: $count) } } `
/*! * Pusher JavaScript Library v6.0.1 * https://pusher.com/ * * Copyright 2017, Pusher * Released under the MIT licence. */ var Pusher = /******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 2); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright (C) 2016 Dmitry Chestnykh // MIT License. See LICENSE file for details. 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 __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); /** * Package base64 implements Base64 encoding and decoding. */ // Invalid character used in decoding to indicate // that the character to decode is out of range of // alphabet and cannot be decoded. var INVALID_BYTE = 256; /** * Implements standard Base64 encoding. * * Operates in constant time. */ var Coder = /** @class */ (function () { // TODO(dchest): methods to encode chunk-by-chunk. function Coder(_paddingCharacter) { if (_paddingCharacter === void 0) { _paddingCharacter = "="; } this._paddingCharacter = _paddingCharacter; } Coder.prototype.encodedLength = function (length) { if (!this._paddingCharacter) { return (length * 8 + 5) / 6 | 0; } return (length + 2) / 3 * 4 | 0; }; Coder.prototype.encode = function (data) { var out = ""; var i = 0; for (; i < data.length - 2; i += 3) { var c = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]); out += this._encodeByte((c >>> 3 * 6) & 63); out += this._encodeByte((c >>> 2 * 6) & 63); out += this._encodeByte((c >>> 1 * 6) & 63); out += this._encodeByte((c >>> 0 * 6) & 63); } var left = data.length - i; if (left > 0) { var c = (data[i] << 16) | (left === 2 ? data[i + 1] << 8 : 0); out += this._encodeByte((c >>> 3 * 6) & 63); out += this._encodeByte((c >>> 2 * 6) & 63); if (left === 2) { out += this._encodeByte((c >>> 1 * 6) & 63); } else { out += this._paddingCharacter || ""; } out += this._paddingCharacter || ""; } return out; }; Coder.prototype.maxDecodedLength = function (length) { if (!this._paddingCharacter) { return (length * 6 + 7) / 8 | 0; } return length / 4 * 3 | 0; }; Coder.prototype.decodedLength = function (s) { return this.maxDecodedLength(s.length - this._getPaddingLength(s)); }; Coder.prototype.decode = function (s) { if (s.length === 0) { return new Uint8Array(0); } var paddingLength = this._getPaddingLength(s); var length = s.length - paddingLength; var out = new Uint8Array(this.maxDecodedLength(length)); var op = 0; var i = 0; var haveBad = 0; var v0 = 0, v1 = 0, v2 = 0, v3 = 0; for (; i < length - 4; i += 4) { v0 = this._decodeChar(s.charCodeAt(i + 0)); v1 = this._decodeChar(s.charCodeAt(i + 1)); v2 = this._decodeChar(s.charCodeAt(i + 2)); v3 = this._decodeChar(s.charCodeAt(i + 3)); out[op++] = (v0 << 2) | (v1 >>> 4); out[op++] = (v1 << 4) | (v2 >>> 2); out[op++] = (v2 << 6) | v3; haveBad |= v0 & INVALID_BYTE; haveBad |= v1 & INVALID_BYTE; haveBad |= v2 & INVALID_BYTE; haveBad |= v3 & INVALID_BYTE; } if (i < length - 1) { v0 = this._decodeChar(s.charCodeAt(i)); v1 = this._decodeChar(s.charCodeAt(i + 1)); out[op++] = (v0 << 2) | (v1 >>> 4); haveBad |= v0 & INVALID_BYTE; haveBad |= v1 & INVALID_BYTE; } if (i < length - 2) { v2 = this._decodeChar(s.charCodeAt(i + 2)); out[op++] = (v1 << 4) | (v2 >>> 2); haveBad |= v2 & INVALID_BYTE; } if (i < length - 3) { v3 = this._decodeChar(s.charCodeAt(i + 3)); out[op++] = (v2 << 6) | v3; haveBad |= v3 & INVALID_BYTE; } if (haveBad !== 0) { throw new Error("Base64Coder: incorrect characters for decoding"); } return out; }; // Standard encoding have the following encoded/decoded ranges, // which we need to convert between. // // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 + / // Index: 0 - 25 26 - 51 52 - 61 62 63 // ASCII: 65 - 90 97 - 122 48 - 57 43 47 // // Encode 6 bits in b into a new character. Coder.prototype._encodeByte = function (b) { // Encoding uses constant time operations as follows: // // 1. Define comparison of A with B using (A - B) >>> 8: // if A > B, then result is positive integer // if A <= B, then result is 0 // // 2. Define selection of C or 0 using bitwise AND: X & C: // if X == 0, then result is 0 // if X != 0, then result is C // // 3. Start with the smallest comparison (b >= 0), which is always // true, so set the result to the starting ASCII value (65). // // 4. Continue comparing b to higher ASCII values, and selecting // zero if comparison isn't true, otherwise selecting a value // to add to result, which: // // a) undoes the previous addition // b) provides new value to add // var result = b; // b >= 0 result += 65; // b > 25 result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97); // b > 51 result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48); // b > 61 result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 43); // b > 62 result += ((62 - b) >>> 8) & ((62 - 43) - 63 + 47); return String.fromCharCode(result); }; // Decode a character code into a byte. // Must return 256 if character is out of alphabet range. Coder.prototype._decodeChar = function (c) { // Decoding works similar to encoding: using the same comparison // function, but now it works on ranges: result is always incremented // by value, but this value becomes zero if the range is not // satisfied. // // Decoding starts with invalid value, 256, which is then // subtracted when the range is satisfied. If none of the ranges // apply, the function returns 256, which is then checked by // the caller to throw error. var result = INVALID_BYTE; // start with invalid character // c == 43 (c > 42 and c < 44) result += (((42 - c) & (c - 44)) >>> 8) & (-INVALID_BYTE + c - 43 + 62); // c == 47 (c > 46 and c < 48) result += (((46 - c) & (c - 48)) >>> 8) & (-INVALID_BYTE + c - 47 + 63); // c > 47 and c < 58 result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52); // c > 64 and c < 91 result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0); // c > 96 and c < 123 result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26); return result; }; Coder.prototype._getPaddingLength = function (s) { var paddingLength = 0; if (this._paddingCharacter) { for (var i = s.length - 1; i >= 0; i--) { if (s[i] !== this._paddingCharacter) { break; } paddingLength++; } if (s.length < 4 || paddingLength > 2) { throw new Error("Base64Coder: incorrect padding"); } } return paddingLength; }; return Coder; }()); exports.Coder = Coder; var stdCoder = new Coder(); function encode(data) { return stdCoder.encode(data); } exports.encode = encode; function decode(s) { return stdCoder.decode(s); } exports.decode = decode; /** * Implements URL-safe Base64 encoding. * (Same as Base64, but '+' is replaced with '-', and '/' with '_'). * * Operates in constant time. */ var URLSafeCoder = /** @class */ (function (_super) { __extends(URLSafeCoder, _super); function URLSafeCoder() { return _super !== null && _super.apply(this, arguments) || this; } // URL-safe encoding have the following encoded/decoded ranges: // // ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 - _ // Index: 0 - 25 26 - 51 52 - 61 62 63 // ASCII: 65 - 90 97 - 122 48 - 57 45 95 // URLSafeCoder.prototype._encodeByte = function (b) { var result = b; // b >= 0 result += 65; // b > 25 result += ((25 - b) >>> 8) & ((0 - 65) - 26 + 97); // b > 51 result += ((51 - b) >>> 8) & ((26 - 97) - 52 + 48); // b > 61 result += ((61 - b) >>> 8) & ((52 - 48) - 62 + 45); // b > 62 result += ((62 - b) >>> 8) & ((62 - 45) - 63 + 95); return String.fromCharCode(result); }; URLSafeCoder.prototype._decodeChar = function (c) { var result = INVALID_BYTE; // c == 45 (c > 44 and c < 46) result += (((44 - c) & (c - 46)) >>> 8) & (-INVALID_BYTE + c - 45 + 62); // c == 95 (c > 94 and c < 96) result += (((94 - c) & (c - 96)) >>> 8) & (-INVALID_BYTE + c - 95 + 63); // c > 47 and c < 58 result += (((47 - c) & (c - 58)) >>> 8) & (-INVALID_BYTE + c - 48 + 52); // c > 64 and c < 91 result += (((64 - c) & (c - 91)) >>> 8) & (-INVALID_BYTE + c - 65 + 0); // c > 96 and c < 123 result += (((96 - c) & (c - 123)) >>> 8) & (-INVALID_BYTE + c - 97 + 26); return result; }; return URLSafeCoder; }(Coder)); exports.URLSafeCoder = URLSafeCoder; var urlSafeCoder = new URLSafeCoder(); function encodeURLSafe(data) { return urlSafeCoder.encode(data); } exports.encodeURLSafe = encodeURLSafe; function decodeURLSafe(s) { return urlSafeCoder.decode(s); } exports.decodeURLSafe = decodeURLSafe; exports.encodedLength = function (length) { return stdCoder.encodedLength(length); }; exports.maxDecodedLength = function (length) { return stdCoder.maxDecodedLength(length); }; exports.decodedLength = function (s) { return stdCoder.decodedLength(s); }; //# sourceMappingURL=base64.js.map /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; // Copyright (C) 2016 Dmitry Chestnykh // MIT License. See LICENSE file for details. Object.defineProperty(exports, "__esModule", { value: true }); /** * Package utf8 implements UTF-8 encoding and decoding. */ var INVALID_UTF16 = "utf8: invalid string"; var INVALID_UTF8 = "utf8: invalid source encoding"; /** * Encodes the given string into UTF-8 byte array. * Throws if the source string has invalid UTF-16 encoding. */ function encode(s) { // Calculate result length and allocate output array. // encodedLength() also validates string and throws errors, // so we don't need repeat validation here. var arr = new Uint8Array(encodedLength(s)); var pos = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { arr[pos++] = c; } else if (c < 0x800) { arr[pos++] = 0xc0 | c >> 6; arr[pos++] = 0x80 | c & 0x3f; } else if (c < 0xd800) { arr[pos++] = 0xe0 | c >> 12; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } else { i++; // get one more character c = (c & 0x3ff) << 10; c |= s.charCodeAt(i) & 0x3ff; c += 0x10000; arr[pos++] = 0xf0 | c >> 18; arr[pos++] = 0x80 | (c >> 12) & 0x3f; arr[pos++] = 0x80 | (c >> 6) & 0x3f; arr[pos++] = 0x80 | c & 0x3f; } } return arr; } exports.encode = encode; /** * Returns the number of bytes required to encode the given string into UTF-8. * Throws if the source string has invalid UTF-16 encoding. */ function encodedLength(s) { var result = 0; for (var i = 0; i < s.length; i++) { var c = s.charCodeAt(i); if (c < 0x80) { result += 1; } else if (c < 0x800) { result += 2; } else if (c < 0xd800) { result += 3; } else if (c <= 0xdfff) { if (i >= s.length - 1) { throw new Error(INVALID_UTF16); } i++; // "eat" next character result += 4; } else { throw new Error(INVALID_UTF16); } } return result; } exports.encodedLength = encodedLength; /** * Decodes the given byte array from UTF-8 into a string. * Throws if encoding is invalid. */ function decode(arr) { var chars = []; for (var i = 0; i < arr.length; i++) { var b = arr[i]; if (b & 0x80) { var min = void 0; if (b < 0xe0) { // Need 1 more byte. if (i >= arr.length) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; if ((n1 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x1f) << 6 | (n1 & 0x3f); min = 0x80; } else if (b < 0xf0) { // Need 2 more bytes. if (i >= arr.length - 1) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 12 | (n1 & 0x3f) << 6 | (n2 & 0x3f); min = 0x800; } else if (b < 0xf8) { // Need 3 more bytes. if (i >= arr.length - 2) { throw new Error(INVALID_UTF8); } var n1 = arr[++i]; var n2 = arr[++i]; var n3 = arr[++i]; if ((n1 & 0xc0) !== 0x80 || (n2 & 0xc0) !== 0x80 || (n3 & 0xc0) !== 0x80) { throw new Error(INVALID_UTF8); } b = (b & 0x0f) << 18 | (n1 & 0x3f) << 12 | (n2 & 0x3f) << 6 | (n3 & 0x3f); min = 0x10000; } else { throw new Error(INVALID_UTF8); } if (b < min || (b >= 0xd800 && b <= 0xdfff)) { throw new Error(INVALID_UTF8); } if (b >= 0x10000) { // Surrogate pair. if (b > 0x10ffff) { throw new Error(INVALID_UTF8); } b -= 0x10000; chars.push(String.fromCharCode(0xd800 | (b >> 10))); b = 0xdc00 | (b & 0x3ff); } } chars.push(String.fromCharCode(b)); } return chars.join(""); } exports.decode = decode; //# sourceMappingURL=utf8.js.map /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { // required so we don't have to do require('pusher').default etc. module.exports = __webpack_require__(3).default; /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // CONCATENATED MODULE: ./src/core/base64.ts function encode(s) { return btoa(utob(s)); } var fromCharCode = String.fromCharCode; var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var b64tab = {}; for (var base64_i = 0, l = b64chars.length; base64_i < l; base64_i++) { b64tab[b64chars.charAt(base64_i)] = base64_i; } var cb_utob = function (c) { var cc = c.charCodeAt(0); return cc < 0x80 ? c : cc < 0x800 ? fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f)) : fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | (cc & 0x3f)); }; var utob = function (u) { return u.replace(/[^\x00-\x7F]/g, cb_utob); }; var cb_encode = function (ccc) { var padlen = [0, 2, 1][ccc.length % 3]; var ord = (ccc.charCodeAt(0) << 16) | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) | (ccc.length > 2 ? ccc.charCodeAt(2) : 0); var chars = [ b64chars.charAt(ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63) ]; return chars.join(''); }; var btoa = self.btoa || function (b) { return b.replace(/[\s\S]{1,3}/g, cb_encode); }; // CONCATENATED MODULE: ./src/core/utils/timers/abstract_timer.ts var Timer = (function () { function Timer(set, clear, delay, callback) { var _this = this; this.clear = clear; this.timer = set(function () { if (_this.timer) { _this.timer = callback(_this.timer); } }, delay); } Timer.prototype.isRunning = function () { return this.timer !== null; }; Timer.prototype.ensureAborted = function () { if (this.timer) { this.clear(this.timer); this.timer = null; } }; return Timer; }()); /* harmony default export */ var abstract_timer = (Timer); // CONCATENATED MODULE: ./src/core/utils/timers/index.ts var __extends = (undefined && undefined.__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 __()); }; })(); function timers_clearTimeout(timer) { self.clearTimeout(timer); } function timers_clearInterval(timer) { self.clearInterval(timer); } var OneOffTimer = (function (_super) { __extends(OneOffTimer, _super); function OneOffTimer(delay, callback) { return _super.call(this, setTimeout, timers_clearTimeout, delay, function (timer) { callback(); return null; }) || this; } return OneOffTimer; }(abstract_timer)); var PeriodicTimer = (function (_super) { __extends(PeriodicTimer, _super); function PeriodicTimer(delay, callback) { return _super.call(this, setInterval, timers_clearInterval, delay, function (timer) { callback(); return timer; }) || this; } return PeriodicTimer; }(abstract_timer)); // CONCATENATED MODULE: ./src/core/util.ts var Util = { now: function () { if (Date.now) { return Date.now(); } else { return new Date().valueOf(); } }, defer: function (callback) { return new OneOffTimer(0, callback); }, method: function (name) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var boundArguments = Array.prototype.slice.call(arguments, 1); return function (object) { return object[name].apply(object, boundArguments.concat(arguments)); }; } }; /* harmony default export */ var util = (Util); // CONCATENATED MODULE: ./src/core/utils/collections.ts function extend(target) { var sources = []; for (var _i = 1; _i < arguments.length; _i++) { sources[_i - 1] = arguments[_i]; } for (var i = 0; i < sources.length; i++) { var extensions = sources[i]; for (var property in extensions) { if (extensions[property] && extensions[property].constructor && extensions[property].constructor === Object) { target[property] = extend(target[property] || {}, extensions[property]); } else { target[property] = extensions[property]; } } } return target; } function stringify() { var m = ['Pusher']; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] === 'string') { m.push(arguments[i]); } else { m.push(safeJSONStringify(arguments[i])); } } return m.join(' : '); } function arrayIndexOf(array, item) { var nativeIndexOf = Array.prototype.indexOf; if (array === null) { return -1; } if (nativeIndexOf && array.indexOf === nativeIndexOf) { return array.indexOf(item); } for (var i = 0, l = array.length; i < l; i++) { if (array[i] === item) { return i; } } return -1; } function objectApply(object, f) { for (var key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { f(object[key], key, object); } } } function keys(object) { var keys = []; objectApply(object, function (_, key) { keys.push(key); }); return keys; } function values(object) { var values = []; objectApply(object, function (value) { values.push(value); }); return values; } function apply(array, f, context) { for (var i = 0; i < array.length; i++) { f.call(context || self, array[i], i, array); } } function map(array, f) { var result = []; for (var i = 0; i < array.length; i++) { result.push(f(array[i], i, array, result)); } return result; } function mapObject(object, f) { var result = {}; objectApply(object, function (value, key) { result[key] = f(value); }); return result; } function filter(array, test) { test = test || function (value) { return !!value; }; var result = []; for (var i = 0; i < array.length; i++) { if (test(array[i], i, array, result)) { result.push(array[i]); } } return result; } function filterObject(object, test) { var result = {}; objectApply(object, function (value, key) { if ((test && test(value, key, object, result)) || Boolean(value)) { result[key] = value; } }); return result; } function flatten(object) { var result = []; objectApply(object, function (value, key) { result.push([key, value]); }); return result; } function any(array, test) { for (var i = 0; i < array.length; i++) { if (test(array[i], i, array)) { return true; } } return false; } function collections_all(array, test) { for (var i = 0; i < array.length; i++) { if (!test(array[i], i, array)) { return false; } } return true; } function encodeParamsObject(data) { return mapObject(data, function (value) { if (typeof value === 'object') { value = safeJSONStringify(value); } return encodeURIComponent(encode(value.toString())); }); } function buildQueryString(data) { var params = filterObject(data, function (value) { return value !== undefined; }); var query = map(flatten(encodeParamsObject(params)), util.method('join', '=')).join('&'); return query; } function decycleObject(object) { var objects = [], paths = []; return (function derez(value, path) { var i, name, nu; switch (typeof value) { case 'object': if (!value) { return null; } for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return { $ref: paths[i] }; } } objects.push(value); paths.push(path); if (Object.prototype.toString.apply(value) === '[object Array]') { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = derez(value[i], path + '[' + i + ']'); } } else { nu = {}; for (name in value) { if (Object.prototype.hasOwnProperty.call(value, name)) { nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']'); } } } return nu; case 'number': case 'string': case 'boolean': return value; } })(object, '$'); } function safeJSONStringify(source) { try { return JSON.stringify(source); } catch (e) { return JSON.stringify(decycleObject(source)); } } // CONCATENATED MODULE: ./src/core/defaults.ts var Defaults = { VERSION: "6.0.1", PROTOCOL: 7, wsPort: 80, wssPort: 443, wsPath: '', httpHost: 'sockjs.pusher.com', httpPort: 80, httpsPort: 443, httpPath: '/pusher', stats_host: 'stats.pusher.com', authEndpoint: '/pusher/auth', authTransport: 'ajax', activityTimeout: 120000, pongTimeout: 30000, unavailableTimeout: 10000, cluster: 'mt1', cdn_http: "http://js.pusher.com", cdn_https: "https://js.pusher.com", dependency_suffix: "" }; /* harmony default export */ var defaults = (Defaults); // CONCATENATED MODULE: ./src/core/transports/url_schemes.ts function getGenericURL(baseScheme, params, path) { var scheme = baseScheme + (params.useTLS ? 's' : ''); var host = params.useTLS ? params.hostTLS : params.hostNonTLS; return scheme + '://' + host + path; } function getGenericPath(key, queryString) { var path = '/app/' + key; var query = '?protocol=' + defaults.PROTOCOL + '&client=js' + '&version=' + defaults.VERSION + (queryString ? '&' + queryString : ''); return path + query; } var ws = { getInitial: function (key, params) { var path = (params.httpPath || '') + getGenericPath(key, 'flash=false'); return getGenericURL('ws', params, path); } }; var http = { getInitial: function (key, params) { var path = (params.httpPath || '/pusher') + getGenericPath(key); return getGenericURL('http', params, path); } }; var sockjs = { getInitial: function (key, params) { return getGenericURL('http', params, params.httpPath || '/pusher'); }, getPath: function (key, params) { return getGenericPath(key); } }; // CONCATENATED MODULE: ./src/core/events/callback_registry.ts var callback_registry_CallbackRegistry = (function () { function CallbackRegistry() { this._callbacks = {}; } CallbackRegistry.prototype.get = function (name) { return this._callbacks[prefix(name)]; }; CallbackRegistry.prototype.add = function (name, callback, context) { var prefixedEventName = prefix(name); this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || []; this._callbacks[prefixedEventName].push({ fn: callback, context: context }); }; CallbackRegistry.prototype.remove = function (name, callback, context) { if (!name && !callback && !context) { this._callbacks = {}; return; } var names = name ? [prefix(name)] : keys(this._callbacks); if (callback || context) { this.removeCallback(names, callback, context); } else { this.removeAllCallbacks(names); } }; CallbackRegistry.prototype.removeCallback = function (names, callback, context) { apply(names, function (name) { this._callbacks[name] = filter(this._callbacks[name] || [], function (binding) { return ((callback && callback !== binding.fn) || (context && context !== binding.context)); }); if (this._callbacks[name].length === 0) { delete this._callbacks[name]; } }, this); }; CallbackRegistry.prototype.removeAllCallbacks = function (names) { apply(names, function (name) { delete this._callbacks[name]; }, this); }; return CallbackRegistry; }()); /* harmony default export */ var callback_registry = (callback_registry_CallbackRegistry); function prefix(name) { return '_' + name; } // CONCATENATED MODULE: ./src/core/events/dispatcher.ts var dispatcher_Dispatcher = (function () { function Dispatcher(failThrough) { this.callbacks = new callback_registry(); this.global_callbacks = []; this.failThrough = failThrough; } Dispatcher.prototype.bind = function (eventName, callback, context) { this.callbacks.add(eventName, callback, context); return this; }; Dispatcher.prototype.bind_global = function (callback) { this.global_callbacks.push(callback); return this; }; Dispatcher.prototype.unbind = function (eventName, callback, context) { this.callbacks.remove(eventName, callback, context); return this; }; Dispatcher.prototype.unbind_global = function (callback) { if (!callback) { this.global_callbacks = []; return this; } this.global_callbacks = filter(this.global_callbacks || [], function (c) { return c !== callback; }); return this; }; Dispatcher.prototype.unbind_all = function () { this.unbind(); this.unbind_global(); return this; }; Dispatcher.prototype.emit = function (eventName, data, metadata) { for (var i = 0; i < this.global_callbacks.length; i++) { this.global_callbacks[i](eventName, data); } var callbacks = this.callbacks.get(eventName); var args = []; if (metadata) { args.push(data, metadata); } else if (data) { args.push(data); } if (callbacks && callbacks.length > 0) { for (var i = 0; i < callbacks.length; i++) { callbacks[i].fn.apply(callbacks[i].context || self, args); } } else if (this.failThrough) { this.failThrough(eventName, data); } return this; }; return Dispatcher; }()); /* harmony default export */ var dispatcher = (dispatcher_Dispatcher); // CONCATENATED MODULE: ./src/core/logger.ts var logger_Logger = (function () { function Logger() { this.globalLog = function (message) { if (self.console && self.console.log) { self.console.log(message); } }; } Logger.prototype.debug = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.log(this.globalLog, args); }; Logger.prototype.warn = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.log(this.globalLogWarn, args); }; Logger.prototype.error = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } this.log(this.globalLogError, args); }; Logger.prototype.globalLogWarn = function (message) { if (self.console && self.console.warn) { self.console.warn(message); } else { this.globalLog(message); } }; Logger.prototype.globalLogError = function (message) { if (self.console && self.console.error) { self.console.error(message); } else { this.globalLogWarn(message); } }; Logger.prototype.log = function (defaultLoggingFunction) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } var message = stringify.apply(this, arguments); if (core_pusher.log) { core_pusher.log(message); } else if (core_pusher.logToConsole) { var log = defaultLoggingFunction.bind(this); log(message); } }; return Logger; }()); /* harmony default export */ var logger = (new logger_Logger()); // CONCATENATED MODULE: ./src/core/transports/transport_connection.ts var transport_connection_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var transport_connection_TransportConnection = (function (_super) { transport_connection_extends(TransportConnection, _super); function TransportConnection(hooks, name, priority, key, options) { var _this = _super.call(this) || this; _this.initialize = worker_runtime.transportConnectionInitializer; _this.hooks = hooks; _this.name = name; _this.priority = priority; _this.key = key; _this.options = options; _this.state = 'new'; _this.timeline = options.timeline; _this.activityTimeout = options.activityTimeout; _this.id = _this.timeline.generateUniqueID(); return _this; } TransportConnection.prototype.handlesActivityChecks = function () { return Boolean(this.hooks.handlesActivityChecks); }; TransportConnection.prototype.supportsPing = function () { return Boolean(this.hooks.supportsPing); }; TransportConnection.prototype.connect = function () { var _this = this; if (this.socket || this.state !== 'initialized') { return false; } var url = this.hooks.urls.getInitial(this.key, this.options); try { this.socket = this.hooks.getSocket(url, this.options); } catch (e) { util.defer(function () { _this.onError(e); _this.changeState('closed'); }); return false; } this.bindListeners(); logger.debug('Connecting', { transport: this.name, url: url }); this.changeState('connecting'); return true; }; TransportConnection.prototype.close = function () { if (this.socket) { this.socket.close(); return true; } else { return false; } }; TransportConnection.prototype.send = function (data) { var _this = this; if (this.state === 'open') { util.defer(function () { if (_this.socket) { _this.socket.send(data); } }); return true; } else { return false; } }; TransportConnection.prototype.ping = function () { if (this.state === 'open' && this.supportsPing()) { this.socket.ping(); } }; TransportConnection.prototype.onOpen = function () { if (this.hooks.beforeOpen) { this.hooks.beforeOpen(this.socket, this.hooks.urls.getPath(this.key, this.options)); } this.changeState('open'); this.socket.onopen = undefined; }; TransportConnection.prototype.onError = function (error) { this.emit('error', { type: 'WebSocketError', error: error }); this.timeline.error(this.buildTimelineMessage({ error: error.toString() })); }; TransportConnection.prototype.onClose = function (closeEvent) { if (closeEvent) { this.changeState('closed', { code: closeEvent.code, reason: closeEvent.reason, wasClean: closeEvent.wasClean }); } else { this.changeState('closed'); } this.unbindListeners(); this.socket = undefined; }; TransportConnection.prototype.onMessage = function (message) { this.emit('message', message); }; TransportConnection.prototype.onActivity = function () { this.emit('activity'); }; TransportConnection.prototype.bindListeners = function () { var _this = this; this.socket.onopen = function () { _this.onOpen(); }; this.socket.onerror = function (error) { _this.onError(error); }; this.socket.onclose = function (closeEvent) { _this.onClose(closeEvent); }; this.socket.onmessage = function (message) { _this.onMessage(message); }; if (this.supportsPing()) { this.socket.onactivity = function () { _this.onActivity(); }; } }; TransportConnection.prototype.unbindListeners = function () { if (this.socket) { this.socket.onopen = undefined; this.socket.onerror = undefined; this.socket.onclose = undefined; this.socket.onmessage = undefined; if (this.supportsPing()) { this.socket.onactivity = undefined; } } }; TransportConnection.prototype.changeState = function (state, params) { this.state = state; this.timeline.info(this.buildTimelineMessage({ state: state, params: params })); this.emit(state, params); }; TransportConnection.prototype.buildTimelineMessage = function (message) { return extend({ cid: this.id }, message); }; return TransportConnection; }(dispatcher)); /* harmony default export */ var transport_connection = (transport_connection_TransportConnection); // CONCATENATED MODULE: ./src/core/transports/transport.ts var transport_Transport = (function () { function Transport(hooks) { this.hooks = hooks; } Transport.prototype.isSupported = function (environment) { return this.hooks.isSupported(environment); }; Transport.prototype.createConnection = function (name, priority, key, options) { return new transport_connection(this.hooks, name, priority, key, options); }; return Transport; }()); /* harmony default export */ var transports_transport = (transport_Transport); // CONCATENATED MODULE: ./src/runtimes/isomorphic/transports/transports.ts var WSTransport = new transports_transport({ urls: ws, handlesActivityChecks: false, supportsPing: false, isInitialized: function () { return Boolean(worker_runtime.getWebSocketAPI()); }, isSupported: function () { return Boolean(worker_runtime.getWebSocketAPI()); }, getSocket: function (url) { return worker_runtime.createWebSocket(url); } }); var httpConfiguration = { urls: http, handlesActivityChecks: false, supportsPing: true, isInitialized: function () { return true; } }; var streamingConfiguration = extend({ getSocket: function (url) { return worker_runtime.HTTPFactory.createStreamingSocket(url); } }, httpConfiguration); var pollingConfiguration = extend({ getSocket: function (url) { return worker_runtime.HTTPFactory.createPollingSocket(url); } }, httpConfiguration); var xhrConfiguration = { isSupported: function () { return worker_runtime.isXHRSupported(); } }; var XHRStreamingTransport = new transports_transport((extend({}, streamingConfiguration, xhrConfiguration))); var XHRPollingTransport = new transports_transport(extend({}, pollingConfiguration, xhrConfiguration)); var Transports = { ws: WSTransport, xhr_streaming: XHRStreamingTransport, xhr_polling: XHRPollingTransport }; /* harmony default export */ var transports = (Transports); // CONCATENATED MODULE: ./src/core/transports/assistant_to_the_transport_manager.ts var assistant_to_the_transport_manager_AssistantToTheTransportManager = (function () { function AssistantToTheTransportManager(manager, transport, options) { this.manager = manager; this.transport = transport; this.minPingDelay = options.minPingDelay; this.maxPingDelay = options.maxPingDelay; this.pingDelay = undefined; } AssistantToTheTransportManager.prototype.createConnection = function (name, priority, key, options) { var _this = this; options = extend({}, options, { activityTimeout: this.pingDelay }); var connection = this.transport.createConnection(name, priority, key, options); var openTimestamp = null; var onOpen = function () { connection.unbind('open', onOpen); connection.bind('closed', onClosed); openTimestamp = util.now(); }; var onClosed = function (closeEvent) { connection.unbind('closed', onClosed); if (closeEvent.code === 1002 || closeEvent.code === 1003) { _this.manager.reportDeath(); } else if (!closeEvent.wasClean && openTimestamp) { var lifespan = util.now() - openTimestamp; if (lifespan < 2 * _this.maxPingDelay) { _this.manager.reportDeath(); _this.pingDelay = Math.max(lifespan / 2, _this.minPingDelay); } } }; connection.bind('open', onOpen); return connection; }; AssistantToTheTransportManager.prototype.isSupported = function (environment) { return this.manager.isAlive() && this.transport.isSupported(environment); }; return AssistantToTheTransportManager; }()); /* harmony default export */ var assistant_to_the_transport_manager = (assistant_to_the_transport_manager_AssistantToTheTransportManager); // CONCATENATED MODULE: ./src/core/connection/protocol/protocol.ts var Protocol = { decodeMessage: function (messageEvent) { try { var messageData = JSON.parse(messageEvent.data); var pusherEventData = messageData.data; if (typeof pusherEventData === 'string') { try { pusherEventData = JSON.parse(messageData.data); } catch (e) { } } var pusherEvent = { event: messageData.event, channel: messageData.channel, data: pusherEventData }; if (messageData.user_id) { pusherEvent.user_id = messageData.user_id; } return pusherEvent; } catch (e) { throw { type: 'MessageParseError', error: e, data: messageEvent.data }; } }, encodeMessage: function (event) { return JSON.stringify(event); }, processHandshake: function (messageEvent) { var message = Protocol.decodeMessage(messageEvent); if (message.event === 'pusher:connection_established') { if (!message.data.activity_timeout) { throw 'No activity timeout specified in handshake'; } return { action: 'connected', id: message.data.socket_id, activityTimeout: message.data.activity_timeout * 1000 }; } else if (message.event === 'pusher:error') { return { action: this.getCloseAction(message.data), error: this.getCloseError(message.data) }; } else { throw 'Invalid handshake'; } }, getCloseAction: function (closeEvent) { if (closeEvent.code < 4000) { if (closeEvent.code >= 1002 && closeEvent.code <= 1004) { return 'backoff'; } else { return null; } } else if (closeEvent.code === 4000) { return 'tls_only'; } else if (closeEvent.code < 4100) { return 'refused'; } else if (closeEvent.code < 4200) { return 'backoff'; } else if (closeEvent.code < 4300) { return 'retry'; } else { return 'refused'; } }, getCloseError: function (closeEvent) { if (closeEvent.code !== 1000 && closeEvent.code !== 1001) { return { type: 'PusherError', data: { code: closeEvent.code, message: closeEvent.reason || closeEvent.message } }; } else { return null; } } }; /* harmony default export */ var protocol = (Protocol); // CONCATENATED MODULE: ./src/core/connection/connection.ts var connection_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var connection_Connection = (function (_super) { connection_extends(Connection, _super); function Connection(id, transport) { var _this = _super.call(this) || this; _this.id = id; _this.transport = transport; _this.activityTimeout = transport.activityTimeout; _this.bindListeners(); return _this; } Connection.prototype.handlesActivityChecks = function () { return this.transport.handlesActivityChecks(); }; Connection.prototype.send = function (data) { return this.transport.send(data); }; Connection.prototype.send_event = function (name, data, channel) { var event = { event: name, data: data }; if (channel) { event.channel = channel; } logger.debug('Event sent', event); return this.send(protocol.encodeMessage(event)); }; Connection.prototype.ping = function () { if (this.transport.supportsPing()) { this.transport.ping(); } else { this.send_event('pusher:ping', {}); } }; Connection.prototype.close = function () { this.transport.close(); }; Connection.prototype.bindListeners = function () { var _this = this; var listeners = { message: function (messageEvent) { var pusherEvent; try { pusherEvent = protocol.decodeMessage(messageEvent); } catch (e) { _this.emit('error', { type: 'MessageParseError', error: e, data: messageEvent.data }); } if (pusherEvent !== undefined) { logger.debug('Event recd', pusherEvent); switch (pusherEvent.event) { case 'pusher:error': _this.emit('error', { type: 'PusherError', data: pusherEvent.data }); break; case 'pusher:ping': _this.emit('ping'); break; case 'pusher:pong': _this.emit('pong'); break; } _this.emit('message', pusherEvent); } }, activity: function () { _this.emit('activity'); }, error: function (error) { _this.emit('error', { type: 'WebSocketError', error: error }); }, closed: function (closeEvent) { unbindListeners(); if (closeEvent && closeEvent.code) { _this.handleCloseEvent(closeEvent); } _this.transport = null; _this.emit('closed'); } }; var unbindListeners = function () { objectApply(listeners, function (listener, event) { _this.transport.unbind(event, listener); }); }; objectApply(listeners, function (listener, event) { _this.transport.bind(event, listener); }); }; Connection.prototype.handleCloseEvent = function (closeEvent) { var action = protocol.getCloseAction(closeEvent); var error = protocol.getCloseError(closeEvent); if (error) { this.emit('error', error); } if (action) { this.emit(action, { action: action, error: error }); } }; return Connection; }(dispatcher)); /* harmony default export */ var connection_connection = (connection_Connection); // CONCATENATED MODULE: ./src/core/connection/handshake/index.ts var handshake_Handshake = (function () { function Handshake(transport, callback) { this.transport = transport; this.callback = callback; this.bindListeners(); } Handshake.prototype.close = function () { this.unbindListeners(); this.transport.close(); }; Handshake.prototype.bindListeners = function () { var _this = this; this.onMessage = function (m) { _this.unbindListeners(); var result; try { result = protocol.processHandshake(m); } catch (e) { _this.finish('error', { error: e }); _this.transport.close(); return; } if (result.action === 'connected') { _this.finish('connected', { connection: new connection_connection(result.id, _this.transport), activityTimeout: result.activityTimeout }); } else { _this.finish(result.action, { error: result.error }); _this.transport.close(); } }; this.onClosed = function (closeEvent) { _this.unbindListeners(); var action = protocol.getCloseAction(closeEvent) || 'backoff'; var error = protocol.getCloseError(closeEvent); _this.finish(action, { error: error }); }; this.transport.bind('message', this.onMessage); this.transport.bind('closed', this.onClosed); }; Handshake.prototype.unbindListeners = function () { this.transport.unbind('message', this.onMessage); this.transport.unbind('closed', this.onClosed); }; Handshake.prototype.finish = function (action, params) { this.callback(extend({ transport: this.transport, action: action }, params)); }; return Handshake; }()); /* harmony default export */ var connection_handshake = (handshake_Handshake); // CONCATENATED MODULE: ./src/core/auth/pusher_authorizer.ts var pusher_authorizer_PusherAuthorizer = (function () { function PusherAuthorizer(channel, options) { this.channel = channel; var authTransport = options.authTransport; if (typeof worker_runtime.getAuthorizers()[authTransport] === 'undefined') { throw "'" + authTransport + "' is not a recognized auth transport"; } this.type = authTransport; this.options = options; this.authOptions = options.auth || {}; } PusherAuthorizer.prototype.composeQuery = function (socketId) { var query = 'socket_id=' + encodeURIComponent(socketId) + '&channel_name=' + encodeURIComponent(this.channel.name); for (var i in this.authOptions.params) { query += '&' + encodeURIComponent(i) + '=' + encodeURIComponent(this.authOptions.params[i]); } return query; }; PusherAuthorizer.prototype.authorize = function (socketId, callback) { PusherAuthorizer.authorizers = PusherAuthorizer.authorizers || worker_runtime.getAuthorizers(); PusherAuthorizer.authorizers[this.type].call(this, worker_runtime, socketId, callback); }; return PusherAuthorizer; }()); /* harmony default export */ var pusher_authorizer = (pusher_authorizer_PusherAuthorizer); // CONCATENATED MODULE: ./src/core/timeline/timeline_sender.ts var timeline_sender_TimelineSender = (function () { function TimelineSender(timeline, options) { this.timeline = timeline; this.options = options || {}; } TimelineSender.prototype.send = function (useTLS, callback) { if (this.timeline.isEmpty()) { return; } this.timeline.send(worker_runtime.TimelineTransport.getAgent(this, useTLS), callback); }; return TimelineSender; }()); /* harmony default export */ var timeline_sender = (timeline_sender_TimelineSender); // CONCATENATED MODULE: ./src/core/errors.ts var errors_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var BadEventName = (function (_super) { errors_extends(BadEventName, _super); function BadEventName(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return BadEventName; }(Error)); var RequestTimedOut = (function (_super) { errors_extends(RequestTimedOut, _super); function RequestTimedOut(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return RequestTimedOut; }(Error)); var TransportPriorityTooLow = (function (_super) { errors_extends(TransportPriorityTooLow, _super); function TransportPriorityTooLow(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return TransportPriorityTooLow; }(Error)); var TransportClosed = (function (_super) { errors_extends(TransportClosed, _super); function TransportClosed(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return TransportClosed; }(Error)); var UnsupportedFeature = (function (_super) { errors_extends(UnsupportedFeature, _super); function UnsupportedFeature(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return UnsupportedFeature; }(Error)); var UnsupportedTransport = (function (_super) { errors_extends(UnsupportedTransport, _super); function UnsupportedTransport(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return UnsupportedTransport; }(Error)); var UnsupportedStrategy = (function (_super) { errors_extends(UnsupportedStrategy, _super); function UnsupportedStrategy(msg) { var _newTarget = this.constructor; var _this = _super.call(this, msg) || this; Object.setPrototypeOf(_this, _newTarget.prototype); return _this; } return UnsupportedStrategy; }(Error)); // CONCATENATED MODULE: ./src/core/utils/url_store.ts var urlStore = { baseUrl: 'https://pusher.com', urls: { authenticationEndpoint: { path: '/docs/authenticating_users' }, javascriptQuickStart: { path: '/docs/javascript_quick_start' }, triggeringClientEvents: { path: '/docs/client_api_guide/client_events#trigger-events' }, encryptedChannelSupport: { fullUrl: 'https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support' } } }; var buildLogSuffix = function (key) { var urlPrefix = 'See:'; var urlObj = urlStore.urls[key]; if (!urlObj) return ''; var url; if (urlObj.fullUrl) { url = urlObj.fullUrl; } else if (urlObj.path) { url = urlStore.baseUrl + urlObj.path; } if (!url) return ''; return urlPrefix + " " + url; }; /* harmony default export */ var url_store = ({ buildLogSuffix: buildLogSuffix }); // CONCATENATED MODULE: ./src/core/channels/channel.ts var channel_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var channel_Channel = (function (_super) { channel_extends(Channel, _super); function Channel(name, pusher) { var _this = _super.call(this, function (event, data) { logger.debug('No callbacks on ' + name + ' for ' + event); }) || this; _this.name = name; _this.pusher = pusher; _this.subscribed = false; _this.subscriptionPending = false; _this.subscriptionCancelled = false; return _this; } Channel.prototype.authorize = function (socketId, callback) { return callback(false, { auth: '' }); }; Channel.prototype.trigger = function (event, data) { if (event.indexOf('client-') !== 0) { throw new BadEventName("Event '" + event + "' does not start with 'client-'"); } if (!this.subscribed) { var suffix = url_store.buildLogSuffix('triggeringClientEvents'); logger.warn("Client event triggered before channel 'subscription_succeeded' event . " + suffix); } return this.pusher.send_event(event, data, this.name); }; Channel.prototype.disconnect = function () { this.subscribed = false; this.subscriptionPending = false; }; Channel.prototype.handleEvent = function (event) { var eventName = event.event; var data = event.data; if (eventName === 'pusher_internal:subscription_succeeded') { this.handleSubscriptionSucceededEvent(event); } else if (eventName.indexOf('pusher_internal:') !== 0) { var metadata = {}; this.emit(eventName, data, metadata); } }; Channel.prototype.handleSubscriptionSucceededEvent = function (event) { this.subscriptionPending = false; this.subscribed = true; if (this.subscriptionCancelled) { this.pusher.unsubscribe(this.name); } else { this.emit('pusher:subscription_succeeded', event.data); } }; Channel.prototype.subscribe = function () { var _this = this; if (this.subscribed) { return; } this.subscriptionPending = true; this.subscriptionCancelled = false; this.authorize(this.pusher.connection.socket_id, function (error, data) { if (error) { logger.error(data); _this.emit('pusher:subscription_error', data); } else { data = data; _this.pusher.send_event('pusher:subscribe', { auth: data.auth, channel_data: data.channel_data, channel: _this.name }); } }); }; Channel.prototype.unsubscribe = function () { this.subscribed = false; this.pusher.send_event('pusher:unsubscribe', { channel: this.name }); }; Channel.prototype.cancelSubscription = function () { this.subscriptionCancelled = true; }; Channel.prototype.reinstateSubscription = function () { this.subscriptionCancelled = false; }; return Channel; }(dispatcher)); /* harmony default export */ var channels_channel = (channel_Channel); // CONCATENATED MODULE: ./src/core/channels/private_channel.ts var private_channel_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var private_channel_PrivateChannel = (function (_super) { private_channel_extends(PrivateChannel, _super); function PrivateChannel() { return _super !== null && _super.apply(this, arguments) || this; } PrivateChannel.prototype.authorize = function (socketId, callback) { var authorizer = factory.createAuthorizer(this, this.pusher.config); return authorizer.authorize(socketId, callback); }; return PrivateChannel; }(channels_channel)); /* harmony default export */ var private_channel = (private_channel_PrivateChannel); // CONCATENATED MODULE: ./src/core/channels/members.ts var members_Members = (function () { function Members() { this.reset(); } Members.prototype.get = function (id) { if (Object.prototype.hasOwnProperty.call(this.members, id)) { return { id: id, info: this.members[id] }; } else { return null; } }; Members.prototype.each = function (callback) { var _this = this; objectApply(this.members, function (member, id) { callback(_this.get(id)); }); }; Members.prototype.setMyID = function (id) { this.myID = id; }; Members.prototype.onSubscription = function (subscriptionData) { this.members = subscriptionData.presence.hash; this.count = subscriptionData.presence.count; this.me = this.get(this.myID); }; Members.prototype.addMember = function (memberData) { if (this.get(memberData.user_id) === null) { this.count++; } this.members[memberData.user_id] = memberData.user_info; return this.get(memberData.user_id); }; Members.prototype.removeMember = function (memberData) { var member = this.get(memberData.user_id); if (member) { delete this.members[memberData.user_id]; this.count--; } return member; }; Members.prototype.reset = function () { this.members = {}; this.count = 0; this.myID = null; this.me = null; }; return Members; }()); /* harmony default export */ var members = (members_Members); // CONCATENATED MODULE: ./src/core/channels/presence_channel.ts var presence_channel_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var presence_channel_PresenceChannel = (function (_super) { presence_channel_extends(PresenceChannel, _super); function PresenceChannel(name, pusher) { var _this = _super.call(this, name, pusher) || this; _this.members = new members(); return _this; } PresenceChannel.prototype.authorize = function (socketId, callback) { var _this = this; _super.prototype.authorize.call(this, socketId, function (error, authData) { if (!error) { authData = authData; if (authData.channel_data === undefined) { var suffix = url_store.buildLogSuffix('authenticationEndpoint'); logger.error("Invalid auth response for channel '" + _this.name + "'," + ("expected 'channel_data' field. " + suffix)); callback('Invalid auth response'); return; } var channelData = JSON.parse(authData.channel_data); _this.members.setMyID(channelData.user_id); } callback(error, authData); }); }; PresenceChannel.prototype.handleEvent = function (event) { var eventName = event.event; if (eventName.indexOf('pusher_internal:') === 0) { this.handleInternalEvent(event); } else { var data = event.data; var metadata = {}; if (event.user_id) { metadata.user_id = event.user_id; } this.emit(eventName, data, metadata); } }; PresenceChannel.prototype.handleInternalEvent = function (event) { var eventName = event.event; var data = event.data; switch (eventName) { case 'pusher_internal:subscription_succeeded': this.handleSubscriptionSucceededEvent(event); break; case 'pusher_internal:member_added': var addedMember = this.members.addMember(data); this.emit('pusher:member_added', addedMember); break; case 'pusher_internal:member_removed': var removedMember = this.members.removeMember(data); if (removedMember) { this.emit('pusher:member_removed', removedMember); } break; } }; PresenceChannel.prototype.handleSubscriptionSucceededEvent = function (event) { this.subscriptionPending = false; this.subscribed = true; if (this.subscriptionCancelled) { this.pusher.unsubscribe(this.name); } else { this.members.onSubscription(event.data); this.emit('pusher:subscription_succeeded', this.members); } }; PresenceChannel.prototype.disconnect = function () { this.members.reset(); _super.prototype.disconnect.call(this); }; return PresenceChannel; }(private_channel)); /* harmony default export */ var presence_channel = (presence_channel_PresenceChannel); // EXTERNAL MODULE: ./node_modules/@stablelib/utf8/lib/utf8.js var utf8 = __webpack_require__(1); // EXTERNAL MODULE: ./node_modules/@stablelib/base64/lib/base64.js var base64 = __webpack_require__(0); // CONCATENATED MODULE: ./src/core/channels/encrypted_channel.ts var encrypted_channel_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var encrypted_channel_EncryptedChannel = (function (_super) { encrypted_channel_extends(EncryptedChannel, _super); function EncryptedChannel(name, pusher, nacl) { var _this = _super.call(this, name, pusher) || this; _this.key = null; _this.nacl = nacl; return _this; } EncryptedChannel.prototype.authorize = function (socketId, callback) { var _this = this; _super.prototype.authorize.call(this, socketId, function (error, authData) { if (error) { callback(true, authData); return; } var sharedSecret = authData['shared_secret']; if (!sharedSecret) { var errorMsg = "No shared_secret key in auth payload for encrypted channel: " + _this.name; callback(true, errorMsg); return; } _this.key = Object(base64["decode"])(sharedSecret); delete authData['shared_secret']; callback(false, authData); }); }; EncryptedChannel.prototype.trigger = function (event, data) { throw new UnsupportedFeature('Client events are not currently supported for encrypted channels'); }; EncryptedChannel.prototype.handleEvent = function (event) { var eventName = event.event; var data = event.data; if (eventName.indexOf('pusher_internal:') === 0 || eventName.indexOf('pusher:') === 0) { _super.prototype.handleEvent.call(this, event); return; } this.handleEncryptedEvent(eventName, data); }; EncryptedChannel.prototype.handleEncryptedEvent = function (event, data) { var _this = this; if (!this.key) { logger.debug('Received encrypted event before key has been retrieved from the authEndpoint'); return; } if (!data.ciphertext || !data.nonce) { logger.error('Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: ' + data); return; } var cipherText = Object(base64["decode"])(data.ciphertext); if (cipherText.length < this.nacl.secretbox.overheadLength) { logger.error("Expected encrypted event ciphertext length to be " + this.nacl.secretbox.overheadLength + ", got: " + cipherText.length); return; } var nonce = Object(base64["decode"])(data.nonce); if (nonce.length < this.nacl.secretbox.nonceLength) { logger.error("Expected encrypted event nonce length to be " + this.nacl.secretbox.nonceLength + ", got: " + nonce.length); return; } var bytes = this.nacl.secretbox.open(cipherText, nonce, this.key); if (bytes === null) { logger.debug('Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint...'); this.authorize(this.pusher.connection.socket_id, function (error, authData) { if (error) { logger.error("Failed to make a request to the authEndpoint: " + authData + ". Unable to fetch new key, so dropping encrypted event"); return; } bytes = _this.nacl.secretbox.open(cipherText, nonce, _this.key); if (bytes === null) { logger.error("Failed to decrypt event with new key. Dropping encrypted event"); return; } _this.emitJSON(event, Object(utf8["decode"])(bytes)); return; }); return; } this.emitJSON(event, Object(utf8["decode"])(bytes)); }; EncryptedChannel.prototype.emitJSON = function (eventName, data) { try { this.emit(eventName, JSON.parse(data)); } catch (e) { this.emit(eventName, data); } return this; }; return EncryptedChannel; }(private_channel)); /* harmony default export */ var encrypted_channel = (encrypted_channel_EncryptedChannel); // CONCATENATED MODULE: ./src/core/connection/connection_manager.ts var connection_manager_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var connection_manager_ConnectionManager = (function (_super) { connection_manager_extends(ConnectionManager, _super); function ConnectionManager(key, options) { var _this = _super.call(this) || this; _this.state = 'initialized'; _this.connection = null; _this.key = key; _this.options = options; _this.timeline = _this.options.timeline; _this.usingTLS = _this.options.useTLS; _this.errorCallbacks = _this.buildErrorCallbacks(); _this.connectionCallbacks = _this.buildConnectionCallbacks(_this.errorCallbacks); _this.handshakeCallbacks = _this.buildHandshakeCallbacks(_this.errorCallbacks); var Network = worker_runtime.getNetwork(); Network.bind('online', function () { _this.timeline.info({ netinfo: 'online' }); if (_this.state === 'connecting' || _this.state === 'unavailable') { _this.retryIn(0); } }); Network.bind('offline', function () { _this.timeline.info({ netinfo: 'offline' }); if (_this.connection) { _this.sendActivityCheck(); } }); _this.updateStrategy(); return _this; } ConnectionManager.prototype.connect = function () { if (this.connection || this.runner) { return; } if (!this.strategy.isSupported()) { this.updateState('failed'); return; } this.updateState('connecting'); this.startConnecting(); this.setUnavailableTimer(); }; ConnectionManager.prototype.send = function (data) { if (this.connection) { return this.connection.send(data); } else { return false; } }; ConnectionManager.prototype.send_event = function (name, data, channel) { if (this.connection) { return this.connection.send_event(name, data, channel); } else { return false; } }; ConnectionManager.prototype.disconnect = function () { this.disconnectInternally(); this.updateState('disconnected'); }; ConnectionManager.prototype.isUsingTLS = function () { return this.usingTLS; }; ConnectionManager.prototype.startConnecting = function () { var _this = this; var callback = function (error, handshake) { if (error) { _this.runner = _this.strategy.connect(0, callback); } else { if (handshake.action === 'error') { _this.emit('error', { type: 'HandshakeError', error: handshake.error }); _this.timeline.error({ handshakeError: handshake.error }); } else { _this.abortConnecting(); _this.handshakeCallbacks[handshake.action](handshake); } } }; this.runner = this.strategy.connect(0, callback); }; ConnectionManager.prototype.abortConnecting = function () { if (this.runner) { this.runner.abort(); this.runner = null; } }; ConnectionManager.prototype.disconnectInternally = function () { this.abortConnecting(); this.clearRetryTimer(); this.clearUnavailableTimer(); if (this.connection) { var connection = this.abandonConnection(); connection.close(); } }; ConnectionManager.prototype.updateStrategy = function () { this.strategy = this.options.getStrategy({ key: this.key, timeline: this.timeline, useTLS: this.usingTLS }); }; ConnectionManager.prototype.retryIn = function (delay) { var _this = this; this.timeline.info({ action: 'retry', delay: delay }); if (delay > 0) { this.emit('connecting_in', Math.round(delay / 1000)); } this.retryTimer = new OneOffTimer(delay || 0, function () { _this.disconnectInternally(); _this.connect(); }); }; ConnectionManager.prototype.clearRetryTimer = function () { if (this.retryTimer) { this.retryTimer.ensureAborted(); this.retryTimer = null; } }; ConnectionManager.prototype.setUnavailableTimer = function () { var _this = this; this.unavailableTimer = new OneOffTimer(this.options.unavailableTimeout, function () { _this.updateState('unavailable'); }); }; ConnectionManager.prototype.clearUnavailableTimer = function () { if (this.unavailableTimer) { this.unavailableTimer.ensureAborted(); } }; ConnectionManager.prototype.sendActivityCheck = function () { var _this = this; this.stopActivityCheck(); this.connection.ping(); this.activityTimer = new OneOffTimer(this.options.pongTimeout, function () { _this.timeline.error({ pong_timed_out: _this.options.pongTimeout }); _this.retryIn(0); }); }; ConnectionManager.prototype.resetActivityCheck = function () { var _this = this; this.stopActivityCheck(); if (this.connection && !this.connection.handlesActivityChecks()) { this.activityTimer = new OneOffTimer(this.activityTimeout, function () { _this.sendActivityCheck(); }); } }; ConnectionManager.prototype.stopActivityCheck = function () { if (this.activityTimer) { this.activityTimer.ensureAborted(); } }; ConnectionManager.prototype.buildConnectionCallbacks = function (errorCallbacks) { var _this = this; return extend({}, errorCallbacks, { message: function (message) { _this.resetActivityCheck(); _this.emit('message', message); }, ping: function () { _this.send_event('pusher:pong', {}); }, activity: function () { _this.resetActivityCheck(); }, error: function (error) { _this.emit('error', { type: 'WebSocketError', error: error }); }, closed: function () { _this.abandonConnection(); if (_this.shouldRetry()) { _this.retryIn(1000); } } }); }; ConnectionManager.prototype.buildHandshakeCallbacks = function (errorCallbacks) { var _this = this; return extend({}, errorCallbacks, { connected: function (handshake) { _this.activityTimeout = Math.min(_this.options.activityTimeout, handshake.activityTimeout, handshake.connection.activityTimeout || Infinity); _this.clearUnavailableTimer(); _this.setConnection(handshake.connection); _this.socket_id = _this.connection.id; _this.updateState('connected', { socket_id: _this.socket_id }); } }); }; ConnectionManager.prototype.buildErrorCallbacks = function () { var _this = this; var withErrorEmitted = function (callback) { return function (result) { if (result.error) { _this.emit('error', { type: 'WebSocketError', error: result.error }); } callback(result); }; }; return { tls_only: withErrorEmitted(function () { _this.usingTLS = true; _this.updateStrategy(); _this.retryIn(0); }), refused: withErrorEmitted(function () { _this.disconnect(); }), backoff: withErrorEmitted(function () { _this.retryIn(1000); }), retry: withErrorEmitted(function () { _this.retryIn(0); }) }; }; ConnectionManager.prototype.setConnection = function (connection) { this.connection = connection; for (var event in this.connectionCallbacks) { this.connection.bind(event, this.connectionCallbacks[event]); } this.resetActivityCheck(); }; ConnectionManager.prototype.abandonConnection = function () { if (!this.connection) { return; } this.stopActivityCheck(); for (var event in this.connectionCallbacks) { this.connection.unbind(event, this.connectionCallbacks[event]); } var connection = this.connection; this.connection = null; return connection; }; ConnectionManager.prototype.updateState = function (newState, data) { var previousState = this.state; this.state = newState; if (previousState !== newState) { var newStateDescription = newState; if (newStateDescription === 'connected') { newStateDescription += ' with new socket ID ' + data.socket_id; } logger.debug('State changed', previousState + ' -> ' + newStateDescription); this.timeline.info({ state: newState, params: data }); this.emit('state_change', { previous: previousState, current: newState }); this.emit(newState, data); } }; ConnectionManager.prototype.shouldRetry = function () { return this.state === 'connecting' || this.state === 'connected'; }; return ConnectionManager; }(dispatcher)); /* harmony default export */ var connection_manager = (connection_manager_ConnectionManager); // CONCATENATED MODULE: ./src/core/channels/channels.ts var channels_Channels = (function () { function Channels() { this.channels = {}; } Channels.prototype.add = function (name, pusher) { if (!this.channels[name]) { this.channels[name] = createChannel(name, pusher); } return this.channels[name]; }; Channels.prototype.all = function () { return values(this.channels); }; Channels.prototype.find = function (name) { return this.channels[name]; }; Channels.prototype.remove = function (name) { var channel = this.channels[name]; delete this.channels[name]; return channel; }; Channels.prototype.disconnect = function () { objectApply(this.channels, function (channel) { channel.disconnect(); }); }; return Channels; }()); /* harmony default export */ var channels = (channels_Channels); function createChannel(name, pusher) { if (name.indexOf('private-encrypted-') === 0) { if (pusher.config.nacl) { return factory.createEncryptedChannel(name, pusher, pusher.config.nacl); } var errMsg = 'Tried to subscribe to a private-encrypted- channel but no nacl implementation available'; var suffix = url_store.buildLogSuffix('encryptedChannelSupport'); throw new UnsupportedFeature(errMsg + ". " + suffix); } else if (name.indexOf('private-') === 0) { return factory.createPrivateChannel(name, pusher); } else if (name.indexOf('presence-') === 0) { return factory.createPresenceChannel(name, pusher); } else { return factory.createChannel(name, pusher); } } // CONCATENATED MODULE: ./src/core/utils/factory.ts var Factory = { createChannels: function () { return new channels(); }, createConnectionManager: function (key, options) { return new connection_manager(key, options); }, createChannel: function (name, pusher) { return new channels_channel(name, pusher); }, createPrivateChannel: function (name, pusher) { return new private_channel(name, pusher); }, createPresenceChannel: function (name, pusher) { return new presence_channel(name, pusher); }, createEncryptedChannel: function (name, pusher, nacl) { return new encrypted_channel(name, pusher, nacl); }, createTimelineSender: function (timeline, options) { return new timeline_sender(timeline, options); }, createAuthorizer: function (channel, options) { if (options.authorizer) { return options.authorizer(channel, options); } return new pusher_authorizer(channel, options); }, createHandshake: function (transport, callback) { return new connection_handshake(transport, callback); }, createAssistantToTheTransportManager: function (manager, transport, options) { return new assistant_to_the_transport_manager(manager, transport, options); } }; /* harmony default export */ var factory = (Factory); // CONCATENATED MODULE: ./src/core/transports/transport_manager.ts var transport_manager_TransportManager = (function () { function TransportManager(options) { this.options = options || {}; this.livesLeft = this.options.lives || Infinity; } TransportManager.prototype.getAssistant = function (transport) { return factory.createAssistantToTheTransportManager(this, transport, { minPingDelay: this.options.minPingDelay, maxPingDelay: this.options.maxPingDelay }); }; TransportManager.prototype.isAlive = function () { return this.livesLeft > 0; }; TransportManager.prototype.reportDeath = function () { this.livesLeft -= 1; }; return TransportManager; }()); /* harmony default export */ var transport_manager = (transport_manager_TransportManager); // CONCATENATED MODULE: ./src/core/strategies/sequential_strategy.ts var sequential_strategy_SequentialStrategy = (function () { function SequentialStrategy(strategies, options) { this.strategies = strategies; this.loop = Boolean(options.loop); this.failFast = Boolean(options.failFast); this.timeout = options.timeout; this.timeoutLimit = options.timeoutLimit; } SequentialStrategy.prototype.isSupported = function () { return any(this.strategies, util.method('isSupported')); }; SequentialStrategy.prototype.connect = function (minPriority, callback) { var _this = this; var strategies = this.strategies; var current = 0; var timeout = this.timeout; var runner = null; var tryNextStrategy = function (error, handshake) { if (handshake) { callback(null, handshake); } else { current = current + 1; if (_this.loop) { current = current % strategies.length; } if (current < strategies.length) { if (timeout) { timeout = timeout * 2; if (_this.timeoutLimit) { timeout = Math.min(timeout, _this.timeoutLimit); } } runner = _this.tryStrategy(strategies[current], minPriority, { timeout: timeout, failFast: _this.failFast }, tryNextStrategy); } else { callback(true); } } }; runner = this.tryStrategy(strategies[current], minPriority, { timeout: timeout, failFast: this.failFast }, tryNextStrategy); return { abort: function () { runner.abort(); }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; SequentialStrategy.prototype.tryStrategy = function (strategy, minPriority, options, callback) { var timer = null; var runner = null; if (options.timeout > 0) { timer = new OneOffTimer(options.timeout, function () { runner.abort(); callback(true); }); } runner = strategy.connect(minPriority, function (error, handshake) { if (error && timer && timer.isRunning() && !options.failFast) { return; } if (timer) { timer.ensureAborted(); } callback(error, handshake); }); return { abort: function () { if (timer) { timer.ensureAborted(); } runner.abort(); }, forceMinPriority: function (p) { runner.forceMinPriority(p); } }; }; return SequentialStrategy; }()); /* harmony default export */ var sequential_strategy = (sequential_strategy_SequentialStrategy); // CONCATENATED MODULE: ./src/core/strategies/best_connected_ever_strategy.ts var best_connected_ever_strategy_BestConnectedEverStrategy = (function () { function BestConnectedEverStrategy(strategies) { this.strategies = strategies; } BestConnectedEverStrategy.prototype.isSupported = function () { return any(this.strategies, util.method('isSupported')); }; BestConnectedEverStrategy.prototype.connect = function (minPriority, callback) { return connect(this.strategies, minPriority, function (i, runners) { return function (error, handshake) { runners[i].error = error; if (error) { if (allRunnersFailed(runners)) { callback(true); } return; } apply(runners, function (runner) { runner.forceMinPriority(handshake.transport.priority); }); callback(null, handshake); }; }); }; return BestConnectedEverStrategy; }()); /* harmony default export */ var best_connected_ever_strategy = (best_connected_ever_strategy_BestConnectedEverStrategy); function connect(strategies, minPriority, callbackBuilder) { var runners = map(strategies, function (strategy, i, _, rs) { return strategy.connect(minPriority, callbackBuilder(i, rs)); }); return { abort: function () { apply(runners, abortRunner); }, forceMinPriority: function (p) { apply(runners, function (runner) { runner.forceMinPriority(p); }); } }; } function allRunnersFailed(runners) { return collections_all(runners, function (runner) { return Boolean(runner.error); }); } function abortRunner(runner) { if (!runner.error && !runner.aborted) { runner.abort(); runner.aborted = true; } } // CONCATENATED MODULE: ./src/core/strategies/cached_strategy.ts var cached_strategy_CachedStrategy = (function () { function CachedStrategy(strategy, transports, options) { this.strategy = strategy; this.transports = transports; this.ttl = options.ttl || 1800 * 1000; this.usingTLS = options.useTLS; this.timeline = options.timeline; } CachedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; CachedStrategy.prototype.connect = function (minPriority, callback) { var usingTLS = this.usingTLS; var info = fetchTransportCache(usingTLS); var strategies = [this.strategy]; if (info && info.timestamp + this.ttl >= util.now()) { var transport = this.transports[info.transport]; if (transport) { this.timeline.info({ cached: true, transport: info.transport, latency: info.latency }); strategies.push(new sequential_strategy([transport], { timeout: info.latency * 2 + 1000, failFast: true })); } } var startTimestamp = util.now(); var runner = strategies .pop() .connect(minPriority, function cb(error, handshake) { if (error) { flushTransportCache(usingTLS); if (strategies.length > 0) { startTimestamp = util.now(); runner = strategies.pop().connect(minPriority, cb); } else { callback(error); } } else { storeTransportCache(usingTLS, handshake.transport.name, util.now() - startTimestamp); callback(null, handshake); } }); return { abort: function () { runner.abort(); }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; return CachedStrategy; }()); /* harmony default export */ var cached_strategy = (cached_strategy_CachedStrategy); function getTransportCacheKey(usingTLS) { return 'pusherTransport' + (usingTLS ? 'TLS' : 'NonTLS'); } function fetchTransportCache(usingTLS) { var storage = worker_runtime.getLocalStorage(); if (storage) { try { var serializedCache = storage[getTransportCacheKey(usingTLS)]; if (serializedCache) { return JSON.parse(serializedCache); } } catch (e) { flushTransportCache(usingTLS); } } return null; } function storeTransportCache(usingTLS, transport, latency) { var storage = worker_runtime.getLocalStorage(); if (storage) { try { storage[getTransportCacheKey(usingTLS)] = safeJSONStringify({ timestamp: util.now(), transport: transport, latency: latency }); } catch (e) { } } } function flushTransportCache(usingTLS) { var storage = worker_runtime.getLocalStorage(); if (storage) { try { delete storage[getTransportCacheKey(usingTLS)]; } catch (e) { } } } // CONCATENATED MODULE: ./src/core/strategies/delayed_strategy.ts var delayed_strategy_DelayedStrategy = (function () { function DelayedStrategy(strategy, _a) { var number = _a.delay; this.strategy = strategy; this.options = { delay: number }; } DelayedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; DelayedStrategy.prototype.connect = function (minPriority, callback) { var strategy = this.strategy; var runner; var timer = new OneOffTimer(this.options.delay, function () { runner = strategy.connect(minPriority, callback); }); return { abort: function () { timer.ensureAborted(); if (runner) { runner.abort(); } }, forceMinPriority: function (p) { minPriority = p; if (runner) { runner.forceMinPriority(p); } } }; }; return DelayedStrategy; }()); /* harmony default export */ var delayed_strategy = (delayed_strategy_DelayedStrategy); // CONCATENATED MODULE: ./src/core/strategies/if_strategy.ts var IfStrategy = (function () { function IfStrategy(test, trueBranch, falseBranch) { this.test = test; this.trueBranch = trueBranch; this.falseBranch = falseBranch; } IfStrategy.prototype.isSupported = function () { var branch = this.test() ? this.trueBranch : this.falseBranch; return branch.isSupported(); }; IfStrategy.prototype.connect = function (minPriority, callback) { var branch = this.test() ? this.trueBranch : this.falseBranch; return branch.connect(minPriority, callback); }; return IfStrategy; }()); /* harmony default export */ var if_strategy = (IfStrategy); // CONCATENATED MODULE: ./src/core/strategies/first_connected_strategy.ts var FirstConnectedStrategy = (function () { function FirstConnectedStrategy(strategy) { this.strategy = strategy; } FirstConnectedStrategy.prototype.isSupported = function () { return this.strategy.isSupported(); }; FirstConnectedStrategy.prototype.connect = function (minPriority, callback) { var runner = this.strategy.connect(minPriority, function (error, handshake) { if (handshake) { runner.abort(); } callback(error, handshake); }); return runner; }; return FirstConnectedStrategy; }()); /* harmony default export */ var first_connected_strategy = (FirstConnectedStrategy); // CONCATENATED MODULE: ./src/runtimes/isomorphic/default_strategy.ts function testSupportsStrategy(strategy) { return function () { return strategy.isSupported(); }; } var getDefaultStrategy = function (config, baseOptions, defineTransport) { var definedTransports = {}; function defineTransportStrategy(name, type, priority, options, manager) { var transport = defineTransport(config, name, type, priority, options, manager); definedTransports[name] = transport; return transport; } var ws_options = Object.assign({}, baseOptions, { hostNonTLS: config.wsHost + ':' + config.wsPort, hostTLS: config.wsHost + ':' + config.wssPort, httpPath: config.wsPath }); var wss_options = extend({}, ws_options, { useTLS: true }); var http_options = Object.assign({}, baseOptions, { hostNonTLS: config.httpHost + ':' + config.httpPort, hostTLS: config.httpHost + ':' + config.httpsPort, httpPath: config.httpPath }); var timeouts = { loop: true, timeout: 15000, timeoutLimit: 60000 }; var ws_manager = new transport_manager({ lives: 2, minPingDelay: 10000, maxPingDelay: config.activityTimeout }); var streaming_manager = new transport_manager({ lives: 2, minPingDelay: 10000, maxPingDelay: config.activityTimeout }); var ws_transport = defineTransportStrategy('ws', 'ws', 3, ws_options, ws_manager); var wss_transport = defineTransportStrategy('wss', 'ws', 3, wss_options, ws_manager); var xhr_streaming_transport = defineTransportStrategy('xhr_streaming', 'xhr_streaming', 1, http_options, streaming_manager); var xhr_polling_transport = defineTransportStrategy('xhr_polling', 'xhr_polling', 1, http_options); var ws_loop = new sequential_strategy([ws_transport], timeouts); var wss_loop = new sequential_strategy([wss_transport], timeouts); var streaming_loop = new sequential_strategy([xhr_streaming_transport], timeouts); var polling_loop = new sequential_strategy([xhr_polling_transport], timeouts); var http_loop = new sequential_strategy([ new if_strategy(testSupportsStrategy(streaming_loop), new best_connected_ever_strategy([ streaming_loop, new delayed_strategy(polling_loop, { delay: 4000 }) ]), polling_loop) ], timeouts); var wsStrategy; if (baseOptions.useTLS) { wsStrategy = new best_connected_ever_strategy([ ws_loop, new delayed_strategy(http_loop, { delay: 2000 }) ]); } else { wsStrategy = new best_connected_ever_strategy([ ws_loop, new delayed_strategy(wss_loop, { delay: 2000 }), new delayed_strategy(http_loop, { delay: 5000 }) ]); } return new cached_strategy(new first_connected_strategy(new if_strategy(testSupportsStrategy(ws_transport), wsStrategy, http_loop)), definedTransports, { ttl: 1800000, timeline: baseOptions.timeline, useTLS: baseOptions.useTLS }); }; /* harmony default export */ var default_strategy = (getDefaultStrategy); // CONCATENATED MODULE: ./src/runtimes/isomorphic/transports/transport_connection_initializer.ts /* harmony default export */ var transport_connection_initializer = (function () { var self = this; self.timeline.info(self.buildTimelineMessage({ transport: self.name + (self.options.useTLS ? 's' : '') })); if (self.hooks.isInitialized()) { self.changeState('initialized'); } else { self.onClose(); } }); // CONCATENATED MODULE: ./src/core/http/http_request.ts var http_request_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var MAX_BUFFER_LENGTH = 256 * 1024; var http_request_HTTPRequest = (function (_super) { http_request_extends(HTTPRequest, _super); function HTTPRequest(hooks, method, url) { var _this = _super.call(this) || this; _this.hooks = hooks; _this.method = method; _this.url = url; return _this; } HTTPRequest.prototype.start = function (payload) { var _this = this; this.position = 0; this.xhr = this.hooks.getRequest(this); this.unloader = function () { _this.close(); }; worker_runtime.addUnloadListener(this.unloader); this.xhr.open(this.method, this.url, true); if (this.xhr.setRequestHeader) { this.xhr.setRequestHeader('Content-Type', 'application/json'); } this.xhr.send(payload); }; HTTPRequest.prototype.close = function () { if (this.unloader) { worker_runtime.removeUnloadListener(this.unloader); this.unloader = null; } if (this.xhr) { this.hooks.abortRequest(this.xhr); this.xhr = null; } }; HTTPRequest.prototype.onChunk = function (status, data) { while (true) { var chunk = this.advanceBuffer(data); if (chunk) { this.emit('chunk', { status: status, data: chunk }); } else { break; } } if (this.isBufferTooLong(data)) { this.emit('buffer_too_long'); } }; HTTPRequest.prototype.advanceBuffer = function (buffer) { var unreadData = buffer.slice(this.position); var endOfLinePosition = unreadData.indexOf('\n'); if (endOfLinePosition !== -1) { this.position += endOfLinePosition + 1; return unreadData.slice(0, endOfLinePosition); } else { return null; } }; HTTPRequest.prototype.isBufferTooLong = function (buffer) { return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH; }; return HTTPRequest; }(dispatcher)); /* harmony default export */ var http_request = (http_request_HTTPRequest); // CONCATENATED MODULE: ./src/core/http/state.ts var State; (function (State) { State[State["CONNECTING"] = 0] = "CONNECTING"; State[State["OPEN"] = 1] = "OPEN"; State[State["CLOSED"] = 3] = "CLOSED"; })(State || (State = {})); /* harmony default export */ var state = (State); // CONCATENATED MODULE: ./src/core/http/http_socket.ts var autoIncrement = 1; var http_socket_HTTPSocket = (function () { function HTTPSocket(hooks, url) { this.hooks = hooks; this.session = randomNumber(1000) + '/' + randomString(8); this.location = getLocation(url); this.readyState = state.CONNECTING; this.openStream(); } HTTPSocket.prototype.send = function (payload) { return this.sendRaw(JSON.stringify([payload])); }; HTTPSocket.prototype.ping = function () { this.hooks.sendHeartbeat(this); }; HTTPSocket.prototype.close = function (code, reason) { this.onClose(code, reason, true); }; HTTPSocket.prototype.sendRaw = function (payload) { if (this.readyState === state.OPEN) { try { worker_runtime.createSocketRequest('POST', getUniqueURL(getSendURL(this.location, this.session))).start(payload); return true; } catch (e) { return false; } } else { return false; } }; HTTPSocket.prototype.reconnect = function () { this.closeStream(); this.openStream(); }; HTTPSocket.prototype.onClose = function (code, reason, wasClean) { this.closeStream(); this.readyState = state.CLOSED; if (this.onclose) { this.onclose({ code: code, reason: reason, wasClean: wasClean }); } }; HTTPSocket.prototype.onChunk = function (chunk) { if (chunk.status !== 200) { return; } if (this.readyState === state.OPEN) { this.onActivity(); } var payload; var type = chunk.data.slice(0, 1); switch (type) { case 'o': payload = JSON.parse(chunk.data.slice(1) || '{}'); this.onOpen(payload); break; case 'a': payload = JSON.parse(chunk.data.slice(1) || '[]'); for (var i = 0; i < payload.length; i++) { this.onEvent(payload[i]); } break; case 'm': payload = JSON.parse(chunk.data.slice(1) || 'null'); this.onEvent(payload); break; case 'h': this.hooks.onHeartbeat(this); break; case 'c': payload = JSON.parse(chunk.data.slice(1) || '[]'); this.onClose(payload[0], payload[1], true); break; } }; HTTPSocket.prototype.onOpen = function (options) { if (this.readyState === state.CONNECTING) { if (options && options.hostname) { this.location.base = replaceHost(this.location.base, options.hostname); } this.readyState = state.OPEN; if (this.onopen) { this.onopen(); } } else { this.onClose(1006, 'Server lost session', true); } }; HTTPSocket.prototype.onEvent = function (event) { if (this.readyState === state.OPEN && this.onmessage) { this.onmessage({ data: event }); } }; HTTPSocket.prototype.onActivity = function () { if (this.onactivity) { this.onactivity(); } }; HTTPSocket.prototype.onError = function (error) { if (this.onerror) { this.onerror(error); } }; HTTPSocket.prototype.openStream = function () { var _this = this; this.stream = worker_runtime.createSocketRequest('POST', getUniqueURL(this.hooks.getReceiveURL(this.location, this.session))); this.stream.bind('chunk', function (chunk) { _this.onChunk(chunk); }); this.stream.bind('finished', function (status) { _this.hooks.onFinished(_this, status); }); this.stream.bind('buffer_too_long', function () { _this.reconnect(); }); try { this.stream.start(); } catch (error) { util.defer(function () { _this.onError(error); _this.onClose(1006, 'Could not start streaming', false); }); } }; HTTPSocket.prototype.closeStream = function () { if (this.stream) { this.stream.unbind_all(); this.stream.close(); this.stream = null; } }; return HTTPSocket; }()); function getLocation(url) { var parts = /([^\?]*)\/*(\??.*)/.exec(url); return { base: parts[1], queryString: parts[2] }; } function getSendURL(url, session) { return url.base + '/' + session + '/xhr_send'; } function getUniqueURL(url) { var separator = url.indexOf('?') === -1 ? '?' : '&'; return url + separator + 't=' + +new Date() + '&n=' + autoIncrement++; } function replaceHost(url, hostname) { var urlParts = /(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(url); return urlParts[1] + hostname + urlParts[3]; } function randomNumber(max) { return Math.floor(Math.random() * max); } function randomString(length) { var result = []; for (var i = 0; i < length; i++) { result.push(randomNumber(32).toString(32)); } return result.join(''); } /* harmony default export */ var http_socket = (http_socket_HTTPSocket); // CONCATENATED MODULE: ./src/core/http/http_streaming_socket.ts var http_streaming_socket_hooks = { getReceiveURL: function (url, session) { return url.base + '/' + session + '/xhr_streaming' + url.queryString; }, onHeartbeat: function (socket) { socket.sendRaw('[]'); }, sendHeartbeat: function (socket) { socket.sendRaw('[]'); }, onFinished: function (socket, status) { socket.onClose(1006, 'Connection interrupted (' + status + ')', false); } }; /* harmony default export */ var http_streaming_socket = (http_streaming_socket_hooks); // CONCATENATED MODULE: ./src/core/http/http_polling_socket.ts var http_polling_socket_hooks = { getReceiveURL: function (url, session) { return url.base + '/' + session + '/xhr' + url.queryString; }, onHeartbeat: function () { }, sendHeartbeat: function (socket) { socket.sendRaw('[]'); }, onFinished: function (socket, status) { if (status === 200) { socket.reconnect(); } else { socket.onClose(1006, 'Connection interrupted (' + status + ')', false); } } }; /* harmony default export */ var http_polling_socket = (http_polling_socket_hooks); // CONCATENATED MODULE: ./src/runtimes/isomorphic/http/http_xhr_request.ts var http_xhr_request_hooks = { getRequest: function (socket) { var Constructor = worker_runtime.getXHRAPI(); var xhr = new Constructor(); xhr.onreadystatechange = xhr.onprogress = function () { switch (xhr.readyState) { case 3: if (xhr.responseText && xhr.responseText.length > 0) { socket.onChunk(xhr.status, xhr.responseText); } break; case 4: if (xhr.responseText && xhr.responseText.length > 0) { socket.onChunk(xhr.status, xhr.responseText); } socket.emit('finished', xhr.status); socket.close(); break; } }; return xhr; }, abortRequest: function (xhr) { xhr.onreadystatechange = null; xhr.abort(); } }; /* harmony default export */ var http_xhr_request = (http_xhr_request_hooks); // CONCATENATED MODULE: ./src/runtimes/isomorphic/http/http.ts var HTTP = { createStreamingSocket: function (url) { return this.createSocket(http_streaming_socket, url); }, createPollingSocket: function (url) { return this.createSocket(http_polling_socket, url); }, createSocket: function (hooks, url) { return new http_socket(hooks, url); }, createXHR: function (method, url) { return this.createRequest(http_xhr_request, method, url); }, createRequest: function (hooks, method, url) { return new http_request(hooks, method, url); } }; /* harmony default export */ var http_http = (HTTP); // CONCATENATED MODULE: ./src/runtimes/isomorphic/runtime.ts var Isomorphic = { getDefaultStrategy: default_strategy, Transports: transports, transportConnectionInitializer: transport_connection_initializer, HTTPFactory: http_http, setup: function (PusherClass) { PusherClass.ready(); }, getLocalStorage: function () { return undefined; }, getClientFeatures: function () { return keys(filterObject({ ws: transports.ws }, function (t) { return t.isSupported({}); })); }, getProtocol: function () { return 'http:'; }, isXHRSupported: function () { return true; }, createSocketRequest: function (method, url) { if (this.isXHRSupported()) { return this.HTTPFactory.createXHR(method, url); } else { throw 'Cross-origin HTTP requests are not supported'; } }, createXHR: function () { var Constructor = this.getXHRAPI(); return new Constructor(); }, createWebSocket: function (url) { var Constructor = this.getWebSocketAPI(); return new Constructor(url); }, addUnloadListener: function (listener) { }, removeUnloadListener: function (listener) { } }; /* harmony default export */ var runtime = (Isomorphic); // CONCATENATED MODULE: ./src/runtimes/worker/net_info.ts var net_info_extends = (undefined && undefined.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var NetInfo = (function (_super) { net_info_extends(NetInfo, _super); function NetInfo() { return _super !== null && _super.apply(this, arguments) || this; } NetInfo.prototype.isOnline = function () { return true; }; return NetInfo; }(dispatcher)); var net_info_Network = new NetInfo(); // CONCATENATED MODULE: ./src/runtimes/worker/auth/fetch_auth.ts var fetchAuth = function (context, socketId, callback) { var headers = new Headers(); headers.set('Content-Type', 'application/x-www-form-urlencoded'); for (var headerName in this.authOptions.headers) { headers.set(headerName, this.authOptions.headers[headerName]); } var body = this.composeQuery(socketId); var request = new Request(this.options.authEndpoint, { headers: headers, body: body, credentials: 'same-origin', method: 'POST' }); return fetch(request) .then(function (response) { var status = response.status; if (status === 200) { return response.text(); } else { logger.error("Couldn't get auth info from your auth endpoint", status); throw status; } }) .then(function (data) { try { data = JSON.parse(data); } catch (e) { var message = 'JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ' + data; logger.error(message); throw message; } callback(false, data); })["catch"](function (err) { callback(true, err); }); }; /* harmony default export */ var fetch_auth = (fetchAuth); // CONCATENATED MODULE: ./src/runtimes/worker/timeline/fetch_timeline.ts var getAgent = function (sender, useTLS) { return function (data, callback) { var scheme = 'http' + (useTLS ? 's' : '') + '://'; var url = scheme + (sender.host || sender.options.host) + sender.options.path; var query = buildQueryString(data); url += '/' + 2 + '?' + query; fetch(url) .then(function (response) { if (response.status !== 200) { throw "received " + response.status + " from stats.pusher.com"; } return response.json(); }) .then(function (_a) { var host = _a.host; if (host) { sender.host = host; } })["catch"](function (err) { logger.debug('TimelineSender Error: ', err); }); }; }; var fetchTimeline = { name: 'xhr', getAgent: getAgent }; /* harmony default export */ var fetch_timeline = (fetchTimeline); // CONCATENATED MODULE: ./src/runtimes/worker/runtime.ts var runtime_getDefaultStrategy = runtime.getDefaultStrategy, runtime_Transports = runtime.Transports, setup = runtime.setup, getProtocol = runtime.getProtocol, isXHRSupported = runtime.isXHRSupported, getLocalStorage = runtime.getLocalStorage, createXHR = runtime.createXHR, createWebSocket = runtime.createWebSocket, addUnloadListener = runtime.addUnloadListener, removeUnloadListener = runtime.removeUnloadListener, transportConnectionInitializer = runtime.transportConnectionInitializer, createSocketRequest = runtime.createSocketRequest, HTTPFactory = runtime.HTTPFactory; var Worker = { getDefaultStrategy: runtime_getDefaultStrategy, Transports: runtime_Transports, setup: setup, getProtocol: getProtocol, isXHRSupported: isXHRSupported, getLocalStorage: getLocalStorage, createXHR: createXHR, createWebSocket: createWebSocket, addUnloadListener: addUnloadListener, removeUnloadListener: removeUnloadListener, transportConnectionInitializer: transportConnectionInitializer, createSocketRequest: createSocketRequest, HTTPFactory: HTTPFactory, TimelineTransport: fetch_timeline, getAuthorizers: function () { return { ajax: fetch_auth }; }, getWebSocketAPI: function () { return WebSocket; }, getXHRAPI: function () { return XMLHttpRequest; }, getNetwork: function () { return net_info_Network; } }; /* harmony default export */ var worker_runtime = (Worker); // CONCATENATED MODULE: ./src/core/timeline/level.ts var TimelineLevel; (function (TimelineLevel) { TimelineLevel[TimelineLevel["ERROR"] = 3] = "ERROR"; TimelineLevel[TimelineLevel["INFO"] = 6] = "INFO"; TimelineLevel[TimelineLevel["DEBUG"] = 7] = "DEBUG"; })(TimelineLevel || (TimelineLevel = {})); /* harmony default export */ var timeline_level = (TimelineLevel); // CONCATENATED MODULE: ./src/core/timeline/timeline.ts var timeline_Timeline = (function () { function Timeline(key, session, options) { this.key = key; this.session = session; this.events = []; this.options = options || {}; this.sent = 0; this.uniqueID = 0; } Timeline.prototype.log = function (level, event) { if (level <= this.options.level) { this.events.push(extend({}, event, { timestamp: util.now() })); if (this.options.limit && this.events.length > this.options.limit) { this.events.shift(); } } }; Timeline.prototype.error = function (event) { this.log(timeline_level.ERROR, event); }; Timeline.prototype.info = function (event) { this.log(timeline_level.INFO, event); }; Timeline.prototype.debug = function (event) { this.log(timeline_level.DEBUG, event); }; Timeline.prototype.isEmpty = function () { return this.events.length === 0; }; Timeline.prototype.send = function (sendfn, callback) { var _this = this; var data = extend({ session: this.session, bundle: this.sent + 1, key: this.key, lib: 'js', version: this.options.version, cluster: this.options.cluster, features: this.options.features, timeline: this.events }, this.options.params); this.events = []; sendfn(data, function (error, result) { if (!error) { _this.sent++; } if (callback) { callback(error, result); } }); return true; }; Timeline.prototype.generateUniqueID = function () { this.uniqueID++; return this.uniqueID; }; return Timeline; }()); /* harmony default export */ var timeline_timeline = (timeline_Timeline); // CONCATENATED MODULE: ./src/core/strategies/transport_strategy.ts var transport_strategy_TransportStrategy = (function () { function TransportStrategy(name, priority, transport, options) { this.name = name; this.priority = priority; this.transport = transport; this.options = options || {}; } TransportStrategy.prototype.isSupported = function () { return this.transport.isSupported({ useTLS: this.options.useTLS }); }; TransportStrategy.prototype.connect = function (minPriority, callback) { var _this = this; if (!this.isSupported()) { return failAttempt(new UnsupportedStrategy(), callback); } else if (this.priority < minPriority) { return failAttempt(new TransportPriorityTooLow(), callback); } var connected = false; var transport = this.transport.createConnection(this.name, this.priority, this.options.key, this.options); var handshake = null; var onInitialized = function () { transport.unbind('initialized', onInitialized); transport.connect(); }; var onOpen = function () { handshake = factory.createHandshake(transport, function (result) { connected = true; unbindListeners(); callback(null, result); }); }; var onError = function (error) { unbindListeners(); callback(error); }; var onClosed = function () { unbindListeners(); var serializedTransport; serializedTransport = safeJSONStringify(transport); callback(new TransportClosed(serializedTransport)); }; var unbindListeners = function () { transport.unbind('initialized', onInitialized); transport.unbind('open', onOpen); transport.unbind('error', onError); transport.unbind('closed', onClosed); }; transport.bind('initialized', onInitialized); transport.bind('open', onOpen); transport.bind('error', onError); transport.bind('closed', onClosed); transport.initialize(); return { abort: function () { if (connected) { return; } unbindListeners(); if (handshake) { handshake.close(); } else { transport.close(); } }, forceMinPriority: function (p) { if (connected) { return; } if (_this.priority < p) { if (handshake) { handshake.close(); } else { transport.close(); } } } }; }; return TransportStrategy; }()); /* harmony default export */ var transport_strategy = (transport_strategy_TransportStrategy); function failAttempt(error, callback) { util.defer(function () { callback(error); }); return { abort: function () { }, forceMinPriority: function () { } }; } // CONCATENATED MODULE: ./src/core/strategies/strategy_builder.ts var strategy_builder_Transports = worker_runtime.Transports; var strategy_builder_defineTransport = function (config, name, type, priority, options, manager) { var transportClass = strategy_builder_Transports[type]; if (!transportClass) { throw new UnsupportedTransport(type); } var enabled = (!config.enabledTransports || arrayIndexOf(config.enabledTransports, name) !== -1) && (!config.disabledTransports || arrayIndexOf(config.disabledTransports, name) === -1); var transport; if (enabled) { options = Object.assign({ ignoreNullOrigin: config.ignoreNullOrigin }, options); transport = new transport_strategy(name, priority, manager ? manager.getAssistant(transportClass) : transportClass, options); } else { transport = strategy_builder_UnsupportedStrategy; } return transport; }; var strategy_builder_UnsupportedStrategy = { isSupported: function () { return false; }, connect: function (_, callback) { var deferred = util.defer(function () { callback(new UnsupportedStrategy()); }); return { abort: function () { deferred.ensureAborted(); }, forceMinPriority: function () { } }; } }; // CONCATENATED MODULE: ./src/core/config.ts function getConfig(opts) { var config = { activityTimeout: opts.activityTimeout || defaults.activityTimeout, authEndpoint: opts.authEndpoint || defaults.authEndpoint, authTransport: opts.authTransport || defaults.authTransport, cluster: opts.cluster || defaults.cluster, httpPath: opts.httpPath || defaults.httpPath, httpPort: opts.httpPort || defaults.httpPort, httpsPort: opts.httpsPort || defaults.httpsPort, pongTimeout: opts.pongTimeout || defaults.pongTimeout, statsHost: opts.statsHost || defaults.stats_host, unavailableTimeout: opts.unavailableTimeout || defaults.unavailableTimeout, wsPath: opts.wsPath || defaults.wsPath, wsPort: opts.wsPort || defaults.wsPort, wssPort: opts.wssPort || defaults.wssPort, enableStats: getEnableStatsConfig(opts), httpHost: getHttpHost(opts), useTLS: shouldUseTLS(opts), wsHost: getWebsocketHost(opts) }; if ('auth' in opts) config.auth = opts.auth; if ('authorizer' in opts) config.authorizer = opts.authorizer; if ('disabledTransports' in opts) config.disabledTransports = opts.disabledTransports; if ('enabledTransports' in opts) config.enabledTransports = opts.enabledTransports; if ('ignoreNullOrigin' in opts) config.ignoreNullOrigin = opts.ignoreNullOrigin; if ('timelineParams' in opts) config.timelineParams = opts.timelineParams; if ('nacl' in opts) { config.nacl = opts.nacl; } return config; } function getHttpHost(opts) { if (opts.httpHost) { return opts.httpHost; } if (opts.cluster) { return "sockjs-" + opts.cluster + ".pusher.com"; } return defaults.httpHost; } function getWebsocketHost(opts) { if (opts.wsHost) { return opts.wsHost; } if (opts.cluster) { return getWebsocketHostFromCluster(opts.cluster); } return getWebsocketHostFromCluster(defaults.cluster); } function getWebsocketHostFromCluster(cluster) { return "ws-" + cluster + ".pusher.com"; } function shouldUseTLS(opts) { if (worker_runtime.getProtocol() === 'https:') { return true; } else if (opts.forceTLS === false) { return false; } return true; } function getEnableStatsConfig(opts) { if ('enableStats' in opts) { return opts.enableStats; } if ('disableStats' in opts) { return !opts.disableStats; } return false; } // CONCATENATED MODULE: ./src/core/pusher.ts var pusher_Pusher = (function () { function Pusher(app_key, options) { var _this = this; checkAppKey(app_key); options = options || {}; if (!options.cluster && !(options.wsHost || options.httpHost)) { var suffix = url_store.buildLogSuffix('javascriptQuickStart'); logger.warn("You should always specify a cluster when connecting. " + suffix); } if ('disableStats' in options) { logger.warn('The disableStats option is deprecated in favor of enableStats'); } this.key = app_key; this.config = getConfig(options); this.channels = factory.createChannels(); this.global_emitter = new dispatcher(); this.sessionID = Math.floor(Math.random() * 1000000000); this.timeline = new timeline_timeline(this.key, this.sessionID, { cluster: this.config.cluster, features: Pusher.getClientFeatures(), params: this.config.timelineParams || {}, limit: 50, level: timeline_level.INFO, version: defaults.VERSION }); if (this.config.enableStats) { this.timelineSender = factory.createTimelineSender(this.timeline, { host: this.config.statsHost, path: '/timeline/v2/' + worker_runtime.TimelineTransport.name }); } var getStrategy = function (options) { return worker_runtime.getDefaultStrategy(_this.config, options, strategy_builder_defineTransport); }; this.connection = factory.createConnectionManager(this.key, { getStrategy: getStrategy, timeline: this.timeline, activityTimeout: this.config.activityTimeout, pongTimeout: this.config.pongTimeout, unavailableTimeout: this.config.unavailableTimeout, useTLS: Boolean(this.config.useTLS) }); this.connection.bind('connected', function () { _this.subscribeAll(); if (_this.timelineSender) { _this.timelineSender.send(_this.connection.isUsingTLS()); } }); this.connection.bind('message', function (event) { var eventName = event.event; var internal = eventName.indexOf('pusher_internal:') === 0; if (event.channel) { var channel = _this.channel(event.channel); if (channel) { channel.handleEvent(event); } } if (!internal) { _this.global_emitter.emit(event.event, event.data); } }); this.connection.bind('connecting', function () { _this.channels.disconnect(); }); this.connection.bind('disconnected', function () { _this.channels.disconnect(); }); this.connection.bind('error', function (err) { logger.warn(err); }); Pusher.instances.push(this); this.timeline.info({ instances: Pusher.instances.length }); if (Pusher.isReady) { this.connect(); } } Pusher.ready = function () { Pusher.isReady = true; for (var i = 0, l = Pusher.instances.length; i < l; i++) { Pusher.instances[i].connect(); } }; Pusher.getClientFeatures = function () { return keys(filterObject({ ws: worker_runtime.Transports.ws }, function (t) { return t.isSupported({}); })); }; Pusher.prototype.channel = function (name) { return this.channels.find(name); }; Pusher.prototype.allChannels = function () { return this.channels.all(); }; Pusher.prototype.connect = function () { this.connection.connect(); if (this.timelineSender) { if (!this.timelineSenderTimer) { var usingTLS = this.connection.isUsingTLS(); var timelineSender = this.timelineSender; this.timelineSenderTimer = new PeriodicTimer(60000, function () { timelineSender.send(usingTLS); }); } } }; Pusher.prototype.disconnect = function () { this.connection.disconnect(); if (this.timelineSenderTimer) { this.timelineSenderTimer.ensureAborted(); this.timelineSenderTimer = null; } }; Pusher.prototype.bind = function (event_name, callback, context) { this.global_emitter.bind(event_name, callback, context); return this; }; Pusher.prototype.unbind = function (event_name, callback, context) { this.global_emitter.unbind(event_name, callback, context); return this; }; Pusher.prototype.bind_global = function (callback) { this.global_emitter.bind_global(callback); return this; }; Pusher.prototype.unbind_global = function (callback) { this.global_emitter.unbind_global(callback); return this; }; Pusher.prototype.unbind_all = function (callback) { this.global_emitter.unbind_all(); return this; }; Pusher.prototype.subscribeAll = function () { var channelName; for (channelName in this.channels.channels) { if (this.channels.channels.hasOwnProperty(channelName)) { this.subscribe(channelName); } } }; Pusher.prototype.subscribe = function (channel_name) { var channel = this.channels.add(channel_name, this); if (channel.subscriptionPending && channel.subscriptionCancelled) { channel.reinstateSubscription(); } else if (!channel.subscriptionPending && this.connection.state === 'connected') { channel.subscribe(); } return channel; }; Pusher.prototype.unsubscribe = function (channel_name) { var channel = this.channels.find(channel_name); if (channel && channel.subscriptionPending) { channel.cancelSubscription(); } else { channel = this.channels.remove(channel_name); if (channel && this.connection.state === 'connected') { channel.unsubscribe(); } } }; Pusher.prototype.send_event = function (event_name, data, channel) { return this.connection.send_event(event_name, data, channel); }; Pusher.prototype.shouldUseTLS = function () { return this.config.useTLS; }; Pusher.instances = []; Pusher.isReady = false; Pusher.logToConsole = false; Pusher.Runtime = worker_runtime; Pusher.ScriptReceivers = worker_runtime.ScriptReceivers; Pusher.DependenciesReceivers = worker_runtime.DependenciesReceivers; Pusher.auth_callbacks = worker_runtime.auth_callbacks; return Pusher; }()); /* harmony default export */ var core_pusher = __webpack_exports__["default"] = (pusher_Pusher); function checkAppKey(key) { if (key === null || key === undefined) { throw 'You must pass your app key when you instantiate Pusher.'; } } worker_runtime.setup(pusher_Pusher); /***/ }) /******/ ]);
$(document).ready(function(){ var currentPosition = 0; var slideWidth = 560; var slides = $('.slide'); var numberOfSlides = slides.length; // Remove scrollbar in JS $('#slidesContainer').css('overflow', 'hidden'); // Wrap all .slides with #slideInner div slides .wrapAll('<div id="slideInner"></div>') // Float left to display horizontally, readjust .slides width .css({ 'float' : 'left', 'width' : slideWidth }); // Set #slideInner width equal to total width of all slides $('#slideInner').css('width', slideWidth * numberOfSlides); // Insert controls in the DOM $('#slideshow') .prepend('<span class="control" id="leftControl">Clicking moves left</span>') .append('<span class="control" id="rightControl">Clicking moves right</span>'); // Hide left arrow control on first load manageControls(currentPosition); // Create event listeners for .controls clicks $('.control') .bind('click', function(){ // Determine new position currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1; // Hide / show controls manageControls(currentPosition); // Move slideInner using margin-left $('#slideInner').animate({ 'marginLeft' : slideWidth*(-currentPosition) }); }); // manageControls: Hides and Shows controls depending on currentPosition function manageControls(position){ // Hide left arrow if position is first slide if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() } // Hide right arrow if position is last slide if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() } } });
/** * Menu */ $(document).ready(function(){ var touch = $('#touch-menu'); var menu = $('#main-menu'); $(touch).on('click', function(e) { e.preventDefault(); menu.slideToggle(); }); $(window).resize(function(){ var w = $(window).width(); if(w > 767 && menu.is(':hidden')) { menu.removeAttr('style'); } }); // Buttom $("#touch-menu").click(function(){ $(this).toggleClass("active"); }); });
search_result['431']=["topic_00000000000000D5_attached_props--.html","LocaleHelper Attached Properties",""];
// Generated on 2014-10-16 using generator-angular 0.9.8 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Configurable paths for the application var appConfig = { app: require('./bower.json').appPath || 'app', dist: 'dist' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings yeoman: appConfig, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, coffee: { files: ['<%= yeoman.app %>/scripts/{,*/}*.{coffee,litcoffee,coffee.md}'], tasks: ['newer:coffee:dist'] }, coffeeTest: { files: ['test/spec/{,*/}*.{coffee,litcoffee,coffee.md}'], tasks: ['newer:coffee:test', 'karma'] }, styles: { files: ['<%= yeoman.app %>/styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, less: { files: ['<%= yeoman.app %>/styles/{,*/}*.less'], tasks: ['less:dist'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= yeoman.app %>/**/*.html', '<%= yeoman.app %>/**/*.less', '.tmp/styles/{,*/}*.css', '.tmp/scripts/{,*/}*.js', '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] } }, // The actual grunt server settings connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, middleware: function (connect) { return [ connect.static('.tmp'), connect().use( '/bower_components', connect.static('./bower_components') ), connect.static(appConfig.app) ]; } } }, test: { options: { port: 9001, middleware: function (connect) { return [ connect.static('.tmp'), connect.static('test'), connect().use( '/bower_components', connect.static('./bower_components') ), connect.static(appConfig.app) ]; } } }, dist: { options: { open: true, base: '<%= yeoman.dist %>' } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: { src: [ 'Gruntfile.js' ] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/{,*/}*', '!<%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the app wiredep: { app: { src: ['<%= yeoman.app %>/index.html'], ignorePath: /\.\.\//, exclude: "bower_components/bootstrap/dist/css/bootstrap.css" } }, // Compiles CoffeeScript to JavaScript coffee: { options: { sourceMap: true, sourceRoot: '' }, dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/scripts', src: '{,*/}*.coffee', dest: '.tmp/scripts', ext: '.js' }] }, test: { files: [{ expand: true, cwd: 'test/spec', src: '{,*/}*.coffee', dest: '.tmp/spec', ext: '.js' }] } }, // Renames files for browser caching purposes filerev: { dist: { src: [ '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/styles/{,*/}*.css', '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= yeoman.dist %>/styles/fonts/*' ] } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: '<%= yeoman.app %>/index.html', options: { dest: '<%= yeoman.dist %>', flow: { html: { steps: { js: ['concat', 'uglifyjs'], css: ['cssmin'] }, post: {} } } } }, // Performs rewrites based on filerev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'], options: { assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images'] } }, // The following *-min tasks will produce minified files in the dist folder // By default, your `index.html`'s <!-- Usemin block --> will take care of // minification. These next options are pre-configured if you do not wish // to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= yeoman.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css' // ] // } // } // }, // uglify: { // dist: { // files: { // '<%= yeoman.dist %>/scripts/scripts.js': [ // '<%= yeoman.dist %>/scripts/scripts.js' // ] // } // } // }, // concat: { // dist: {} // }, imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.{png,jpg,jpeg,gif}', dest: '<%= yeoman.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseWhitespace: true, conservativeCollapse: true, collapseBooleanAttributes: true, removeCommentsFromCDATA: true, removeOptionalTags: true }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', src: ['*.html', 'views/{,*/}*.html'], dest: '<%= yeoman.dist %>' }] } }, // ng-annotate tries to make the code safe for minification automatically // by using the Angular long form for dependency injection. ngAnnotate: { dist: { files: [{ expand: true, cwd: '.tmp/concat/scripts', src: ['*.js', '!oldieshim.js'], dest: '.tmp/concat/scripts' }] } }, // Replace Google CDN references cdnify: { dist: { html: ['<%= yeoman.dist %>/*.html'] } }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', '*.html', 'views/{,*/}*.html', 'images/{,*/}*.{webp}', 'fonts/*' ] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }, { expand: true, cwd: 'bower_components/bootstrap/dist', src: 'fonts/*', dest: '<%= yeoman.dist %>' }] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Run some tasks in parallel to speed up the build process concurrent: { server: [ 'coffee:dist', 'copy:styles' ], test: [ 'coffee', 'copy:styles' ], dist: [ 'coffee', 'copy:styles', 'imagemin', 'svgmin' ] }, // Test settings karma: { unit: { configFile: 'test/karma.conf.coffee', singleRun: true } }, less: { dist: { files: { '<%= yeoman.app %>/styles/main.css': ['<%= yeoman.app %>/styles/main.less'] }, options: { sourceMap: true, sourceMapFilename: '<%= yeoman.app %>/styles/main.css.map', sourceMapBasepath: '<%= yeoman.app %>/', sourceMapRootpath: '/' } } } }); grunt.registerTask('serve', 'Compile then start a connect web server', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve:' + target]); }); grunt.registerTask('test', [ 'clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', 'karma' ]); grunt.registerTask('build', [ 'clean:dist', 'wiredep', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'ngAnnotate', 'copy:dist', 'cdnify', 'cssmin', 'uglify', 'filerev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); };
var dialogsCommon = require("./dialogs-common"); var appmodule = require("application"); var types = require("utils/types"); global.moduleMerge(dialogsCommon, exports); function createAlertDialog(options) { var alert = new android.app.AlertDialog.Builder(appmodule.android.currentContext); alert.setTitle(options && types.isString(options.title) ? options.title : ""); alert.setMessage(options && types.isString(options.message) ? options.message : ""); if (options && options.cancelable === false) { alert.setCancelable(false); } return alert; } function showDialog(builder) { var dlg = builder.show(); var labelColor = dialogsCommon.getLabelColor(); if (labelColor) { var textViewId = dlg.getContext().getResources().getIdentifier("android:id/alertTitle", null, null); if (textViewId) { var tv = dlg.findViewById(textViewId); if (tv) { tv.setTextColor(labelColor.android); } } var messageTextViewId = dlg.getContext().getResources().getIdentifier("android:id/message", null, null); if (messageTextViewId) { var messageTextView = dlg.findViewById(messageTextViewId); if (messageTextView) { messageTextView.setTextColor(labelColor.android); } } } var buttonColor = dialogsCommon.getButtonColor(); if (buttonColor) { var buttons = []; for (var i = 0; i < 3; i++) { var id = dlg.getContext().getResources().getIdentifier("android:id/button" + i, null, null); buttons[i] = dlg.findViewById(id); } buttons.forEach(function (button) { if (button) { button.setTextColor(buttonColor.android); } }); } } function addButtonsToAlertDialog(alert, options, callback) { if (!options) { return; } if (options.okButtonText) { alert.setPositiveButton(options.okButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog, id) { dialog.cancel(); callback(true); } })); } if (options.cancelButtonText) { alert.setNegativeButton(options.cancelButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog, id) { dialog.cancel(); callback(false); } })); } if (options.neutralButtonText) { alert.setNeutralButton(options.neutralButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog, id) { dialog.cancel(); callback(undefined); } })); } alert.setOnDismissListener(new android.content.DialogInterface.OnDismissListener({ onDismiss: function () { callback(false); } })); } function alert(arg) { return new Promise(function (resolve, reject) { try { var options = !dialogsCommon.isDialogOptions(arg) ? { title: dialogsCommon.ALERT, okButtonText: dialogsCommon.OK, message: arg + "" } : arg; var alert = createAlertDialog(options); alert.setPositiveButton(options.okButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog, id) { dialog.cancel(); resolve(); } })); alert.setOnDismissListener(new android.content.DialogInterface.OnDismissListener({ onDismiss: function () { resolve(); } })); showDialog(alert); } catch (ex) { reject(ex); } }); } exports.alert = alert; function confirm(arg) { return new Promise(function (resolve, reject) { try { var options = !dialogsCommon.isDialogOptions(arg) ? { title: dialogsCommon.CONFIRM, okButtonText: dialogsCommon.OK, cancelButtonText: dialogsCommon.CANCEL, message: arg + "" } : arg; var alert = createAlertDialog(options); addButtonsToAlertDialog(alert, options, function (result) { resolve(result); }); showDialog(alert); } catch (ex) { reject(ex); } }); } exports.confirm = confirm; function prompt(arg) { var options; var defaultOptions = { title: dialogsCommon.PROMPT, okButtonText: dialogsCommon.OK, cancelButtonText: dialogsCommon.CANCEL, inputType: dialogsCommon.inputType.text, }; if (arguments.length === 1) { if (types.isString(arg)) { options = defaultOptions; options.message = arg; } else { options = arg; } } else if (arguments.length === 2) { if (types.isString(arguments[0]) && types.isString(arguments[1])) { options = defaultOptions; options.message = arguments[0]; options.defaultText = arguments[1]; } } return new Promise(function (resolve, reject) { try { var alert = createAlertDialog(options); var input = new android.widget.EditText(appmodule.android.currentContext); if (options && options.inputType === dialogsCommon.inputType.password) { input.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); } input.setText(options && options.defaultText || ""); alert.setView(input); var getText = function () { return input.getText().toString(); }; addButtonsToAlertDialog(alert, options, function (r) { resolve({ result: r, text: getText() }); }); showDialog(alert); } catch (ex) { reject(ex); } }); } exports.prompt = prompt; function login(arg) { var options; var defaultOptions = { title: dialogsCommon.LOGIN, okButtonText: dialogsCommon.OK, cancelButtonText: dialogsCommon.CANCEL }; if (arguments.length === 1) { if (types.isString(arguments[0])) { options = defaultOptions; options.message = arguments[0]; } else { options = arguments[0]; } } else if (arguments.length === 2) { if (types.isString(arguments[0]) && types.isString(arguments[1])) { options = defaultOptions; options.message = arguments[0]; options.userName = arguments[1]; } } else if (arguments.length === 3) { if (types.isString(arguments[0]) && types.isString(arguments[1]) && types.isString(arguments[2])) { options = defaultOptions; options.message = arguments[0]; options.userName = arguments[1]; options.password = arguments[2]; } } return new Promise(function (resolve, reject) { try { var context = appmodule.android.currentContext; var alert = createAlertDialog(options); var userNameInput = new android.widget.EditText(context); userNameInput.setText(options.userName ? options.userName : ""); var passwordInput = new android.widget.EditText(context); passwordInput.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); passwordInput.setText(options.password ? options.password : ""); var layout = new android.widget.LinearLayout(context); layout.setOrientation(1); layout.addView(userNameInput); layout.addView(passwordInput); alert.setView(layout); addButtonsToAlertDialog(alert, options, function (r) { resolve({ result: r, userName: userNameInput.getText().toString(), password: passwordInput.getText().toString() }); }); showDialog(alert); } catch (ex) { reject(ex); } }); } exports.login = login; function action(arg) { var options; var defaultOptions = { title: null, cancelButtonText: dialogsCommon.CANCEL }; if (arguments.length === 1) { if (types.isString(arguments[0])) { options = defaultOptions; options.message = arguments[0]; } else { options = arguments[0]; } } else if (arguments.length === 2) { if (types.isString(arguments[0]) && types.isString(arguments[1])) { options = defaultOptions; options.message = arguments[0]; options.cancelButtonText = arguments[1]; } } else if (arguments.length === 3) { if (types.isString(arguments[0]) && types.isString(arguments[1]) && types.isDefined(arguments[2])) { options = defaultOptions; options.message = arguments[0]; options.cancelButtonText = arguments[1]; options.actions = arguments[2]; } } return new Promise(function (resolve, reject) { try { var activity = appmodule.android.foregroundActivity || appmodule.android.startActivity; var alert = new android.app.AlertDialog.Builder(activity); var message = options && types.isString(options.message) ? options.message : ""; var title = options && types.isString(options.title) ? options.title : ""; if (options && options.cancelable === false) { alert.setCancelable(false); } if (title) { alert.setTitle(title); if (!options.actions) { alert.setMessage(message); } } else { alert.setTitle(message); } if (options.actions) { alert.setItems(options.actions, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog, which) { resolve(options.actions[which]); } })); } if (types.isString(options.cancelButtonText)) { alert.setNegativeButton(options.cancelButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog, id) { dialog.cancel(); resolve(options.cancelButtonText); } })); } alert.setOnDismissListener(new android.content.DialogInterface.OnDismissListener({ onDismiss: function () { if (types.isString(options.cancelButtonText)) { resolve(options.cancelButtonText); } else { resolve(""); } } })); showDialog(alert); } catch (ex) { reject(ex); } }); } exports.action = action; //# sourceMappingURL=dialogs.js.map
function main(){ console.log("Hello, world!"); } setInterval(main, 250);
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'colorbutton', 'sr', { auto: 'Аутоматски', bgColorTitle: 'Боја позадине', colors: { '000': 'Black', '800000': 'Maroon', '8B4513': 'Saddle Brown', '2F4F4F': 'Dark Slate Gray', '008080': 'Teal', '000080': 'Navy', '4B0082': 'Indigo', '696969': 'Dark Gray', B22222: 'Fire Brick', A52A2A: 'Brown', DAA520: 'Golden Rod', '006400': 'Dark Green', '40E0D0': 'Turquoise', '0000CD': 'Medium Blue', '800080': 'Purple', '808080': 'Gray', F00: 'Red', FF8C00: 'Dark Orange', FFD700: 'Gold', '008000': 'Green', '0FF': 'Cyan', '00F': 'Blue', EE82EE: 'Violet', A9A9A9: 'Dim Gray', FFA07A: 'Light Salmon', FFA500: 'Orange', FFFF00: 'Yellow', '00FF00': 'Lime', AFEEEE: 'Pale Turquoise', ADD8E6: 'Light Blue', DDA0DD: 'Plum', D3D3D3: 'Light Grey', FFF0F5: 'Lavender Blush', FAEBD7: 'Antique White', FFFFE0: 'Light Yellow', F0FFF0: 'Honeydew', F0FFFF: 'Azure', F0F8FF: 'Alice Blue', E6E6FA: 'Lavender', FFF: 'White' }, more: 'Више боја...', panelTitle: 'Colors', textColorTitle: 'Боја текста' } );
define([ 'expect', 'views/footer' ], function(expect, FooterView) { 'use strict'; describe('FooterView', function() { describe('#template', function() { it('should render template', function() { FooterView.prototype.autoRender = false; var footerView = new FooterView(); expect(footerView.template). to.be(require('text!views/templates/footer.ejs')); footerView.dispose(); FooterView.prototype.autoRender = true; }); }); describe('#autoRender', function() { it('should be auto render', function() { expect(FooterView.prototype.autoRender).to.be(true); }); }); describe('#region', function() { it('should be in footer region', function() { expect(FooterView.prototype.region).to.be('footer'); }); }); }); });
'use strict'; //Setting up route angular.module('questionresponses').config(['$stateProvider', function($stateProvider) { // Questionresponses state routing $stateProvider. state('listQuestionresponses', { url: '/questionresponses', templateUrl: 'modules/questionresponses/views/list-questionresponses.client.view.html' }). state('createQuestionresponse', { url: '/questionresponses/:questionId/create', templateUrl: 'modules/questionresponses/views/create-questionresponse.client.view.html' }). state('viewQuestionresponse', { url: '/questionresponses/:questionresponseId', templateUrl: 'modules/questionresponses/views/view-questionresponse.client.view.html' }). state('editQuestionresponse', { url: '/questionresponses/:questionresponseId/edit', templateUrl: 'modules/questionresponses/views/edit-questionresponse.client.view.html' }); } ]);
/** * Collects all requests that didnt match any route * @author Johan Kanefur <johan.canefur@gmail.com> * @param {Error} err Error from middleware before * @param {Request} req Express request object * @param {Response} res Express response object * @param {Function} next Function to next middleware * @return {void} */ module.exports = (err, req, res, next) => { if (err) { return res.status(422).json({ errors: [{ status: '422', title: 'Invalid request' }], }); } next(); };
function httpRequest(url, cb) { var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { cb(xhr.responseText); }; } xhr.send(); } function showWeather(result) { result = JSON.parse(result); var list = result.list; var table = '<table><tr><th>日期</th><th>天气</th><th>最低温度</th><th>最高温度</th></tr>'; for (var i in list) { var d = new Date(list[i].dt * 1000); table += '<tr>'; table += '<td>'+d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()+'</td>'; table += '<td>'+list[i].weather[0].description+'</td>'; table += '<td>'+Math.round(list[i].temp.min-273.15)+' °C</td>'; table += '<td>'+Math.round(list[i].temp.max-273.15)+' °C</td>'; table += '</tr>'; } table += '</table>'; document.getElementById('weather').innerHTML = table; } var city = localStorage.city; city = city ? city : 'beijing'; var url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q='+city+',china&lang=zh_cn'; httpRequest(url, showWeather);
//= require jquery-ui/core //= require jquery-ui/widget //= require jquery-ui/mouse /*! * jQuery UI Draggable 1.11.0 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/draggable/ */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./mouse", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { $.widget("ui.draggable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) { this.element[0].style.position = "relative"; } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._setHandleClassName(); this._mouseInit(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._setHandleClassName(); } }, _destroy: function() { if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) { this.destroyOnClear = true; return; } this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._removeHandleClassName(); this._mouseDestroy(); }, _mouseCapture: function(event) { var document = this.document[ 0 ], o = this.options; // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { // Support: IE9+ // If the <body> is blurred, IE will switch windows, see #9520 if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { // Blur any element that currently has focus, see #4261 $( document.activeElement ).blur(); } } catch ( error ) {} // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>") .css({ width: this.offsetWidth + "px", height: this.offsetHeight + "px", position: "absolute", opacity: "0.001", zIndex: 1000 }) .css($(this).offset()) .appendTo("body"); }); return true; }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if ($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent(); this.offsetParent = this.helper.offsetParent(); this.offsetParentCssPosition = this.offsetParent.css( "position" ); //The element's absolute position on the page minus margins this.offset = this.positionAbs = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; //Reset scroll cache this.offset.scroll = false; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this.position = this._generatePosition( event, false ); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if (this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.offsetParentCssPosition === "fixed" ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition( event, true ); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if (this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } this.helper[ 0 ].style.left = this.position.left + "px"; this.helper[ 0 ].style.top = this.position.top + "px"; if ($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if (this.dropped) { dropped = this.dropped; this.dropped = false; } if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if (that._trigger("stop", event) !== false) { that._clear(); } }); } else { if (this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function(event) { //Remove frame helpers $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } // The interaction is over; whether or not the click resulted in a drag, focus the element this.element.focus(); return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if (this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _setHandleClassName: function() { this._removeHandleClassName(); $( this.options.handle || this.element ).addClass( "ui-draggable-handle" ); }, _removeHandleClassName: function() { this.element.find( ".ui-draggable-handle" ) .addBack() .removeClass( "ui-draggable-handle" ); }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[ 0 ], [ event ])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element); if (!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = { left: +obj[0], top: +obj[1] || 0 }; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _isRootNode: function( element ) { return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ]; }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(), document = this.document[ 0 ]; // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if ( this._isRootNode( this.offsetParent[ 0 ] ) ) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if ( this.cssPosition !== "relative" ) { return { top: 0, left: 0 }; } var p = this.element.position(), scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ), left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 ) }; }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"),10) || 0), top: (parseInt(this.element.css("marginTop"),10) || 0), right: (parseInt(this.element.css("marginRight"),10) || 0), bottom: (parseInt(this.element.css("marginBottom"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var over, c, ce, o = this.options, document = this.document[ 0 ]; this.relative_container = null; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if ( !ce ) { return; } over = c.css( "overflow" ) !== "hidden"; this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ), ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relative_container = c; }, _convertPositionTo: function(d, pos) { if (!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod) ) }; }, _generatePosition: function( event, constrainPosition ) { var containment, co, top, left, o = this.options, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ), pageX = event.pageX, pageY = event.pageY; // Cache the scroll if ( !scrollIsRootNode || !this.offset.scroll ) { this.offset.scroll = { top: this.scrollParent.scrollTop(), left: this.scrollParent.scrollLeft() }; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( constrainPosition ) { if ( this.containment ) { if ( this.relative_container ){ co = this.relative_container.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if (event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if (event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if (event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if (event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if (o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } if ( o.axis === "y" ) { pageX = this.originalPageX; } if ( o.axis === "x" ) { pageY = this.originalPageY; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; if ( this.destroyOnClear ) { this.destroy(); } }, // From now on bulk stuff - mainly helpers _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call( this, type, [ event, ui, this ], true ); //The absolute position has to be recalculated after plugins if (type === "drag") { this.positionAbs = this._convertPositionTo("absolute"); } return $.Widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function( event, ui, inst ) { var o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $( this ).sortable( "instance" ); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). sortable._trigger("activate", event, uiSortable); } }); }, stop: function( event, ui, inst ) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var uiSortable = $.extend( {}, ui, { item: inst.element }); $.each(inst.sortables, function() { if (this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid" if (this.shouldRevert) { this.instance.options.revert = this.shouldRevert; } //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if (inst.options.helper === "original") { this.instance.currentItem.css({ top: "auto", left: "auto" }); } } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function( event, ui, inst ) { var that = this; $.each(inst.sortables, function() { var innermostIntersecting = false, thisSortable = this; //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this.instance._intersectsWith(this.instance.containerCache)) { innermostIntersecting = true; $.each(inst.sortables, function() { this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this !== thisSortable && this.instance._intersectsWith(this.instance.containerCache) && $.contains(thisSortable.instance.element[0], this.instance.element[0]) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if (innermostIntersecting) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if (!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if (this.instance.currentItem) { this.instance._mouseDrag(event); } } else { //If it doesn't intersect with the sortable, and it intersected before, //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval if (this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger("out", event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if (this.instance.placeholder) { this.instance.placeholder.remove(); } inst._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function( event, ui, instance ) { var t = $( "body" ), o = instance.options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function( event, ui, i ) { if ( i.scrollParent[ 0 ] !== i.document[ 0 ] && i.scrollParent[ 0 ].tagName !== "HTML" ) { i.overflowOffset = i.scrollParent.offset(); } }, drag: function( event, ui, i ) { var o = i.options, scrolled = false, document = i.document[ 0 ]; if ( i.scrollParent[ 0 ] !== document && i.scrollParent[ 0 ].tagName !== "HTML" ) { if (!o.axis || o.axis !== "x") { if ((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; } else if (event.pageY - i.overflowOffset.top < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } } if (!o.axis || o.axis !== "y") { if ((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; } else if (event.pageX - i.overflowOffset.left < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; } } } else { if (!o.axis || o.axis !== "x") { if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if (!o.axis || o.axis !== "y") { if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function( event, ui, i ) { var o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if (this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function( event, ui, inst ) { var ts, bs, ls, rs, l, r, t, b, i, first, o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if (inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if (o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; } } first = (ts || bs || ls || rs); if (o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; } } if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function( event, ui, instance ) { var min, o = instance.options, group = $.makeArray($(o.stack)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); return $.ui.draggable; }));
(function(_document, _script, _facebook_sdk) { var facbook_script, facbook_js = _document.getElementsByTagName(_script)[0]; if (_document.getElementById(_facebook_sdk)) return; facbook_script = _document.createElement(_script); facbook_script.id = _facebook_sdk; facbook_script.src = "//connect.facebook.net/vi_VN/sdk.js#xfbml=1&version=v2.3"; facbook_js.parentNode.insertBefore(facbook_script, facbook_js); }(document, "script", "facebook-sdk")); !function(_document, _script, twitter) { var twitter_script,twitter_js=_document.getElementsByTagName(_script)[0],p=/^http:/.test(_document.location)?'http':'https'; if(!_document.getElementById(twitter)){ twitter_script=_document.createElement(_script); twitter_script.id=twitter; twitter_script.src=p+"://platform.twitter.com/widgets.js"; twitter_js.parentNode.insertBefore(twitter_script,twitter_js); }}(document,"script","twitter");
/*! * ui-grid - v4.8.5 - 2020-09-14 * Copyright (c) 2020 ; License: MIT */ (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('pt', { headerCell: { aria: { defaultFilterLabel: 'Filtro por coluna', removeFilter: 'Remover filtro', columnMenuButtonLabel: 'Menu coluna', column: 'Coluna' }, priority: 'Prioridade:', filterLabel: "Filtro por coluna: " }, aggregate: { label: 'itens' }, groupPanel: { description: 'Arraste e solte uma coluna aqui para agrupar por essa coluna' }, search: { aria: { selected: 'Linha selecionada', notSelected: 'Linha não está selecionada' }, placeholder: 'Procurar...', showingItems: 'Mostrando os Itens:', selectedItems: 'Itens Selecionados:', totalItems: 'Total de Itens:', size: 'Tamanho da Página:', first: 'Primeira Página', next: 'Próxima Página', previous: 'Página Anterior', last: 'Última Página' }, menu: { text: 'Selecione as colunas:' }, sort: { ascending: 'Ordenar Ascendente', descending: 'Ordenar Descendente', none: 'Nenhuma Ordem', remove: 'Remover Ordenação' }, column: { hide: 'Esconder coluna' }, aggregation: { count: 'total de linhas: ', sum: 'total: ', avg: 'med: ', min: 'min: ', max: 'max: ' }, pinning: { pinLeft: 'Fixar Esquerda', pinRight: 'Fixar Direita', unpin: 'Desprender' }, columnMenu: { close: 'Fechar' }, gridMenu: { aria: { buttonLabel: 'Menu Grid' }, columns: 'Colunas:', importerTitle: 'Importar ficheiro', exporterAllAsCsv: 'Exportar todos os dados como csv', exporterVisibleAsCsv: 'Exportar dados visíveis como csv', exporterSelectedAsCsv: 'Exportar dados selecionados como csv', exporterAllAsPdf: 'Exportar todos os dados como pdf', exporterVisibleAsPdf: 'Exportar dados visíveis como pdf', exporterSelectedAsPdf: 'Exportar dados selecionados como pdf', exporterAllAsExcel: 'Exportar todos os dados como excel', exporterVisibleAsExcel: 'Exportar dados visíveis como excel', exporterSelectedAsExcel: 'Exportar dados selecionados como excel', clearAllFilters: 'Limpar todos os filtros' }, importer: { noHeaders: 'Nomes de colunas não puderam ser derivados. O ficheiro tem um cabeçalho?', noObjects: 'Objetos não puderam ser derivados. Havia dados no ficheiro, além dos cabeçalhos?', invalidCsv: 'Ficheiro não pode ser processado. É um CSV válido?', invalidJson: 'Ficheiro não pode ser processado. É um Json válido?', jsonNotArray: 'Ficheiro json importado tem que conter um array. Interrompendo.' }, pagination: { aria: { pageToFirst: 'Primeira página', pageBack: 'Página anterior', pageSelected: 'Página Selecionada', pageForward: 'Próxima', pageToLast: 'Anterior' }, sizes: 'itens por página', totalItems: 'itens', through: 'a', of: 'de' }, grouping: { group: 'Agrupar', ungroup: 'Desagrupar', aggregate_count: 'Agr: Contar', aggregate_sum: 'Agr: Soma', aggregate_max: 'Agr: Max', aggregate_min: 'Agr: Min', aggregate_avg: 'Agr: Med', aggregate_remove: 'Agr: Remover' }, validate: { error: 'Erro:', minLength: 'O valor deve ter, no minimo, THRESHOLD caracteres.', maxLength: 'O valor deve ter, no máximo, THRESHOLD caracteres.', required: 'Um valor é necessário.' } }); return $delegate; }]); }]); })();
'use strict'; angular.module('iamTheAnswerApp') .factory('Auth', function Auth($location, $rootScope, Session, User, $cookieStore, TwitterSession, $http) { // Get currentUser from cookie $rootScope.currentUser = $cookieStore.get('user') || null; $cookieStore.remove('user'); function setCookie(httpService, currentRoute) { var deferred = $q.defer(); // set the current route's needsLogin false so the // interceptor doesn't catch this infinitely. currentRoute.needsLogin = false; if (!$cookies.userId) { return httpService.get('/see-if-user-is-logged-in-on-server') .success(function (user) { if (user) { $cookies.userId = user.id; deferred.resolve(); } else { delete $cookies.userId; deferred.reject(); } }) .error(function (user) { deferred.reject(); }); } } return { /** * Authenticate user * * @param {Object} user - login info * @param {Function} callback - optional * @return {Promise} */ login: function(user, callback) { var cb = callback || angular.noop; return Session.save({ email: user.email, password: user.password }, function(user) { $rootScope.currentUser = user; return cb(); }, function(err) { return cb(err); }).$promise; }, loginViaTwitter: function(callback) { var cb = callback || angular.noop; TwitterSession.login(function(user){ // $rootScope.currentUser = user; return cb(); }, function(err) { return cb(err); }); }, /** * Unauthenticate user * * @param {Function} callback - optional * @return {Promise} */ logout: function(callback) { var cb = callback || angular.noop; return Session.delete(function() { $rootScope.currentUser = null; return cb(); }, function(err) { return cb(err); }).$promise; }, /** * Create a new user * * @param {Object} user - user info * @param {Function} callback - optional * @return {Promise} */ createUser: function(user, callback) { var cb = callback || angular.noop; return User.save(user, function(user) { $rootScope.currentUser = user; return cb(user); }, function(err) { return cb(err); }).$promise; }, /** * Change password * * @param {String} oldPassword * @param {String} newPassword * @param {Function} callback - optional * @return {Promise} */ changePassword: function(oldPassword, newPassword, callback) { var cb = callback || angular.noop; return User.update({ oldPassword: oldPassword, newPassword: newPassword }, function(user) { return cb(user); }, function(err) { return cb(err); }).$promise; }, /** * Gets all available info on authenticated user * * @return {Object} user */ currentUser: function() { return User.get(); }, /** * Simple check to see if a user is logged in * * @return {Boolean} */ isLoggedIn: function() { var user = $rootScope.currentUser; return !!user; }, }; });
/* --- name: DropZone.HTML5 description: A DropZone module. Handles uploading using the HTML5 method license: MIT-style license authors: - Mateusz Cyrankiewicz - Juan Lago requires: [DropZone] provides: [DropZone.HTML5] ... */ DropZone.HTML5 = new Class({ Extends: DropZone, initialize: function (options) { this.setOptions(options); this.method = 'HTML5'; this.activate(); }, bound: {}, /** * */ activate: function () { this.parent(); // If drop area is specified, // and in HTML5 mode, // activate dropping if(this.uiDropArea) { // Extend new events Object.append(Element.NativeEvents, { dragenter: 2, dragleave: 2, dragover: 2, drop: 2 }); this.uiDropArea.addEvents( { 'dragenter': function (e) { e.stop(); this.uiDropArea.addClass('hover'); }.bind(this), 'dragleave': function (e) { e.stop(); if (e.target && e.target === this.uiDropArea) { this.uiDropArea.removeClass('hover'); } }.bind(this), 'dragover': function (e) { e.stop(); e.preventDefault(); }.bind(this), 'drop': function (e) { e.stop(); if(e.event.dataTransfer) this.addFiles(e.event.dataTransfer.files); this.uiDropArea.removeClass('hover'); }.bind(this) }); // prevent defaults on window this.bound = { stopEvent: this._stopEvent.bind(this) }; $(document.body).addEvents({ 'dragenter': this.bound.stopEvent, 'dragleave': this.bound.stopEvent, 'dragover': this.bound.stopEvent, 'drop': this.bound.stopEvent }); } // Activate trigger for html file input this._activateHTMLButton(); }, /** * */ upload: function() { this.fileList.each(function(file, i) { if (file.checked && ! file.uploading && this.nCurrentUploads < this.options.max_queue) { // Upload only checked and new files file.uploading = true; this.nCurrentUploads++; this._html5Send(file, 0, false); } }, this); this.parent(); }, /** * * @param file * @param start * @param resume * @private */ _html5Send: function (file, start, resume) { var item; // if (this.uiList) item = this.uiList.getElement('#dropzone_item_' + (file.uniqueid)); // now getting the item globally in case it was moved somewhere else in onItemAdded event // this way it can always remain controlled item = $('dropzone_item_' + file.uniqueid + '_' + file.id); var end = this.options.block_size, chunk, is_blob = true; var header_file_name = file.name; var total = start + end; if (total > file.size) end = total - file.size; // Get slice method : Standard browser first if (file.file.slice) { chunk = file.file.slice(start, total); header_file_name = unescape(encodeURIComponent(file.name)); } // Mozilla based else if (file.file.mozSlice) { chunk = file.file.mozSlice(start, total); header_file_name = unescape(encodeURIComponent(file.name)); } // Chrome 20- and webkit based // Safari slices the file badly else if (file.file.webkitSlice && !Browser.safari) { chunk = file.file.webkitSlice(start, total); } // Safari 5- else { // send as form data instead of Blob chunk = new FormData(); chunk.append('file', file.file); is_blob = false; header_file_name = unescape(encodeURIComponent(file.name)); } // Set headers var headers = { 'Cache-Control': 'no-cache', 'X-Requested-With': 'XMLHttpRequest', 'X-File-Name': header_file_name, 'X-File-Size': file.size, 'X-File-Id': file.id }; if(resume) headers['X-File-Resume'] = resume; // Add file additional vars to the headers ( -> avoid using query string) Object.each(file.vars, function(value, index) { // Some servers don't support underscores in X-Headers index = index.replace(/_/g, '-'); headers['X-' + String.capitalize(index)] = value; }); // Send request var xhr = new Request.Blob({ url: this.url, headers: headers, onProgress: function(e) { if( ! is_blob) { // track xhr progress only if data isn't actually sent as a chunk (eg. in Safari) var perc = e.loaded / e.total * 100; this.fileList[file.id].progress = perc; this._itemProgress(item, perc); } }.bind(this), onSuccess: function (response) { try { response = JSON.decode(response, true); } catch(e){ response = ''; } if(typeof this.fileList[file.id] != 'undefined' && !this.fileList[file.id].cancelled) { if (this._noResponseError(response)) { // || total >= file.size // sometimes the size is measured wrong and fires too early? if (response.finish == true) { // job done! this._itemComplete(item, file, response); if (this.nCurrentUploads != 0 && this.nCurrentUploads < this.options.max_queue && file.checked) this.upload(); } else { // in progress.. if(file.checked) { var perc = (total / file.size) * 100; // it's used to calculate global progress this.fileList[file.id].progress = perc; this._itemProgress(item, perc); // Set the filename as set by the backend : 'name' comes from Filemanager, 'file_name' comes from MY_Upload() file.name = typeOf(response.name) != 'null' ? response.name : response.file_name; // Recursive upload this._html5Send(file, start + response.size.toInt(), true); } } } else { // response error! this._itemError(item, file, response); } } else { // item doesn't exist anymore, probably cancelled this._requestCanceled(item, file, response); } }.bind(this), onFailure: function() { this._itemError(item, file); }.bind(this), onException: function(e, key, value) { console.log('DropZone.HTML5 ERROR : ' + e.message); console.log('DropZone.HTML5 ERROR : ' + key + ' : ' + value); }.bind(this) }); xhr.send(chunk); }, /** * * @param id * @param item */ cancel: function(id, item) { this.parent(id, item); }, /** * */ kill: function() { this.parent(); // remove events if(this.uiDropArea) $(document.body).removeEvents( { 'dragenter': this.bound.stopEvent, 'dragleave': this.bound.stopEvent, 'dragover': this.bound.stopEvent, 'drop': this.bound.stopEvent }); }, reset: function() { this.parent(); if(this.hiddenContainer) this.hiddenContainer.empty(); }, /* Private methods */ /** * * @private */ _newInput: function(){ this.parent(); // add interaction to input this.lastInput.addEvent('change', function (e) { e.stop(); this.addFiles(this.lastInput.files); }.bind(this)); }, /** * * @param item * @param file * @param response * @private */ _itemError: function(item, file, response) { this.parent(item, file, response); /* // Previuoulsy if(this.nCurrentUploads == 0) this._queueComplete(); else if (this.nCurrentUploads != 0 && this.nCurrentUploads < this.options.max_queue) this.upload(); */ if (this.nCurrentUploads != 0 && this.nCurrentUploads < this.options.max_queue) this.upload(); } });
/** * @copyright Copyright 2013 <a href="http://www.extpoint.com">ExtPoint</a> * @author <a href="http://www.affka.ru">Vladimir Kozhin</a> * @license MIT */ /** * @class Jii.app.Application * @extends Jii.base.Module * @property {Jii.components.Db} db * @property {Jii.components.HttpServer} http * @property {Jii.components.Logger} logger * @property {Jii.components.Redis} redis * @property {Jii.components.String} string * @property {Jii.components.Time} time * @property {Jii.components.router.BaseRouter} router * @property {Jii.components.request.JsonRpc} rpcRequest * @property {Jii.components.User} user */ var self = Joints.defineClass('Jii.base.Application', Jii.base.Module, { baseUrl: null, debug: null, profile: null, actionNamespace: 'app.actions' });
import RCGroup from '../../RCGroup' import TransformGroup from '../../meshes/TransformGroup' function wrapper(Name, args) { const params = [Name].concat(args) return Name.bind(...params) } class ChemGroup extends RCGroup { constructor( geoParams, selection, colorer, mode, transforms, polyComplexity, material ) { super() if (this.constructor === ChemGroup) { throw new Error('Can not instantiate abstract class!') } this._selection = selection this._mode = mode this._colorer = colorer this._chunksIdc = selection.chunks this._polyComplexity = polyComplexity this._geo = new (wrapper(geoParams.Geometry, this._makeGeoArgs()))() this._mesh = new TransformGroup(this._geo, geoParams, material, transforms) this.add(this._mesh) this._build() } _makeGeoArgs() { throw new Error('ChemGroup subclass must override _makeGeoArgs() method') } /** * Builds subset geometry by ATOMS index list * * @param {Number} mask - Representation mask * @param {Boolean} innerOnly - if true returns inner bonds only - without halves * @returns {Array} Subset geometry */ getSubset(mask, innerOnly) { innerOnly = innerOnly !== undefined ? innerOnly : false const chunksList = this._calcChunksList(mask, innerOnly) if (chunksList.length === 0) { return [] } return this._mesh.getSubset(chunksList) } _changeSubsetOpacity(mask, value, innerOnly) { const chunksList = this._calcChunksList(mask, innerOnly) if (chunksList.length === 0) { return } this._geo.setOpacity(chunksList, value) } enableSubset(mask, innerOnly) { innerOnly = innerOnly !== undefined ? innerOnly : true this._changeSubsetOpacity(mask, 1.0, innerOnly) } disableSubset(mask, innerOnly) { innerOnly = innerOnly !== undefined ? innerOnly : true this._changeSubsetOpacity(mask, 0.0, innerOnly) } } export default ChemGroup
search_result['2427']=["topic_00000000000005D0.html","SendInvitationCommand.EndDate Property",""];
/*! Element Plus v2.0.3 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ElementPlusLocalePt = factory()); })(this, (function () { 'use strict'; var pt = { name: "pt", el: { colorpicker: { confirm: "Confirmar", clear: "Limpar" }, datepicker: { now: "Agora", today: "Hoje", cancel: "Cancelar", clear: "Limpar", confirm: "Confirmar", selectDate: "Selecione a data", selectTime: "Selecione a hora", startDate: "Data de inicio", startTime: "Hora de inicio", endDate: "Data de fim", endTime: "Hora de fim", prevYear: "Previous Year", nextYear: "Next Year", prevMonth: "Previous Month", nextMonth: "Next Month", year: "", month1: "Janeiro", month2: "Fevereiro", month3: "Mar\xE7o", month4: "Abril", month5: "Maio", month6: "Junho", month7: "Julho", month8: "Agosto", month9: "Setembro", month10: "Outubro", month11: "Novembro", month12: "Dezembro", weeks: { sun: "Dom", mon: "Seg", tue: "Ter", wed: "Qua", thu: "Qui", fri: "Sex", sat: "Sab" }, months: { jan: "Jan", feb: "Fev", mar: "Mar", apr: "Abr", may: "Mai", jun: "Jun", jul: "Jul", aug: "Ago", sep: "Set", oct: "Out", nov: "Nov", dec: "Dez" } }, select: { loading: "A carregar", noMatch: "Sem correspond\xEAncia", noData: "Sem dados", placeholder: "Selecione" }, cascader: { noMatch: "Sem correspond\xEAncia", loading: "A carregar", placeholder: "Selecione", noData: "Sem dados" }, pagination: { goto: "Ir para", pagesize: "/pagina", total: "Total {total}", pageClassifier: "" }, messagebox: { title: "Mensagem", confirm: "Confirmar", cancel: "Cancelar", error: "Erro!" }, upload: { deleteTip: "press delete to remove", delete: "Apagar", preview: "Previsualizar", continue: "Continuar" }, table: { emptyText: "Sem dados", confirmFilter: "Confirmar", resetFilter: "Limpar", clearFilter: "Todos", sumText: "Sum" }, tree: { emptyText: "Sem dados" }, transfer: { noMatch: "Sem correspond\xEAncia", noData: "Sem dados", titles: ["List 1", "List 2"], filterPlaceholder: "Enter keyword", noCheckedFormat: "{total} items", hasCheckedFormat: "{checked}/{total} checked" }, image: { error: "FAILED" }, pageHeader: { title: "Back" }, popconfirm: { confirmButtonText: "Yes", cancelButtonText: "No" } } }; return pt; }));
/* Riot v4.8.6, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.riot = {})); }(this, (function (exports) { 'use strict'; const COMPONENTS_IMPLEMENTATION_MAP = new Map(), DOM_COMPONENT_INSTANCE_PROPERTY = Symbol('riot-component'), PLUGINS_SET = new Set(), IS_DIRECTIVE = 'is', VALUE_ATTRIBUTE = 'value', MOUNT_METHOD_KEY = 'mount', UPDATE_METHOD_KEY = 'update', UNMOUNT_METHOD_KEY = 'unmount', SHOULD_UPDATE_KEY = 'shouldUpdate', ON_BEFORE_MOUNT_KEY = 'onBeforeMount', ON_MOUNTED_KEY = 'onMounted', ON_BEFORE_UPDATE_KEY = 'onBeforeUpdate', ON_UPDATED_KEY = 'onUpdated', ON_BEFORE_UNMOUNT_KEY = 'onBeforeUnmount', ON_UNMOUNTED_KEY = 'onUnmounted', PROPS_KEY = 'props', STATE_KEY = 'state', SLOTS_KEY = 'slots', ROOT_KEY = 'root', IS_PURE_SYMBOL = Symbol.for('pure'), PARENT_KEY_SYMBOL = Symbol('parent'), ATTRIBUTES_KEY_SYMBOL = Symbol('attributes'), TEMPLATE_KEY_SYMBOL = Symbol('template'); var globals = /*#__PURE__*/Object.freeze({ __proto__: null, COMPONENTS_IMPLEMENTATION_MAP: COMPONENTS_IMPLEMENTATION_MAP, DOM_COMPONENT_INSTANCE_PROPERTY: DOM_COMPONENT_INSTANCE_PROPERTY, PLUGINS_SET: PLUGINS_SET, IS_DIRECTIVE: IS_DIRECTIVE, VALUE_ATTRIBUTE: VALUE_ATTRIBUTE, MOUNT_METHOD_KEY: MOUNT_METHOD_KEY, UPDATE_METHOD_KEY: UPDATE_METHOD_KEY, UNMOUNT_METHOD_KEY: UNMOUNT_METHOD_KEY, SHOULD_UPDATE_KEY: SHOULD_UPDATE_KEY, ON_BEFORE_MOUNT_KEY: ON_BEFORE_MOUNT_KEY, ON_MOUNTED_KEY: ON_MOUNTED_KEY, ON_BEFORE_UPDATE_KEY: ON_BEFORE_UPDATE_KEY, ON_UPDATED_KEY: ON_UPDATED_KEY, ON_BEFORE_UNMOUNT_KEY: ON_BEFORE_UNMOUNT_KEY, ON_UNMOUNTED_KEY: ON_UNMOUNTED_KEY, PROPS_KEY: PROPS_KEY, STATE_KEY: STATE_KEY, SLOTS_KEY: SLOTS_KEY, ROOT_KEY: ROOT_KEY, IS_PURE_SYMBOL: IS_PURE_SYMBOL, PARENT_KEY_SYMBOL: PARENT_KEY_SYMBOL, ATTRIBUTES_KEY_SYMBOL: ATTRIBUTES_KEY_SYMBOL, TEMPLATE_KEY_SYMBOL: TEMPLATE_KEY_SYMBOL }); /** * Quick type checking * @param {*} element - anything * @param {string} type - type definition * @returns {boolean} true if the type corresponds */ function checkType(element, type) { return typeof element === type; } /** * Check that will be passed if its argument is a function * @param {*} value - value to check * @returns {boolean} - true if the value is a function */ function isFunction(value) { return checkType(value, 'function'); } function noop() { return this; } /** * Autobind the methods of a source object to itself * @param {Object} source - probably a riot tag instance * @param {Array<string>} methods - list of the methods to autobind * @returns {Object} the original object received */ function autobindMethods(source, methods) { methods.forEach(method => { source[method] = source[method].bind(source); }); return source; } /** * Call the first argument received only if it's a function otherwise return it as it is * @param {*} source - anything * @returns {*} anything */ function callOrAssign(source) { return isFunction(source) ? source.prototype && source.prototype.constructor ? new source() : source() : source; } /** * Convert a string from camel case to dash-case * @param {string} string - probably a component tag name * @returns {string} component name normalized */ /** * Convert a string containing dashes to camel case * @param {string} string - input string * @returns {string} my-string -> myString */ function dashToCamelCase(string) { return string.replace(/-(\w)/g, (_, c) => c.toUpperCase()); } /** * Move all the child nodes from a source tag to another * @param {HTMLElement} source - source node * @param {HTMLElement} target - target node * @returns {undefined} it's a void method ¯\_(ツ)_/¯ */ // Ignore this helper because it's needed only for svg tags function moveChildren(source, target) { if (source.firstChild) { target.appendChild(source.firstChild); moveChildren(source, target); } } /** * Remove the child nodes from any DOM node * @param {HTMLElement} node - target node * @returns {undefined} */ function cleanNode(node) { clearChildren(node.childNodes); } /** * Clear multiple children in a node * @param {HTMLElement[]} children - direct children nodes * @returns {undefined} */ function clearChildren(children) { Array.from(children).forEach(removeNode); } /** * Remove a node from the DOM * @param {HTMLElement} node - target node * @returns {undefined} */ function removeNode(node) { const { parentNode } = node; if (node.remove) node.remove(); /* istanbul ignore else */ else if (parentNode) parentNode.removeChild(node); } const EACH = 0; const IF = 1; const SIMPLE = 2; const TAG = 3; const SLOT = 4; var bindingTypes = { EACH, IF, SIMPLE, TAG, SLOT }; const ATTRIBUTE = 0; const EVENT = 1; const TEXT = 2; const VALUE = 3; var expressionTypes = { ATTRIBUTE, EVENT, TEXT, VALUE }; /** * Create the template meta object in case of <template> fragments * @param {TemplateChunk} componentTemplate - template chunk object * @returns {Object} the meta property that will be passed to the mount function of the TemplateChunk */ function createTemplateMeta(componentTemplate) { const fragment = componentTemplate.dom.cloneNode(true); return { avoidDOMInjection: true, fragment, children: Array.from(fragment.childNodes) }; } const { indexOf: iOF } = []; const append = (get, parent, children, start, end, before) => { const isSelect = 'selectedIndex' in parent; let noSelection = isSelect; while (start < end) { const child = get(children[start], 1); parent.insertBefore(child, before); if (isSelect && noSelection && child.selected) { noSelection = !noSelection; let { selectedIndex } = parent; parent.selectedIndex = selectedIndex < 0 ? start : iOF.call(parent.querySelectorAll('option'), child); } start++; } }; const eqeq = (a, b) => a == b; const identity = O => O; const indexOf = (moreNodes, moreStart, moreEnd, lessNodes, lessStart, lessEnd, compare) => { const length = lessEnd - lessStart; /* istanbul ignore if */ if (length < 1) return -1; while (moreEnd - moreStart >= length) { let m = moreStart; let l = lessStart; while (m < moreEnd && l < lessEnd && compare(moreNodes[m], lessNodes[l])) { m++; l++; } if (l === lessEnd) return moreStart; moreStart = m + 1; } return -1; }; const isReversed = (futureNodes, futureEnd, currentNodes, currentStart, currentEnd, compare) => { while (currentStart < currentEnd && compare(currentNodes[currentStart], futureNodes[futureEnd - 1])) { currentStart++; futureEnd--; } return futureEnd === 0; }; const next = (get, list, i, length, before) => i < length ? get(list[i], 0) : 0 < i ? get(list[i - 1], -0).nextSibling : before; const remove = (get, children, start, end) => { while (start < end) drop(get(children[start++], -1)); }; // - - - - - - - - - - - - - - - - - - - // diff related constants and utilities // - - - - - - - - - - - - - - - - - - - const DELETION = -1; const INSERTION = 1; const SKIP = 0; const SKIP_OND = 50; const HS = (futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges) => { let k = 0; /* istanbul ignore next */ let minLen = futureChanges < currentChanges ? futureChanges : currentChanges; const link = Array(minLen++); const tresh = Array(minLen); tresh[0] = -1; for (let i = 1; i < minLen; i++) tresh[i] = currentEnd; const nodes = currentNodes.slice(currentStart, currentEnd); for (let i = futureStart; i < futureEnd; i++) { const index = nodes.indexOf(futureNodes[i]); if (-1 < index) { const idxInOld = index + currentStart; k = findK(tresh, minLen, idxInOld); /* istanbul ignore else */ if (-1 < k) { tresh[k] = idxInOld; link[k] = { newi: i, oldi: idxInOld, prev: link[k - 1] }; } } } k = --minLen; --currentEnd; while (tresh[k] > currentEnd) --k; minLen = currentChanges + futureChanges - k; const diff = Array(minLen); let ptr = link[k]; --futureEnd; while (ptr) { const { newi, oldi } = ptr; while (futureEnd > newi) { diff[--minLen] = INSERTION; --futureEnd; } while (currentEnd > oldi) { diff[--minLen] = DELETION; --currentEnd; } diff[--minLen] = SKIP; --futureEnd; --currentEnd; ptr = ptr.prev; } while (futureEnd >= futureStart) { diff[--minLen] = INSERTION; --futureEnd; } while (currentEnd >= currentStart) { diff[--minLen] = DELETION; --currentEnd; } return diff; }; // this is pretty much the same petit-dom code without the delete map part // https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L556-L561 const OND = (futureNodes, futureStart, rows, currentNodes, currentStart, cols, compare) => { const length = rows + cols; const v = []; let d, k, r, c, pv, cv, pd; outer: for (d = 0; d <= length; d++) { /* istanbul ignore if */ if (d > SKIP_OND) return null; pd = d - 1; /* istanbul ignore next */ pv = d ? v[d - 1] : [0, 0]; cv = v[d] = []; for (k = -d; k <= d; k += 2) { if (k === -d || k !== d && pv[pd + k - 1] < pv[pd + k + 1]) { c = pv[pd + k + 1]; } else { c = pv[pd + k - 1] + 1; } r = c - k; while (c < cols && r < rows && compare(currentNodes[currentStart + c], futureNodes[futureStart + r])) { c++; r++; } if (c === cols && r === rows) { break outer; } cv[d + k] = c; } } const diff = Array(d / 2 + length / 2); let diffIdx = diff.length - 1; for (d = v.length - 1; d >= 0; d--) { while (c > 0 && r > 0 && compare(currentNodes[currentStart + c - 1], futureNodes[futureStart + r - 1])) { // diagonal edge = equality diff[diffIdx--] = SKIP; c--; r--; } if (!d) break; pd = d - 1; /* istanbul ignore next */ pv = d ? v[d - 1] : [0, 0]; k = c - r; if (k === -d || k !== d && pv[pd + k - 1] < pv[pd + k + 1]) { // vertical edge = insertion r--; diff[diffIdx--] = INSERTION; } else { // horizontal edge = deletion c--; diff[diffIdx--] = DELETION; } } return diff; }; const applyDiff = (diff, get, parentNode, futureNodes, futureStart, currentNodes, currentStart, currentLength, before) => { const live = []; const length = diff.length; let currentIndex = currentStart; let i = 0; while (i < length) { switch (diff[i++]) { case SKIP: futureStart++; currentIndex++; break; case INSERTION: // TODO: bulk appends for sequential nodes live.push(futureNodes[futureStart]); append(get, parentNode, futureNodes, futureStart++, futureStart, currentIndex < currentLength ? get(currentNodes[currentIndex], 0) : before); break; case DELETION: currentIndex++; break; } } i = 0; while (i < length) { switch (diff[i++]) { case SKIP: currentStart++; break; case DELETION: // TODO: bulk removes for sequential nodes if (-1 < live.indexOf(currentNodes[currentStart])) currentStart++;else remove(get, currentNodes, currentStart++, currentStart); break; } } }; const findK = (ktr, length, j) => { let lo = 1; let hi = length; while (lo < hi) { const mid = (lo + hi) / 2 >>> 0; if (j < ktr[mid]) hi = mid;else lo = mid + 1; } return lo; }; const smartDiff = (get, parentNode, futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges, currentLength, compare, before) => { applyDiff(OND(futureNodes, futureStart, futureChanges, currentNodes, currentStart, currentChanges, compare) || HS(futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges), get, parentNode, futureNodes, futureStart, currentNodes, currentStart, currentLength, before); }; const drop = node => (node.remove || dropChild).call(node); function dropChild() { const { parentNode } = this; /* istanbul ignore else */ if (parentNode) parentNode.removeChild(this); } /*! (c) 2018 Andrea Giammarchi (ISC) */ const domdiff = (parentNode, // where changes happen currentNodes, // Array of current items/nodes futureNodes, // Array of future items/nodes options // optional object with one of the following properties // before: domNode // compare(generic, generic) => true if same generic // node(generic) => Node ) => { if (!options) options = {}; const compare = options.compare || eqeq; const get = options.node || identity; const before = options.before == null ? null : get(options.before, 0); const currentLength = currentNodes.length; let currentEnd = currentLength; let currentStart = 0; let futureEnd = futureNodes.length; let futureStart = 0; // common prefix while (currentStart < currentEnd && futureStart < futureEnd && compare(currentNodes[currentStart], futureNodes[futureStart])) { currentStart++; futureStart++; } // common suffix while (currentStart < currentEnd && futureStart < futureEnd && compare(currentNodes[currentEnd - 1], futureNodes[futureEnd - 1])) { currentEnd--; futureEnd--; } const currentSame = currentStart === currentEnd; const futureSame = futureStart === futureEnd; // same list if (currentSame && futureSame) return futureNodes; // only stuff to add if (currentSame && futureStart < futureEnd) { append(get, parentNode, futureNodes, futureStart, futureEnd, next(get, currentNodes, currentStart, currentLength, before)); return futureNodes; } // only stuff to remove if (futureSame && currentStart < currentEnd) { remove(get, currentNodes, currentStart, currentEnd); return futureNodes; } const currentChanges = currentEnd - currentStart; const futureChanges = futureEnd - futureStart; let i = -1; // 2 simple indels: the shortest sequence is a subsequence of the longest if (currentChanges < futureChanges) { i = indexOf(futureNodes, futureStart, futureEnd, currentNodes, currentStart, currentEnd, compare); // inner diff if (-1 < i) { append(get, parentNode, futureNodes, futureStart, i, get(currentNodes[currentStart], 0)); append(get, parentNode, futureNodes, i + currentChanges, futureEnd, next(get, currentNodes, currentEnd, currentLength, before)); return futureNodes; } } /* istanbul ignore else */ else if (futureChanges < currentChanges) { i = indexOf(currentNodes, currentStart, currentEnd, futureNodes, futureStart, futureEnd, compare); // outer diff if (-1 < i) { remove(get, currentNodes, currentStart, i); remove(get, currentNodes, i + futureChanges, currentEnd); return futureNodes; } } // common case with one replacement for many nodes // or many nodes replaced for a single one /* istanbul ignore else */ if (currentChanges < 2 || futureChanges < 2) { append(get, parentNode, futureNodes, futureStart, futureEnd, get(currentNodes[currentStart], 0)); remove(get, currentNodes, currentStart, currentEnd); return futureNodes; } // the half match diff part has been skipped in petit-dom // https://github.com/yelouafi/petit-dom/blob/bd6f5c919b5ae5297be01612c524c40be45f14a7/src/vdom.js#L391-L397 // accordingly, I think it's safe to skip in here too // if one day it'll come out like the speediest thing ever to do // then I might add it in here too // Extra: before going too fancy, what about reversed lists ? // This should bail out pretty quickly if that's not the case. if (currentChanges === futureChanges && isReversed(futureNodes, futureEnd, currentNodes, currentStart, currentEnd, compare)) { append(get, parentNode, futureNodes, futureStart, futureEnd, next(get, currentNodes, currentEnd, currentLength, before)); return futureNodes; } // last resort through a smart diff smartDiff(get, parentNode, futureNodes, futureStart, futureEnd, futureChanges, currentNodes, currentStart, currentEnd, currentChanges, currentLength, compare, before); return futureNodes; }; /** * Quick type checking * @param {*} element - anything * @param {string} type - type definition * @returns {boolean} true if the type corresponds */ function checkType$1(element, type) { return typeof element === type; } /** * Check if an element is part of an svg * @param {HTMLElement} el - element to check * @returns {boolean} true if we are in an svg context */ function isSvg(el) { const owner = el.ownerSVGElement; return !!owner || owner === null; } /** * Check if an element is a template tag * @param {HTMLElement} el - element to check * @returns {boolean} true if it's a <template> */ function isTemplate(el) { return !isNil(el.content); } /** * Check that will be passed if its argument is a function * @param {*} value - value to check * @returns {boolean} - true if the value is a function */ function isFunction$1(value) { return checkType$1(value, 'function'); } /** * Check if a value is a Boolean * @param {*} value - anything * @returns {boolean} true only for the value is a boolean */ function isBoolean(value) { return checkType$1(value, 'boolean'); } /** * Check if a value is an Object * @param {*} value - anything * @returns {boolean} true only for the value is an object */ function isObject(value) { return !isNil(value) && checkType$1(value, 'object'); } /** * Check if a value is null or undefined * @param {*} value - anything * @returns {boolean} true only for the 'undefined' and 'null' types */ function isNil(value) { return value === null || value === undefined; } const UNMOUNT_SCOPE = Symbol('unmount'); const EachBinding = Object.seal({ // dynamic binding properties // childrenMap: null, // node: null, // root: null, // condition: null, // evaluate: null, // template: null, // isTemplateTag: false, nodes: [], // getKey: null, // indexName: null, // itemName: null, // afterPlaceholder: null, // placeholder: null, // API methods mount(scope, parentScope) { return this.update(scope, parentScope); }, update(scope, parentScope) { const { placeholder, nodes, childrenMap } = this; const collection = scope === UNMOUNT_SCOPE ? null : this.evaluate(scope); const items = collection ? Array.from(collection) : []; const parent = placeholder.parentNode; // prepare the diffing const { newChildrenMap, batches, futureNodes } = createPatch(items, scope, parentScope, this); // patch the DOM only if there are new nodes domdiff(parent, nodes, futureNodes, { before: placeholder, node: patch(Array.from(childrenMap.values()), parentScope) }); // trigger the mounts and the updates batches.forEach(fn => fn()); // update the children map this.childrenMap = newChildrenMap; this.nodes = futureNodes; return this; }, unmount(scope, parentScope) { this.update(UNMOUNT_SCOPE, parentScope); return this; } }); /** * Patch the DOM while diffing * @param {TemplateChunk[]} redundant - redundant tepmplate chunks * @param {*} parentScope - scope of the parent template * @returns {Function} patch function used by domdiff */ function patch(redundant, parentScope) { return (item, info) => { if (info < 0) { const element = redundant.pop(); if (element) { const { template, context } = element; // notice that we pass null as last argument because // the root node and its children will be removed by domdiff template.unmount(context, parentScope, null); } } return item; }; } /** * Check whether a template must be filtered from a loop * @param {Function} condition - filter function * @param {Object} context - argument passed to the filter function * @returns {boolean} true if this item should be skipped */ function mustFilterItem(condition, context) { return condition ? Boolean(condition(context)) === false : false; } /** * Extend the scope of the looped template * @param {Object} scope - current template scope * @param {string} options.itemName - key to identify the looped item in the new context * @param {string} options.indexName - key to identify the index of the looped item * @param {number} options.index - current index * @param {*} options.item - collection item looped * @returns {Object} enhanced scope object */ function extendScope(scope, _ref) { let { itemName, indexName, index, item } = _ref; scope[itemName] = item; if (indexName) scope[indexName] = index; return scope; } /** * Loop the current template items * @param {Array} items - expression collection value * @param {*} scope - template scope * @param {*} parentScope - scope of the parent template * @param {EeachBinding} binding - each binding object instance * @returns {Object} data * @returns {Map} data.newChildrenMap - a Map containing the new children template structure * @returns {Array} data.batches - array containing the template lifecycle functions to trigger * @returns {Array} data.futureNodes - array containing the nodes we need to diff */ function createPatch(items, scope, parentScope, binding) { const { condition, template, childrenMap, itemName, getKey, indexName, root, isTemplateTag } = binding; const newChildrenMap = new Map(); const batches = []; const futureNodes = []; items.forEach((item, index) => { const context = extendScope(Object.create(scope), { itemName, indexName, index, item }); const key = getKey ? getKey(context) : index; const oldItem = childrenMap.get(key); if (mustFilterItem(condition, context)) { return; } const componentTemplate = oldItem ? oldItem.template : template.clone(); const el = oldItem ? componentTemplate.el : root.cloneNode(); const mustMount = !oldItem; const meta = isTemplateTag && mustMount ? createTemplateMeta(componentTemplate) : {}; if (mustMount) { batches.push(() => componentTemplate.mount(el, context, parentScope, meta)); } else { batches.push(() => componentTemplate.update(context, parentScope)); } // create the collection of nodes to update or to add // in case of template tags we need to add all its children nodes if (isTemplateTag) { const children = meta.children || componentTemplate.children; futureNodes.push(...children); // add fake children into the childrenMap in order to preserve // the index in case of unmount calls children.forEach(child => newChildrenMap.set(child, null)); } else { futureNodes.push(el); } // delete the old item from the children map childrenMap.delete(key); // update the children map newChildrenMap.set(key, { template: componentTemplate, context, index }); }); return { newChildrenMap, batches, futureNodes }; } function create(node, _ref2) { let { evaluate, condition, itemName, indexName, getKey, template } = _ref2; const placeholder = document.createTextNode(''); const parent = node.parentNode; const root = node.cloneNode(); parent.insertBefore(placeholder, node); removeNode(node); return Object.assign({}, EachBinding, { childrenMap: new Map(), node, root, condition, evaluate, isTemplateTag: isTemplate(root), template: template.createDOM(node), getKey, indexName, itemName, placeholder }); } /** * Binding responsible for the `if` directive */ const IfBinding = Object.seal({ // dynamic binding properties // node: null, // evaluate: null, // isTemplateTag: false, // placeholder: null, // template: null, // API methods mount(scope, parentScope) { return this.update(scope, parentScope); }, update(scope, parentScope) { const value = !!this.evaluate(scope); const mustMount = !this.value && value; const mustUnmount = this.value && !value; const mount = () => { const pristine = this.node.cloneNode(); this.placeholder.parentNode.insertBefore(pristine, this.placeholder); this.template = this.template.clone(); this.template.mount(pristine, scope, parentScope); }; switch (true) { case mustMount: mount(); break; case mustUnmount: this.unmount(scope); break; default: if (value) this.template.update(scope, parentScope); } this.value = value; return this; }, unmount(scope, parentScope) { this.template.unmount(scope, parentScope, true); return this; } }); function create$1(node, _ref3) { let { evaluate, template } = _ref3; const parent = node.parentNode; const placeholder = document.createTextNode(''); parent.insertBefore(placeholder, node); removeNode(node); return Object.assign({}, IfBinding, { node, evaluate, placeholder, template: template.createDOM(node) }); } /** * Returns the memoized (cached) function. * // borrowed from https://www.30secondsofcode.org/js/s/memoize * @param {Function} fn - function to memoize * @returns {Function} memoize function */ function memoize(fn) { const cache = new Map(); const cached = val => { return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val); }; cached.cache = cache; return cached; } /** * Evaluate a list of attribute expressions * @param {Array} attributes - attribute expressions generated by the riot compiler * @returns {Object} key value pairs with the result of the computation */ function evaluateAttributeExpressions(attributes) { return attributes.reduce((acc, attribute) => { const { value, type } = attribute; switch (true) { // spread attribute case !attribute.name && type === ATTRIBUTE: return Object.assign({}, acc, {}, value); // value attribute case type === VALUE: acc.value = attribute.value; break; // normal attributes default: acc[dashToCamelCase(attribute.name)] = attribute.value; } return acc; }, {}); } const REMOVE_ATTRIBUTE = 'removeAttribute'; const SET_ATTIBUTE = 'setAttribute'; const ElementProto = typeof Element === 'undefined' ? {} : Element.prototype; const isNativeHtmlProperty = memoize(name => ElementProto.hasOwnProperty(name)); // eslint-disable-line /** * Add all the attributes provided * @param {HTMLElement} node - target node * @param {Object} attributes - object containing the attributes names and values * @returns {undefined} sorry it's a void function :( */ function setAllAttributes(node, attributes) { Object.entries(attributes).forEach((_ref4) => { let [name, value] = _ref4; return attributeExpression(node, { name }, value); }); } /** * Remove all the attributes provided * @param {HTMLElement} node - target node * @param {Object} attributes - object containing all the attribute names * @returns {undefined} sorry it's a void function :( */ function removeAllAttributes(node, attributes) { Object.keys(attributes).forEach(attribute => node.removeAttribute(attribute)); } /** * This methods handles the DOM attributes updates * @param {HTMLElement} node - target node * @param {Object} expression - expression object * @param {string} expression.name - attribute name * @param {*} value - new expression value * @param {*} oldValue - the old expression cached value * @returns {undefined} */ function attributeExpression(node, _ref5, value, oldValue) { let { name } = _ref5; // is it a spread operator? {...attributes} if (!name) { // is the value still truthy? if (value) { setAllAttributes(node, value); } else if (oldValue) { // otherwise remove all the old attributes removeAllAttributes(node, oldValue); } return; } // handle boolean attributes if (!isNativeHtmlProperty(name) && (isBoolean(value) || isObject(value) || isFunction$1(value))) { node[name] = value; } node[getMethod(value)](name, normalizeValue(name, value)); } /** * Get the attribute modifier method * @param {*} value - if truthy we return `setAttribute` othewise `removeAttribute` * @returns {string} the node attribute modifier method name */ function getMethod(value) { return isNil(value) || value === false || value === '' || isObject(value) || isFunction$1(value) ? REMOVE_ATTRIBUTE : SET_ATTIBUTE; } /** * Get the value as string * @param {string} name - attribute name * @param {*} value - user input value * @returns {string} input value as string */ function normalizeValue(name, value) { // be sure that expressions like selected={ true } will be always rendered as selected='selected' if (value === true) return name; return value; } const RE_EVENTS_PREFIX = /^on/; /** * Set a new event listener * @param {HTMLElement} node - target node * @param {Object} expression - expression object * @param {string} expression.name - event name * @param {*} value - new expression value * @param {*} oldValue - old expression value * @returns {value} the callback just received */ function eventExpression(node, _ref6, value, oldValue) { let { name } = _ref6; const normalizedEventName = name.replace(RE_EVENTS_PREFIX, ''); if (oldValue) { node.removeEventListener(normalizedEventName, oldValue); } if (value) { node.addEventListener(normalizedEventName, value, false); } } /** * Normalize the user value in order to render a empty string in case of falsy values * @param {*} value - user input value * @returns {string} hopefully a string */ function normalizeStringValue(value) { return isNil(value) ? '' : value; } /** * Get the the target text node to update or create one from of a comment node * @param {HTMLElement} node - any html element containing childNodes * @param {number} childNodeIndex - index of the text node in the childNodes list * @returns {HTMLTextNode} the text node to update */ const getTextNode = (node, childNodeIndex) => { const target = node.childNodes[childNodeIndex]; if (target.nodeType === Node.COMMENT_NODE) { const textNode = document.createTextNode(''); node.replaceChild(textNode, target); return textNode; } return target; }; /** * This methods handles a simple text expression update * @param {HTMLElement} node - target node * @param {Object} data - expression object * @param {*} value - new expression value * @returns {undefined} */ function textExpression(node, data, value) { node.data = normalizeStringValue(value); } /** * This methods handles the input fileds value updates * @param {HTMLElement} node - target node * @param {Object} expression - expression object * @param {*} value - new expression value * @returns {undefined} */ function valueExpression(node, expression, value) { node.value = normalizeStringValue(value); } var expressions = { [ATTRIBUTE]: attributeExpression, [EVENT]: eventExpression, [TEXT]: textExpression, [VALUE]: valueExpression }; const Expression = Object.seal({ // Static props // node: null, // value: null, // API methods /** * Mount the expression evaluating its initial value * @param {*} scope - argument passed to the expression to evaluate its current values * @returns {Expression} self */ mount(scope) { // hopefully a pure function this.value = this.evaluate(scope); // IO() DOM updates apply(this, this.value); return this; }, /** * Update the expression if its value changed * @param {*} scope - argument passed to the expression to evaluate its current values * @returns {Expression} self */ update(scope) { // pure function const value = this.evaluate(scope); if (this.value !== value) { // IO() DOM updates apply(this, value); this.value = value; } return this; }, /** * Expression teardown method * @returns {Expression} self */ unmount() { // unmount only the event handling expressions if (this.type === EVENT) apply(this, null); return this; } }); /** * IO() function to handle the DOM updates * @param {Expression} expression - expression object * @param {*} value - current expression value * @returns {undefined} */ function apply(expression, value) { return expressions[expression.type](expression.node, expression, value, expression.value); } function create$2(node, data) { return Object.assign({}, Expression, {}, data, { node: data.type === TEXT ? getTextNode(node, data.childNodeIndex) : node }); } /** * Create a flat object having as keys a list of methods that if dispatched will propagate * on the whole collection * @param {Array} collection - collection to iterate * @param {Array<string>} methods - methods to execute on each item of the collection * @param {*} context - context returned by the new methods created * @returns {Object} a new object to simplify the the nested methods dispatching */ function flattenCollectionMethods(collection, methods, context) { return methods.reduce((acc, method) => { return Object.assign({}, acc, { [method]: scope => { return collection.map(item => item[method](scope)) && context; } }); }, {}); } function create$3(node, _ref7) { let { expressions } = _ref7; return Object.assign({}, flattenCollectionMethods(expressions.map(expression => create$2(node, expression)), ['mount', 'update', 'unmount'])); } function extendParentScope(attributes, scope, parentScope) { if (!attributes || !attributes.length) return parentScope; const expressions = attributes.map(attr => Object.assign({}, attr, { value: attr.evaluate(scope) })); return Object.assign(Object.create(parentScope || null), evaluateAttributeExpressions(expressions)); } const SlotBinding = Object.seal({ // dynamic binding properties // node: null, // name: null, attributes: [], // template: null, getTemplateScope(scope, parentScope) { return extendParentScope(this.attributes, scope, parentScope); }, // API methods mount(scope, parentScope) { const templateData = scope.slots ? scope.slots.find((_ref8) => { let { id } = _ref8; return id === this.name; }) : false; const { parentNode } = this.node; this.template = templateData && create$6(templateData.html, templateData.bindings).createDOM(parentNode); if (this.template) { this.template.mount(this.node, this.getTemplateScope(scope, parentScope)); this.template.children = moveSlotInnerContent(this.node); } removeNode(this.node); return this; }, update(scope, parentScope) { if (this.template) { this.template.update(this.getTemplateScope(scope, parentScope)); } return this; }, unmount(scope, parentScope, mustRemoveRoot) { if (this.template) { this.template.unmount(this.getTemplateScope(scope, parentScope), null, mustRemoveRoot); } return this; } }); /** * Move the inner content of the slots outside of them * @param {HTMLNode} slot - slot node * @param {HTMLElement} children - array to fill with the child nodes detected * @returns {HTMLElement[]} list of the node moved */ function moveSlotInnerContent(slot, children) { if (children === void 0) { children = []; } const child = slot.firstChild; if (child) { slot.parentNode.insertBefore(child, slot); return [child, ...moveSlotInnerContent(slot)]; } return children; } /** * Create a single slot binding * @param {HTMLElement} node - slot node * @param {string} options.name - slot id * @returns {Object} Slot binding object */ function createSlot(node, _ref9) { let { name, attributes } = _ref9; return Object.assign({}, SlotBinding, { attributes, node, name }); } /** * Create a new tag object if it was registered before, otherwise fallback to the simple * template chunk * @param {Function} component - component factory function * @param {Array<Object>} slots - array containing the slots markup * @param {Array} attributes - dynamic attributes that will be received by the tag element * @returns {TagImplementation|TemplateChunk} a tag implementation or a template chunk as fallback */ function getTag(component, slots, attributes) { if (slots === void 0) { slots = []; } if (attributes === void 0) { attributes = []; } // if this tag was registered before we will return its implementation if (component) { return component({ slots, attributes }); } // otherwise we return a template chunk return create$6(slotsToMarkup(slots), [...slotBindings(slots), { // the attributes should be registered as binding // if we fallback to a normal template chunk expressions: attributes.map(attr => { return Object.assign({ type: ATTRIBUTE }, attr); }) }]); } /** * Merge all the slots bindings into a single array * @param {Array<Object>} slots - slots collection * @returns {Array<Bindings>} flatten bindings array */ function slotBindings(slots) { return slots.reduce((acc, _ref10) => { let { bindings } = _ref10; return acc.concat(bindings); }, []); } /** * Merge all the slots together in a single markup string * @param {Array<Object>} slots - slots collection * @returns {string} markup of all the slots in a single string */ function slotsToMarkup(slots) { return slots.reduce((acc, slot) => { return acc + slot.html; }, ''); } const TagBinding = Object.seal({ // dynamic binding properties // node: null, // evaluate: null, // name: null, // slots: null, // tag: null, // attributes: null, // getComponent: null, mount(scope) { return this.update(scope); }, update(scope, parentScope) { const name = this.evaluate(scope); // simple update if (name === this.name) { this.tag.update(scope); } else { // unmount the old tag if it exists this.unmount(scope, parentScope, true); // mount the new tag this.name = name; this.tag = getTag(this.getComponent(name), this.slots, this.attributes); this.tag.mount(this.node, scope); } return this; }, unmount(scope, parentScope, keepRootTag) { if (this.tag) { // keep the root tag this.tag.unmount(keepRootTag); } return this; } }); function create$4(node, _ref11) { let { evaluate, getComponent, slots, attributes } = _ref11; return Object.assign({}, TagBinding, { node, evaluate, slots, attributes, getComponent }); } var bindings = { [IF]: create$1, [SIMPLE]: create$3, [EACH]: create, [TAG]: create$4, [SLOT]: createSlot }; /** * Text expressions in a template tag will get childNodeIndex value normalized * depending on the position of the <template> tag offset * @param {Expression[]} expressions - riot expressions array * @param {number} textExpressionsOffset - offset of the <template> tag * @returns {Expression[]} expressions containing the text expressions normalized */ function fixTextExpressionsOffset(expressions, textExpressionsOffset) { return expressions.map(e => e.type === TEXT ? Object.assign({}, e, { childNodeIndex: e.childNodeIndex + textExpressionsOffset }) : e); } /** * Bind a new expression object to a DOM node * @param {HTMLElement} root - DOM node where to bind the expression * @param {Object} binding - binding data * @param {number|null} templateTagOffset - if it's defined we need to fix the text expressions childNodeIndex offset * @returns {Binding} Binding object */ function create$5(root, binding, templateTagOffset) { const { selector, type, redundantAttribute, expressions } = binding; // find the node to apply the bindings const node = selector ? root.querySelector(selector) : root; // remove eventually additional attributes created only to select this node if (redundantAttribute) node.removeAttribute(redundantAttribute); const bindingExpressions = expressions || []; // init the binding return (bindings[type] || bindings[SIMPLE])(node, Object.assign({}, binding, { expressions: templateTagOffset && !selector ? fixTextExpressionsOffset(bindingExpressions, templateTagOffset) : bindingExpressions })); } // in this case a simple innerHTML is enough function createHTMLTree(html, root) { const template = isTemplate(root) ? root : document.createElement('template'); template.innerHTML = html; return template.content; } // for svg nodes we need a bit more work function createSVGTree(html, container) { // create the SVGNode const svgNode = container.ownerDocument.importNode(new window.DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${html}</svg>`, 'application/xml').documentElement, true); return svgNode; } /** * Create the DOM that will be injected * @param {Object} root - DOM node to find out the context where the fragment will be created * @param {string} html - DOM to create as string * @returns {HTMLDocumentFragment|HTMLElement} a new html fragment */ function createDOMTree(root, html) { if (isSvg(root)) return createSVGTree(html, root); return createHTMLTree(html, root); } /** * Inject the DOM tree into a target node * @param {HTMLElement} el - target element * @param {HTMLFragment|SVGElement} dom - dom tree to inject * @returns {undefined} */ function injectDOM(el, dom) { switch (true) { case isSvg(el): moveChildren(dom, el); break; case isTemplate(el): el.parentNode.replaceChild(dom, el); break; default: el.appendChild(dom); } } /** * Create the Template DOM skeleton * @param {HTMLElement} el - root node where the DOM will be injected * @param {string} html - markup that will be injected into the root node * @returns {HTMLFragment} fragment that will be injected into the root node */ function createTemplateDOM(el, html) { return html && (typeof html === 'string' ? createDOMTree(el, html) : html); } /** * Template Chunk model * @type {Object} */ const TemplateChunk = Object.freeze({ // Static props // bindings: null, // bindingsData: null, // html: null, // isTemplateTag: false, // fragment: null, // children: null, // dom: null, // el: null, /** * Create the template DOM structure that will be cloned on each mount * @param {HTMLElement} el - the root node * @returns {TemplateChunk} self */ createDOM(el) { // make sure that the DOM gets created before cloning the template this.dom = this.dom || createTemplateDOM(el, this.html); return this; }, // API methods /** * Attach the template to a DOM node * @param {HTMLElement} el - target DOM node * @param {*} scope - template data * @param {*} parentScope - scope of the parent template tag * @param {Object} meta - meta properties needed to handle the <template> tags in loops * @returns {TemplateChunk} self */ mount(el, scope, parentScope, meta) { if (meta === void 0) { meta = {}; } if (!el) throw new Error('Please provide DOM node to mount properly your template'); if (this.el) this.unmount(scope); // <template> tags require a bit more work // the template fragment might be already created via meta outside of this call const { fragment, children, avoidDOMInjection } = meta; // <template> bindings of course can not have a root element // so we check the parent node to set the query selector bindings const { parentNode } = children ? children[0] : el; const isTemplateTag = isTemplate(el); const templateTagOffset = isTemplateTag ? Math.max(Array.from(parentNode.children).indexOf(el), 0) : null; this.isTemplateTag = isTemplateTag; // create the DOM if it wasn't created before this.createDOM(el); if (this.dom) { // create the new template dom fragment if it want already passed in via meta this.fragment = fragment || this.dom.cloneNode(true); } // store root node // notice that for template tags the root note will be the parent tag this.el = this.isTemplateTag ? parentNode : el; // create the children array only for the <template> fragments this.children = this.isTemplateTag ? children || Array.from(this.fragment.childNodes) : null; // inject the DOM into the el only if a fragment is available if (!avoidDOMInjection && this.fragment) injectDOM(el, this.fragment); // create the bindings this.bindings = this.bindingsData.map(binding => create$5(this.el, binding, templateTagOffset)); this.bindings.forEach(b => b.mount(scope, parentScope)); return this; }, /** * Update the template with fresh data * @param {*} scope - template data * @param {*} parentScope - scope of the parent template tag * @returns {TemplateChunk} self */ update(scope, parentScope) { this.bindings.forEach(b => b.update(scope, parentScope)); return this; }, /** * Remove the template from the node where it was initially mounted * @param {*} scope - template data * @param {*} parentScope - scope of the parent template tag * @param {boolean|null} mustRemoveRoot - if true remove the root element, * if false or undefined clean the root tag content, if null don't touch the DOM * @returns {TemplateChunk} self */ unmount(scope, parentScope, mustRemoveRoot) { if (this.el) { this.bindings.forEach(b => b.unmount(scope, parentScope, mustRemoveRoot)); switch (true) { // <template> tags should be treated a bit differently // we need to clear their children only if it's explicitly required by the caller // via mustRemoveRoot !== null case this.children && mustRemoveRoot !== null: clearChildren(this.children); break; // remove the root node only if the mustRemoveRoot === true case mustRemoveRoot === true: removeNode(this.el); break; // otherwise we clean the node children case mustRemoveRoot !== null: cleanNode(this.el); break; } this.el = null; } return this; }, /** * Clone the template chunk * @returns {TemplateChunk} a clone of this object resetting the this.el property */ clone() { return Object.assign({}, this, { el: null }); } }); /** * Create a template chunk wiring also the bindings * @param {string|HTMLElement} html - template string * @param {Array} bindings - bindings collection * @returns {TemplateChunk} a new TemplateChunk copy */ function create$6(html, bindings) { if (bindings === void 0) { bindings = []; } return Object.assign({}, TemplateChunk, { html, bindingsData: bindings }); } /** * Helper function to set an immutable property * @param {Object} source - object where the new property will be set * @param {string} key - object key where the new property will be stored * @param {*} value - value of the new property * @param {Object} options - set the propery overriding the default options * @returns {Object} - the original object modified */ function defineProperty(source, key, value, options) { if (options === void 0) { options = {}; } /* eslint-disable fp/no-mutating-methods */ Object.defineProperty(source, key, Object.assign({ value, enumerable: false, writable: false, configurable: true }, options)); /* eslint-enable fp/no-mutating-methods */ return source; } /** * Define multiple properties on a target object * @param {Object} source - object where the new properties will be set * @param {Object} properties - object containing as key pair the key + value properties * @param {Object} options - set the propery overriding the default options * @returns {Object} the original object modified */ function defineProperties(source, properties, options) { Object.entries(properties).forEach((_ref) => { let [key, value] = _ref; defineProperty(source, key, value, options); }); return source; } /** * Define default properties if they don't exist on the source object * @param {Object} source - object that will receive the default properties * @param {Object} defaults - object containing additional optional keys * @returns {Object} the original object received enhanced */ function defineDefaults(source, defaults) { Object.entries(defaults).forEach((_ref2) => { let [key, value] = _ref2; if (!source[key]) source[key] = value; }); return source; } const ATTRIBUTE$1 = 0; const VALUE$1 = 3; /** * Convert a string from camel case to dash-case * @param {string} string - probably a component tag name * @returns {string} component name normalized */ function camelToDashCase(string) { return string.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } /** * Convert a string containing dashes to camel case * @param {string} string - input string * @returns {string} my-string -> myString */ function dashToCamelCase$1(string) { return string.replace(/-(\w)/g, (_, c) => c.toUpperCase()); } /** * Throw an error with a descriptive message * @param { string } message - error message * @returns { undefined } hoppla.. at this point the program should stop working */ function panic(message) { throw new Error(message); } /** * Evaluate a list of attribute expressions * @param {Array} attributes - attribute expressions generated by the riot compiler * @returns {Object} key value pairs with the result of the computation */ function evaluateAttributeExpressions$1(attributes) { return attributes.reduce((acc, attribute) => { const { value, type } = attribute; switch (true) { // spread attribute case !attribute.name && type === ATTRIBUTE$1: return Object.assign({}, acc, {}, value); // value attribute case type === VALUE$1: acc.value = attribute.value; break; // normal attributes default: acc[dashToCamelCase$1(attribute.name)] = attribute.value; } return acc; }, {}); } /** * Converts any DOM node/s to a loopable array * @param { HTMLElement|NodeList } els - single html element or a node list * @returns { Array } always a loopable object */ function domToArray(els) { // can this object be already looped? if (!Array.isArray(els)) { // is it a node list? if (/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(els)) && typeof els.length === 'number') return Array.from(els);else // if it's a single node // it will be returned as "array" with one single entry return [els]; } // this object could be looped out of the box return els; } /** * Simple helper to find DOM nodes returning them as array like loopable object * @param { string|DOMNodeList } selector - either the query or the DOM nodes to arraify * @param { HTMLElement } ctx - context defining where the query will search for the DOM nodes * @returns { Array } DOM nodes found as array */ function $(selector, ctx) { return domToArray(typeof selector === 'string' ? (ctx || document).querySelectorAll(selector) : selector); } /** * Normalize the return values, in case of a single value we avoid to return an array * @param { Array } values - list of values we want to return * @returns { Array|string|boolean } either the whole list of values or the single one found * @private */ const normalize = values => values.length === 1 ? values[0] : values; /** * Parse all the nodes received to get/remove/check their attributes * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse * @param { string|Array } name - name or list of attributes * @param { string } method - method that will be used to parse the attributes * @returns { Array|string } result of the parsing in a list or a single value * @private */ function parseNodes(els, name, method) { const names = typeof name === 'string' ? [name] : name; return normalize(domToArray(els).map(el => { return normalize(names.map(n => el[method](n))); })); } /** * Set any attribute on a single or a list of DOM nodes * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse * @param { string|Object } name - either the name of the attribute to set * or a list of properties as object key - value * @param { string } value - the new value of the attribute (optional) * @returns { HTMLElement|NodeList|Array } the original array of elements passed to this function * * @example * * import { set } from 'bianco.attr' * * const img = document.createElement('img') * * set(img, 'width', 100) * * // or also * set(img, { * width: 300, * height: 300 * }) * */ function set(els, name, value) { const attrs = typeof name === 'object' ? name : { [name]: value }; const props = Object.keys(attrs); domToArray(els).forEach(el => { props.forEach(prop => el.setAttribute(prop, attrs[prop])); }); return els; } /** * Get any attribute from a single or a list of DOM nodes * @param { HTMLElement|NodeList|Array } els - DOM node/s to parse * @param { string|Array } name - name or list of attributes to get * @returns { Array|string } list of the attributes found * * @example * * import { get } from 'bianco.attr' * * const img = document.createElement('img') * * get(img, 'width') // => '200' * * // or also * get(img, ['width', 'height']) // => ['200', '300'] * * // or also * get([img1, img2], ['width', 'height']) // => [['200', '300'], ['500', '200']] */ function get(els, name) { return parseNodes(els, name, 'getAttribute'); } const CSS_BY_NAME = new Map(); const STYLE_NODE_SELECTOR = 'style[riot]'; // memoized curried function const getStyleNode = (style => { return () => { // lazy evaluation: // if this function was already called before // we return its cached result if (style) return style; // create a new style element or use an existing one // and cache it internally style = $(STYLE_NODE_SELECTOR)[0] || document.createElement('style'); set(style, 'type', 'text/css'); /* istanbul ignore next */ if (!style.parentNode) document.head.appendChild(style); return style; }; })(); /** * Object that will be used to inject and manage the css of every tag instance */ var cssManager = { CSS_BY_NAME, /** * Save a tag style to be later injected into DOM * @param { string } name - if it's passed we will map the css to a tagname * @param { string } css - css string * @returns {Object} self */ add(name, css) { if (!CSS_BY_NAME.has(name)) { CSS_BY_NAME.set(name, css); this.inject(); } return this; }, /** * Inject all previously saved tag styles into DOM * innerHTML seems slow: http://jsperf.com/riot-insert-style * @returns {Object} self */ inject() { getStyleNode().innerHTML = [...CSS_BY_NAME.values()].join('\n'); return this; }, /** * Remove a tag style from the DOM * @param {string} name a registered tagname * @returns {Object} self */ remove(name) { if (CSS_BY_NAME.has(name)) { CSS_BY_NAME.delete(name); this.inject(); } return this; } }; /** * Function to curry any javascript method * @param {Function} fn - the target function we want to curry * @param {...[args]} acc - initial arguments * @returns {Function|*} it will return a function until the target function * will receive all of its arguments */ function curry(fn) { for (var _len = arguments.length, acc = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { acc[_key - 1] = arguments[_key]; } return function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } args = [...acc, ...args]; return args.length < fn.length ? curry(fn, ...args) : fn(...args); }; } /** * Get the tag name of any DOM node * @param {HTMLElement} element - DOM node we want to inspect * @returns {string} name to identify this dom node in riot */ function getName(element) { return get(element, IS_DIRECTIVE) || element.tagName.toLowerCase(); } const COMPONENT_CORE_HELPERS = Object.freeze({ // component helpers $(selector) { return $(selector, this.root)[0]; }, $$(selector) { return $(selector, this.root); } }); const PURE_COMPONENT_API = Object.freeze({ [MOUNT_METHOD_KEY]: noop, [UPDATE_METHOD_KEY]: noop, [UNMOUNT_METHOD_KEY]: noop }); const COMPONENT_LIFECYCLE_METHODS = Object.freeze({ [SHOULD_UPDATE_KEY]: noop, [ON_BEFORE_MOUNT_KEY]: noop, [ON_MOUNTED_KEY]: noop, [ON_BEFORE_UPDATE_KEY]: noop, [ON_UPDATED_KEY]: noop, [ON_BEFORE_UNMOUNT_KEY]: noop, [ON_UNMOUNTED_KEY]: noop }); const MOCKED_TEMPLATE_INTERFACE = Object.assign({}, PURE_COMPONENT_API, { clone: noop, createDOM: noop }); /** * Wrap the Riot.js core API methods using a mapping function * @param {Function} mapFunction - lifting function * @returns {Object} an object having the { mount, update, unmount } functions */ function createCoreAPIMethods(mapFunction) { return [MOUNT_METHOD_KEY, UPDATE_METHOD_KEY, UNMOUNT_METHOD_KEY].reduce((acc, method) => { acc[method] = mapFunction(method); return acc; }, {}); } /** * Factory function to create the component templates only once * @param {Function} template - component template creation function * @param {Object} components - object containing the nested components * @returns {TemplateChunk} template chunk object */ function componentTemplateFactory(template, components) { return template(create$6, expressionTypes, bindingTypes, name => { return components[name] || COMPONENTS_IMPLEMENTATION_MAP.get(name); }); } /** * Create a pure component * @param {Function} pureFactoryFunction - pure component factory function * @param {Array} options.slots - component slots * @param {Array} options.attributes - component attributes * @param {Array} options.template - template factory function * @param {Array} options.template - template factory function * @param {any} options.props - initial component properties * @returns {Object} pure component object */ function createPureComponent(pureFactoryFunction, _ref) { let { slots, attributes, props, css, template } = _ref; if (template) panic('Pure components can not have html'); if (css) panic('Pure components do not have css'); const component = defineDefaults(pureFactoryFunction({ slots, attributes, props }), PURE_COMPONENT_API); return createCoreAPIMethods(method => function () { component[method](...arguments); return component; }); } /** * Create the component interface needed for the @riotjs/dom-bindings tag bindings * @param {string} options.css - component css * @param {Function} options.template - functon that will return the dom-bindings template function * @param {Object} options.exports - component interface * @param {string} options.name - component name * @returns {Object} component like interface */ function createComponent(_ref2) { let { css, template, exports, name } = _ref2; const templateFn = template ? componentTemplateFactory(template, exports ? createSubcomponents(exports.components) : {}) : MOCKED_TEMPLATE_INTERFACE; return (_ref3) => { let { slots, attributes, props } = _ref3; // pure components rendering will be managed by the end user if (exports && exports[IS_PURE_SYMBOL]) return createPureComponent(exports, { slots, attributes, props, css, template }); const componentAPI = callOrAssign(exports) || {}; const component = defineComponent({ css, template: templateFn, componentAPI, name })({ slots, attributes, props }); // notice that for the components create via tag binding // we need to invert the mount (state/parentScope) arguments // the template bindings will only forward the parentScope updates // and never deal with the component state return { mount(element, parentScope, state) { return component.mount(element, state, parentScope); }, update(parentScope, state) { return component.update(state, parentScope); }, unmount(preserveRoot) { return component.unmount(preserveRoot); } }; }; } /** * Component definition function * @param {Object} implementation - the componen implementation will be generated via compiler * @param {Object} component - the component initial properties * @returns {Object} a new component implementation object */ function defineComponent(_ref4) { let { css, template, componentAPI, name } = _ref4; // add the component css into the DOM if (css && name) cssManager.add(name, css); return curry(enhanceComponentAPI)(defineProperties( // set the component defaults without overriding the original component API defineDefaults(componentAPI, Object.assign({}, COMPONENT_LIFECYCLE_METHODS, { [STATE_KEY]: {} })), Object.assign({ // defined during the component creation [SLOTS_KEY]: null, [ROOT_KEY]: null }, COMPONENT_CORE_HELPERS, { name, css, template }))); } /** * Create the bindings to update the component attributes * @param {HTMLElement} node - node where we will bind the expressions * @param {Array} attributes - list of attribute bindings * @returns {TemplateChunk} - template bindings object */ function createAttributeBindings(node, attributes) { if (attributes === void 0) { attributes = []; } const expressions = attributes.map(a => create$2(node, a)); const binding = {}; return Object.assign(binding, Object.assign({ expressions }, createCoreAPIMethods(method => scope => { expressions.forEach(e => e[method](scope)); return binding; }))); } /** * Create the subcomponents that can be included inside a tag in runtime * @param {Object} components - components imported in runtime * @returns {Object} all the components transformed into Riot.Component factory functions */ function createSubcomponents(components) { if (components === void 0) { components = {}; } return Object.entries(callOrAssign(components)).reduce((acc, _ref5) => { let [key, value] = _ref5; acc[camelToDashCase(key)] = createComponent(value); return acc; }, {}); } /** * Run the component instance through all the plugins set by the user * @param {Object} component - component instance * @returns {Object} the component enhanced by the plugins */ function runPlugins(component) { return [...PLUGINS_SET].reduce((c, fn) => fn(c) || c, component); } /** * Compute the component current state merging it with its previous state * @param {Object} oldState - previous state object * @param {Object} newState - new state givent to the `update` call * @returns {Object} new object state */ function computeState(oldState, newState) { return Object.assign({}, oldState, {}, callOrAssign(newState)); } /** * Add eventually the "is" attribute to link this DOM node to its css * @param {HTMLElement} element - target root node * @param {string} name - name of the component mounted * @returns {undefined} it's a void function */ function addCssHook(element, name) { if (getName(element) !== name) { set(element, IS_DIRECTIVE, name); } } /** * Component creation factory function that will enhance the user provided API * @param {Object} component - a component implementation previously defined * @param {Array} options.slots - component slots generated via riot compiler * @param {Array} options.attributes - attribute expressions generated via riot compiler * @returns {Riot.Component} a riot component instance */ function enhanceComponentAPI(component, _ref6) { let { slots, attributes, props } = _ref6; return autobindMethods(runPlugins(defineProperties(Object.create(component), { mount(element, state, parentScope) { if (state === void 0) { state = {}; } this[ATTRIBUTES_KEY_SYMBOL] = createAttributeBindings(element, attributes).mount(parentScope); defineProperty(this, PROPS_KEY, Object.freeze(Object.assign({}, props, {}, evaluateAttributeExpressions$1(this[ATTRIBUTES_KEY_SYMBOL].expressions)))); this[STATE_KEY] = computeState(this[STATE_KEY], state); this[TEMPLATE_KEY_SYMBOL] = this.template.createDOM(element).clone(); // link this object to the DOM node element[DOM_COMPONENT_INSTANCE_PROPERTY] = this; // add eventually the 'is' attribute component.name && addCssHook(element, component.name); // define the root element defineProperty(this, ROOT_KEY, element); // define the slots array defineProperty(this, SLOTS_KEY, slots); // before mount lifecycle event this[ON_BEFORE_MOUNT_KEY](this[PROPS_KEY], this[STATE_KEY]); // mount the template this[TEMPLATE_KEY_SYMBOL].mount(element, this, parentScope); this[PARENT_KEY_SYMBOL] = parentScope; this[ON_MOUNTED_KEY](this[PROPS_KEY], this[STATE_KEY]); return this; }, update(state, parentScope) { if (state === void 0) { state = {}; } if (parentScope) { this[ATTRIBUTES_KEY_SYMBOL].update(parentScope); } const newProps = evaluateAttributeExpressions$1(this[ATTRIBUTES_KEY_SYMBOL].expressions); if (this[SHOULD_UPDATE_KEY](newProps, this[PROPS_KEY]) === false) return; defineProperty(this, PROPS_KEY, Object.freeze(Object.assign({}, props, {}, newProps))); this[STATE_KEY] = computeState(this[STATE_KEY], state); this[ON_BEFORE_UPDATE_KEY](this[PROPS_KEY], this[STATE_KEY]); this[TEMPLATE_KEY_SYMBOL].update(this, this[PARENT_KEY_SYMBOL]); this[ON_UPDATED_KEY](this[PROPS_KEY], this[STATE_KEY]); return this; }, unmount(preserveRoot) { this[ON_BEFORE_UNMOUNT_KEY](this[PROPS_KEY], this[STATE_KEY]); this[ATTRIBUTES_KEY_SYMBOL].unmount(); // if the preserveRoot is null the template html will be left untouched // in that case the DOM cleanup will happen differently from a parent node this[TEMPLATE_KEY_SYMBOL].unmount(this, this[PARENT_KEY_SYMBOL], preserveRoot === null ? null : !preserveRoot); this[ON_UNMOUNTED_KEY](this[PROPS_KEY], this[STATE_KEY]); return this; } })), Object.keys(component).filter(prop => isFunction(component[prop]))); } /** * Component initialization function starting from a DOM node * @param {HTMLElement} element - element to upgrade * @param {Object} initialProps - initial component properties * @param {string} componentName - component id * @returns {Object} a new component instance bound to a DOM node */ function mountComponent(element, initialProps, componentName) { const name = componentName || getName(element); if (!COMPONENTS_IMPLEMENTATION_MAP.has(name)) panic(`The component named "${name}" was never registered`); const component = COMPONENTS_IMPLEMENTATION_MAP.get(name)({ props: initialProps }); return component.mount(element); } /** * Get all the element attributes as object * @param {HTMLElement} element - DOM node we want to parse * @returns {Object} all the attributes found as a key value pairs */ function DOMattributesToObject(element) { return Array.from(element.attributes).reduce((acc, attribute) => { acc[dashToCamelCase$1(attribute.name)] = attribute.value; return acc; }, {}); } /** * Similar to compose but performs from left-to-right function composition.<br/> * {@link https://30secondsofcode.org/function#composeright see also} * @param {...[function]} fns) - list of unary function * @returns {*} result of the computation */ /** * Performs right-to-left function composition.<br/> * Use Array.prototype.reduce() to perform right-to-left function composition.<br/> * The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.<br/> * {@link https://30secondsofcode.org/function#compose original source code} * @param {...[function]} fns) - list of unary function * @returns {*} result of the computation */ function compose() { for (var _len2 = arguments.length, fns = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { fns[_key2] = arguments[_key2]; } return fns.reduce((f, g) => function () { return f(g(...arguments)); }); } const { DOM_COMPONENT_INSTANCE_PROPERTY: DOM_COMPONENT_INSTANCE_PROPERTY$1, COMPONENTS_IMPLEMENTATION_MAP: COMPONENTS_IMPLEMENTATION_MAP$1, PLUGINS_SET: PLUGINS_SET$1 } = globals; /** * Evaluate the component properties either from its real attributes or from its initial user properties * @param {HTMLElement} element - component root * @param {Object} initialProps - initial props * @returns {Object} component props key value pairs */ function evaluateInitialProps(element, initialProps) { if (initialProps === void 0) { initialProps = []; } return Object.assign({}, DOMattributesToObject(element), {}, callOrAssign(initialProps)); } /** * Riot public api */ /** * Register a custom tag by name * @param {string} name - component name * @param {Object} implementation - tag implementation * @returns {Map} map containing all the components implementations */ function register(name, _ref) { let { css, template, exports } = _ref; if (COMPONENTS_IMPLEMENTATION_MAP$1.has(name)) panic(`The component "${name}" was already registered`); COMPONENTS_IMPLEMENTATION_MAP$1.set(name, createComponent({ name, css, template, exports })); return COMPONENTS_IMPLEMENTATION_MAP$1; } /** * Unregister a riot web component * @param {string} name - component name * @returns {Map} map containing all the components implementations */ function unregister(name) { if (!COMPONENTS_IMPLEMENTATION_MAP$1.has(name)) panic(`The component "${name}" was never registered`); COMPONENTS_IMPLEMENTATION_MAP$1.delete(name); cssManager.remove(name); return COMPONENTS_IMPLEMENTATION_MAP$1; } /** * Mounting function that will work only for the components that were globally registered * @param {string|HTMLElement} selector - query for the selection or a DOM element * @param {Object} initialProps - the initial component properties * @param {string} name - optional component name * @returns {Array} list of nodes upgraded */ function mount(selector, initialProps, name) { return $(selector).map(element => mountComponent(element, evaluateInitialProps(element, initialProps), name)); } /** * Sweet unmounting helper function for the DOM node mounted manually by the user * @param {string|HTMLElement} selector - query for the selection or a DOM element * @param {boolean|null} keepRootElement - if true keep the root element * @returns {Array} list of nodes unmounted */ function unmount(selector, keepRootElement) { return $(selector).map(element => { if (element[DOM_COMPONENT_INSTANCE_PROPERTY$1]) { element[DOM_COMPONENT_INSTANCE_PROPERTY$1].unmount(keepRootElement); } return element; }); } /** * Define a riot plugin * @param {Function} plugin - function that will receive all the components created * @returns {Set} the set containing all the plugins installed */ function install(plugin) { if (!isFunction(plugin)) panic('Plugins must be of type function'); if (PLUGINS_SET$1.has(plugin)) panic('This plugin was already install'); PLUGINS_SET$1.add(plugin); return PLUGINS_SET$1; } /** * Uninstall a riot plugin * @param {Function} plugin - plugin previously installed * @returns {Set} the set containing all the plugins installed */ function uninstall(plugin) { if (!PLUGINS_SET$1.has(plugin)) panic('This plugin was never installed'); PLUGINS_SET$1.delete(plugin); return PLUGINS_SET$1; } /** * Helpter method to create component without relying on the registered ones * @param {Object} implementation - component implementation * @returns {Function} function that will allow you to mount a riot component on a DOM node */ function component(implementation) { return function (el, props, _temp) { let { slots, attributes } = _temp === void 0 ? {} : _temp; return compose(c => c.mount(el), c => c({ props: evaluateInitialProps(el, props), slots, attributes }), createComponent)(implementation); }; } /** * Lift a riot component Interface into a pure riot object * @param {Function} func - RiotPureComponent factory function * @returns {Function} the lifted original function received as argument */ function pure(func) { if (!isFunction(func)) panic('riot.pure accepts only arguments of type "function"'); func[IS_PURE_SYMBOL] = true; return func; } /** @type {string} current riot version */ const version = 'v4.8.6'; // expose some internal stuff that might be used from external tools const __ = { cssManager, createComponent, defineComponent, globals }; exports.__ = __; exports.component = component; exports.install = install; exports.mount = mount; exports.pure = pure; exports.register = register; exports.uninstall = uninstall; exports.unmount = unmount; exports.unregister = unregister; exports.version = version; Object.defineProperty(exports, '__esModule', { value: true }); })));
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactBootstrap"] = factory(require("react"), require("react-dom")); else root["ReactBootstrap"] = factory(root["React"], root["ReactDOM"]); })(self, function(__WEBPACK_EXTERNAL_MODULE__787__, __WEBPACK_EXTERNAL_MODULE__156__) { return /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 814: /***/ ((module, exports) => { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2018 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames() { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { if (arg.length) { var inner = classNames.apply(null, arg); if (inner) { classes.push(inner); } } } else if (argType === 'object') { if (arg.toString === Object.prototype.toString) { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } else { classes.push(arg.toString()); } } } return classes.join(' '); } if ( true && module.exports) { classNames.default = classNames; module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () { return classNames; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} })(); /***/ }), /***/ 286: /***/ ((module) => { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function (condition, format, a, b, c, d, e, f) { if (false) {} if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }), /***/ 946: /***/ ((module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = all; var _createChainableTypeChecker = __webpack_require__(844); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function all() { for (var _len = arguments.length, validators = Array(_len), _key = 0; _key < _len; _key++) { validators[_key] = arguments[_key]; } function allPropTypes() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } var error = null; validators.forEach(function (validator) { if (error != null) { return; } var result = validator.apply(undefined, args); if (result != null) { error = result; } }); return error; } return (0, _createChainableTypeChecker2.default)(allPropTypes); } module.exports = exports['default']; /***/ }), /***/ 964: /***/ ((module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _react = __webpack_require__(787); var _react2 = _interopRequireDefault(_react); var _createChainableTypeChecker = __webpack_require__(844); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement. You can usually obtain a ReactComponent or DOMElement ' + 'from a ReactElement by attaching a ref to it.'); } if ((propType !== 'object' || typeof propValue.render !== 'function') && propValue.nodeType !== 1) { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement.'); } return null; } exports["default"] = (0, _createChainableTypeChecker2.default)(validate); module.exports = exports['default']; /***/ }), /***/ 647: /***/ ((module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = deprecated; var _warning = __webpack_require__(459); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var warned = {}; function deprecated(validator, reason) { return function validate(props, propName, componentName, location, propFullName) { var componentNameSafe = componentName || '<<anonymous>>'; var propFullNameSafe = propFullName || propName; if (props[propName] != null) { var messageKey = componentName + '.' + propName; (0, _warning2.default)(warned[messageKey], 'The ' + location + ' `' + propFullNameSafe + '` of ' + ('`' + componentNameSafe + '` is deprecated. ' + reason + '.')); warned[messageKey] = true; } for (var _len = arguments.length, args = Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) { args[_key - 5] = arguments[_key]; } return validator.apply(undefined, [props, propName, componentName, location, propFullName].concat(args)); }; } /* eslint-disable no-underscore-dangle */ function _resetWarned() { warned = {}; } deprecated._resetWarned = _resetWarned; /* eslint-enable no-underscore-dangle */ module.exports = exports['default']; /***/ }), /***/ 835: /***/ ((module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); var _react = __webpack_require__(787); var _react2 = _interopRequireDefault(_react); var _reactIs = __webpack_require__(532); var _createChainableTypeChecker = __webpack_require__(844); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function elementType(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`,expected an element type (a string ') + ', component class, or function component).'); } if (!(0, _reactIs.isValidElementType)(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + ', component class, or function component).'); } return null; } exports["default"] = (0, _createChainableTypeChecker2.default)(elementType); module.exports = exports['default']; /***/ }), /***/ 517: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; var __webpack_unused_export__; __webpack_unused_export__ = ({ value: true }); __webpack_unused_export__ = exports.nm = __webpack_unused_export__ = exports.ax = __webpack_unused_export__ = undefined; var _all = __webpack_require__(946); var _all2 = _interopRequireDefault(_all); var _componentOrElement = __webpack_require__(964); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _deprecated = __webpack_require__(647); var _deprecated2 = _interopRequireDefault(_deprecated); var _elementType = __webpack_require__(835); var _elementType2 = _interopRequireDefault(_elementType); var _isRequiredForA11y = __webpack_require__(422); var _isRequiredForA11y2 = _interopRequireDefault(_isRequiredForA11y); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } __webpack_unused_export__ = _all2.default; exports.ax = _componentOrElement2.default; __webpack_unused_export__ = _deprecated2.default; exports.nm = _elementType2.default; __webpack_unused_export__ = _isRequiredForA11y2.default; /***/ }), /***/ 422: /***/ ((module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = isRequiredForA11y; function isRequiredForA11y(validator) { return function validate(props, propName, componentName, location, propFullName) { var componentNameSafe = componentName || '<<anonymous>>'; var propFullNameSafe = propFullName || propName; if (props[propName] == null) { return new Error('The ' + location + ' `' + propFullNameSafe + '` is required to make ' + ('`' + componentNameSafe + '` accessible for users of assistive ') + 'technologies such as screen readers.'); } for (var _len = arguments.length, args = Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) { args[_key - 5] = arguments[_key]; } return validator.apply(undefined, [props, propName, componentName, location, propFullName].concat(args)); }; } module.exports = exports['default']; /***/ }), /***/ 844: /***/ ((module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports["default"] = createChainableTypeChecker; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ // Mostly taken from ReactPropTypes. function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { var componentNameSafe = componentName || '<<anonymous>>'; var propFullNameSafe = propFullName || propName; if (props[propName] == null) { if (isRequired) { return new Error('Required ' + location + ' `' + propFullNameSafe + '` was not specified ' + ('in `' + componentNameSafe + '`.')); } return null; } for (var _len = arguments.length, args = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) { args[_key - 6] = arguments[_key]; } return validate.apply(undefined, [props, propName, componentNameSafe, location, propFullNameSafe].concat(args)); } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } module.exports = exports['default']; /***/ }), /***/ 428: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = __webpack_require__(134); function emptyFunction() {} function emptyFunctionWithReset() {} emptyFunctionWithReset.resetWarningCache = emptyFunction; module.exports = function () { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret) { // It is still safe when called from React. return; } var err = new Error('Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types'); err.name = 'Invariant Violation'; throw err; } ; shim.isRequired = shim; function getShim() { return shim; } ; // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, elementType: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim, checkPropTypes: emptyFunctionWithReset, resetWarningCache: emptyFunction }; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /***/ 526: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (false) { var throwOnDirectAccess, ReactIs; } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = __webpack_require__(428)(); } /***/ }), /***/ 134: /***/ ((module) => { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /***/ 15: /***/ ((__unused_webpack_module, exports) => { "use strict"; /** @license React v16.13.1 * react-is.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var b = "function" === typeof Symbol && Symbol.for, c = b ? Symbol.for("react.element") : 60103, d = b ? Symbol.for("react.portal") : 60106, e = b ? Symbol.for("react.fragment") : 60107, f = b ? Symbol.for("react.strict_mode") : 60108, g = b ? Symbol.for("react.profiler") : 60114, h = b ? Symbol.for("react.provider") : 60109, k = b ? Symbol.for("react.context") : 60110, l = b ? Symbol.for("react.async_mode") : 60111, m = b ? Symbol.for("react.concurrent_mode") : 60111, n = b ? Symbol.for("react.forward_ref") : 60112, p = b ? Symbol.for("react.suspense") : 60113, q = b ? Symbol.for("react.suspense_list") : 60120, r = b ? Symbol.for("react.memo") : 60115, t = b ? Symbol.for("react.lazy") : 60116, v = b ? Symbol.for("react.block") : 60121, w = b ? Symbol.for("react.fundamental") : 60117, x = b ? Symbol.for("react.responder") : 60118, y = b ? Symbol.for("react.scope") : 60119; function z(a) { if ("object" === typeof a && null !== a) { var u = a.$$typeof; switch (u) { case c: switch (a = a.type, a) { case l: case m: case e: case g: case f: case p: return a; default: switch (a = a && a.$$typeof, a) { case k: case n: case t: case r: case h: return a; default: return u; } } case d: return u; } } } function A(a) { return z(a) === m; } exports.AsyncMode = l; exports.ConcurrentMode = m; exports.ContextConsumer = k; exports.ContextProvider = h; exports.Element = c; exports.ForwardRef = n; exports.Fragment = e; exports.Lazy = t; exports.Memo = r; exports.Portal = d; exports.Profiler = g; exports.StrictMode = f; exports.Suspense = p; exports.isAsyncMode = function (a) { return A(a) || z(a) === l; }; exports.isConcurrentMode = A; exports.isContextConsumer = function (a) { return z(a) === k; }; exports.isContextProvider = function (a) { return z(a) === h; }; exports.isElement = function (a) { return "object" === typeof a && null !== a && a.$$typeof === c; }; exports.isForwardRef = function (a) { return z(a) === n; }; exports.isFragment = function (a) { return z(a) === e; }; exports.isLazy = function (a) { return z(a) === t; }; exports.isMemo = function (a) { return z(a) === r; }; exports.isPortal = function (a) { return z(a) === d; }; exports.isProfiler = function (a) { return z(a) === g; }; exports.isStrictMode = function (a) { return z(a) === f; }; exports.isSuspense = function (a) { return z(a) === p; }; exports.isValidElementType = function (a) { return "string" === typeof a || "function" === typeof a || a === e || a === m || a === g || a === f || a === p || a === q || "object" === typeof a && null !== a && (a.$$typeof === t || a.$$typeof === r || a.$$typeof === h || a.$$typeof === k || a.$$typeof === n || a.$$typeof === w || a.$$typeof === x || a.$$typeof === y || a.$$typeof === v); }; exports.typeOf = z; /***/ }), /***/ 532: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; if (true) { module.exports = __webpack_require__(15); } else {} /***/ }), /***/ 955: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /** @license React v16.14.0 * react-jsx-dev-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ __webpack_require__(787); exports.Fragment = 60107; if ("function" === typeof Symbol && Symbol.for) { var a = Symbol.for; exports.Fragment = a("react.fragment"); } exports.jsxDEV = void 0; /***/ }), /***/ 356: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; /** @license React v16.14.0 * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var f = __webpack_require__(787), g = 60103; exports.Fragment = 60107; if ("function" === typeof Symbol && Symbol.for) { var h = Symbol.for; g = h("react.element"); exports.Fragment = h("react.fragment"); } var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: !0, ref: !0, __self: !0, __source: !0 }; function q(c, a, k) { var b, d = {}, e = null, l = null; void 0 !== k && (e = "" + k); void 0 !== a.key && (e = "" + a.key); void 0 !== a.ref && (l = a.ref); for (b in a) n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]); return { $$typeof: g, type: c, key: e, ref: l, props: d, _owner: m.current }; } exports.jsx = q; exports.jsxs = q; /***/ }), /***/ 485: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; if (true) { module.exports = __webpack_require__(955); } else {} /***/ }), /***/ 373: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; if (true) { module.exports = __webpack_require__(356); } else {} /***/ }), /***/ 459: /***/ ((module) => { "use strict"; /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var __DEV__ = "production" !== 'production'; var warning = function () {}; if (__DEV__) { var printWarning = function printWarning(format, args) { var len = arguments.length; args = new Array(len > 1 ? len - 1 : 0); for (var key = 1; key < len; key++) { args[key - 1] = arguments[key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function (condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { printWarning.apply(null, [format].concat(args)); } }; } module.exports = warning; /***/ }), /***/ 787: /***/ ((module) => { "use strict"; module.exports = __WEBPACK_EXTERNAL_MODULE__787__; /***/ }), /***/ 156: /***/ ((module) => { "use strict"; module.exports = __WEBPACK_EXTERNAL_MODULE__156__; /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (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] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry need to be wrapped in an IIFE because it need to be in strict mode. (() => { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "Accordion": () => (/* reexport */ src_Accordion), "AccordionButton": () => (/* reexport */ src_AccordionButton), "AccordionCollapse": () => (/* reexport */ src_AccordionCollapse), "AccordionContext": () => (/* reexport */ AccordionContext), "Alert": () => (/* reexport */ src_Alert), "Anchor": () => (/* reexport */ src_Anchor), "Badge": () => (/* reexport */ src_Badge), "Breadcrumb": () => (/* reexport */ src_Breadcrumb), "BreadcrumbItem": () => (/* reexport */ src_BreadcrumbItem), "Button": () => (/* reexport */ src_Button), "ButtonGroup": () => (/* reexport */ src_ButtonGroup), "ButtonToolbar": () => (/* reexport */ src_ButtonToolbar), "Card": () => (/* reexport */ src_Card), "CardGroup": () => (/* reexport */ CardGroup), "CardImg": () => (/* reexport */ src_CardImg), "Carousel": () => (/* reexport */ src_Carousel), "CarouselItem": () => (/* reexport */ src_CarouselItem), "CloseButton": () => (/* reexport */ src_CloseButton), "Col": () => (/* reexport */ src_Col), "Collapse": () => (/* reexport */ src_Collapse), "Container": () => (/* reexport */ src_Container), "Dropdown": () => (/* reexport */ src_Dropdown), "DropdownButton": () => (/* reexport */ src_DropdownButton), "Fade": () => (/* reexport */ src_Fade), "Figure": () => (/* reexport */ src_Figure), "FloatingLabel": () => (/* reexport */ src_FloatingLabel), "Form": () => (/* reexport */ src_Form), "FormCheck": () => (/* reexport */ src_FormCheck), "FormControl": () => (/* reexport */ src_FormControl), "FormFloating": () => (/* reexport */ FormFloating), "FormGroup": () => (/* reexport */ src_FormGroup), "FormLabel": () => (/* reexport */ src_FormLabel), "FormSelect": () => (/* reexport */ src_FormSelect), "FormText": () => (/* reexport */ src_FormText), "Image": () => (/* reexport */ src_Image), "InputGroup": () => (/* reexport */ src_InputGroup), "ListGroup": () => (/* reexport */ src_ListGroup), "ListGroupItem": () => (/* reexport */ src_ListGroupItem), "Modal": () => (/* reexport */ src_Modal), "ModalBody": () => (/* reexport */ ModalBody), "ModalDialog": () => (/* reexport */ src_ModalDialog), "ModalFooter": () => (/* reexport */ ModalFooter), "ModalTitle": () => (/* reexport */ ModalTitle), "Nav": () => (/* reexport */ src_Nav), "NavDropdown": () => (/* reexport */ src_NavDropdown), "NavItem": () => (/* reexport */ src_NavItem), "NavLink": () => (/* reexport */ src_NavLink), "Navbar": () => (/* reexport */ src_Navbar), "NavbarBrand": () => (/* reexport */ src_NavbarBrand), "Offcanvas": () => (/* reexport */ src_Offcanvas), "OffcanvasBody": () => (/* reexport */ OffcanvasBody), "OffcanvasHeader": () => (/* reexport */ src_OffcanvasHeader), "OffcanvasTitle": () => (/* reexport */ OffcanvasTitle), "Overlay": () => (/* reexport */ src_Overlay), "OverlayTrigger": () => (/* reexport */ src_OverlayTrigger), "PageItem": () => (/* reexport */ src_PageItem), "Pagination": () => (/* reexport */ src_Pagination), "Placeholder": () => (/* reexport */ src_Placeholder), "PlaceholderButton": () => (/* reexport */ src_PlaceholderButton), "Popover": () => (/* reexport */ src_Popover), "PopoverBody": () => (/* reexport */ PopoverBody), "PopoverHeader": () => (/* reexport */ PopoverHeader), "ProgressBar": () => (/* reexport */ src_ProgressBar), "Ratio": () => (/* reexport */ src_Ratio), "Row": () => (/* reexport */ src_Row), "SSRProvider": () => (/* reexport */ src_SSRProvider), "Spinner": () => (/* reexport */ src_Spinner), "SplitButton": () => (/* reexport */ src_SplitButton), "Stack": () => (/* reexport */ src_Stack), "Tab": () => (/* reexport */ src_Tab), "TabContainer": () => (/* reexport */ src_TabContainer), "TabContent": () => (/* reexport */ TabContent), "TabPane": () => (/* reexport */ src_TabPane), "Table": () => (/* reexport */ src_Table), "Tabs": () => (/* reexport */ src_Tabs), "ThemeProvider": () => (/* reexport */ src_ThemeProvider), "Toast": () => (/* reexport */ src_Toast), "ToastBody": () => (/* reexport */ ToastBody), "ToastContainer": () => (/* reexport */ src_ToastContainer), "ToastHeader": () => (/* reexport */ src_ToastHeader), "ToggleButton": () => (/* reexport */ src_ToggleButton), "ToggleButtonGroup": () => (/* reexport */ src_ToggleButtonGroup), "Tooltip": () => (/* reexport */ src_Tooltip), "useAccordionButton": () => (/* reexport */ useAccordionButton) }); // EXTERNAL MODULE: ./node_modules/classnames/index.js var classnames = __webpack_require__(814); var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames); // EXTERNAL MODULE: external {"root":"React","commonjs2":"react","commonjs":"react","amd":"react"} var external_root_React_commonjs2_react_commonjs_react_amd_react_ = __webpack_require__(787); var external_root_React_commonjs2_react_commonjs_react_amd_react_default = /*#__PURE__*/__webpack_require__.n(external_root_React_commonjs2_react_commonjs_react_amd_react_); // EXTERNAL MODULE: ./node_modules/prop-types/index.js var prop_types = __webpack_require__(526); var prop_types_default = /*#__PURE__*/__webpack_require__.n(prop_types); ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js function extends_extends() { 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_extends.apply(this, arguments); } ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js function objectWithoutPropertiesLoose_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } // EXTERNAL MODULE: ./node_modules/invariant/browser.js var browser = __webpack_require__(286); var browser_default = /*#__PURE__*/__webpack_require__.n(browser); ;// CONCATENATED MODULE: ./node_modules/uncontrollable/lib/esm/utils.js var noop = function noop() {}; function readOnlyPropType(handler, name) { return function (props, propName) { if (props[propName] !== undefined) { if (!props[handler]) { return new Error("You have provided a `" + propName + "` prop to `" + name + "` " + ("without an `" + handler + "` handler prop. This will render a read-only field. ") + ("If the field should be mutable use `" + defaultKey(propName) + "`. ") + ("Otherwise, set `" + handler + "`.")); } } }; } function uncontrolledPropTypes(controlledValues, displayName) { var propTypes = {}; Object.keys(controlledValues).forEach(function (prop) { // add default propTypes for folks that use runtime checks propTypes[defaultKey(prop)] = noop; if (false) { var handler; } }); return propTypes; } function isProp(props, prop) { return props[prop] !== undefined; } function defaultKey(key) { return 'default' + key.charAt(0).toUpperCase() + key.substr(1); } /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ function canAcceptRef(component) { return !!component && (typeof component !== 'function' || component.prototype && component.prototype.isReactComponent); } ;// CONCATENATED MODULE: ./node_modules/uncontrollable/lib/esm/hook.js function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function useUncontrolledProp(propValue, defaultValue, handler) { var wasPropRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(propValue !== undefined); var _useState = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(defaultValue), stateValue = _useState[0], setState = _useState[1]; var isProp = propValue !== undefined; var wasProp = wasPropRef.current; wasPropRef.current = isProp; /** * If a prop switches from controlled to Uncontrolled * reset its value to the defaultValue */ if (!isProp && wasProp && stateValue !== defaultValue) { setState(defaultValue); } return [isProp ? propValue : stateValue, (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(function (value) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (handler) handler.apply(void 0, [value].concat(args)); setState(value); }, [handler])]; } function useUncontrolled(props, config) { return Object.keys(config).reduce(function (result, fieldName) { var _extends2; var _ref = result, defaultValue = _ref[defaultKey(fieldName)], propsValue = _ref[fieldName], rest = objectWithoutPropertiesLoose_objectWithoutPropertiesLoose(_ref, [defaultKey(fieldName), fieldName].map(_toPropertyKey)); var handlerName = config[fieldName]; var _useUncontrolledProp = useUncontrolledProp(propsValue, defaultValue, props[handlerName]), value = _useUncontrolledProp[0], handler = _useUncontrolledProp[1]; return extends_extends({}, rest, (_extends2 = {}, _extends2[fieldName] = value, _extends2[handlerName] = handler, _extends2)); }, props); } ;// CONCATENATED MODULE: ./node_modules/react-lifecycles-compat/react-lifecycles-compat.es.js /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ function componentWillMount() { // Call this.constructor.gDSFP to support sub-classes. var state = this.constructor.getDerivedStateFromProps(this.props, this.state); if (state !== null && state !== undefined) { this.setState(state); } } function componentWillReceiveProps(nextProps) { // Call this.constructor.gDSFP to support sub-classes. // Use the setState() updater to ensure state isn't stale in certain edge cases. function updater(prevState) { var state = this.constructor.getDerivedStateFromProps(nextProps, prevState); return state !== null && state !== undefined ? state : null; } // Binding "this" is important for shallow renderer support. this.setState(updater.bind(this)); } function componentWillUpdate(nextProps, nextState) { try { var prevProps = this.props; var prevState = this.state; this.props = nextProps; this.state = nextState; this.__reactInternalSnapshotFlag = true; this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(prevProps, prevState); } finally { this.props = prevProps; this.state = prevState; } } // React may warn about cWM/cWRP/cWU methods being deprecated. // Add a flag to suppress these warnings for this special case. componentWillMount.__suppressDeprecationWarning = true; componentWillReceiveProps.__suppressDeprecationWarning = true; componentWillUpdate.__suppressDeprecationWarning = true; function react_lifecycles_compat_es_polyfill(Component) { var prototype = Component.prototype; if (!prototype || !prototype.isReactComponent) { throw new Error('Can only polyfill class components'); } if (typeof Component.getDerivedStateFromProps !== 'function' && typeof prototype.getSnapshotBeforeUpdate !== 'function') { return Component; } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Error if any of these lifecycles are present, // Because they would work differently between older and newer (16.3+) versions of React. var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; if (typeof prototype.componentWillMount === 'function') { foundWillMountName = 'componentWillMount'; } else if (typeof prototype.UNSAFE_componentWillMount === 'function') { foundWillMountName = 'UNSAFE_componentWillMount'; } if (typeof prototype.componentWillReceiveProps === 'function') { foundWillReceivePropsName = 'componentWillReceiveProps'; } else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') { foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; } if (typeof prototype.componentWillUpdate === 'function') { foundWillUpdateName = 'componentWillUpdate'; } else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') { foundWillUpdateName = 'UNSAFE_componentWillUpdate'; } if (foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null) { var componentName = Component.displayName || Component.name; var newApiName = typeof Component.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; throw Error('Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + componentName + ' uses ' + newApiName + ' but also contains the following legacy lifecycles:' + (foundWillMountName !== null ? '\n ' + foundWillMountName : '') + (foundWillReceivePropsName !== null ? '\n ' + foundWillReceivePropsName : '') + (foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') + '\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-async-component-lifecycle-hooks'); } // React <= 16.2 does not support static getDerivedStateFromProps. // As a workaround, use cWM and cWRP to invoke the new static lifecycle. // Newer versions of React will ignore these lifecycles if gDSFP exists. if (typeof Component.getDerivedStateFromProps === 'function') { prototype.componentWillMount = componentWillMount; prototype.componentWillReceiveProps = componentWillReceiveProps; } // React <= 16.2 does not support getSnapshotBeforeUpdate. // As a workaround, use cWU to invoke the new lifecycle. // Newer versions of React will ignore that lifecycle if gSBU exists. if (typeof prototype.getSnapshotBeforeUpdate === 'function') { if (typeof prototype.componentDidUpdate !== 'function') { throw new Error('Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'); } prototype.componentWillUpdate = componentWillUpdate; var componentDidUpdate = prototype.componentDidUpdate; prototype.componentDidUpdate = function componentDidUpdatePolyfill(prevProps, prevState, maybeSnapshot) { // 16.3+ will not execute our will-update method; // It will pass a snapshot value to did-update though. // Older versions will require our polyfilled will-update value. // We need to handle both cases, but can't just check for the presence of "maybeSnapshot", // Because for <= 15.x versions this might be a "prevContext" object. // We also can't just check "__reactInternalSnapshot", // Because get-snapshot might return a falsy value. // So check for the explicit __reactInternalSnapshotFlag flag to determine behavior. var snapshot = this.__reactInternalSnapshotFlag ? this.__reactInternalSnapshot : maybeSnapshot; componentDidUpdate.call(this, prevProps, prevState, snapshot); }; } return Component; } ;// CONCATENATED MODULE: ./node_modules/uncontrollable/lib/esm/uncontrollable.js var _jsxFileName = "/Users/jquense/src/uncontrollable/src/uncontrollable.js"; function uncontrollable(Component, controlledValues, methods) { if (methods === void 0) { methods = []; } var displayName = Component.displayName || Component.name || 'Component'; var canAcceptRef = Utils.canAcceptRef(Component); var controlledProps = Object.keys(controlledValues); var PROPS_TO_OMIT = controlledProps.map(Utils.defaultKey); !(canAcceptRef || !methods.length) ? false ? 0 : invariant(false) : void 0; var UncontrolledComponent = /*#__PURE__*/function (_React$Component) { _inheritsLoose(UncontrolledComponent, _React$Component); function UncontrolledComponent() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this; _this.handlers = Object.create(null); controlledProps.forEach(function (propName) { var handlerName = controlledValues[propName]; var handleChange = function handleChange(value) { if (_this.props[handlerName]) { var _this$props; _this._notifying = true; for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } (_this$props = _this.props)[handlerName].apply(_this$props, [value].concat(args)); _this._notifying = false; } if (!_this.unmounted) _this.setState(function (_ref) { var _extends2; var values = _ref.values; return { values: _extends(Object.create(null), values, (_extends2 = {}, _extends2[propName] = value, _extends2)) }; }); }; _this.handlers[handlerName] = handleChange; }); if (methods.length) _this.attachRef = function (ref) { _this.inner = ref; }; var values = Object.create(null); controlledProps.forEach(function (key) { values[key] = _this.props[Utils.defaultKey(key)]; }); _this.state = { values: values, prevProps: {} }; return _this; } var _proto = UncontrolledComponent.prototype; _proto.shouldComponentUpdate = function shouldComponentUpdate() { //let setState trigger the update return !this._notifying; }; UncontrolledComponent.getDerivedStateFromProps = function getDerivedStateFromProps(props, _ref2) { var values = _ref2.values, prevProps = _ref2.prevProps; var nextState = { values: _extends(Object.create(null), values), prevProps: {} }; controlledProps.forEach(function (key) { /** * If a prop switches from controlled to Uncontrolled * reset its value to the defaultValue */ nextState.prevProps[key] = props[key]; if (!Utils.isProp(props, key) && Utils.isProp(prevProps, key)) { nextState.values[key] = props[Utils.defaultKey(key)]; } }); return nextState; }; _proto.componentWillUnmount = function componentWillUnmount() { this.unmounted = true; }; _proto.render = function render() { var _this2 = this; var _this$props2 = this.props, innerRef = _this$props2.innerRef, props = _objectWithoutPropertiesLoose(_this$props2, ["innerRef"]); PROPS_TO_OMIT.forEach(function (prop) { delete props[prop]; }); var newProps = {}; controlledProps.forEach(function (propName) { var propValue = _this2.props[propName]; newProps[propName] = propValue !== undefined ? propValue : _this2.state.values[propName]; }); return React.createElement(Component, _extends({}, props, newProps, this.handlers, { ref: innerRef || this.attachRef })); }; return UncontrolledComponent; }(React.Component); polyfill(UncontrolledComponent); UncontrolledComponent.displayName = "Uncontrolled(" + displayName + ")"; UncontrolledComponent.propTypes = _extends({ innerRef: function innerRef() {} }, Utils.uncontrolledPropTypes(controlledValues, displayName)); methods.forEach(function (method) { UncontrolledComponent.prototype[method] = function $proxiedMethod() { var _this$inner; return (_this$inner = this.inner)[method].apply(_this$inner, arguments); }; }); var WrappedComponent = UncontrolledComponent; if (React.forwardRef) { WrappedComponent = React.forwardRef(function (props, ref) { return React.createElement(UncontrolledComponent, _extends({}, props, { innerRef: ref, __source: { fileName: _jsxFileName, lineNumber: 128 }, __self: this })); }); WrappedComponent.propTypes = UncontrolledComponent.propTypes; } WrappedComponent.ControlledComponent = Component; /** * useful when wrapping a Component and you want to control * everything */ WrappedComponent.deferControlTo = function (newComponent, additions, nextMethods) { if (additions === void 0) { additions = {}; } return uncontrollable(newComponent, _extends({}, controlledValues, additions), nextMethods); }; return WrappedComponent; } ;// CONCATENATED MODULE: ./node_modules/uncontrollable/lib/esm/index.js // EXTERNAL MODULE: ./node_modules/react/jsx-dev-runtime.js var jsx_dev_runtime = __webpack_require__(485); ;// CONCATENATED MODULE: ./src/ThemeProvider.tsx var ThemeProvider_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ThemeProvider.tsx"; const ThemeContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext({ prefixes: {} }); const { Consumer, Provider } = ThemeContext; function ThemeProvider({ prefixes = {}, dir, children }) { const contextValue = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ prefixes: { ...prefixes }, dir }), [prefixes, dir]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Provider, { value: contextValue, children: children }, void 0, false, { fileName: ThemeProvider_jsxFileName, lineNumber: 26, columnNumber: 10 }, this); } ThemeProvider.propTypes = { prefixes: (prop_types_default()).object, dir: (prop_types_default()).string }; function useBootstrapPrefix(prefix, defaultPrefix) { const { prefixes } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(ThemeContext); return prefix || prefixes[defaultPrefix] || defaultPrefix; } function useIsRTL() { const { dir } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(ThemeContext); return dir === 'rtl'; } function createBootstrapComponent(Component, opts) { if (typeof opts === 'string') opts = { prefix: opts }; const isClassy = Component.prototype && Component.prototype.isReactComponent; // If it's a functional component make sure we don't break it with a ref const { prefix, forwardRefAs = isClassy ? 'ref' : 'innerRef' } = opts; const Wrapped = /*#__PURE__*/React.forwardRef(({ ...props }, ref) => { props[forwardRefAs] = ref; const bsPrefix = useBootstrapPrefix(props.bsPrefix, prefix); return /*#__PURE__*/_jsxDEV(Component, { ...props, bsPrefix: bsPrefix }, void 0, false, { fileName: ThemeProvider_jsxFileName, lineNumber: 56, columnNumber: 12 }, this); }); Wrapped.displayName = `Bootstrap(${Component.displayName || Component.name})`; return Wrapped; } /* harmony default export */ const src_ThemeProvider = (ThemeProvider); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/ownerDocument.js /** * Returns the owner document of a given element. * * @param node the element */ function ownerDocument(node) { return node && node.ownerDocument || document; } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/ownerWindow.js /** * Returns the owner window of a given element. * * @param node the element */ function ownerWindow(node) { var doc = ownerDocument(node); return doc && doc.defaultView || window; } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/getComputedStyle.js /** * Returns one or all computed style properties of an element. * * @param node the element * @param psuedoElement the style property */ function getComputedStyle_getComputedStyle(node, psuedoElement) { return ownerWindow(node).getComputedStyle(node, psuedoElement); } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/hyphenate.js var rUpper = /([A-Z])/g; function hyphenate(string) { return string.replace(rUpper, '-$1').toLowerCase(); } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/hyphenateStyle.js /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js */ var msPattern = /^ms-/; function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/isTransform.js var supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i; function isTransform(value) { return !!(value && supportedTransforms.test(value)); } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/css.js function style(node, property) { var css = ''; var transforms = ''; if (typeof property === 'string') { return node.style.getPropertyValue(hyphenateStyleName(property)) || getComputedStyle_getComputedStyle(node).getPropertyValue(hyphenateStyleName(property)); } Object.keys(property).forEach(function (key) { var value = property[key]; if (!value && value !== 0) { node.style.removeProperty(hyphenateStyleName(key)); } else if (isTransform(key)) { transforms += key + "(" + value + ") "; } else { css += hyphenateStyleName(key) + ": " + value + ";"; } }); if (transforms) { css += "transform: " + transforms + ";"; } node.style.cssText += ";" + css; } /* harmony default export */ const css = (style); ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/inheritsLoose.js function inheritsLoose_inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } // EXTERNAL MODULE: external {"root":"ReactDOM","commonjs2":"react-dom","commonjs":"react-dom","amd":"react-dom"} var external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_ = __webpack_require__(156); var external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_default = /*#__PURE__*/__webpack_require__.n(external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_); ;// CONCATENATED MODULE: ./node_modules/react-transition-group/esm/config.js /* harmony default export */ const config = ({ disabled: false }); ;// CONCATENATED MODULE: ./node_modules/react-transition-group/esm/TransitionGroupContext.js /* harmony default export */ const TransitionGroupContext = (external_root_React_commonjs2_react_commonjs_react_amd_react_default().createContext(null)); ;// CONCATENATED MODULE: ./node_modules/react-transition-group/esm/Transition.js var UNMOUNTED = 'unmounted'; var EXITED = 'exited'; var ENTERING = 'entering'; var ENTERED = 'entered'; var EXITING = 'exiting'; /** * The Transition component lets you describe a transition from one component * state to another _over time_ with a simple declarative API. Most commonly * it's used to animate the mounting and unmounting of a component, but can also * be used to describe in-place transition states as well. * * --- * * **Note**: `Transition` is a platform-agnostic base component. If you're using * transitions in CSS, you'll probably want to use * [`CSSTransition`](https://reactcommunity.org/react-transition-group/css-transition) * instead. It inherits all the features of `Transition`, but contains * additional features necessary to play nice with CSS transitions (hence the * name of the component). * * --- * * By default the `Transition` component does not alter the behavior of the * component it renders, it only tracks "enter" and "exit" states for the * components. It's up to you to give meaning and effect to those states. For * example we can add styles to a component when it enters or exits: * * ```jsx * import { Transition } from 'react-transition-group'; * * const duration = 300; * * const defaultStyle = { * transition: `opacity ${duration}ms ease-in-out`, * opacity: 0, * } * * const transitionStyles = { * entering: { opacity: 1 }, * entered: { opacity: 1 }, * exiting: { opacity: 0 }, * exited: { opacity: 0 }, * }; * * const Fade = ({ in: inProp }) => ( * <Transition in={inProp} timeout={duration}> * {state => ( * <div style={{ * ...defaultStyle, * ...transitionStyles[state] * }}> * I'm a fade Transition! * </div> * )} * </Transition> * ); * ``` * * There are 4 main states a Transition can be in: * - `'entering'` * - `'entered'` * - `'exiting'` * - `'exited'` * * Transition state is toggled via the `in` prop. When `true` the component * begins the "Enter" stage. During this stage, the component will shift from * its current transition state, to `'entering'` for the duration of the * transition and then to the `'entered'` stage once it's complete. Let's take * the following example (we'll use the * [useState](https://reactjs.org/docs/hooks-reference.html#usestate) hook): * * ```jsx * function App() { * const [inProp, setInProp] = useState(false); * return ( * <div> * <Transition in={inProp} timeout={500}> * {state => ( * // ... * )} * </Transition> * <button onClick={() => setInProp(true)}> * Click to Enter * </button> * </div> * ); * } * ``` * * When the button is clicked the component will shift to the `'entering'` state * and stay there for 500ms (the value of `timeout`) before it finally switches * to `'entered'`. * * When `in` is `false` the same thing happens except the state moves from * `'exiting'` to `'exited'`. */ var Transition = /*#__PURE__*/function (_React$Component) { inheritsLoose_inheritsLoose(Transition, _React$Component); function Transition(props, context) { var _this; _this = _React$Component.call(this, props, context) || this; var parentGroup = context; // In the context of a TransitionGroup all enters are really appears var appear = parentGroup && !parentGroup.isMounting ? props.enter : props.appear; var initialStatus; _this.appearStatus = null; if (props.in) { if (appear) { initialStatus = EXITED; _this.appearStatus = ENTERING; } else { initialStatus = ENTERED; } } else { if (props.unmountOnExit || props.mountOnEnter) { initialStatus = UNMOUNTED; } else { initialStatus = EXITED; } } _this.state = { status: initialStatus }; _this.nextCallback = null; return _this; } Transition.getDerivedStateFromProps = function getDerivedStateFromProps(_ref, prevState) { var nextIn = _ref.in; if (nextIn && prevState.status === UNMOUNTED) { return { status: EXITED }; } return null; } // getSnapshotBeforeUpdate(prevProps) { // let nextStatus = null // if (prevProps !== this.props) { // const { status } = this.state // if (this.props.in) { // if (status !== ENTERING && status !== ENTERED) { // nextStatus = ENTERING // } // } else { // if (status === ENTERING || status === ENTERED) { // nextStatus = EXITING // } // } // } // return { nextStatus } // } ; var _proto = Transition.prototype; _proto.componentDidMount = function componentDidMount() { this.updateStatus(true, this.appearStatus); }; _proto.componentDidUpdate = function componentDidUpdate(prevProps) { var nextStatus = null; if (prevProps !== this.props) { var status = this.state.status; if (this.props.in) { if (status !== ENTERING && status !== ENTERED) { nextStatus = ENTERING; } } else { if (status === ENTERING || status === ENTERED) { nextStatus = EXITING; } } } this.updateStatus(false, nextStatus); }; _proto.componentWillUnmount = function componentWillUnmount() { this.cancelNextCallback(); }; _proto.getTimeouts = function getTimeouts() { var timeout = this.props.timeout; var exit, enter, appear; exit = enter = appear = timeout; if (timeout != null && typeof timeout !== 'number') { exit = timeout.exit; enter = timeout.enter; // TODO: remove fallback for next major appear = timeout.appear !== undefined ? timeout.appear : enter; } return { exit: exit, enter: enter, appear: appear }; }; _proto.updateStatus = function updateStatus(mounting, nextStatus) { if (mounting === void 0) { mounting = false; } if (nextStatus !== null) { // nextStatus will always be ENTERING or EXITING. this.cancelNextCallback(); if (nextStatus === ENTERING) { this.performEnter(mounting); } else { this.performExit(); } } else if (this.props.unmountOnExit && this.state.status === EXITED) { this.setState({ status: UNMOUNTED }); } }; _proto.performEnter = function performEnter(mounting) { var _this2 = this; var enter = this.props.enter; var appearing = this.context ? this.context.isMounting : mounting; var _ref2 = this.props.nodeRef ? [appearing] : [external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_default().findDOMNode(this), appearing], maybeNode = _ref2[0], maybeAppearing = _ref2[1]; var timeouts = this.getTimeouts(); var enterTimeout = appearing ? timeouts.appear : timeouts.enter; // no enter animation skip right to ENTERED // if we are mounting and running this it means appear _must_ be set if (!mounting && !enter || config.disabled) { this.safeSetState({ status: ENTERED }, function () { _this2.props.onEntered(maybeNode); }); return; } this.props.onEnter(maybeNode, maybeAppearing); this.safeSetState({ status: ENTERING }, function () { _this2.props.onEntering(maybeNode, maybeAppearing); _this2.onTransitionEnd(enterTimeout, function () { _this2.safeSetState({ status: ENTERED }, function () { _this2.props.onEntered(maybeNode, maybeAppearing); }); }); }); }; _proto.performExit = function performExit() { var _this3 = this; var exit = this.props.exit; var timeouts = this.getTimeouts(); var maybeNode = this.props.nodeRef ? undefined : external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_default().findDOMNode(this); // no exit animation skip right to EXITED if (!exit || config.disabled) { this.safeSetState({ status: EXITED }, function () { _this3.props.onExited(maybeNode); }); return; } this.props.onExit(maybeNode); this.safeSetState({ status: EXITING }, function () { _this3.props.onExiting(maybeNode); _this3.onTransitionEnd(timeouts.exit, function () { _this3.safeSetState({ status: EXITED }, function () { _this3.props.onExited(maybeNode); }); }); }); }; _proto.cancelNextCallback = function cancelNextCallback() { if (this.nextCallback !== null) { this.nextCallback.cancel(); this.nextCallback = null; } }; _proto.safeSetState = function safeSetState(nextState, callback) { // This shouldn't be necessary, but there are weird race conditions with // setState callbacks and unmounting in testing, so always make sure that // we can cancel any pending setState callbacks after we unmount. callback = this.setNextCallback(callback); this.setState(nextState, callback); }; _proto.setNextCallback = function setNextCallback(callback) { var _this4 = this; var active = true; this.nextCallback = function (event) { if (active) { active = false; _this4.nextCallback = null; callback(event); } }; this.nextCallback.cancel = function () { active = false; }; return this.nextCallback; }; _proto.onTransitionEnd = function onTransitionEnd(timeout, handler) { this.setNextCallback(handler); var node = this.props.nodeRef ? this.props.nodeRef.current : external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_default().findDOMNode(this); var doesNotHaveTimeoutOrListener = timeout == null && !this.props.addEndListener; if (!node || doesNotHaveTimeoutOrListener) { setTimeout(this.nextCallback, 0); return; } if (this.props.addEndListener) { var _ref3 = this.props.nodeRef ? [this.nextCallback] : [node, this.nextCallback], maybeNode = _ref3[0], maybeNextCallback = _ref3[1]; this.props.addEndListener(maybeNode, maybeNextCallback); } if (timeout != null) { setTimeout(this.nextCallback, timeout); } }; _proto.render = function render() { var status = this.state.status; if (status === UNMOUNTED) { return null; } var _this$props = this.props, children = _this$props.children, _in = _this$props.in, _mountOnEnter = _this$props.mountOnEnter, _unmountOnExit = _this$props.unmountOnExit, _appear = _this$props.appear, _enter = _this$props.enter, _exit = _this$props.exit, _timeout = _this$props.timeout, _addEndListener = _this$props.addEndListener, _onEnter = _this$props.onEnter, _onEntering = _this$props.onEntering, _onEntered = _this$props.onEntered, _onExit = _this$props.onExit, _onExiting = _this$props.onExiting, _onExited = _this$props.onExited, _nodeRef = _this$props.nodeRef, childProps = objectWithoutPropertiesLoose_objectWithoutPropertiesLoose(_this$props, ["children", "in", "mountOnEnter", "unmountOnExit", "appear", "enter", "exit", "timeout", "addEndListener", "onEnter", "onEntering", "onEntered", "onExit", "onExiting", "onExited", "nodeRef"]); return ( /*#__PURE__*/ // allows for nested Transitions external_root_React_commonjs2_react_commonjs_react_amd_react_default().createElement(TransitionGroupContext.Provider, { value: null }, typeof children === 'function' ? children(status, childProps) : external_root_React_commonjs2_react_commonjs_react_amd_react_default().cloneElement(external_root_React_commonjs2_react_commonjs_react_amd_react_default().Children.only(children), childProps)) ); }; return Transition; }((external_root_React_commonjs2_react_commonjs_react_amd_react_default()).Component); Transition.contextType = TransitionGroupContext; Transition.propTypes = false ? 0 : {}; // Name the function so it is clearer in the documentation function Transition_noop() {} Transition.defaultProps = { in: false, mountOnEnter: false, unmountOnExit: false, appear: false, enter: true, exit: true, onEnter: Transition_noop, onEntering: Transition_noop, onEntered: Transition_noop, onExit: Transition_noop, onExiting: Transition_noop, onExited: Transition_noop }; Transition.UNMOUNTED = UNMOUNTED; Transition.EXITED = EXITED; Transition.ENTERING = ENTERING; Transition.ENTERED = ENTERED; Transition.EXITING = EXITING; /* harmony default export */ const esm_Transition = (Transition); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/canUseDOM.js /* harmony default export */ const canUseDOM = (!!(typeof window !== 'undefined' && window.document && window.document.createElement)); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/addEventListener.js /* eslint-disable no-return-assign */ var optionsSupported = false; var onceSupported = false; try { var options = { get passive() { return optionsSupported = true; }, get once() { // eslint-disable-next-line no-multi-assign return onceSupported = optionsSupported = true; } }; if (canUseDOM) { window.addEventListener('test', options, options); window.removeEventListener('test', options, true); } } catch (e) { /* */ } /** * An `addEventListener` ponyfill, supports the `once` option * * @param node the element * @param eventName the event name * @param handle the handler * @param options event options */ function addEventListener(node, eventName, handler, options) { if (options && typeof options !== 'boolean' && !onceSupported) { var once = options.once, capture = options.capture; var wrappedHandler = handler; if (!onceSupported && once) { wrappedHandler = handler.__once || function onceHandler(event) { this.removeEventListener(eventName, onceHandler, capture); handler.call(this, event); }; handler.__once = wrappedHandler; } node.addEventListener(eventName, wrappedHandler, optionsSupported ? options : capture); } node.addEventListener(eventName, handler, options); } /* harmony default export */ const esm_addEventListener = (addEventListener); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/removeEventListener.js /** * A `removeEventListener` ponyfill * * @param node the element * @param eventName the event name * @param handle the handler * @param options event options */ function removeEventListener(node, eventName, handler, options) { var capture = options && typeof options !== 'boolean' ? options.capture : options; node.removeEventListener(eventName, handler, capture); if (handler.__once) { node.removeEventListener(eventName, handler.__once, capture); } } /* harmony default export */ const esm_removeEventListener = (removeEventListener); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/listen.js function listen(node, eventName, handler, options) { esm_addEventListener(node, eventName, handler, options); return function () { esm_removeEventListener(node, eventName, handler, options); }; } /* harmony default export */ const esm_listen = (listen); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/triggerEvent.js /** * Triggers an event on a given element. * * @param node the element * @param eventName the event name to trigger * @param bubbles whether the event should bubble up * @param cancelable whether the event should be cancelable */ function triggerEvent(node, eventName, bubbles, cancelable) { if (bubbles === void 0) { bubbles = false; } if (cancelable === void 0) { cancelable = true; } if (node) { var event = document.createEvent('HTMLEvents'); event.initEvent(eventName, bubbles, cancelable); node.dispatchEvent(event); } } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/transitionEnd.js function parseDuration(node) { var str = css(node, 'transitionDuration') || ''; var mult = str.indexOf('ms') === -1 ? 1000 : 1; return parseFloat(str) * mult; } function emulateTransitionEnd(element, duration, padding) { if (padding === void 0) { padding = 5; } var called = false; var handle = setTimeout(function () { if (!called) triggerEvent(element, 'transitionend', true); }, duration + padding); var remove = esm_listen(element, 'transitionend', function () { called = true; }, { once: true }); return function () { clearTimeout(handle); remove(); }; } function transitionEnd(element, handler, duration, padding) { if (duration == null) duration = parseDuration(element) || 0; var removeEmulate = emulateTransitionEnd(element, duration, padding); var remove = esm_listen(element, 'transitionend', handler); return function () { removeEmulate(); remove(); }; } ;// CONCATENATED MODULE: ./src/transitionEndListener.ts function transitionEndListener_parseDuration(node, property) { const str = css(node, property) || ''; const mult = str.indexOf('ms') === -1 ? 1000 : 1; return parseFloat(str) * mult; } function transitionEndListener(element, handler) { const duration = transitionEndListener_parseDuration(element, 'transitionDuration'); const delay = transitionEndListener_parseDuration(element, 'transitionDelay'); const remove = transitionEnd(element, e => { if (e.target === element) { remove(); handler(e); } }, duration + delay); } ;// CONCATENATED MODULE: ./src/createChainedFunction.tsx /** * Safe chained function * * Will only create a new function if needed, * otherwise will pass back existing functions or null. * * @param {function} functions to chain * @returns {function|null} */ function createChainedFunction(...funcs) { return funcs.filter(f => f != null).reduce((acc, f) => { if (typeof f !== 'function') { throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.'); } if (acc === null) return f; return function chainedFunction(...args) { // @ts-ignore acc.apply(this, args); // @ts-ignore f.apply(this, args); }; }, null); } /* harmony default export */ const src_createChainedFunction = (createChainedFunction); ;// CONCATENATED MODULE: ./src/triggerBrowserReflow.tsx // reading a dimension prop will cause the browser to recalculate, // which will let our animations work function triggerBrowserReflow(node) { // eslint-disable-next-line @typescript-eslint/no-unused-expressions node.offsetHeight; } ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useMergedRefs.js var toFnRef = function toFnRef(ref) { return !ref || typeof ref === 'function' ? ref : function (value) { ref.current = value; }; }; function mergeRefs(refA, refB) { var a = toFnRef(refA); var b = toFnRef(refB); return function (value) { if (a) a(value); if (b) b(value); }; } /** * Create and returns a single callback ref composed from two other Refs. * * ```tsx * const Button = React.forwardRef((props, ref) => { * const [element, attachRef] = useCallbackRef<HTMLButtonElement>(); * const mergedRef = useMergedRefs(ref, attachRef); * * return <button ref={mergedRef} {...props}/> * }) * ``` * * @param refA A Callback or mutable Ref * @param refB A Callback or mutable Ref * @category refs */ function useMergedRefs(refA, refB) { return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(function () { return mergeRefs(refA, refB); }, [refA, refB]); } /* harmony default export */ const esm_useMergedRefs = (useMergedRefs); ;// CONCATENATED MODULE: ./src/safeFindDOMNode.ts function safeFindDOMNode(componentOrElement) { if (componentOrElement && 'setState' in componentOrElement) { return external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_default().findDOMNode(componentOrElement); } return componentOrElement != null ? componentOrElement : null; } ;// CONCATENATED MODULE: ./src/TransitionWrapper.tsx var TransitionWrapper_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/TransitionWrapper.tsx"; // Normalizes Transition callbacks when nodeRef is used. const TransitionWrapper = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_default().forwardRef(({ onEnter, onEntering, onEntered, onExit, onExiting, onExited, addEndListener, children, childRef, ...props }, ref) => { const nodeRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); const mergedRef = esm_useMergedRefs(nodeRef, childRef); const attachRef = r => { mergedRef(safeFindDOMNode(r)); }; const normalize = callback => param => { if (callback && nodeRef.current) { callback(nodeRef.current, param); } }; /* eslint-disable react-hooks/exhaustive-deps */ const handleEnter = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(normalize(onEnter), [onEnter]); const handleEntering = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(normalize(onEntering), [onEntering]); const handleEntered = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(normalize(onEntered), [onEntered]); const handleExit = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(normalize(onExit), [onExit]); const handleExiting = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(normalize(onExiting), [onExiting]); const handleExited = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(normalize(onExited), [onExited]); const handleAddEndListener = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(normalize(addEndListener), [addEndListener]); /* eslint-enable react-hooks/exhaustive-deps */ return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Transition, { ref: ref, ...props, onEnter: handleEnter, onEntered: handleEntered, onEntering: handleEntering, onExit: handleExit, onExited: handleExited, onExiting: handleExiting, addEndListener: handleAddEndListener, nodeRef: nodeRef, children: typeof children === 'function' ? (status, innerProps) => children(status, { ...innerProps, ref: attachRef }) : /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_default().cloneElement(children, { ref: attachRef }) }, void 0, false, { fileName: TransitionWrapper_jsxFileName, lineNumber: 68, columnNumber: 7 }, undefined); }); /* harmony default export */ const src_TransitionWrapper = (TransitionWrapper); ;// CONCATENATED MODULE: ./src/Collapse.tsx var Collapse_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Collapse.tsx"; const MARGINS = { height: ['marginTop', 'marginBottom'], width: ['marginLeft', 'marginRight'] }; function getDefaultDimensionValue(dimension, elem) { const offset = `offset${dimension[0].toUpperCase()}${dimension.slice(1)}`; const value = elem[offset]; const margins = MARGINS[dimension]; return value + // @ts-ignore parseInt(css(elem, margins[0]), 10) + // @ts-ignore parseInt(css(elem, margins[1]), 10); } const collapseStyles = { [EXITED]: 'collapse', [EXITING]: 'collapsing', [ENTERING]: 'collapsing', [ENTERED]: 'collapse show' }; const propTypes = { /** * Show the component; triggers the expand or collapse animation */ in: (prop_types_default()).bool, /** * Wait until the first "enter" transition to mount the component (add it to the DOM) */ mountOnEnter: (prop_types_default()).bool, /** * Unmount the component (remove it from the DOM) when it is collapsed */ unmountOnExit: (prop_types_default()).bool, /** * Run the expand animation when the component mounts, if it is initially * shown */ appear: (prop_types_default()).bool, /** * Duration of the collapse animation in milliseconds, to ensure that * finishing callbacks are fired even if the original browser transition end * events are canceled */ timeout: (prop_types_default()).number, /** * Callback fired before the component expands */ onEnter: (prop_types_default()).func, /** * Callback fired after the component starts to expand */ onEntering: (prop_types_default()).func, /** * Callback fired after the component has expanded */ onEntered: (prop_types_default()).func, /** * Callback fired before the component collapses */ onExit: (prop_types_default()).func, /** * Callback fired after the component starts to collapse */ onExiting: (prop_types_default()).func, /** * Callback fired after the component has collapsed */ onExited: (prop_types_default()).func, /** * The dimension used when collapsing, or a function that returns the * dimension */ dimension: prop_types_default().oneOfType([prop_types_default().oneOf(['height', 'width']), (prop_types_default()).func]), /** * Function that returns the height or width of the animating DOM node * * Allows for providing some custom logic for how much the Collapse component * should animate in its specified dimension. Called with the current * dimension prop value and the DOM node. * * @default element.offsetWidth | element.offsetHeight */ getDimensionValue: (prop_types_default()).func, /** * ARIA role of collapsible element */ role: (prop_types_default()).string, /** * You must provide a single JSX child element to this component and that element cannot be a \<React.Fragment\> */ children: (prop_types_default()).element.isRequired }; const defaultProps = { in: false, timeout: 300, mountOnEnter: false, unmountOnExit: false, appear: false, getDimensionValue: getDefaultDimensionValue }; const Collapse = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_default().forwardRef(({ onEnter, onEntering, onEntered, onExit, onExiting, className, children, dimension = 'height', getDimensionValue = getDefaultDimensionValue, ...props }, ref) => { /* Compute dimension */ const computedDimension = typeof dimension === 'function' ? dimension() : dimension; /* -- Expanding -- */ const handleEnter = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => src_createChainedFunction(elem => { elem.style[computedDimension] = '0'; }, onEnter), [computedDimension, onEnter]); const handleEntering = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => src_createChainedFunction(elem => { const scroll = `scroll${computedDimension[0].toUpperCase()}${computedDimension.slice(1)}`; elem.style[computedDimension] = `${elem[scroll]}px`; }, onEntering), [computedDimension, onEntering]); const handleEntered = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => src_createChainedFunction(elem => { elem.style[computedDimension] = null; }, onEntered), [computedDimension, onEntered]); /* -- Collapsing -- */ const handleExit = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => src_createChainedFunction(elem => { elem.style[computedDimension] = `${getDimensionValue(computedDimension, elem)}px`; triggerBrowserReflow(elem); }, onExit), [onExit, getDimensionValue, computedDimension]); const handleExiting = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => src_createChainedFunction(elem => { elem.style[computedDimension] = null; }, onExiting), [computedDimension, onExiting]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_TransitionWrapper, { ref: ref, addEndListener: transitionEndListener, ...props, "aria-expanded": props.role ? props.in : null, onEnter: handleEnter, onEntering: handleEntering, onEntered: handleEntered, onExit: handleExit, onExiting: handleExiting, childRef: children.ref, children: (state, innerProps) => /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_default().cloneElement(children, { ...innerProps, className: classnames_default()(className, children.props.className, collapseStyles[state], computedDimension === 'width' && 'collapse-horizontal') }) }, void 0, false, { fileName: Collapse_jsxFileName, lineNumber: 226, columnNumber: 7 }, undefined); }); // @ts-ignore Collapse.propTypes = propTypes; // @ts-ignore Collapse.defaultProps = defaultProps; /* harmony default export */ const src_Collapse = (Collapse); ;// CONCATENATED MODULE: ./src/AccordionContext.ts function isAccordionItemSelected(activeEventKey, eventKey) { return Array.isArray(activeEventKey) ? activeEventKey.includes(eventKey) : activeEventKey === eventKey; } const context = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext({}); context.displayName = 'AccordionContext'; /* harmony default export */ const AccordionContext = (context); ;// CONCATENATED MODULE: ./src/AccordionCollapse.tsx var AccordionCollapse_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/AccordionCollapse.tsx"; const AccordionCollapse_propTypes = { /** Set a custom element for this component */ as: (prop_types_default()).elementType, /** * A key that corresponds to the toggler that triggers this collapse's expand or collapse. */ eventKey: (prop_types_default()).string.isRequired, /** Children prop should only contain a single child, and is enforced as such */ children: (prop_types_default()).element.isRequired }; const AccordionCollapse = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ as: Component = 'div', bsPrefix, className, children, eventKey, ...props }, ref) => { const { activeEventKey } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(AccordionContext); bsPrefix = useBootstrapPrefix(bsPrefix, 'accordion-collapse'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Collapse, { ref: ref, in: isAccordionItemSelected(activeEventKey, eventKey), ...props, className: classnames_default()(className, bsPrefix), children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { children: external_root_React_commonjs2_react_commonjs_react_amd_react_.Children.only(children) }, void 0, false, { fileName: AccordionCollapse_jsxFileName, lineNumber: 53, columnNumber: 9 }, undefined) }, void 0, false, { fileName: AccordionCollapse_jsxFileName, lineNumber: 47, columnNumber: 7 }, undefined); }); AccordionCollapse.propTypes = AccordionCollapse_propTypes; AccordionCollapse.displayName = 'AccordionCollapse'; /* harmony default export */ const src_AccordionCollapse = (AccordionCollapse); ;// CONCATENATED MODULE: ./src/AccordionItemContext.ts const AccordionItemContext_context = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext({ eventKey: '' }); AccordionItemContext_context.displayName = 'AccordionItemContext'; /* harmony default export */ const AccordionItemContext = (AccordionItemContext_context); ;// CONCATENATED MODULE: ./src/AccordionBody.tsx var AccordionBody_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/AccordionBody.tsx"; const AccordionBody_propTypes = { /** Set a custom element for this component */ as: (prop_types_default()).elementType, /** @default 'accordion-body' */ bsPrefix: (prop_types_default()).string }; const AccordionBody = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', bsPrefix, className, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'accordion-body'); const { eventKey } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(AccordionItemContext); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_AccordionCollapse, { eventKey: eventKey, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, bsPrefix) }, void 0, false, { fileName: AccordionBody_jsxFileName, lineNumber: 39, columnNumber: 11 }, undefined) }, void 0, false, { fileName: AccordionBody_jsxFileName, lineNumber: 38, columnNumber: 9 }, undefined); }); AccordionBody.propTypes = AccordionBody_propTypes; AccordionBody.displayName = 'AccordionBody'; /* harmony default export */ const src_AccordionBody = (AccordionBody); ;// CONCATENATED MODULE: ./src/AccordionButton.tsx var AccordionButton_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/AccordionButton.tsx"; const AccordionButton_propTypes = { /** Set a custom element for this component */ as: (prop_types_default()).elementType, /** @default 'accordion-button' */ bsPrefix: (prop_types_default()).string, /** A callback function for when this component is clicked */ onClick: (prop_types_default()).func }; function useAccordionButton(eventKey, onClick) { const { activeEventKey, onSelect, alwaysOpen } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(AccordionContext); return e => { /* Compare the event key in context with the given event key. If they are the same, then collapse the component. */ let eventKeyPassed = eventKey === activeEventKey ? null : eventKey; if (alwaysOpen) { if (Array.isArray(activeEventKey)) { if (activeEventKey.includes(eventKey)) { eventKeyPassed = activeEventKey.filter(k => k !== eventKey); } else { eventKeyPassed = [...activeEventKey, eventKey]; } } else { // activeEventKey is undefined. eventKeyPassed = [eventKey]; } } onSelect == null ? void 0 : onSelect(eventKeyPassed, e); onClick == null ? void 0 : onClick(e); }; } const AccordionButton = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'button', bsPrefix, className, onClick, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'accordion-button'); const { eventKey } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(AccordionItemContext); const accordionOnClick = useAccordionButton(eventKey, onClick); const { activeEventKey } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(AccordionContext); if (Component === 'button') { props.type = 'button'; } return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, onClick: accordionOnClick, ...props, "aria-expanded": eventKey === activeEventKey, className: classnames_default()(className, bsPrefix, !isAccordionItemSelected(activeEventKey, eventKey) && 'collapsed') }, void 0, false, { fileName: AccordionButton_jsxFileName, lineNumber: 86, columnNumber: 7 }, undefined); }); AccordionButton.propTypes = AccordionButton_propTypes; AccordionButton.displayName = 'AccordionButton'; /* harmony default export */ const src_AccordionButton = (AccordionButton); ;// CONCATENATED MODULE: ./src/AccordionHeader.tsx var AccordionHeader_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/AccordionHeader.tsx"; const AccordionHeader_propTypes = { /** Set a custom element for this component */ as: (prop_types_default()).elementType, /** @default 'accordion-header' */ bsPrefix: (prop_types_default()).string, /** Click handler for the `AccordionButton` element */ onClick: (prop_types_default()).func }; const AccordionHeader = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'h2', bsPrefix, className, children, onClick, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'accordion-header'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, bsPrefix), children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_AccordionButton, { onClick: onClick, children: children }, void 0, false, { fileName: AccordionHeader_jsxFileName, lineNumber: 47, columnNumber: 9 }, undefined) }, void 0, false, { fileName: AccordionHeader_jsxFileName, lineNumber: 42, columnNumber: 7 }, undefined); }); AccordionHeader.propTypes = AccordionHeader_propTypes; AccordionHeader.displayName = 'AccordionHeader'; /* harmony default export */ const src_AccordionHeader = (AccordionHeader); ;// CONCATENATED MODULE: ./src/AccordionItem.tsx var AccordionItem_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/AccordionItem.tsx"; const AccordionItem_propTypes = { /** Set a custom element for this component */ as: (prop_types_default()).elementType, /** @default 'accordion-item' */ bsPrefix: (prop_types_default()).string, /** * A unique key used to control this item's collapse/expand. * @required */ eventKey: (prop_types_default()).string.isRequired }; const AccordionItem = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', bsPrefix, className, eventKey, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'accordion-item'); const contextValue = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ eventKey }), [eventKey]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(AccordionItemContext.Provider, { value: contextValue, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, bsPrefix) }, void 0, false, { fileName: AccordionItem_jsxFileName, lineNumber: 54, columnNumber: 11 }, undefined) }, void 0, false, { fileName: AccordionItem_jsxFileName, lineNumber: 53, columnNumber: 9 }, undefined); }); AccordionItem.propTypes = AccordionItem_propTypes; AccordionItem.displayName = 'AccordionItem'; /* harmony default export */ const src_AccordionItem = (AccordionItem); ;// CONCATENATED MODULE: ./src/Accordion.tsx var Accordion_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Accordion.tsx"; const Accordion_propTypes = { /** Set a custom element for this component */ as: (prop_types_default()).elementType, /** @default 'accordion' */ bsPrefix: (prop_types_default()).string, /** The current active key that corresponds to the currently expanded card */ activeKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).array]), /** The default active key that is expanded on start */ defaultActiveKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).array]), /** Renders accordion edge-to-edge with its parent container */ flush: (prop_types_default()).bool, /** Allow accordion items to stay open when another item is opened */ alwaysOpen: (prop_types_default()).bool }; const Accordion = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, ref) => { const { // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', activeKey, bsPrefix, className, onSelect, flush, alwaysOpen, ...controlledProps } = useUncontrolled(props, { activeKey: 'onSelect' }); const prefix = useBootstrapPrefix(bsPrefix, 'accordion'); const contextValue = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ activeEventKey: activeKey, onSelect, alwaysOpen }), [activeKey, onSelect, alwaysOpen]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(AccordionContext.Provider, { value: contextValue, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...controlledProps, className: classnames_default()(className, prefix, flush && `${prefix}-flush`) }, void 0, false, { fileName: Accordion_jsxFileName, lineNumber: 76, columnNumber: 9 }, undefined) }, void 0, false, { fileName: Accordion_jsxFileName, lineNumber: 75, columnNumber: 7 }, undefined); }); Accordion.displayName = 'Accordion'; Accordion.propTypes = Accordion_propTypes; /* harmony default export */ const src_Accordion = (Object.assign(Accordion, { Button: src_AccordionButton, Collapse: src_AccordionCollapse, Item: src_AccordionItem, Header: src_AccordionHeader, Body: src_AccordionBody })); // EXTERNAL MODULE: ./node_modules/prop-types-extra/lib/index.js var lib = __webpack_require__(517); ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useCommittedRef.js /** * Creates a `Ref` whose value is updated in an effect, ensuring the most recent * value is the one rendered with. Generally only required for Concurrent mode usage * where previous work in `render()` may be discarded before being used. * * This is safe to access in an event handler. * * @param value The `Ref` value */ function useCommittedRef_useCommittedRef(value) { var ref = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(value); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { ref.current = value; }, [value]); return ref; } /* harmony default export */ const esm_useCommittedRef = (useCommittedRef_useCommittedRef); ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useEventCallback.js function useEventCallback(fn) { var ref = esm_useCommittedRef(fn); return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(function () { return ref.current && ref.current.apply(ref, arguments); }, [ref]); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useCallbackRef.js /** * A convenience hook around `useState` designed to be paired with * the component [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs) api. * Callback refs are useful over `useRef()` when you need to respond to the ref being set * instead of lazily accessing it in an effect. * * ```ts * const [element, attachRef] = useCallbackRef<HTMLDivElement>() * * useEffect(() => { * if (!element) return * * const calendar = new FullCalendar.Calendar(element) * * return () => { * calendar.destroy() * } * }, [element]) * * return <div ref={attachRef} /> * ``` * * @category refs */ function useCallbackRef() { return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(null); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useCommittedRef.js /** * Creates a `Ref` whose value is updated in an effect, ensuring the most recent * value is the one rendered with. Generally only required for Concurrent mode usage * where previous work in `render()` may be discarded befor being used. * * This is safe to access in an event handler. * * @param value The `Ref` value */ function esm_useCommittedRef_useCommittedRef(value) { var ref = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(value); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { ref.current = value; }, [value]); return ref; } /* harmony default export */ const hooks_esm_useCommittedRef = (esm_useCommittedRef_useCommittedRef); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useEventCallback.js function useEventCallback_useEventCallback(fn) { var ref = hooks_esm_useCommittedRef(fn); return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(function () { return ref.current && ref.current.apply(ref, arguments); }, [ref]); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useEventListener.js /** * Attaches an event handler outside directly to specified DOM element * bypassing the react synthetic event system. * * @param element The target to listen for events on * @param event The DOM event name * @param handler An event handler * @param capture Whether or not to listen during the capture event phase */ function useEventListener_useEventListener(eventTarget, event, listener, capture) { if (capture === void 0) { capture = false; } var handler = useEventCallback_useEventCallback(listener); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { var target = typeof eventTarget === 'function' ? eventTarget() : eventTarget; target.addEventListener(event, handler, capture); return function () { return target.removeEventListener(event, handler, capture); }; }, [eventTarget]); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useGlobalListener.js /** * Attaches an event handler outside directly to the `document`, * bypassing the react synthetic event system. * * ```ts * useGlobalListener('keydown', (event) => { * console.log(event.key) * }) * ``` * * @param event The DOM event name * @param handler An event handler * @param capture Whether or not to listen during the capture event phase */ function useGlobalListener(event, handler, capture) { if (capture === void 0) { capture = false; } var documentTarget = useCallback(function () { return document; }, []); return useEventListener(documentTarget, event, handler, capture); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useInterval.js /** * Creates a `setInterval` that is properly cleaned up when a component unmounted * * ```tsx * function Timer() { * const [timer, setTimer] = useState(0) * useInterval(() => setTimer(i => i + 1), 1000) * * return <span>{timer} seconds past</span> * } * ``` * * @param fn an function run on each interval * @param ms The milliseconds duration of the interval */ function useInterval(fn, ms, paused, runImmediately) { if (paused === void 0) { paused = false; } if (runImmediately === void 0) { runImmediately = false; } var handle; var fnRef = useCommittedRef(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle // orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable. var pausedRef = useCommittedRef(paused); var tick = function tick() { if (pausedRef.current) return; fnRef.current(); schedule(); // eslint-disable-line no-use-before-define }; var schedule = function schedule() { clearTimeout(handle); handle = setTimeout(tick, ms); }; useEffect(function () { if (runImmediately) { tick(); } else { schedule(); } return function () { return clearTimeout(handle); }; }, [paused, runImmediately]); } /* harmony default export */ const esm_useInterval = ((/* unused pure expression or super */ null && (useInterval))); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useRafInterval.js function useRafInterval(fn, ms, paused) { if (paused === void 0) { paused = false; } var handle; var start = new Date().getTime(); var fnRef = useCommittedRef(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle // orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable. var pausedRef = useCommittedRef(paused); function loop() { var current = new Date().getTime(); var delta = current - start; if (pausedRef.current) return; if (delta >= ms && fnRef.current) { fnRef.current(); start = new Date().getTime(); } cancelAnimationFrame(handle); handle = requestAnimationFrame(loop); } useEffect(function () { handle = requestAnimationFrame(loop); return function () { return cancelAnimationFrame(handle); }; }, []); } /* harmony default export */ const esm_useRafInterval = ((/* unused pure expression or super */ null && (useRafInterval))); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useMergeState.js function useMergeState_extends() { useMergeState_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 useMergeState_extends.apply(this, arguments); } /** * Mimics a React class component's state model, of having a single unified * `state` object and an updater that merges updates into the existing state, as * opposed to replacing it. * * ```js * const [state, setState] = useMergeState({ name: 'Betsy', age: 24 }) * * setState({ name: 'Johan' }) // { name: 'Johan', age: 24 } * * setState(state => ({ age: state.age + 10 })) // { name: 'Johan', age: 34 } * ``` * * @param initialState The initial state object */ function useMergeState_useMergeState(initialState) { var _useState = useState(initialState), state = _useState[0], setState = _useState[1]; var updater = useCallback(function (update) { if (update === null) return; if (typeof update === 'function') { setState(function (state) { var nextState = update(state); return nextState == null ? state : useMergeState_extends({}, state, nextState); }); } else { setState(function (state) { return useMergeState_extends({}, state, update); }); } }, [setState]); return [state, updater]; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useMergeStateFromProps.js function useMergeStateFromProps(props, gDSFP, initialState) { var _useMergeState = useMergeState(initialState), state = _useMergeState[0], setState = _useMergeState[1]; var nextState = gDSFP(props, state); if (nextState !== null) setState(nextState); return [state, setState]; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useMounted.js /** * Track whether a component is current mounted. Generally less preferable than * properlly canceling effects so they don't run after a component is unmounted, * but helpful in cases where that isn't feasible, such as a `Promise` resolution. * * @returns a function that returns the current isMounted state of the component * * ```ts * const [data, setData] = useState(null) * const isMounted = useMounted() * * useEffect(() => { * fetchdata().then((newData) => { * if (isMounted()) { * setData(newData); * } * }) * }) * ``` */ function useMounted() { var mounted = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(true); var isMounted = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(function () { return mounted.current; }); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { return function () { mounted.current = false; }; }, []); return isMounted.current; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/usePrevious.js /** * Store the last of some value. Tracked via a `Ref` only updating it * after the component renders. * * Helpful if you need to compare a prop value to it's previous value during render. * * ```ts * function Component(props) { * const lastProps = usePrevious(props) * * if (lastProps.foo !== props.foo) * resetValueFromProps(props.foo) * } * ``` * * @param value the value to track */ function usePrevious(value) { var ref = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { ref.current = value; }); return ref.current; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useImage.js /** * Fetch and load an image for programatic use such as in a `<canvas>` element. * * @param imageOrUrl The `HtmlImageElement` or image url to load * @param crossOrigin The `crossorigin` attribute to set * * ```ts * const { image, error } = useImage('/static/kittens.png') * const ref = useRef<HTMLCanvasElement>() * * useEffect(() => { * const ctx = ref.current.getContext('2d') * * if (image) { * ctx.drawImage(image, 0, 0) * } * }, [ref, image]) * * return ( * <> * {error && "there was a problem loading the image"} * <canvas ref={ref} /> * </> * ``` */ function useImage(imageOrUrl, crossOrigin) { var _useState = useState({ image: null, error: null }), state = _useState[0], setState = _useState[1]; useEffect(function () { if (!imageOrUrl) return undefined; var image; if (typeof imageOrUrl === 'string') { image = new Image(); if (crossOrigin) image.crossOrigin = crossOrigin; image.src = imageOrUrl; } else { image = imageOrUrl; if (image.complete && image.naturalHeight > 0) { setState({ image: image, error: null }); return; } } function onLoad() { setState({ image: image, error: null }); } function onError(error) { setState({ image: image, error: error }); } image.addEventListener('load', onLoad); image.addEventListener('error', onError); return function () { image.removeEventListener('load', onLoad); image.removeEventListener('error', onError); }; }, [imageOrUrl, crossOrigin]); return state; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useIsomorphicEffect.js var isReactNative = typeof __webpack_require__.g !== 'undefined' && // @ts-ignore __webpack_require__.g.navigator && // @ts-ignore __webpack_require__.g.navigator.product === 'ReactNative'; var isDOM = typeof document !== 'undefined'; /** * Is `useLayoutEffect` in a DOM or React Native environment, otherwise resolves to useEffect * Only useful to avoid the console warning. * * PREFER `useEffect` UNLESS YOU KNOW WHAT YOU ARE DOING. * * @category effects */ /* harmony default export */ const useIsomorphicEffect = (isDOM || isReactNative ? external_root_React_commonjs2_react_commonjs_react_amd_react_.useLayoutEffect : external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useResizeObserver.js var targetMap = new WeakMap(); var resizeObserver; function getResizeObserver() { // eslint-disable-next-line no-return-assign return resizeObserver = resizeObserver || new window.ResizeObserver(function (entries) { entries.forEach(function (entry) { var handler = targetMap.get(entry.target); if (handler) handler(entry.contentRect); }); }); } /** * Efficiently observe size changes on an element. Depends on the `ResizeObserver` api, * and polyfills are needed in older browsers. * * ```ts * const [ref, attachRef] = useCallbackRef(null); * * const rect = useResizeObserver(ref); * * return ( * <div ref={attachRef}> * {JSON.stringify(rect)} * </div> * ) * ``` * * @param element The DOM element to observe */ function useResizeObserver(element) { var _useState = useState(null), rect = _useState[0], setRect = _useState[1]; useEffect(function () { if (!element) return; getResizeObserver().observe(element); setRect(element.getBoundingClientRect()); targetMap.set(element, function (rect) { setRect(rect); }); return function () { targetMap.delete(element); }; }, [element]); return rect; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/index.js // EXTERNAL MODULE: ./node_modules/react/jsx-runtime.js var jsx_runtime = __webpack_require__(373); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/Button.js const _excluded = ["as", "disabled"]; function Button_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function isTrivialHref(href) { return !href || href.trim() === '#'; } function useButtonProps({ tagName, disabled, href, target, rel, onClick, tabIndex = 0, type }) { if (!tagName) { if (href != null || target != null || rel != null) { tagName = 'a'; } else { tagName = 'button'; } } const meta = { tagName }; if (tagName === 'button') { return [{ type: type || 'button', disabled }, meta]; } const handleClick = event => { if (disabled || tagName === 'a' && isTrivialHref(href)) { event.preventDefault(); } if (disabled) { event.stopPropagation(); return; } onClick == null ? void 0 : onClick(event); }; const handleKeyDown = event => { if (event.key === ' ') { event.preventDefault(); handleClick(event); } }; return [{ role: 'button', // explicitly undefined so that it overrides the props disabled in a spread // e.g. <Tag {...props} {...hookProps} /> disabled: undefined, tabIndex: disabled ? undefined : tabIndex, href: tagName === 'a' && disabled ? undefined : href, target: tagName === 'a' ? target : undefined, 'aria-disabled': !disabled ? undefined : disabled, rel: tagName === 'a' ? rel : undefined, onClick: handleClick, onKeyDown: handleKeyDown }, meta]; } const Button = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((_ref, ref) => { let { as: asProp, disabled } = _ref, props = Button_objectWithoutPropertiesLoose(_ref, _excluded); const [buttonProps, { tagName: Component }] = useButtonProps(Object.assign({ tagName: asProp, disabled }, props)); return /*#__PURE__*/(0,jsx_runtime.jsx)(Component, Object.assign({}, props, buttonProps, { ref: ref })); }); Button.displayName = 'Button'; /* harmony default export */ const esm_Button = (Button); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/Anchor.js const Anchor_excluded = ["onKeyDown"]; function Anchor_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /* eslint-disable jsx-a11y/no-static-element-interactions */ /* eslint-disable jsx-a11y/anchor-has-content */ function Anchor_isTrivialHref(href) { return !href || href.trim() === '#'; } /** * An generic `<a>` component that covers a few A11y cases, ensuring that * cases where the `href` is missing or trivial like "#" are treated like buttons. */ const Anchor = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((_ref, ref) => { let { onKeyDown } = _ref, props = Anchor_objectWithoutPropertiesLoose(_ref, Anchor_excluded); const [buttonProps] = useButtonProps(Object.assign({ tagName: 'a' }, props)); const handleKeyDown = useEventCallback_useEventCallback(e => { buttonProps.onKeyDown(e); onKeyDown == null ? void 0 : onKeyDown(e); }); if (Anchor_isTrivialHref(props.href) && !props.role || props.role === 'button') { return /*#__PURE__*/(0,jsx_runtime.jsx)("a", Object.assign({ ref: ref }, props, buttonProps, { onKeyDown: handleKeyDown })); } return /*#__PURE__*/(0,jsx_runtime.jsx)("a", Object.assign({ ref: ref }, props, { onKeyDown: onKeyDown })); }); Anchor.displayName = 'Anchor'; /* harmony default export */ const esm_Anchor = (Anchor); ;// CONCATENATED MODULE: ./src/Fade.tsx var Fade_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Fade.tsx"; const Fade_propTypes = { /** * Show the component; triggers the fade in or fade out animation */ in: (prop_types_default()).bool, /** * Wait until the first "enter" transition to mount the component (add it to the DOM) */ mountOnEnter: (prop_types_default()).bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: (prop_types_default()).bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ appear: (prop_types_default()).bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: (prop_types_default()).number, /** * Callback fired before the component fades in */ onEnter: (prop_types_default()).func, /** * Callback fired after the component starts to fade in */ onEntering: (prop_types_default()).func, /** * Callback fired after the has component faded in */ onEntered: (prop_types_default()).func, /** * Callback fired before the component fades out */ onExit: (prop_types_default()).func, /** * Callback fired after the component starts to fade out */ onExiting: (prop_types_default()).func, /** * Callback fired after the component has faded out */ onExited: (prop_types_default()).func, /** * You must provide a single JSX child element to this component and that element cannot be a \<React.Fragment\> */ children: (prop_types_default()).element.isRequired, /** * Applies additional specified classes during the transition. Takes an object * where the keys correspond to the Transition status */ transitionClasses: (prop_types_default()).object }; const Fade_defaultProps = { in: false, timeout: 300, mountOnEnter: false, unmountOnExit: false, appear: false }; const fadeStyles = { [ENTERING]: 'show', [ENTERED]: 'show' }; const Fade = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ className, children, transitionClasses = {}, ...props }, ref) => { const handleEnter = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)((node, isAppearing) => { triggerBrowserReflow(node); props.onEnter == null ? void 0 : props.onEnter(node, isAppearing); }, [props]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_TransitionWrapper, { ref: ref, addEndListener: transitionEndListener, ...props, onEnter: handleEnter, childRef: children.ref, children: (status, innerProps) => /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement(children, { ...innerProps, className: classnames_default()('fade', className, children.props.className, fadeStyles[status], transitionClasses[status]) }) }, void 0, false, { fileName: Fade_jsxFileName, lineNumber: 116, columnNumber: 7 }, undefined); }); Fade.propTypes = Fade_propTypes; Fade.defaultProps = Fade_defaultProps; Fade.displayName = 'Fade'; /* harmony default export */ const src_Fade = (Fade); ;// CONCATENATED MODULE: ./src/CloseButton.tsx var CloseButton_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/CloseButton.tsx"; const CloseButton_propTypes = { 'aria-label': (prop_types_default()).string, onClick: (prop_types_default()).func, /** * Render different color variant for the button. * * Omitting this will render the default dark color. */ variant: prop_types_default().oneOf(['white']) }; const CloseButton_defaultProps = { 'aria-label': 'Close' }; const CloseButton = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ className, variant, ...props }, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("button", { ref: ref, type: "button", className: classnames_default()('btn-close', variant && `btn-close-${variant}`, className), ...props }, void 0, false, { fileName: CloseButton_jsxFileName, lineNumber: 30, columnNumber: 5 }, undefined)); CloseButton.displayName = 'CloseButton'; CloseButton.propTypes = CloseButton_propTypes; CloseButton.defaultProps = CloseButton_defaultProps; /* harmony default export */ const src_CloseButton = (CloseButton); ;// CONCATENATED MODULE: ./src/divWithClassName.tsx var divWithClassName_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/divWithClassName.tsx"; /* harmony default export */ const divWithClassName = (className => /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((p, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ...p, ref: ref, className: classnames_default()(p.className, className) }, void 0, false, { fileName: divWithClassName_jsxFileName, lineNumber: 6, columnNumber: 5 }, undefined))); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/camelize.js var rHyphen = /-(.)/g; function camelize(string) { return string.replace(rHyphen, function (_, chr) { return chr.toUpperCase(); }); } ;// CONCATENATED MODULE: ./src/createWithBsPrefix.tsx var createWithBsPrefix_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/createWithBsPrefix.tsx"; const pascalCase = str => str[0].toUpperCase() + camelize(str).slice(1); // TODO: emstricten & fix the typing here! `createWithBsPrefix<TElementType>...` function createWithBsPrefix(prefix, { displayName = pascalCase(prefix), Component, defaultProps } = {}) { const BsComponent = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ className, bsPrefix, as: Tag = Component || 'div', ...props }, ref) => { const resolvedPrefix = useBootstrapPrefix(bsPrefix, prefix); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Tag, { ref: ref, className: classnames_default()(className, resolvedPrefix), ...props }, void 0, false, { fileName: createWithBsPrefix_jsxFileName, lineNumber: 33, columnNumber: 9 }, this); }); BsComponent.defaultProps = defaultProps; BsComponent.displayName = displayName; return BsComponent; } ;// CONCATENATED MODULE: ./src/Alert.tsx var Alert_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Alert.tsx"; const DivStyledAsH4 = divWithClassName('h4'); DivStyledAsH4.displayName = 'DivStyledAsH4'; const AlertHeading = createWithBsPrefix('alert-heading', { Component: DivStyledAsH4 }); const AlertLink = createWithBsPrefix('alert-link', { Component: esm_Anchor }); const Alert_propTypes = { /** * @default 'alert' */ bsPrefix: (prop_types_default()).string, /** * The Alert visual variant * * @type {'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'dark' | 'light'} */ variant: (prop_types_default()).string, /** * Renders a properly aligned dismiss button, as well as * adding extra horizontal padding to the Alert. */ dismissible: (prop_types_default()).bool, /** * Controls the visual state of the Alert. * * @controllable onClose */ show: (prop_types_default()).bool, /** * Callback fired when alert is closed. * * @controllable show */ onClose: (prop_types_default()).func, /** * Sets the text for alert close button. */ closeLabel: (prop_types_default()).string, /** * Sets the variant for close button. */ closeVariant: prop_types_default().oneOf(['white']), /** * Animate the alert dismissal. Defaults to using `<Fade>` animation or use * `false` to disable. A custom `react-transition-group` Transition can also * be provided. */ transition: prop_types_default().oneOfType([(prop_types_default()).bool, lib/* elementType */.nm]) }; const Alert_defaultProps = { variant: 'primary', show: true, transition: src_Fade, closeLabel: 'Close alert' }; const Alert = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((uncontrolledProps, ref) => { const { bsPrefix, show, closeLabel, closeVariant, className, children, variant, onClose, dismissible, transition, ...props } = useUncontrolled(uncontrolledProps, { show: 'onClose' }); const prefix = useBootstrapPrefix(bsPrefix, 'alert'); const handleClose = useEventCallback(e => { if (onClose) { onClose(false, e); } }); const Transition = transition === true ? src_Fade : transition; const alert = /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { role: "alert", ...(!Transition ? props : undefined), ref: ref, className: classnames_default()(className, prefix, variant && `${prefix}-${variant}`, dismissible && `${prefix}-dismissible`), children: [dismissible && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_CloseButton, { onClick: handleClose, "aria-label": closeLabel, variant: closeVariant }, void 0, false, { fileName: Alert_jsxFileName, lineNumber: 134, columnNumber: 11 }, undefined), children] }, void 0, true, { fileName: Alert_jsxFileName, lineNumber: 122, columnNumber: 7 }, undefined); if (!Transition) return show ? alert : null; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Transition, { unmountOnExit: true, ...props, ref: undefined, in: show, children: alert }, void 0, false, { fileName: Alert_jsxFileName, lineNumber: 147, columnNumber: 7 }, undefined); }); Alert.displayName = 'Alert'; Alert.defaultProps = Alert_defaultProps; Alert.propTypes = Alert_propTypes; /* harmony default export */ const src_Alert = (Object.assign(Alert, { Link: AlertLink, Heading: AlertHeading })); ;// CONCATENATED MODULE: ./src/Anchor.tsx /* harmony default export */ const src_Anchor = (esm_Anchor); ;// CONCATENATED MODULE: ./src/Badge.tsx var Badge_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Badge.tsx"; const Badge_propTypes = { /** @default 'badge' */ bsPrefix: (prop_types_default()).string, /** * The visual style of the badge * * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'light'|'dark')} */ bg: (prop_types_default()).string, /** * Add the `pill` modifier to make badges more rounded with * some additional horizontal padding */ pill: (prop_types_default()).bool, /** * Sets badge text color * * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'light'|'dark')} */ text: (prop_types_default()).string, /** @default span */ as: (prop_types_default()).elementType }; const Badge_defaultProps = { bg: 'primary', pill: false }; const Badge = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, bg, pill, text, className, as: Component = 'span', ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'badge'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, prefix, pill && `rounded-pill`, text && `text-${text}`, bg && `bg-${bg}`) }, void 0, false, { fileName: Badge_jsxFileName, lineNumber: 58, columnNumber: 9 }, undefined); }); Badge.displayName = 'Badge'; Badge.propTypes = Badge_propTypes; Badge.defaultProps = Badge_defaultProps; /* harmony default export */ const src_Badge = (Badge); ;// CONCATENATED MODULE: ./src/BreadcrumbItem.tsx var BreadcrumbItem_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/BreadcrumbItem.tsx"; const BreadcrumbItem_propTypes = { /** * @default 'breadcrumb-item' */ bsPrefix: (prop_types_default()).string, /** * Adds a visual "active" state to a Breadcrumb * Item and disables the link. */ active: (prop_types_default()).bool, /** * `href` attribute for the inner `a` element */ href: (prop_types_default()).string, /** * You can use a custom element type for this component's inner link. */ linkAs: (prop_types_default()).elementType, /** * `title` attribute for the inner `a` element */ title: (prop_types_default()).node, /** * `target` attribute for the inner `a` element */ target: (prop_types_default()).string, /** * Additional props passed as-is to the underlying link for non-active items. */ linkProps: (prop_types_default()).object, as: (prop_types_default()).elementType }; const BreadcrumbItem_defaultProps = { active: false, linkProps: {} }; const BreadcrumbItem = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, active, children, className, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'li', linkAs: LinkComponent = esm_Anchor, linkProps, href, title, target, ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'breadcrumb-item'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(prefix, className, { active }), "aria-current": active ? 'page' : undefined, children: active ? children : /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(LinkComponent, { ...linkProps, href: href, title: title, target: target, children: children }, void 0, false, { fileName: BreadcrumbItem_jsxFileName, lineNumber: 91, columnNumber: 11 }, undefined) }, void 0, false, { fileName: BreadcrumbItem_jsxFileName, lineNumber: 82, columnNumber: 7 }, undefined); }); BreadcrumbItem.displayName = 'BreadcrumbItem'; BreadcrumbItem.propTypes = BreadcrumbItem_propTypes; BreadcrumbItem.defaultProps = BreadcrumbItem_defaultProps; /* harmony default export */ const src_BreadcrumbItem = (BreadcrumbItem); ;// CONCATENATED MODULE: ./src/Breadcrumb.tsx var Breadcrumb_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Breadcrumb.tsx"; const Breadcrumb_propTypes = { /** * @default 'breadcrumb' */ bsPrefix: (prop_types_default()).string, /** * ARIA label for the nav element * https://www.w3.org/TR/wai-aria-practices/#breadcrumb */ label: (prop_types_default()).string, /** * Additional props passed as-is to the underlying `<ol>` element */ listProps: (prop_types_default()).object, as: (prop_types_default()).elementType }; const Breadcrumb_defaultProps = { label: 'breadcrumb', listProps: {} }; const Breadcrumb = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, listProps, children, label, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'nav', ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'breadcrumb'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { "aria-label": label, className: className, ref: ref, ...props, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("ol", { ...listProps, className: classnames_default()(prefix, listProps == null ? void 0 : listProps.className), children: children }, void 0, false, { fileName: Breadcrumb_jsxFileName, lineNumber: 65, columnNumber: 11 }, undefined) }, void 0, false, { fileName: Breadcrumb_jsxFileName, lineNumber: 59, columnNumber: 9 }, undefined); }); Breadcrumb.displayName = 'Breadcrumb'; Breadcrumb.propTypes = Breadcrumb_propTypes; Breadcrumb.defaultProps = Breadcrumb_defaultProps; /* harmony default export */ const src_Breadcrumb = (Object.assign(Breadcrumb, { Item: src_BreadcrumbItem })); ;// CONCATENATED MODULE: ./src/Button.tsx var Button_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Button.tsx"; const Button_propTypes = { /** * @default 'btn' */ bsPrefix: (prop_types_default()).string, /** * One or more button variant combinations * * buttons may be one of a variety of visual variants such as: * * `'primary', 'secondary', 'success', 'danger', 'warning', 'info', 'dark', 'light', 'link'` * * as well as "outline" versions (prefixed by 'outline-*') * * `'outline-primary', 'outline-secondary', 'outline-success', 'outline-danger', 'outline-warning', 'outline-info', 'outline-dark', 'outline-light'` */ variant: (prop_types_default()).string, /** * Specifies a large or small button. * * @type ('sm'|'lg') */ size: (prop_types_default()).string, /** Manually set the visual state of the button to `:active` */ active: (prop_types_default()).bool, /** * Disables the Button, preventing mouse events, * even if the underlying component is an `<a>` element */ disabled: (prop_types_default()).bool, /** Providing a `href` will render an `<a>` element, _styled_ as a button. */ href: (prop_types_default()).string, /** * Defines HTML button type attribute. * * @default 'button' */ type: prop_types_default().oneOf(['button', 'reset', 'submit', null]), as: (prop_types_default()).elementType }; const Button_defaultProps = { variant: 'primary', active: false, disabled: false }; const Button_Button = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ as, bsPrefix, variant, size, active, className, ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'btn'); const [buttonProps, { tagName }] = useButtonProps({ tagName: as, ...props }); const Component = tagName; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ...buttonProps, ref: ref, className: classnames_default()(className, prefix, active && 'active', variant && `${prefix}-${variant}`, size && `${prefix}-${size}`, props.href && props.disabled && 'disabled') }, void 0, false, { fileName: Button_jsxFileName, lineNumber: 88, columnNumber: 9 }, undefined); }); Button_Button.displayName = 'Button'; Button_Button.propTypes = Button_propTypes; Button_Button.defaultProps = Button_defaultProps; /* harmony default export */ const src_Button = (Button_Button); ;// CONCATENATED MODULE: ./src/ButtonGroup.tsx var ButtonGroup_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ButtonGroup.tsx"; const ButtonGroup_propTypes = { /** * @default 'btn-group' */ bsPrefix: (prop_types_default()).string, /** * Sets the size for all Buttons in the group. * * @type ('sm'|'lg') */ size: (prop_types_default()).string, /** Make the set of Buttons appear vertically stacked. */ vertical: (prop_types_default()).bool, /** * An ARIA role describing the button group. Usually the default * "group" role is fine. An `aria-label` or `aria-labelledby` * prop is also recommended. */ role: (prop_types_default()).string, as: (prop_types_default()).elementType }; const ButtonGroup_defaultProps = { vertical: false, role: 'group' }; const ButtonGroup = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, size, vertical, className, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', ...rest }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'btn-group'); let baseClass = prefix; if (vertical) baseClass = `${prefix}-vertical`; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...rest, ref: ref, className: classnames_default()(className, baseClass, size && `${prefix}-${size}`) }, void 0, false, { fileName: ButtonGroup_jsxFileName, lineNumber: 66, columnNumber: 9 }, undefined); }); ButtonGroup.displayName = 'ButtonGroup'; ButtonGroup.propTypes = ButtonGroup_propTypes; ButtonGroup.defaultProps = ButtonGroup_defaultProps; /* harmony default export */ const src_ButtonGroup = (ButtonGroup); ;// CONCATENATED MODULE: ./src/ButtonToolbar.tsx var ButtonToolbar_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ButtonToolbar.tsx"; const ButtonToolbar_propTypes = { /** * @default 'btn-toolbar' */ bsPrefix: (prop_types_default()).string, /** * The ARIA role describing the button toolbar. Generally the default * "toolbar" role is correct. An `aria-label` or `aria-labelledby` * prop is also recommended. */ role: (prop_types_default()).string }; const ButtonToolbar_defaultProps = { role: 'toolbar' }; const ButtonToolbar = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'btn-toolbar'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ...props, ref: ref, className: classnames_default()(className, prefix) }, void 0, false, { fileName: ButtonToolbar_jsxFileName, lineNumber: 36, columnNumber: 7 }, undefined); }); ButtonToolbar.displayName = 'ButtonToolbar'; ButtonToolbar.propTypes = ButtonToolbar_propTypes; ButtonToolbar.defaultProps = ButtonToolbar_defaultProps; /* harmony default export */ const src_ButtonToolbar = (ButtonToolbar); ;// CONCATENATED MODULE: ./src/CardImg.tsx var CardImg_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/CardImg.tsx"; const CardImg_propTypes = { /** * @default 'card-img' */ bsPrefix: (prop_types_default()).string, /** * Defines image position inside * the card. * * @type {('top'|'bottom')} */ variant: prop_types_default().oneOf(['top', 'bottom']), as: (prop_types_default()).elementType }; const CardImg = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef( // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 ({ bsPrefix, className, variant, as: Component = 'img', ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'card-img'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, className: classnames_default()(variant ? `${prefix}-${variant}` : prefix, className), ...props }, void 0, false, { fileName: CardImg_jsxFileName, lineNumber: 47, columnNumber: 9 }, undefined); }); CardImg.displayName = 'CardImg'; CardImg.propTypes = CardImg_propTypes; /* harmony default export */ const src_CardImg = (CardImg); ;// CONCATENATED MODULE: ./src/CardHeaderContext.tsx const CardHeaderContext_context = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext(null); CardHeaderContext_context.displayName = 'CardHeaderContext'; /* harmony default export */ const CardHeaderContext = (CardHeaderContext_context); ;// CONCATENATED MODULE: ./src/CardHeader.tsx var CardHeader_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/CardHeader.tsx"; const CardHeader_propTypes = { /** * @default 'card-header' */ bsPrefix: (prop_types_default()).string, as: (prop_types_default()).elementType }; const CardHeader = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'card-header'); const contextValue = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ cardHeaderBsPrefix: prefix }), [prefix]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(CardHeaderContext.Provider, { value: contextValue, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, prefix) }, void 0, false, { fileName: CardHeader_jsxFileName, lineNumber: 45, columnNumber: 11 }, undefined) }, void 0, false, { fileName: CardHeader_jsxFileName, lineNumber: 44, columnNumber: 9 }, undefined); }); CardHeader.displayName = 'CardHeader'; CardHeader.propTypes = CardHeader_propTypes; /* harmony default export */ const src_CardHeader = (CardHeader); ;// CONCATENATED MODULE: ./src/Card.tsx var Card_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Card.tsx"; const DivStyledAsH5 = divWithClassName('h5'); const DivStyledAsH6 = divWithClassName('h6'); const CardBody = createWithBsPrefix('card-body'); const CardTitle = createWithBsPrefix('card-title', { Component: DivStyledAsH5 }); const CardSubtitle = createWithBsPrefix('card-subtitle', { Component: DivStyledAsH6 }); const CardLink = createWithBsPrefix('card-link', { Component: 'a' }); const CardText = createWithBsPrefix('card-text', { Component: 'p' }); const CardFooter = createWithBsPrefix('card-footer'); const CardImgOverlay = createWithBsPrefix('card-img-overlay'); const Card_propTypes = { /** * @default 'card' */ bsPrefix: (prop_types_default()).string, /** * Sets card background * * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'dark'|'light')} */ bg: (prop_types_default()).string, /** * Sets card text color * * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'dark'|'light'|'white'|'muted')} */ text: (prop_types_default()).string, /** * Sets card border color * * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'dark'|'light')} */ border: (prop_types_default()).string, /** * When this prop is set, it creates a Card with a Card.Body inside * passing the children directly to it */ body: (prop_types_default()).bool, as: (prop_types_default()).elementType }; const Card_defaultProps = { body: false }; const Card = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, bg, text, border, body, children, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'card'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, prefix, bg && `bg-${bg}`, text && `text-${text}`, border && `border-${border}`), children: body ? /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(CardBody, { children: children }, void 0, false, { fileName: Card_jsxFileName, lineNumber: 109, columnNumber: 17 }, undefined) : children }, void 0, false, { fileName: Card_jsxFileName, lineNumber: 98, columnNumber: 7 }, undefined); }); Card.displayName = 'Card'; Card.propTypes = Card_propTypes; Card.defaultProps = Card_defaultProps; /* harmony default export */ const src_Card = (Object.assign(Card, { Img: src_CardImg, Title: CardTitle, Subtitle: CardSubtitle, Body: CardBody, Link: CardLink, Text: CardText, Header: src_CardHeader, Footer: CardFooter, ImgOverlay: CardImgOverlay })); ;// CONCATENATED MODULE: ./src/CardGroup.tsx /* harmony default export */ const CardGroup = (createWithBsPrefix('card-group')); ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useUpdateEffect.js /** * Runs an effect only when the dependencies have changed, skipping the * initial "on mount" run. Caution, if the dependency list never changes, * the effect is **never run** * * ```ts * const ref = useRef<HTMLInput>(null); * * // focuses an element only if the focus changes, and not on mount * useUpdateEffect(() => { * const element = ref.current?.children[focusedIdx] as HTMLElement * * element?.focus() * * }, [focusedIndex]) * ``` * @param effect An effect to run on mount * * @category effects */ function useUpdateEffect(fn, deps) { var isFirst = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(true); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { if (isFirst.current) { isFirst.current = false; return; } return fn(); }, deps); } /* harmony default export */ const esm_useUpdateEffect = (useUpdateEffect); ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useMounted.js /** * Track whether a component is current mounted. Generally less preferable than * properlly canceling effects so they don't run after a component is unmounted, * but helpful in cases where that isn't feasible, such as a `Promise` resolution. * * @returns a function that returns the current isMounted state of the component * * ```ts * const [data, setData] = useState(null) * const isMounted = useMounted() * * useEffect(() => { * fetchdata().then((newData) => { * if (isMounted()) { * setData(newData); * } * }) * }) * ``` */ function useMounted_useMounted() { var mounted = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(true); var isMounted = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(function () { return mounted.current; }); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { return function () { mounted.current = false; }; }, []); return isMounted.current; } ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useUpdatedRef.js /** * Returns a ref that is immediately updated with the new value * * @param value The Ref value * @category refs */ function useUpdatedRef(value) { var valueRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(value); valueRef.current = value; return valueRef; } ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useWillUnmount.js /** * Attach a callback that fires when a component unmounts * * @param fn Handler to run when the component unmounts * @category effects */ function useWillUnmount(fn) { var onUnmount = useUpdatedRef(fn); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { return function () { return onUnmount.current(); }; }, []); } ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useTimeout.js /* * Browsers including Internet Explorer, Chrome, Safari, and Firefox store the * delay as a 32-bit signed integer internally. This causes an integer overflow * when using delays larger than 2,147,483,647 ms (about 24.8 days), * resulting in the timeout being executed immediately. * * via: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout */ var MAX_DELAY_MS = Math.pow(2, 31) - 1; function setChainedTimeout(handleRef, fn, timeoutAtMs) { var delayMs = timeoutAtMs - Date.now(); handleRef.current = delayMs <= MAX_DELAY_MS ? setTimeout(fn, delayMs) : setTimeout(function () { return setChainedTimeout(handleRef, fn, timeoutAtMs); }, MAX_DELAY_MS); } /** * Returns a controller object for setting a timeout that is properly cleaned up * once the component unmounts. New timeouts cancel and replace existing ones. * * * * ```tsx * const { set, clear } = useTimeout(); * const [hello, showHello] = useState(false); * //Display hello after 5 seconds * set(() => showHello(true), 5000); * return ( * <div className="App"> * {hello ? <h3>Hello</h3> : null} * </div> * ); * ``` */ function useTimeout() { var isMounted = useMounted_useMounted(); // types are confused between node and web here IDK var handleRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(); useWillUnmount(function () { return clearTimeout(handleRef.current); }); return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(function () { var clear = function clear() { return clearTimeout(handleRef.current); }; function set(fn, delayMs) { if (delayMs === void 0) { delayMs = 0; } if (!isMounted()) return; clear(); if (delayMs <= MAX_DELAY_MS) { // For simplicity, if the timeout is short, just set a normal timeout. handleRef.current = setTimeout(fn, delayMs); } else { setChainedTimeout(handleRef, fn, Date.now() + delayMs); } } return { set: set, clear: clear }; }, []); } ;// CONCATENATED MODULE: ./src/CarouselCaption.tsx /* harmony default export */ const CarouselCaption = (createWithBsPrefix('carousel-caption')); ;// CONCATENATED MODULE: ./src/CarouselItem.tsx var CarouselItem_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/CarouselItem.tsx"; const CarouselItem_propTypes = { /** Set a custom element for this component */ as: (prop_types_default()).elementType, /** @default 'carousel-item' */ bsPrefix: (prop_types_default()).string, /** The amount of time to delay between automatically cycling this specific item. Will default to the Carousel's `interval` prop value if none is specified. */ interval: (prop_types_default()).number }; const CarouselItem = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', bsPrefix, className, ...props }, ref) => { const finalClassName = classnames_default()(className, useBootstrapPrefix(bsPrefix, 'carousel-item')); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: finalClassName }, void 0, false, { fileName: CarouselItem_jsxFileName, lineNumber: 40, columnNumber: 14 }, undefined); }); CarouselItem.displayName = 'CarouselItem'; CarouselItem.propTypes = CarouselItem_propTypes; /* harmony default export */ const src_CarouselItem = (CarouselItem); ;// CONCATENATED MODULE: ./src/ElementChildren.tsx /** * Iterates through children that are typically specified as `props.children`, * but only maps over children that are "valid elements". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * */ function map(children, func) { let index = 0; return external_root_React_commonjs2_react_commonjs_react_amd_react_.Children.map(children, child => /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.isValidElement(child) ? func(child, index++) : child); } /** * Iterates through children that are "valid elements". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". */ function forEach(children, func) { let index = 0; external_root_React_commonjs2_react_commonjs_react_amd_react_.Children.forEach(children, child => { if ( /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.isValidElement(child)) func(child, index++); }); } /** * Finds whether a component's `children` prop includes a React element of the * specified type. */ function hasChildOfType(children, type) { return external_root_React_commonjs2_react_commonjs_react_amd_react_.Children.toArray(children).some(child => /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.isValidElement(child) && child.type === type); } ;// CONCATENATED MODULE: ./src/Carousel.tsx var Carousel_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Carousel.tsx"; const SWIPE_THRESHOLD = 40; const Carousel_propTypes = { /** * @default 'carousel' */ bsPrefix: (prop_types_default()).string, as: (prop_types_default()).elementType, /** * Enables animation on the Carousel as it transitions between slides. */ slide: (prop_types_default()).bool, /** Animates slides with a crossfade animation instead of the default slide animation */ fade: (prop_types_default()).bool, /** * Show the Carousel previous and next arrows for changing the current slide */ controls: (prop_types_default()).bool, /** * Show a set of slide position indicators */ indicators: (prop_types_default()).bool, /** * An array of labels for the indicators. Defaults to "Slide #" if not provided. */ indicatorLabels: (prop_types_default()).array, /** * Controls the current visible slide * * @controllable onSelect */ activeIndex: (prop_types_default()).number, /** * Callback fired when the active item changes. * * ```js * (eventKey: number, event: Object | null) => void * ``` * * @controllable activeIndex */ onSelect: (prop_types_default()).func, /** * Callback fired when a slide transition starts. * * ```js * (eventKey: number, direction: 'left' | 'right') => void */ onSlide: (prop_types_default()).func, /** * Callback fired when a slide transition ends. * * ```js * (eventKey: number, direction: 'left' | 'right') => void */ onSlid: (prop_types_default()).func, /** * The amount of time to delay between automatically cycling an item. If `null`, carousel will not automatically cycle. */ interval: (prop_types_default()).number, /** Whether the carousel should react to keyboard events. */ keyboard: (prop_types_default()).bool, /** * If set to `"hover"`, pauses the cycling of the carousel on `mouseenter` and resumes the cycling of the carousel on `mouseleave`. If set to `false`, hovering over the carousel won't pause it. * * On touch-enabled devices, when set to `"hover"`, cycling will pause on `touchend` (once the user finished interacting with the carousel) for two intervals, before automatically resuming. Note that this is in addition to the above mouse behavior. */ pause: prop_types_default().oneOf(['hover', false]), /** Whether the carousel should cycle continuously or have hard stops. */ wrap: (prop_types_default()).bool, /** * Whether the carousel should support left/right swipe interactions on touchscreen devices. */ touch: (prop_types_default()).bool, /** Override the default button icon for the "previous" control */ prevIcon: (prop_types_default()).node, /** * Label shown to screen readers only, can be used to show the previous element * in the carousel. * Set to null to deactivate. */ prevLabel: (prop_types_default()).string, /** Override the default button icon for the "next" control */ nextIcon: (prop_types_default()).node, /** * Label shown to screen readers only, can be used to show the next element * in the carousel. * Set to null to deactivate. */ nextLabel: (prop_types_default()).string, /** * Color variant that controls the colors of the controls, indicators * and captions. */ variant: prop_types_default().oneOf(['dark']) }; const Carousel_defaultProps = { slide: true, fade: false, controls: true, indicators: true, indicatorLabels: [], defaultActiveIndex: 0, interval: 5000, keyboard: true, pause: 'hover', wrap: true, touch: true, prevIcon: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { "aria-hidden": "true", className: "carousel-control-prev-icon" }, void 0, false, { fileName: Carousel_jsxFileName, lineNumber: 191, columnNumber: 13 }, undefined), prevLabel: 'Previous', nextIcon: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { "aria-hidden": "true", className: "carousel-control-next-icon" }, void 0, false, { fileName: Carousel_jsxFileName, lineNumber: 194, columnNumber: 13 }, undefined), nextLabel: 'Next' }; function isVisible(element) { if (!element || !element.style || !element.parentNode || !element.parentNode.style) { return false; } const elementStyle = getComputedStyle(element); return elementStyle.display !== 'none' && elementStyle.visibility !== 'hidden' && getComputedStyle(element.parentNode).display !== 'none'; } const Carousel = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((uncontrolledProps, ref) => { const { // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', bsPrefix, slide, fade, controls, indicators, indicatorLabels, activeIndex, onSelect, onSlide, onSlid, interval, keyboard, onKeyDown, pause, onMouseOver, onMouseOut, wrap, touch, onTouchStart, onTouchMove, onTouchEnd, prevIcon, prevLabel, nextIcon, nextLabel, variant, className, children, ...props } = useUncontrolled(uncontrolledProps, { activeIndex: 'onSelect' }); const prefix = useBootstrapPrefix(bsPrefix, 'carousel'); const isRTL = useIsRTL(); const nextDirectionRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); const [direction, setDirection] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)('next'); const [paused, setPaused] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(false); const [isSliding, setIsSliding] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(false); const [renderedActiveIndex, setRenderedActiveIndex] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(activeIndex || 0); if (!isSliding && activeIndex !== renderedActiveIndex) { if (nextDirectionRef.current) { setDirection(nextDirectionRef.current); } else { setDirection((activeIndex || 0) > renderedActiveIndex ? 'next' : 'prev'); } if (slide) { setIsSliding(true); } setRenderedActiveIndex(activeIndex || 0); } (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (nextDirectionRef.current) { nextDirectionRef.current = null; } }); let numChildren = 0; let activeChildInterval; // Iterate to grab all of the children's interval values // (and count them, too) forEach(children, (child, index) => { ++numChildren; if (index === activeIndex) { activeChildInterval = child.props.interval; } }); const activeChildIntervalRef = esm_useCommittedRef(activeChildInterval); const prev = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(event => { if (isSliding) { return; } let nextActiveIndex = renderedActiveIndex - 1; if (nextActiveIndex < 0) { if (!wrap) { return; } nextActiveIndex = numChildren - 1; } nextDirectionRef.current = 'prev'; onSelect == null ? void 0 : onSelect(nextActiveIndex, event); }, [isSliding, renderedActiveIndex, onSelect, wrap, numChildren]); // This is used in the setInterval, so it should not invalidate. const next = useEventCallback(event => { if (isSliding) { return; } let nextActiveIndex = renderedActiveIndex + 1; if (nextActiveIndex >= numChildren) { if (!wrap) { return; } nextActiveIndex = 0; } nextDirectionRef.current = 'next'; onSelect == null ? void 0 : onSelect(nextActiveIndex, event); }); const elementRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useImperativeHandle)(ref, () => ({ element: elementRef.current, prev, next })); // This is used in the setInterval, so it should not invalidate. const nextWhenVisible = useEventCallback(() => { if (!document.hidden && isVisible(elementRef.current)) { if (isRTL) { prev(); } else { next(); } } }); const slideDirection = direction === 'next' ? 'start' : 'end'; esm_useUpdateEffect(() => { if (slide) { // These callbacks will be handled by the <Transition> callbacks. return; } onSlide == null ? void 0 : onSlide(renderedActiveIndex, slideDirection); onSlid == null ? void 0 : onSlid(renderedActiveIndex, slideDirection); }, [renderedActiveIndex]); const orderClassName = `${prefix}-item-${direction}`; const directionalClassName = `${prefix}-item-${slideDirection}`; const handleEnter = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(node => { triggerBrowserReflow(node); onSlide == null ? void 0 : onSlide(renderedActiveIndex, slideDirection); }, [onSlide, renderedActiveIndex, slideDirection]); const handleEntered = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(() => { setIsSliding(false); onSlid == null ? void 0 : onSlid(renderedActiveIndex, slideDirection); }, [onSlid, renderedActiveIndex, slideDirection]); const handleKeyDown = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(event => { if (keyboard && !/input|textarea/i.test(event.target.tagName)) { switch (event.key) { case 'ArrowLeft': event.preventDefault(); if (isRTL) { next(event); } else { prev(event); } return; case 'ArrowRight': event.preventDefault(); if (isRTL) { prev(event); } else { next(event); } return; default: } } onKeyDown == null ? void 0 : onKeyDown(event); }, [keyboard, onKeyDown, prev, next, isRTL]); const handleMouseOver = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(event => { if (pause === 'hover') { setPaused(true); } onMouseOver == null ? void 0 : onMouseOver(event); }, [pause, onMouseOver]); const handleMouseOut = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(event => { setPaused(false); onMouseOut == null ? void 0 : onMouseOut(event); }, [onMouseOut]); const touchStartXRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(0); const touchDeltaXRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(0); const touchUnpauseTimeout = useTimeout(); const handleTouchStart = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(event => { touchStartXRef.current = event.touches[0].clientX; touchDeltaXRef.current = 0; if (pause === 'hover') { setPaused(true); } onTouchStart == null ? void 0 : onTouchStart(event); }, [pause, onTouchStart]); const handleTouchMove = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(event => { if (event.touches && event.touches.length > 1) { touchDeltaXRef.current = 0; } else { touchDeltaXRef.current = event.touches[0].clientX - touchStartXRef.current; } onTouchMove == null ? void 0 : onTouchMove(event); }, [onTouchMove]); const handleTouchEnd = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(event => { if (touch) { const touchDeltaX = touchDeltaXRef.current; if (Math.abs(touchDeltaX) > SWIPE_THRESHOLD) { if (touchDeltaX > 0) { prev(event); } else { next(event); } } } if (pause === 'hover') { touchUnpauseTimeout.set(() => { setPaused(false); }, interval || undefined); } onTouchEnd == null ? void 0 : onTouchEnd(event); }, [touch, pause, prev, next, touchUnpauseTimeout, interval, onTouchEnd]); const shouldPlay = interval != null && !paused && !isSliding; const intervalHandleRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { var _ref, _activeChildIntervalR; if (!shouldPlay) { return undefined; } const nextFunc = isRTL ? prev : next; intervalHandleRef.current = window.setInterval(document.visibilityState ? nextWhenVisible : nextFunc, (_ref = (_activeChildIntervalR = activeChildIntervalRef.current) != null ? _activeChildIntervalR : interval) != null ? _ref : undefined); return () => { if (intervalHandleRef.current !== null) { clearInterval(intervalHandleRef.current); } }; }, [shouldPlay, prev, next, activeChildIntervalRef, interval, nextWhenVisible, isRTL]); const indicatorOnClicks = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => indicators && Array.from({ length: numChildren }, (_, index) => event => { onSelect == null ? void 0 : onSelect(index, event); }), [indicators, numChildren, onSelect]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: elementRef, ...props, onKeyDown: handleKeyDown, onMouseOver: handleMouseOver, onMouseOut: handleMouseOut, onTouchStart: handleTouchStart, onTouchMove: handleTouchMove, onTouchEnd: handleTouchEnd, className: classnames_default()(className, prefix, slide && 'slide', fade && `${prefix}-fade`, variant && `${prefix}-${variant}`), children: [indicators && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { className: `${prefix}-indicators`, children: map(children, (_, index) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("button", { type: "button", "data-bs-target": "" // Bootstrap requires this in their css. , "aria-label": indicatorLabels != null && indicatorLabels.length ? indicatorLabels[index] : `Slide ${index + 1}`, className: index === renderedActiveIndex ? 'active' : undefined, onClick: indicatorOnClicks ? indicatorOnClicks[index] : undefined, "aria-current": index === renderedActiveIndex }, index, false, { fileName: Carousel_jsxFileName, lineNumber: 558, columnNumber: 15 }, undefined)) }, void 0, false, { fileName: Carousel_jsxFileName, lineNumber: 556, columnNumber: 11 }, undefined), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { className: `${prefix}-inner`, children: map(children, (child, index) => { const isActive = index === renderedActiveIndex; return slide ? /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_TransitionWrapper, { in: isActive, onEnter: isActive ? handleEnter : undefined, onEntered: isActive ? handleEntered : undefined, addEndListener: transitionEndListener, children: (status, innerProps) => /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement(child, { ...innerProps, className: classnames_default()(child.props.className, isActive && status !== 'entered' && orderClassName, (status === 'entered' || status === 'exiting') && 'active', (status === 'entering' || status === 'exiting') && directionalClassName) }) }, void 0, false, { fileName: Carousel_jsxFileName, lineNumber: 582, columnNumber: 15 }, undefined) : /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement(child, { className: classnames_default()(child.props.className, isActive && 'active') }); }) }, void 0, false, { fileName: Carousel_jsxFileName, lineNumber: 577, columnNumber: 9 }, undefined), controls && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(jsx_dev_runtime.Fragment, { children: [(wrap || activeIndex !== 0) && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Anchor, { className: `${prefix}-control-prev`, onClick: prev, children: [prevIcon, prevLabel && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { className: "visually-hidden", children: prevLabel }, void 0, false, { fileName: Carousel_jsxFileName, lineNumber: 622, columnNumber: 19 }, undefined)] }, void 0, true, { fileName: Carousel_jsxFileName, lineNumber: 619, columnNumber: 15 }, undefined), (wrap || activeIndex !== numChildren - 1) && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Anchor, { className: `${prefix}-control-next`, onClick: next, children: [nextIcon, nextLabel && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { className: "visually-hidden", children: nextLabel }, void 0, false, { fileName: Carousel_jsxFileName, lineNumber: 630, columnNumber: 19 }, undefined)] }, void 0, true, { fileName: Carousel_jsxFileName, lineNumber: 627, columnNumber: 15 }, undefined)] }, void 0, true)] }, void 0, true, { fileName: Carousel_jsxFileName, lineNumber: 538, columnNumber: 7 }, undefined); }); Carousel.displayName = 'Carousel'; Carousel.propTypes = Carousel_propTypes; Carousel.defaultProps = Carousel_defaultProps; /* harmony default export */ const src_Carousel = (Object.assign(Carousel, { Caption: CarouselCaption, Item: src_CarouselItem })); ;// CONCATENATED MODULE: ./src/Col.tsx var Col_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Col.tsx"; const DEVICE_SIZES = ['xxl', 'xl', 'lg', 'md', 'sm', 'xs']; const colSize = prop_types_default().oneOfType([(prop_types_default()).bool, (prop_types_default()).number, (prop_types_default()).string, prop_types_default().oneOf(['auto'])]); const stringOrNumber = prop_types_default().oneOfType([(prop_types_default()).number, (prop_types_default()).string]); const column = prop_types_default().oneOfType([colSize, prop_types_default().shape({ size: colSize, order: stringOrNumber, offset: stringOrNumber })]); const Col_propTypes = { /** * @default 'col' */ bsPrefix: (prop_types_default()).string, as: (prop_types_default()).elementType, /** * The number of columns to span on extra small devices (<576px) * * @type {(boolean|"auto"|number|{ span: boolean|"auto"|number, offset: number, order: "first"|"last"|number })} */ xs: column, /** * The number of columns to span on small devices (≥576px) * * @type {(boolean|"auto"|number|{ span: boolean|"auto"|number, offset: number, order: "first"|"last"|number })} */ sm: column, /** * The number of columns to span on medium devices (≥768px) * * @type {(boolean|"auto"|number|{ span: boolean|"auto"|number, offset: number, order: "first"|"last"|number })} */ md: column, /** * The number of columns to span on large devices (≥992px) * * @type {(boolean|"auto"|number|{ span: boolean|"auto"|number, offset: number, order: "first"|"last"|number })} */ lg: column, /** * The number of columns to span on extra large devices (≥1200px) * * @type {(boolean|"auto"|number|{ span: boolean|"auto"|number, offset: number, order: "first"|"last"|number })} */ xl: column, /** * The number of columns to span on extra extra large devices (≥1400px) * * @type {(boolean|"auto"|number|{ span: boolean|"auto"|number, offset: number, order: "first"|"last"|number })} */ xxl: column }; function useCol({ as, bsPrefix, className, ...props }) { bsPrefix = useBootstrapPrefix(bsPrefix, 'col'); const spans = []; const classes = []; DEVICE_SIZES.forEach(brkPoint => { const propValue = props[brkPoint]; delete props[brkPoint]; let span; let offset; let order; if (typeof propValue === 'object' && propValue != null) { ({ span, offset, order } = propValue); } else { span = propValue; } const infix = brkPoint !== 'xs' ? `-${brkPoint}` : ''; if (span) spans.push(span === true ? `${bsPrefix}${infix}` : `${bsPrefix}${infix}-${span}`); if (order != null) classes.push(`order${infix}-${order}`); if (offset != null) classes.push(`offset${infix}-${offset}`); }); return [{ ...props, className: classnames_default()(className, ...spans, ...classes) }, { as, bsPrefix, spans }]; } const Col = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef( // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 (props, ref) => { const [{ className, ...colProps }, { as: Component = 'div', bsPrefix, spans }] = useCol(props); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...colProps, ref: ref, className: classnames_default()(className, !spans.length && bsPrefix) }, void 0, false, { fileName: Col_jsxFileName, lineNumber: 178, columnNumber: 7 }, undefined); }); Col.displayName = 'Col'; Col.propTypes = Col_propTypes; /* harmony default export */ const src_Col = (Col); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/querySelectorAll.js var toArray = Function.prototype.bind.call(Function.prototype.call, [].slice); /** * Runs `querySelectorAll` on a given element. * * @param element the element * @param selector the selector */ function qsa(element, selector) { return toArray(element.querySelectorAll(selector)); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useForceUpdate.js /** * Returns a function that triggers a component update. the hook equivalent to * `this.forceUpdate()` in a class component. In most cases using a state value directly * is preferable but may be required in some advanced usages of refs for interop or * when direct DOM manipulation is required. * * ```ts * const forceUpdate = useForceUpdate(); * * const updateOnClick = useCallback(() => { * forceUpdate() * }, [forceUpdate]) * * return <button type="button" onClick={updateOnClick}>Hi there</button> * ``` */ function useForceUpdate() { // The toggling state value is designed to defeat React optimizations for skipping // updates when they are stricting equal to the last state value var _useReducer = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useReducer)(function (state) { return !state; }, false), dispatch = _useReducer[1]; return dispatch; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/DropdownContext.js const DropdownContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext(null); /* harmony default export */ const esm_DropdownContext = (DropdownContext); ;// CONCATENATED MODULE: ./node_modules/dequal/dist/index.mjs var has = Object.prototype.hasOwnProperty; function find(iter, tar, key) { for (key of iter.keys()) { if (dequal(key, tar)) return key; } } function dequal(foo, bar) { var ctor, len, tmp; if (foo === bar) return true; if (foo && bar && (ctor=foo.constructor) === bar.constructor) { if (ctor === Date) return foo.getTime() === bar.getTime(); if (ctor === RegExp) return foo.toString() === bar.toString(); if (ctor === Array) { if ((len=foo.length) === bar.length) { while (len-- && dequal(foo[len], bar[len])); } return len === -1; } if (ctor === Set) { if (foo.size !== bar.size) { return false; } for (len of foo) { tmp = len; if (tmp && typeof tmp === 'object') { tmp = find(bar, tmp); if (!tmp) return false; } if (!bar.has(tmp)) return false; } return true; } if (ctor === Map) { if (foo.size !== bar.size) { return false; } for (len of foo) { tmp = len[0]; if (tmp && typeof tmp === 'object') { tmp = find(bar, tmp); if (!tmp) return false; } if (!dequal(len[1], bar.get(tmp))) { return false; } } return true; } if (ctor === ArrayBuffer) { foo = new Uint8Array(foo); bar = new Uint8Array(bar); } else if (ctor === DataView) { if ((len=foo.byteLength) === bar.byteLength) { while (len-- && foo.getInt8(len) === bar.getInt8(len)); } return len === -1; } if (ArrayBuffer.isView(foo)) { if ((len=foo.byteLength) === bar.byteLength) { while (len-- && foo[len] === bar[len]); } return len === -1; } if (!ctor || typeof foo === 'object') { len = 0; for (ctor in foo) { if (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false; if (!(ctor in bar) || !dequal(foo[ctor], bar[ctor])) return false; } return Object.keys(bar).length === len; } } return foo !== foo && bar !== bar; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useSafeState.js function useSafeState(state) { var isMounted = useMounted(); return [state[0], (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(function (nextState) { if (!isMounted()) return; return state[1](nextState); }, [isMounted, state[1]])]; } /* harmony default export */ const esm_useSafeState = (useSafeState); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getBasePlacement.js function getBasePlacement(placement) { return placement.split('-')[0]; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindow.js function getWindow(node) { if (node == null) { return window; } if (node.toString() !== '[object Window]') { var ownerDocument = node.ownerDocument; return ownerDocument ? ownerDocument.defaultView || window : window; } return node; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/instanceOf.js function isElement(node) { var OwnElement = getWindow(node).Element; return node instanceof OwnElement || node instanceof Element; } function isHTMLElement(node) { var OwnElement = getWindow(node).HTMLElement; return node instanceof OwnElement || node instanceof HTMLElement; } function isShadowRoot(node) { // IE 11 has no ShadowRoot if (typeof ShadowRoot === 'undefined') { return false; } var OwnElement = getWindow(node).ShadowRoot; return node instanceof OwnElement || node instanceof ShadowRoot; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js var round = Math.round; function getBoundingClientRect(element, includeScale) { if (includeScale === void 0) { includeScale = false; } var rect = element.getBoundingClientRect(); var scaleX = 1; var scaleY = 1; if (isHTMLElement(element) && includeScale) { var offsetHeight = element.offsetHeight; var offsetWidth = element.offsetWidth; // Do not attempt to divide by 0, otherwise we get `Infinity` as scale // Fallback to 1 in case both values are `0` if (offsetWidth > 0) { scaleX = rect.width / offsetWidth || 1; } if (offsetHeight > 0) { scaleY = rect.height / offsetHeight || 1; } } return { width: round(rect.width / scaleX), height: round(rect.height / scaleY), top: round(rect.top / scaleY), right: round(rect.right / scaleX), bottom: round(rect.bottom / scaleY), left: round(rect.left / scaleX), x: round(rect.left / scaleX), y: round(rect.top / scaleY) }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js // Returns the layout rect of an element relative to its offsetParent. Layout // means it doesn't take into account transforms. function getLayoutRect(element) { var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed. // Fixes https://github.com/popperjs/popper-core/issues/1223 var width = element.offsetWidth; var height = element.offsetHeight; if (Math.abs(clientRect.width - width) <= 1) { width = clientRect.width; } if (Math.abs(clientRect.height - height) <= 1) { height = clientRect.height; } return { x: element.offsetLeft, y: element.offsetTop, width: width, height: height }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/contains.js 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; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getNodeName.js function getNodeName(element) { return element ? (element.nodeName || '').toLowerCase() : null; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js function dom_utils_getComputedStyle_getComputedStyle(element) { return getWindow(element).getComputedStyle(element); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/isTableElement.js function isTableElement(element) { return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js function getDocumentElement(element) { // $FlowFixMe[incompatible-return]: assume body is always available return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing] element.document) || window.document).documentElement; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getParentNode.js 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 isShadowRoot(element) ? element.host : null) || // ShadowRoot detected // $FlowFixMe[incompatible-call]: HTMLElement is a Node getDocumentElement(element) // fallback ); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js function getTrueOffsetParent(element) { if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837 dom_utils_getComputedStyle_getComputedStyle(element).position === 'fixed') { return null; } return element.offsetParent; } // `.offsetParent` reports `null` for fixed elements, while absolute elements // return the containing block function getContainingBlock(element) { var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1; var isIE = navigator.userAgent.indexOf('Trident') !== -1; if (isIE && isHTMLElement(element)) { // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport var elementCss = dom_utils_getComputedStyle_getComputedStyle(element); if (elementCss.position === 'fixed') { return null; } } var currentNode = getParentNode(element); while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) { var css = dom_utils_getComputedStyle_getComputedStyle(currentNode); // This is non-exhaustive but covers the most common CSS properties that // create a containing block. // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') { 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) && dom_utils_getComputedStyle_getComputedStyle(offsetParent).position === 'static') { offsetParent = getTrueOffsetParent(offsetParent); } if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && dom_utils_getComputedStyle_getComputedStyle(offsetParent).position === 'static')) { return window; } return offsetParent || getContainingBlock(element) || window; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js function getMainAxisFromPlacement(placement) { return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y'; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/math.js var math_max = Math.max; var math_min = Math.min; var math_round = Math.round; ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/within.js function within(min, value, max) { return math_max(min, math_min(value, max)); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getFreshSideObject.js function getFreshSideObject() { return { top: 0, right: 0, bottom: 0, left: 0 }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/mergePaddingObject.js function mergePaddingObject(paddingObject) { return Object.assign({}, getFreshSideObject(), paddingObject); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/expandToHashMap.js function expandToHashMap(value, keys) { return keys.reduce(function (hashMap, key) { hashMap[key] = value; return hashMap; }, {}); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/enums.js var enums_top = 'top'; var bottom = 'bottom'; var right = 'right'; var left = 'left'; var auto = 'auto'; var basePlacements = [enums_top, bottom, right, left]; var start = 'start'; var end = 'end'; var clippingParents = 'clippingParents'; var viewport = 'viewport'; var popper = 'popper'; var reference = 'reference'; var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) { return acc.concat([placement + "-" + start, placement + "-" + end]); }, []); var enums_placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) { return acc.concat([placement, placement + "-" + start, placement + "-" + end]); }, []); // modifiers that need to read the DOM 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]; ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/arrow.js // eslint-disable-next-line import/no-unused-modules var toPaddingObject = function toPaddingObject(padding, state) { padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, { placement: state.placement })) : padding; return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); }; function arrow(_ref) { var _state$modifiersData$; var state = _ref.state, name = _ref.name, options = _ref.options; var arrowElement = state.elements.arrow; var popperOffsets = state.modifiersData.popperOffsets; var basePlacement = getBasePlacement(state.placement); var axis = getMainAxisFromPlacement(basePlacement); var isVertical = [left, right].indexOf(basePlacement) >= 0; var len = isVertical ? 'height' : 'width'; if (!arrowElement || !popperOffsets) { return; } var paddingObject = toPaddingObject(options.padding, state); var arrowRect = getLayoutRect(arrowElement); var minProp = axis === 'y' ? enums_top : left; var maxProp = axis === 'y' ? bottom : right; var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len]; var startDiff = popperOffsets[axis] - state.rects.reference[axis]; var arrowOffsetParent = getOffsetParent(arrowElement); var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is // outside of the popper bounds var min = paddingObject[minProp]; var max = clientSize - arrowRect[len] - paddingObject[maxProp]; var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; var offset = within(min, center, max); // Prevents breaking syntax highlighting... var axisProp = axis; state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$); } function effect(_ref2) { var state = _ref2.state, options = _ref2.options; var _options$element = options.element, arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element; if (arrowElement == null) { return; } // CSS selector if (typeof arrowElement === 'string') { arrowElement = state.elements.popper.querySelector(arrowElement); if (!arrowElement) { return; } } if (false) {} if (!contains(state.elements.popper, arrowElement)) { if (false) {} return; } state.elements.arrow = arrowElement; } // eslint-disable-next-line import/no-unused-modules /* harmony default export */ const modifiers_arrow = ({ name: 'arrow', enabled: true, phase: 'main', fn: arrow, effect: effect, requires: ['popperOffsets'], requiresIfExists: ['preventOverflow'] }); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getVariation.js function getVariation(placement) { return placement.split('-')[1]; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/computeStyles.js // eslint-disable-next-line import/no-unused-modules 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: math_round(math_round(x * dpr) / dpr) || 0, y: math_round(math_round(y * dpr) / dpr) || 0 }; } function mapToStyles(_ref2) { var _Object$assign2; var popper = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, 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 = enums_top; var win = window; if (adaptive) { var offsetParent = getOffsetParent(popper); var heightProp = 'clientHeight'; var widthProp = 'clientWidth'; if (offsetParent === getWindow(popper)) { offsetParent = getDocumentElement(popper); if (dom_utils_getComputedStyle_getComputedStyle(offsetParent).position !== 'static' && position === 'absolute') { heightProp = 'scrollHeight'; widthProp = 'scrollWidth'; } } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it offsetParent = offsetParent; if (placement === enums_top || (placement === left || placement === right) && variation === end) { sideY = bottom; // $FlowFixMe[prop-missing] y -= offsetParent[heightProp] - popperRect.height; y *= gpuAcceleration ? 1 : -1; } if (placement === left || (placement === enums_top || placement === bottom) && variation === end) { sideX = right; // $FlowFixMe[prop-missing] x -= offsetParent[widthProp] - popperRect.width; x *= gpuAcceleration ? 1 : -1; } } var commonStyles = Object.assign({ position: position }, adaptive && unsetSides); if (gpuAcceleration) { var _Object$assign; return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); } return 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 (false) { var transitionProperty; } var commonStyles = { placement: getBasePlacement(state.placement), variation: getVariation(state.placement), popper: state.elements.popper, popperRect: state.rects.popper, gpuAcceleration: gpuAcceleration }; if (state.modifiersData.popperOffsets != null) { state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(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({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { offsets: state.modifiersData.arrow, position: 'absolute', adaptive: false, roundOffsets: roundOffsets }))); } state.attributes.popper = Object.assign({}, state.attributes.popper, { 'data-popper-placement': state.placement }); } // eslint-disable-next-line import/no-unused-modules /* harmony default export */ const modifiers_computeStyles = ({ name: 'computeStyles', enabled: true, phase: 'beforeWrite', fn: computeStyles, data: {} }); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/eventListeners.js // eslint-disable-next-line import/no-unused-modules var passive = { passive: true }; function eventListeners_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 /* harmony default export */ const eventListeners = ({ name: 'eventListeners', enabled: true, phase: 'write', fn: function fn() {}, effect: eventListeners_effect, data: {} }); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getOppositePlacement.js var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; function getOppositePlacement(placement) { return placement.replace(/left|right|bottom|top/g, function (matched) { return hash[matched]; }); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js var getOppositeVariationPlacement_hash = { start: 'end', end: 'start' }; function getOppositeVariationPlacement(placement) { return placement.replace(/start|end/g, function (matched) { return getOppositeVariationPlacement_hash[matched]; }); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js function getWindowScroll(node) { var win = getWindow(node); var scrollLeft = win.pageXOffset; var scrollTop = win.pageYOffset; return { scrollLeft: scrollLeft, scrollTop: scrollTop }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js 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; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js 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 }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js // Gets the entire size of the scrollable document area, even extending outside // of the `<html>` and `<body>` rect bounds if horizontally scrollable function getDocumentRect(element) { var _element$ownerDocumen; var html = getDocumentElement(element); var winScroll = getWindowScroll(element); var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.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 (dom_utils_getComputedStyle_getComputedStyle(body || html).direction === 'rtl') { x += math_max(html.clientWidth, body ? body.clientWidth : 0) - width; } return { width: width, height: height, x: x, y: y }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js function isScrollParent(element) { // Firefox wants us to check `-x` and `-y` variations as well var _getComputedStyle = dom_utils_getComputedStyle_getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY; return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js 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)); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js /* 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) { var _element$ownerDocumen; if (list === void 0) { list = []; } var scrollParent = getScrollParent(element); var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.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))); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/rectToClientRect.js function rectToClientRect(rect) { return Object.assign({}, rect, { left: rect.x, top: rect.y, right: rect.x + rect.width, bottom: rect.y + rect.height }); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js 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(dom_utils_getComputedStyle_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; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/computeOffsets.js 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 enums_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; default: } } return offsets; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/detectOverflow.js // eslint-disable-next-line import/no-unused-modules 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 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(state.elements.reference); var popperOffsets = computeOffsets({ reference: referenceClientRect, element: popperRect, strategy: 'absolute', placement: placement }); var popperClientRect = rectToClientRect(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 = [enums_top, bottom].indexOf(key) >= 0 ? 'y' : 'x'; overflowOffsets[key] += offset[axis] * multiply; }); } return overflowOffsets; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js function computeAutoPlacement(state, options) { if (options === void 0) { options = {}; } var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? enums_placements : _options$allowedAutoP; var variation = getVariation(placement); var placements = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) { return getVariation(placement) === variation; }) : basePlacements; var allowedPlacements = placements.filter(function (placement) { return allowedAutoPlacements.indexOf(placement) >= 0; }); if (allowedPlacements.length === 0) { allowedPlacements = placements; if (false) {} } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions... var overflows = allowedPlacements.reduce(function (acc, placement) { acc[placement] = detectOverflow(state, { placement: placement, boundary: boundary, rootBoundary: rootBoundary, padding: padding })[getBasePlacement(placement)]; return acc; }, {}); return Object.keys(overflows).sort(function (a, b) { return overflows[a] - overflows[b]; }); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/flip.js // eslint-disable-next-line import/no-unused-modules function getExpandedFallbackPlacements(placement) { if (getBasePlacement(placement) === auto) { return []; } var oppositePlacement = getOppositePlacement(placement); return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; } function flip(_ref) { var state = _ref.state, options = _ref.options, name = _ref.name; if (state.modifiersData[name]._skip) { return; } var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements; var preferredPlacement = state.options.placement; var basePlacement = getBasePlacement(preferredPlacement); var isBasePlacement = basePlacement === preferredPlacement; var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) { return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, { placement: placement, boundary: boundary, rootBoundary: rootBoundary, padding: padding, flipVariations: flipVariations, allowedAutoPlacements: allowedAutoPlacements }) : placement); }, []); var referenceRect = state.rects.reference; var popperRect = state.rects.popper; var checksMap = new Map(); var makeFallbackChecks = true; var firstFittingPlacement = placements[0]; for (var i = 0; i < placements.length; i++) { var placement = placements[i]; var _basePlacement = getBasePlacement(placement); var isStartVariation = getVariation(placement) === start; var isVertical = [enums_top, bottom].indexOf(_basePlacement) >= 0; var len = isVertical ? 'width' : 'height'; var overflow = detectOverflow(state, { placement: placement, boundary: boundary, rootBoundary: rootBoundary, altBoundary: altBoundary, padding: padding }); var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : enums_top; if (referenceRect[len] > popperRect[len]) { mainVariationSide = getOppositePlacement(mainVariationSide); } var altVariationSide = getOppositePlacement(mainVariationSide); var checks = []; if (checkMainAxis) { checks.push(overflow[_basePlacement] <= 0); } if (checkAltAxis) { checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); } if (checks.every(function (check) { return check; })) { firstFittingPlacement = placement; makeFallbackChecks = false; break; } checksMap.set(placement, checks); } if (makeFallbackChecks) { // `2` may be desired in some cases – research later var numberOfChecks = flipVariations ? 3 : 1; var _loop = function _loop(_i) { var fittingPlacement = placements.find(function (placement) { var checks = checksMap.get(placement); if (checks) { return checks.slice(0, _i).every(function (check) { return check; }); } }); if (fittingPlacement) { firstFittingPlacement = fittingPlacement; return "break"; } }; for (var _i = numberOfChecks; _i > 0; _i--) { var _ret = _loop(_i); if (_ret === "break") break; } } if (state.placement !== firstFittingPlacement) { state.modifiersData[name]._skip = true; state.placement = firstFittingPlacement; state.reset = true; } } // eslint-disable-next-line import/no-unused-modules /* harmony default export */ const modifiers_flip = ({ name: 'flip', enabled: true, phase: 'main', fn: flip, requiresIfExists: ['offset'], data: { _skip: false } }); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/hide.js function getSideOffsets(overflow, rect, preventedOffsets) { if (preventedOffsets === void 0) { preventedOffsets = { x: 0, y: 0 }; } return { top: overflow.top - rect.height - preventedOffsets.y, right: overflow.right - rect.width + preventedOffsets.x, bottom: overflow.bottom - rect.height + preventedOffsets.y, left: overflow.left - rect.width - preventedOffsets.x }; } function isAnySideFullyClipped(overflow) { return [enums_top, right, bottom, left].some(function (side) { return overflow[side] >= 0; }); } function hide(_ref) { var state = _ref.state, name = _ref.name; var referenceRect = state.rects.reference; var popperRect = state.rects.popper; var preventedOffsets = state.modifiersData.preventOverflow; var referenceOverflow = detectOverflow(state, { elementContext: 'reference' }); var popperAltOverflow = detectOverflow(state, { altBoundary: true }); var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); state.modifiersData[name] = { referenceClippingOffsets: referenceClippingOffsets, popperEscapeOffsets: popperEscapeOffsets, isReferenceHidden: isReferenceHidden, hasPopperEscaped: hasPopperEscaped }; state.attributes.popper = Object.assign({}, state.attributes.popper, { 'data-popper-reference-hidden': isReferenceHidden, 'data-popper-escaped': hasPopperEscaped }); } // eslint-disable-next-line import/no-unused-modules /* harmony default export */ const modifiers_hide = ({ name: 'hide', enabled: true, phase: 'main', requiresIfExists: ['preventOverflow'], fn: hide }); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/offset.js function distanceAndSkiddingToXY(placement, rects, offset) { var basePlacement = getBasePlacement(placement); var invertDistance = [left, enums_top].indexOf(basePlacement) >= 0 ? -1 : 1; var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, { placement: placement })) : offset, skidding = _ref[0], distance = _ref[1]; skidding = skidding || 0; distance = (distance || 0) * invertDistance; return [left, right].indexOf(basePlacement) >= 0 ? { x: distance, y: skidding } : { x: skidding, y: distance }; } function offset(_ref2) { var state = _ref2.state, options = _ref2.options, name = _ref2.name; var _options$offset = options.offset, offset = _options$offset === void 0 ? [0, 0] : _options$offset; var data = enums_placements.reduce(function (acc, placement) { acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset); return acc; }, {}); var _data$state$placement = data[state.placement], x = _data$state$placement.x, y = _data$state$placement.y; if (state.modifiersData.popperOffsets != null) { state.modifiersData.popperOffsets.x += x; state.modifiersData.popperOffsets.y += y; } state.modifiersData[name] = data; } // eslint-disable-next-line import/no-unused-modules /* harmony default export */ const modifiers_offset = ({ name: 'offset', enabled: true, phase: 'main', requires: ['popperOffsets'], fn: offset }); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/popperOffsets.js 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 /* harmony default export */ const modifiers_popperOffsets = ({ name: 'popperOffsets', enabled: true, phase: 'read', fn: popperOffsets, data: {} }); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/getAltAxis.js function getAltAxis(axis) { return axis === 'x' ? 'y' : 'x'; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/modifiers/preventOverflow.js function preventOverflow(_ref) { var state = _ref.state, options = _ref.options, name = _ref.name; var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; var overflow = detectOverflow(state, { boundary: boundary, rootBoundary: rootBoundary, padding: padding, altBoundary: altBoundary }); var basePlacement = getBasePlacement(state.placement); var variation = getVariation(state.placement); var isBasePlacement = !variation; var mainAxis = getMainAxisFromPlacement(basePlacement); var altAxis = getAltAxis(mainAxis); var popperOffsets = state.modifiersData.popperOffsets; var referenceRect = state.rects.reference; var popperRect = state.rects.popper; var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, { placement: state.placement })) : tetherOffset; var data = { x: 0, y: 0 }; if (!popperOffsets) { return; } if (checkMainAxis || checkAltAxis) { var mainSide = mainAxis === 'y' ? enums_top : left; var altSide = mainAxis === 'y' ? bottom : right; var len = mainAxis === 'y' ? 'height' : 'width'; var offset = popperOffsets[mainAxis]; var min = popperOffsets[mainAxis] + overflow[mainSide]; var max = popperOffsets[mainAxis] - overflow[altSide]; var additive = tether ? -popperRect[len] / 2 : 0; var minLen = variation === start ? referenceRect[len] : popperRect[len]; var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go // outside the reference bounds var arrowElement = state.elements.arrow; var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { width: 0, height: 0 }; var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject(); var arrowPaddingMin = arrowPaddingObject[mainSide]; var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want // to include its full size in the calculation. If the reference is small // and near the edge of a boundary, the popper can overflow even if the // reference is not overflowing as well (e.g. virtual elements with no // width or height) var arrowLen = within(0, referenceRect[len], arrowRect[len]); var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - tetherOffsetValue : minLen - arrowLen - arrowPaddingMin - tetherOffsetValue; var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + tetherOffsetValue : maxLen + arrowLen + arrowPaddingMax + tetherOffsetValue; var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; var offsetModifierValue = state.modifiersData.offset ? state.modifiersData.offset[state.placement][mainAxis] : 0; var tetherMin = popperOffsets[mainAxis] + minOffset - offsetModifierValue - clientOffset; var tetherMax = popperOffsets[mainAxis] + maxOffset - offsetModifierValue; if (checkMainAxis) { var preventedOffset = within(tether ? math_min(min, tetherMin) : min, offset, tether ? math_max(max, tetherMax) : max); popperOffsets[mainAxis] = preventedOffset; data[mainAxis] = preventedOffset - offset; } if (checkAltAxis) { var _mainSide = mainAxis === 'x' ? enums_top : left; var _altSide = mainAxis === 'x' ? bottom : right; var _offset = popperOffsets[altAxis]; var _min = _offset + overflow[_mainSide]; var _max = _offset - overflow[_altSide]; var _preventedOffset = within(tether ? math_min(_min, tetherMin) : _min, _offset, tether ? math_max(_max, tetherMax) : _max); popperOffsets[altAxis] = _preventedOffset; data[altAxis] = _preventedOffset - _offset; } } state.modifiersData[name] = data; } // eslint-disable-next-line import/no-unused-modules /* harmony default export */ const modifiers_preventOverflow = ({ name: 'preventOverflow', enabled: true, phase: 'main', fn: preventOverflow, requiresIfExists: ['offset'] }); ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js function getHTMLElementScroll(element) { return { scrollLeft: element.scrollLeft, scrollTop: element.scrollTop }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js function getNodeScroll(node) { if (node === getWindow(node) || !isHTMLElement(node)) { return getWindowScroll(node); } else { return getHTMLElementScroll(node); } } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js function isElementScaled(element) { var rect = element.getBoundingClientRect(); var scaleX = rect.width / element.offsetWidth || 1; var scaleY = rect.height / element.offsetHeight || 1; return scaleX !== 1 || scaleY !== 1; } // Returns the composite rect of an element relative to its offsetParent. // Composite means it takes into account transforms as well as layout. function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { if (isFixed === void 0) { isFixed = false; } var isOffsetParentAnElement = isHTMLElement(offsetParent); var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); var documentElement = getDocumentElement(offsetParent); var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled); 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, true); 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 }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/orderModifiers.js // source: https://stackoverflow.com/questions/49875255 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; })); }, []); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/debounce.js function debounce(fn) { var pending; return function () { if (!pending) { pending = new Promise(function (resolve) { Promise.resolve().then(function () { pending = undefined; resolve(fn()); }); }); } return pending; }; } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/utils/mergeByName.js function mergeByName(modifiers) { var merged = modifiers.reduce(function (merged, current) { var existing = merged[current.name]; merged[current.name] = existing ? Object.assign({}, existing, current, { options: Object.assign({}, existing.options, current.options), data: 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]; }); } ;// CONCATENATED MODULE: ./node_modules/@popperjs/core/lib/createPopper.js 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({}, DEFAULT_OPTIONS, defaultOptions), modifiersData: {}, elements: { reference: reference, popper: popper }, attributes: {}, styles: {} }; var effectCleanupFns = []; var isDestroyed = false; var instance = { state: state, setOptions: function setOptions(setOptionsAction) { var options = typeof setOptionsAction === 'function' ? setOptionsAction(state.options) : setOptionsAction; cleanupModifierEffects(); state.options = 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 (false) { var _getComputedStyle, marginTop, marginRight, marginBottom, marginLeft, flipModifier, modifiers; } 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 (false) {} 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 (false) {} 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 (false) {} 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 createPopper = /*#__PURE__*/(/* unused pure expression or super */ null && (popperGenerator())); // eslint-disable-next-line import/no-unused-modules ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/popper.js // For the common JS build we will turn this file into a bundle with no imports. // This is b/c the Popper lib is all esm files, and would break in a common js only environment const popper_createPopper = popperGenerator({ defaultModifiers: [modifiers_hide, modifiers_popperOffsets, modifiers_computeStyles, eventListeners, modifiers_offset, modifiers_flip, modifiers_preventOverflow, modifiers_arrow] }); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/usePopper.js const usePopper_excluded = ["enabled", "placement", "strategy", "modifiers"]; function usePopper_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } const disabledApplyStylesModifier = { name: 'applyStyles', enabled: false, phase: 'afterWrite', fn: () => undefined }; // until docjs supports type exports... const ariaDescribedByModifier = { name: 'ariaDescribedBy', enabled: true, phase: 'afterWrite', effect: ({ state }) => () => { const { reference, popper } = state.elements; if ('removeAttribute' in reference) { const ids = (reference.getAttribute('aria-describedby') || '').split(',').filter(id => id.trim() !== popper.id); if (!ids.length) reference.removeAttribute('aria-describedby');else reference.setAttribute('aria-describedby', ids.join(',')); } }, fn: ({ state }) => { var _popper$getAttribute; const { popper, reference } = state.elements; const role = (_popper$getAttribute = popper.getAttribute('role')) == null ? void 0 : _popper$getAttribute.toLowerCase(); if (popper.id && role === 'tooltip' && 'setAttribute' in reference) { const ids = reference.getAttribute('aria-describedby'); if (ids && ids.split(',').indexOf(popper.id) !== -1) { return; } reference.setAttribute('aria-describedby', ids ? `${ids},${popper.id}` : popper.id); } } }; const EMPTY_MODIFIERS = []; /** * Position an element relative some reference element using Popper.js * * @param referenceElement * @param popperElement * @param {object} options * @param {object=} options.modifiers Popper.js modifiers * @param {boolean=} options.enabled toggle the popper functionality on/off * @param {string=} options.placement The popper element placement relative to the reference element * @param {string=} options.strategy the positioning strategy * @param {function=} options.onCreate called when the popper is created * @param {function=} options.onUpdate called when the popper is updated * * @returns {UsePopperState} The popper state */ function usePopper(referenceElement, popperElement, _ref = {}) { let { enabled = true, placement = 'bottom', strategy = 'absolute', modifiers = EMPTY_MODIFIERS } = _ref, config = usePopper_objectWithoutPropertiesLoose(_ref, usePopper_excluded); const prevModifiers = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(modifiers); const popperInstanceRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(); const update = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(() => { var _popperInstanceRef$cu; (_popperInstanceRef$cu = popperInstanceRef.current) == null ? void 0 : _popperInstanceRef$cu.update(); }, []); const forceUpdate = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(() => { var _popperInstanceRef$cu2; (_popperInstanceRef$cu2 = popperInstanceRef.current) == null ? void 0 : _popperInstanceRef$cu2.forceUpdate(); }, []); const [popperState, setState] = esm_useSafeState((0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)({ placement, update, forceUpdate, attributes: {}, styles: { popper: {}, arrow: {} } })); const updateModifier = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ name: 'updateStateModifier', enabled: true, phase: 'write', requires: ['computeStyles'], fn: ({ state }) => { const styles = {}; const attributes = {}; Object.keys(state.elements).forEach(element => { styles[element] = state.styles[element]; attributes[element] = state.attributes[element]; }); setState({ state, styles, attributes, update, forceUpdate, placement: state.placement }); } }), [update, forceUpdate, setState]); const nextModifiers = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => { if (!dequal(prevModifiers.current, modifiers)) { prevModifiers.current = modifiers; } return prevModifiers.current; }, [modifiers]); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (!popperInstanceRef.current || !enabled) return; popperInstanceRef.current.setOptions({ placement, strategy, modifiers: [...nextModifiers, updateModifier, disabledApplyStylesModifier] }); }, [strategy, placement, updateModifier, enabled, nextModifiers]); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (!enabled || referenceElement == null || popperElement == null) { return undefined; } popperInstanceRef.current = popper_createPopper(referenceElement, popperElement, Object.assign({}, config, { placement, strategy, modifiers: [...nextModifiers, ariaDescribedByModifier, updateModifier] })); return () => { if (popperInstanceRef.current != null) { popperInstanceRef.current.destroy(); popperInstanceRef.current = undefined; setState(s => Object.assign({}, s, { attributes: {}, styles: { popper: {} } })); } }; // This is only run once to _create_ the popper // eslint-disable-next-line react-hooks/exhaustive-deps }, [enabled, referenceElement, popperElement]); return popperState; } /* harmony default export */ const esm_usePopper = (usePopper); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/contains.js /* eslint-disable no-bitwise, no-cond-assign */ /** * Checks if an element contains another given element. * * @param context the context element * @param node the element to check */ function contains_contains(context, node) { // HTML DOM and SVG DOM may have different support levels, // so we need to check on context instead of a document root element. if (context.contains) return context.contains(node); if (context.compareDocumentPosition) return context === node || !!(context.compareDocumentPosition(node) & 16); } // EXTERNAL MODULE: ./node_modules/warning/warning.js var warning = __webpack_require__(459); var warning_default = /*#__PURE__*/__webpack_require__.n(warning); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/useRootClose.js const escapeKeyCode = 27; const useRootClose_noop = () => {}; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } const getRefTarget = ref => ref && ('current' in ref ? ref.current : ref); /** * The `useRootClose` hook registers your callback on the document * when rendered. Powers the `<Overlay/>` component. This is used achieve modal * style behavior where your callback is triggered when the user tries to * interact with the rest of the document or hits the `esc` key. * * @param {Ref<HTMLElement>| HTMLElement} ref The element boundary * @param {function} onRootClose * @param {object=} options * @param {boolean=} options.disabled * @param {string=} options.clickTrigger The DOM event name (click, mousedown, etc) to attach listeners on */ function useRootClose(ref, onRootClose, { disabled, clickTrigger = 'click' } = {}) { const preventMouseRootCloseRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(false); const onClose = onRootClose || useRootClose_noop; const handleMouseCapture = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(e => { const currentTarget = getRefTarget(ref); warning_default()(!!currentTarget, 'RootClose captured a close event but does not have a ref to compare it to. ' + 'useRootClose(), should be passed a ref that resolves to a DOM node'); preventMouseRootCloseRef.current = !currentTarget || isModifiedEvent(e) || !isLeftClickEvent(e) || !!contains_contains(currentTarget, e.target); }, [ref]); const handleMouse = useEventCallback_useEventCallback(e => { if (!preventMouseRootCloseRef.current) { onClose(e); } }); const handleKeyUp = useEventCallback_useEventCallback(e => { if (e.keyCode === escapeKeyCode) { onClose(e); } }); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (disabled || ref == null) return undefined; const doc = ownerDocument(getRefTarget(ref)); // Store the current event to avoid triggering handlers immediately // https://github.com/facebook/react/issues/20074 let currentEvent = (doc.defaultView || window).event; // Use capture for this listener so it fires before React's listener, to // avoid false positives in the contains() check below if the target DOM // element is removed in the React mouse callback. const removeMouseCaptureListener = esm_listen(doc, clickTrigger, handleMouseCapture, true); const removeMouseListener = esm_listen(doc, clickTrigger, e => { // skip if this event is the same as the one running when we added the handlers if (e === currentEvent) { currentEvent = undefined; return; } handleMouse(e); }); const removeKeyupListener = esm_listen(doc, 'keyup', e => { // skip if this event is the same as the one running when we added the handlers if (e === currentEvent) { currentEvent = undefined; return; } handleKeyUp(e); }); let mobileSafariHackListeners = []; if ('ontouchstart' in doc.documentElement) { mobileSafariHackListeners = [].slice.call(doc.body.children).map(el => esm_listen(el, 'mousemove', useRootClose_noop)); } return () => { removeMouseCaptureListener(); removeMouseListener(); removeKeyupListener(); mobileSafariHackListeners.forEach(remove => remove()); }; }, [ref, disabled, clickTrigger, handleMouseCapture, handleMouse, handleKeyUp]); } /* harmony default export */ const esm_useRootClose = (useRootClose); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/mergeOptionsWithPopperConfig.js function toModifierMap(modifiers) { const result = {}; if (!Array.isArray(modifiers)) { return modifiers || result; } // eslint-disable-next-line no-unused-expressions modifiers == null ? void 0 : modifiers.forEach(m => { result[m.name] = m; }); return result; } function toModifierArray(map = {}) { if (Array.isArray(map)) return map; return Object.keys(map).map(k => { map[k].name = k; return map[k]; }); } function mergeOptionsWithPopperConfig({ enabled, enableEvents, placement, flip, offset, fixed, containerPadding, arrowElement, popperConfig = {} }) { var _modifiers$preventOve, _modifiers$preventOve2, _modifiers$offset, _modifiers$arrow; const modifiers = toModifierMap(popperConfig.modifiers); return Object.assign({}, popperConfig, { placement, enabled, strategy: fixed ? 'fixed' : popperConfig.strategy, modifiers: toModifierArray(Object.assign({}, modifiers, { eventListeners: { enabled: enableEvents }, preventOverflow: Object.assign({}, modifiers.preventOverflow, { options: containerPadding ? Object.assign({ padding: containerPadding }, (_modifiers$preventOve = modifiers.preventOverflow) == null ? void 0 : _modifiers$preventOve.options) : (_modifiers$preventOve2 = modifiers.preventOverflow) == null ? void 0 : _modifiers$preventOve2.options }), offset: { options: Object.assign({ offset }, (_modifiers$offset = modifiers.offset) == null ? void 0 : _modifiers$offset.options) }, arrow: Object.assign({}, modifiers.arrow, { enabled: !!arrowElement, options: Object.assign({}, (_modifiers$arrow = modifiers.arrow) == null ? void 0 : _modifiers$arrow.options, { element: arrowElement }) }), flip: Object.assign({ enabled: !!flip }, modifiers.flip) })) }); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/DropdownMenu.js const DropdownMenu_excluded = ["children"]; function DropdownMenu_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } const DropdownMenu_noop = () => {}; /** * @memberOf Dropdown * @param {object} options * @param {boolean} options.flip Automatically adjust the menu `drop` position based on viewport edge detection * @param {[number, number]} options.offset Define an offset distance between the Menu and the Toggle * @param {boolean} options.show Display the menu manually, ignored in the context of a `Dropdown` * @param {boolean} options.usePopper opt in/out of using PopperJS to position menus. When disabled you must position it yourself. * @param {string} options.rootCloseEvent The pointer event to listen for when determining "clicks outside" the menu for triggering a close. * @param {object} options.popperConfig Options passed to the [`usePopper`](/api/usePopper) hook. */ function useDropdownMenu(options = {}) { const context = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_DropdownContext); const [arrowElement, attachArrowRef] = useCallbackRef(); const hasShownRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(false); const { flip, offset, rootCloseEvent, fixed = false, placement: placementOverride, popperConfig = {}, enableEventListeners = true, usePopper: shouldUsePopper = !!context } = options; const show = (context == null ? void 0 : context.show) == null ? !!options.show : context.show; if (show && !hasShownRef.current) { hasShownRef.current = true; } const handleClose = e => { context == null ? void 0 : context.toggle(false, e); }; const { placement, setMenu, menuElement, toggleElement } = context || {}; const popper = esm_usePopper(toggleElement, menuElement, mergeOptionsWithPopperConfig({ placement: placementOverride || placement || 'bottom-start', enabled: shouldUsePopper, enableEvents: enableEventListeners == null ? show : enableEventListeners, offset, flip, fixed, arrowElement, popperConfig })); const menuProps = Object.assign({ ref: setMenu || DropdownMenu_noop, 'aria-labelledby': toggleElement == null ? void 0 : toggleElement.id }, popper.attributes.popper, { style: popper.styles.popper }); const metadata = { show, placement, hasShown: hasShownRef.current, toggle: context == null ? void 0 : context.toggle, popper: shouldUsePopper ? popper : null, arrowProps: shouldUsePopper ? Object.assign({ ref: attachArrowRef }, popper.attributes.arrow, { style: popper.styles.arrow }) : {} }; esm_useRootClose(menuElement, handleClose, { clickTrigger: rootCloseEvent, disabled: !show }); return [menuProps, metadata]; } const DropdownMenu_defaultProps = { usePopper: true }; /** * Also exported as `<Dropdown.Menu>` from `Dropdown`. * * @displayName DropdownMenu * @memberOf Dropdown */ function DropdownMenu(_ref) { let { children } = _ref, options = DropdownMenu_objectWithoutPropertiesLoose(_ref, DropdownMenu_excluded); const [props, meta] = useDropdownMenu(options); return /*#__PURE__*/(0,jsx_runtime.jsx)(jsx_runtime.Fragment, { children: children(props, meta) }); } DropdownMenu.displayName = 'DropdownMenu'; DropdownMenu.defaultProps = DropdownMenu_defaultProps; /** @component */ /* harmony default export */ const esm_DropdownMenu = (DropdownMenu); ;// CONCATENATED MODULE: ./node_modules/@react-aria/ssr/dist/module.js // Default context value to use in case there is no SSRProvider. This is fine for // client-only apps. In order to support multiple copies of React Aria potentially // being on the page at once, the prefix is set to a random number. SSRProvider // will reset this to zero for consistency between server and client, so in the // SSR case multiple copies of React Aria is not supported. const $f01a183cc7bdff77849e49ad26eb904$var$defaultContext = { prefix: Math.round(Math.random() * 10000000000), current: 0 }; const $f01a183cc7bdff77849e49ad26eb904$var$SSRContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_default().createContext($f01a183cc7bdff77849e49ad26eb904$var$defaultContext); /** * When using SSR with React Aria, applications must be wrapped in an SSRProvider. * This ensures that auto generated ids are consistent between the client and server. */ function SSRProvider(props) { let cur = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)($f01a183cc7bdff77849e49ad26eb904$var$SSRContext); let value = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ // If this is the first SSRProvider, set to zero, otherwise increment. prefix: cur === $f01a183cc7bdff77849e49ad26eb904$var$defaultContext ? 0 : ++cur.prefix, current: 0 }), [cur]); return /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_default().createElement($f01a183cc7bdff77849e49ad26eb904$var$SSRContext.Provider, { value: value }, props.children); } let $f01a183cc7bdff77849e49ad26eb904$var$canUseDOM = Boolean(typeof window !== 'undefined' && window.document && window.document.createElement); /** @private */ function useSSRSafeId(defaultId) { let ctx = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)($f01a183cc7bdff77849e49ad26eb904$var$SSRContext); // If we are rendering in a non-DOM environment, and there's no SSRProvider, // provide a warning to hint to the developer to add one. if (ctx === $f01a183cc7bdff77849e49ad26eb904$var$defaultContext && !$f01a183cc7bdff77849e49ad26eb904$var$canUseDOM) { console.warn('When server rendering, you must wrap your application in an <SSRProvider> to ensure consistent ids are generated between the client and server.'); } return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => defaultId || "react-aria-" + ctx.prefix + "-" + ++ctx.current, [defaultId]); } /** * Returns whether the component is currently being server side rendered or * hydrated on the client. Can be used to delay browser-specific rendering * until after hydration. */ function useIsSSR() { let cur = useContext($f01a183cc7bdff77849e49ad26eb904$var$SSRContext); let isInSSRContext = cur !== $f01a183cc7bdff77849e49ad26eb904$var$defaultContext; let [isSSR, setIsSSR] = useState(isInSSRContext); // If on the client, and the component was initially server rendered, // then schedule a layout effect to update the component after hydration. if (typeof window !== 'undefined' && isInSSRContext) { // This if statement technically breaks the rules of hooks, but is safe // because the condition never changes after mounting. // eslint-disable-next-line react-hooks/rules-of-hooks useLayoutEffect(() => { setIsSSR(false); }, []); } return isSSR; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/DropdownToggle.js const isRoleMenu = el => { var _el$getAttribute; return ((_el$getAttribute = el.getAttribute('role')) == null ? void 0 : _el$getAttribute.toLowerCase()) === 'menu'; }; const DropdownToggle_noop = () => {}; /** * Wires up Dropdown toggle functionality, returning a set a props to attach * to the element that functions as the dropdown toggle (generally a button). * * @memberOf Dropdown */ function useDropdownToggle() { const id = useSSRSafeId(); const { show = false, toggle = DropdownToggle_noop, setToggle, menuElement } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_DropdownContext) || {}; const handleClick = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(e => { toggle(!show, e); }, [show, toggle]); const props = { id, ref: setToggle || DropdownToggle_noop, onClick: handleClick, 'aria-expanded': !!show }; // This is maybe better down in an effect, but // the component is going to update anyway when the menu element // is set so might return new props. if (menuElement && isRoleMenu(menuElement)) { props['aria-haspopup'] = true; } return [props, { show, toggle }]; } /** * Also exported as `<Dropdown.Toggle>` from `Dropdown`. * * @displayName DropdownToggle * @memberOf Dropdown */ function DropdownToggle({ children }) { const [props, meta] = useDropdownToggle(); return /*#__PURE__*/(0,jsx_runtime.jsx)(jsx_runtime.Fragment, { children: children(props, meta) }); } DropdownToggle.displayName = 'DropdownToggle'; /** @component */ /* harmony default export */ const esm_DropdownToggle = (DropdownToggle); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/SelectableContext.js const SelectableContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext(null); const makeEventKey = (eventKey, href = null) => { if (eventKey != null) return String(eventKey); return href || null; }; /* harmony default export */ const esm_SelectableContext = (SelectableContext); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/NavContext.js const NavContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext(null); NavContext.displayName = 'NavContext'; /* harmony default export */ const esm_NavContext = (NavContext); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/DataKey.js const ATTRIBUTE_PREFIX = `data-rr-ui-`; const PROPERTY_PREFIX = `rrUi`; function dataAttr(property) { return `${ATTRIBUTE_PREFIX}${property}`; } function dataProp(property) { return `${PROPERTY_PREFIX}${property}`; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/DropdownItem.js const DropdownItem_excluded = ["eventKey", "disabled", "onClick", "active", "as"]; function DropdownItem_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Create a dropdown item. Returns a set of props for the dropdown item component * including an `onClick` handler that prevents selection when the item is disabled */ function useDropdownItem({ key, href, active, disabled, onClick }) { const onSelectCtx = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_SelectableContext); const navContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_NavContext); const { activeKey } = navContext || {}; const eventKey = makeEventKey(key, href); const isActive = active == null && key != null ? makeEventKey(activeKey) === eventKey : active; const handleClick = useEventCallback_useEventCallback(event => { if (disabled) return; onClick == null ? void 0 : onClick(event); if (onSelectCtx && !event.isPropagationStopped()) { onSelectCtx(eventKey, event); } }); return [{ onClick: handleClick, 'aria-disabled': disabled || undefined, 'aria-selected': isActive, [dataAttr('dropdown-item')]: '' }, { isActive }]; } const DropdownItem = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((_ref, ref) => { let { eventKey, disabled, onClick, active, as: Component = esm_Button } = _ref, props = DropdownItem_objectWithoutPropertiesLoose(_ref, DropdownItem_excluded); const [dropdownItemProps] = useDropdownItem({ key: eventKey, href: props.href, disabled, onClick, active }); return /*#__PURE__*/(0,jsx_runtime.jsx)(Component, Object.assign({}, props, { ref: ref }, dropdownItemProps)); }); DropdownItem.displayName = 'DropdownItem'; /* harmony default export */ const esm_DropdownItem = (DropdownItem); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/useWindow.js const Context = /*#__PURE__*/(0,external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext)(canUseDOM ? window : undefined); const WindowProvider = Context.Provider; /** * The document "window" placed in React context. Helpful for determining * SSR context, or when rendering into an iframe. * * @returns the current window */ function useWindow() { return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(Context); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/Dropdown.js function useRefWithUpdate() { const forceUpdate = useForceUpdate(); const ref = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); const attachRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(element => { ref.current = element; // ensure that a menu set triggers an update for consumers forceUpdate(); }, [forceUpdate]); return [ref, attachRef]; } /** * @displayName Dropdown * @public */ function Dropdown({ defaultShow, show: rawShow, onSelect, onToggle: rawOnToggle, itemSelector = `* [${dataAttr('dropdown-item')}]`, focusFirstItemOnShow, placement = 'bottom-start', children }) { const window = useWindow(); const [show, onToggle] = useUncontrolledProp(rawShow, defaultShow, rawOnToggle); // We use normal refs instead of useCallbackRef in order to populate the // the value as quickly as possible, otherwise the effect to focus the element // may run before the state value is set const [menuRef, setMenu] = useRefWithUpdate(); const menuElement = menuRef.current; const [toggleRef, setToggle] = useRefWithUpdate(); const toggleElement = toggleRef.current; const lastShow = usePrevious(show); const lastSourceEvent = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); const focusInDropdown = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(false); const onSelectCtx = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_SelectableContext); const toggle = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)((nextShow, event, source = event == null ? void 0 : event.type) => { onToggle(nextShow, { originalEvent: event, source }); }, [onToggle]); const handleSelect = useEventCallback_useEventCallback((key, event) => { onSelect == null ? void 0 : onSelect(key, event); toggle(false, event, 'select'); if (!event.isPropagationStopped()) { onSelectCtx == null ? void 0 : onSelectCtx(key, event); } }); const context = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ toggle, placement, show, menuElement, toggleElement, setMenu, setToggle }), [toggle, placement, show, menuElement, toggleElement, setMenu, setToggle]); if (menuElement && lastShow && !show) { focusInDropdown.current = menuElement.contains(menuElement.ownerDocument.activeElement); } const focusToggle = useEventCallback_useEventCallback(() => { if (toggleElement && toggleElement.focus) { toggleElement.focus(); } }); const maybeFocusFirst = useEventCallback_useEventCallback(() => { const type = lastSourceEvent.current; let focusType = focusFirstItemOnShow; if (focusType == null) { focusType = menuRef.current && isRoleMenu(menuRef.current) ? 'keyboard' : false; } if (focusType === false || focusType === 'keyboard' && !/^key.+$/.test(type)) { return; } const first = qsa(menuRef.current, itemSelector)[0]; if (first && first.focus) first.focus(); }); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (show) maybeFocusFirst();else if (focusInDropdown.current) { focusInDropdown.current = false; focusToggle(); } // only `show` should be changing }, [show, focusInDropdown, focusToggle, maybeFocusFirst]); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { lastSourceEvent.current = null; }); const getNextFocusedChild = (current, offset) => { if (!menuRef.current) return null; const items = qsa(menuRef.current, itemSelector); let index = items.indexOf(current) + offset; index = Math.max(0, Math.min(index, items.length)); return items[index]; }; useEventListener_useEventListener((0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(() => window.document, [window]), 'keydown', event => { var _menuRef$current, _toggleRef$current; const { key } = event; const target = event.target; const fromMenu = (_menuRef$current = menuRef.current) == null ? void 0 : _menuRef$current.contains(target); const fromToggle = (_toggleRef$current = toggleRef.current) == null ? void 0 : _toggleRef$current.contains(target); // Second only to https://github.com/twbs/bootstrap/blob/8cfbf6933b8a0146ac3fbc369f19e520bd1ebdac/js/src/dropdown.js#L400 // in inscrutability const isInput = /input|textarea/i.test(target.tagName); if (isInput && (key === ' ' || key !== 'Escape' && fromMenu)) { return; } if (!fromMenu && !fromToggle) { return; } if (key === 'Tab' && (!menuRef.current || !show)) { return; } lastSourceEvent.current = event.type; const meta = { originalEvent: event, source: event.type }; switch (key) { case 'ArrowUp': { const next = getNextFocusedChild(target, -1); if (next && next.focus) next.focus(); event.preventDefault(); return; } case 'ArrowDown': event.preventDefault(); if (!show) { onToggle(true, meta); } else { const next = getNextFocusedChild(target, 1); if (next && next.focus) next.focus(); } return; case 'Tab': // on keydown the target is the element being tabbed FROM, we need that // to know if this event is relevant to this dropdown (e.g. in this menu). // On `keyup` the target is the element being tagged TO which we use to check // if focus has left the menu esm_addEventListener(target.ownerDocument, 'keyup', e => { var _menuRef$current2; if (e.key === 'Tab' && !e.target || !((_menuRef$current2 = menuRef.current) != null && _menuRef$current2.contains(e.target))) { onToggle(false, meta); } }, { once: true }); break; case 'Escape': if (key === 'Escape') { event.preventDefault(); event.stopPropagation(); } onToggle(false, meta); break; default: } }); return /*#__PURE__*/(0,jsx_runtime.jsx)(esm_SelectableContext.Provider, { value: handleSelect, children: /*#__PURE__*/(0,jsx_runtime.jsx)(esm_DropdownContext.Provider, { value: context, children: children }) }); } Dropdown.displayName = 'Dropdown'; Dropdown.Menu = esm_DropdownMenu; Dropdown.Toggle = esm_DropdownToggle; Dropdown.Item = esm_DropdownItem; /* harmony default export */ const esm_Dropdown = (Dropdown); ;// CONCATENATED MODULE: ./src/DropdownContext.ts const DropdownContext_DropdownContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext({}); DropdownContext_DropdownContext.displayName = 'DropdownContext'; /* harmony default export */ const src_DropdownContext = (DropdownContext_DropdownContext); ;// CONCATENATED MODULE: ./src/DropdownItem.tsx var DropdownItem_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/DropdownItem.tsx"; const DropdownItem_propTypes = { /** @default 'dropdown-item' */ bsPrefix: (prop_types_default()).string, /** * Highlight the menu item as active. */ active: (prop_types_default()).bool, /** * Disable the menu item, making it unselectable. */ disabled: (prop_types_default()).bool, /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]), /** * HTML `href` attribute corresponding to `a.href`. */ href: (prop_types_default()).string, /** * Callback fired when the menu item is clicked. */ onClick: (prop_types_default()).func, as: (prop_types_default()).elementType }; const DropdownItem_DropdownItem = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, eventKey, disabled = false, onClick, active, as: Component = esm_Anchor, ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'dropdown-item'); const [dropdownItemProps, meta] = useDropdownItem({ key: eventKey, href: props.href, disabled, onClick, active }); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ...dropdownItemProps, ref: ref, className: classnames_default()(className, prefix, meta.isActive && 'active', disabled && 'disabled') }, void 0, false, { fileName: DropdownItem_jsxFileName, lineNumber: 75, columnNumber: 7 }, undefined); }); DropdownItem_DropdownItem.displayName = 'DropdownItem'; DropdownItem_DropdownItem.propTypes = DropdownItem_propTypes; /* harmony default export */ const src_DropdownItem = (DropdownItem_DropdownItem); ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useIsomorphicEffect.js var useIsomorphicEffect_isReactNative = typeof __webpack_require__.g !== 'undefined' && // @ts-ignore __webpack_require__.g.navigator && // @ts-ignore __webpack_require__.g.navigator.product === 'ReactNative'; var useIsomorphicEffect_isDOM = typeof document !== 'undefined'; /** * Is `useLayoutEffect` in a DOM or React Native environment, otherwise resolves to useEffect * Only useful to avoid the console warning. * * PREFER `useEffect` UNLESS YOU KNOW WHAT YOU ARE DOING. * * @category effects */ /* harmony default export */ const esm_useIsomorphicEffect = (useIsomorphicEffect_isDOM || useIsomorphicEffect_isReactNative ? external_root_React_commonjs2_react_commonjs_react_amd_react_.useLayoutEffect : external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect); ;// CONCATENATED MODULE: ./src/InputGroupContext.tsx const InputGroupContext_context = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext(null); InputGroupContext_context.displayName = 'InputGroupContext'; /* harmony default export */ const InputGroupContext = (InputGroupContext_context); ;// CONCATENATED MODULE: ./src/NavbarContext.tsx // TODO: check const NavbarContext_context = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext(null); NavbarContext_context.displayName = 'NavbarContext'; /* harmony default export */ const NavbarContext = (NavbarContext_context); ;// CONCATENATED MODULE: ./src/useWrappedRefWithWarning.tsx function useWrappedRefWithWarning(ref, componentName) { // @ts-ignore if (true) return ref; // eslint-disable-next-line react-hooks/rules-of-hooks const warningRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(refValue => { !(refValue == null || !refValue.isReactComponent) ? false ? 0 : browser_default()(false) : void 0; }, [componentName]); // eslint-disable-next-line react-hooks/rules-of-hooks return esm_useMergedRefs(warningRef, ref); } ;// CONCATENATED MODULE: ./src/types.tsx const alignDirection = prop_types_default().oneOf(['start', 'end']); const alignPropType = prop_types_default().oneOfType([alignDirection, prop_types_default().shape({ sm: alignDirection }), prop_types_default().shape({ md: alignDirection }), prop_types_default().shape({ lg: alignDirection }), prop_types_default().shape({ xl: alignDirection }), prop_types_default().shape({ xxl: alignDirection })]); ;// CONCATENATED MODULE: ./src/DropdownMenu.tsx var DropdownMenu_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/DropdownMenu.tsx"; const DropdownMenu_propTypes = { /** * @default 'dropdown-menu' */ bsPrefix: (prop_types_default()).string, /** Controls the visibility of the Dropdown menu */ show: (prop_types_default()).bool, /** Whether to render the dropdown menu in the DOM before the first time it is shown */ renderOnMount: (prop_types_default()).bool, /** Have the dropdown switch to it's opposite placement when necessary to stay on screen. */ flip: (prop_types_default()).bool, /** * Aligns the dropdown menu to the specified side of the container. You can also align * the menu responsively for breakpoints starting at `sm` and up. The alignment * direction will affect the specified breakpoint or larger. * * *Note: Using responsive alignment will disable Popper usage for positioning.* * * @type {"start"|"end"|{ sm: "start"|"end" }|{ md: "start"|"end" }|{ lg: "start"|"end" }|{ xl: "start"|"end"}|{ xxl: "start"|"end"} } */ align: alignPropType, onSelect: (prop_types_default()).func, /** * Which event when fired outside the component will cause it to be closed * * *Note: For custom dropdown components, you will have to pass the * `rootCloseEvent` to `<RootCloseWrapper>` in your custom dropdown menu * component ([similarly to how it is implemented in `<Dropdown.Menu>`](https://github.com/react-bootstrap/react-bootstrap/blob/v0.31.5/src/DropdownMenu.js#L115-L119)).* */ rootCloseEvent: prop_types_default().oneOf(['click', 'mousedown']), /** * Control the rendering of the DropdownMenu. All non-menu props * (listed here) are passed through to the `as` Component. * * If providing a custom, non DOM, component. the `show`, `close` and `align` props * are also injected and should be handled appropriately. */ as: (prop_types_default()).elementType, /** * A set of popper options and props passed directly to Popper. */ popperConfig: (prop_types_default()).object, /** * Menu color variant. * * Omitting this will use the default light color. */ variant: (prop_types_default()).string }; const src_DropdownMenu_defaultProps = { flip: true }; function getDropdownMenuPlacement(alignEnd, dropDirection, isRTL) { const topStart = isRTL ? 'top-end' : 'top-start'; const topEnd = isRTL ? 'top-start' : 'top-end'; const bottomStart = isRTL ? 'bottom-end' : 'bottom-start'; const bottomEnd = isRTL ? 'bottom-start' : 'bottom-end'; const leftStart = isRTL ? 'right-start' : 'left-start'; const leftEnd = isRTL ? 'right-end' : 'left-end'; const rightStart = isRTL ? 'left-start' : 'right-start'; const rightEnd = isRTL ? 'left-end' : 'right-end'; let placement = alignEnd ? bottomEnd : bottomStart; if (dropDirection === 'up') placement = alignEnd ? topEnd : topStart;else if (dropDirection === 'end') placement = alignEnd ? rightEnd : rightStart;else if (dropDirection === 'start') placement = alignEnd ? leftEnd : leftStart; return placement; } const DropdownMenu_DropdownMenu = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, align, rootCloseEvent, flip, show: showProps, renderOnMount, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', popperConfig, variant, ...props }, ref) => { let alignEnd = false; const isNavbar = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(NavbarContext); const prefix = useBootstrapPrefix(bsPrefix, 'dropdown-menu'); const { align: contextAlign, drop, isRTL } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_DropdownContext); align = align || contextAlign; const isInputGroup = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(InputGroupContext); const alignClasses = []; if (align) { if (typeof align === 'object') { const keys = Object.keys(align); false ? 0 : void 0; if (keys.length) { const brkPoint = keys[0]; const direction = align[brkPoint]; // .dropdown-menu-end is required for responsively aligning // left in addition to align left classes. alignEnd = direction === 'start'; alignClasses.push(`${prefix}-${brkPoint}-${direction}`); } } else if (align === 'end') { alignEnd = true; } } const placement = getDropdownMenuPlacement(alignEnd, drop, isRTL); const [menuProps, { hasShown, popper, show, toggle }] = useDropdownMenu({ flip, rootCloseEvent, show: showProps, usePopper: !isNavbar && alignClasses.length === 0, offset: [0, 2], popperConfig, placement }); menuProps.ref = esm_useMergedRefs(useWrappedRefWithWarning(ref, 'DropdownMenu'), menuProps.ref); esm_useIsomorphicEffect(() => { // Popper's initial position for the menu is incorrect when // renderOnMount=true. Need to call update() to correct it. if (show) popper == null ? void 0 : popper.update(); }, [show]); if (!hasShown && !renderOnMount && !isInputGroup) return null; // For custom components provide additional, non-DOM, props; if (typeof Component !== 'string') { menuProps.show = show; menuProps.close = () => toggle == null ? void 0 : toggle(false); menuProps.align = align; } let style = props.style; if (popper != null && popper.placement) { // we don't need the default popper style, // menus are display: none when not shown. style = { ...props.style, ...menuProps.style }; props['x-placement'] = popper.placement; } return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ...menuProps, style: style // Bootstrap css requires this data attrib to style responsive menus. , ...((alignClasses.length || isNavbar) && { 'data-bs-popper': 'static' }), className: classnames_default()(className, prefix, show && 'show', alignEnd && `${prefix}-end`, variant && `${prefix}-${variant}`, ...alignClasses) }, void 0, false, { fileName: DropdownMenu_jsxFileName, lineNumber: 213, columnNumber: 9 }, undefined); }); DropdownMenu_DropdownMenu.displayName = 'DropdownMenu'; DropdownMenu_DropdownMenu.propTypes = DropdownMenu_propTypes; DropdownMenu_DropdownMenu.defaultProps = src_DropdownMenu_defaultProps; /* harmony default export */ const src_DropdownMenu = (DropdownMenu_DropdownMenu); ;// CONCATENATED MODULE: ./src/DropdownToggle.tsx var DropdownToggle_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/DropdownToggle.tsx"; const DropdownToggle_propTypes = { /** * @default 'dropdown-toggle' */ bsPrefix: (prop_types_default()).string, /** * An html id attribute, necessary for assistive technologies, such as screen readers. * @type {string|number} */ id: (prop_types_default()).string, split: (prop_types_default()).bool, as: (prop_types_default()).elementType, /** * to passthrough to the underlying button or whatever from DropdownButton * @private */ childBsPrefix: (prop_types_default()).string }; const DropdownToggle_DropdownToggle = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, split, className, childBsPrefix, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = src_Button, ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'dropdown-toggle'); const dropdownContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_DropdownContext); const isInputGroup = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(InputGroupContext); if (childBsPrefix !== undefined) { props.bsPrefix = childBsPrefix; } const [toggleProps] = useDropdownToggle(); toggleProps.ref = esm_useMergedRefs(toggleProps.ref, useWrappedRefWithWarning(ref, 'DropdownToggle')); // This intentionally forwards size and variant (if set) to the // underlying component, to allow it to render size and style variants. return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { className: classnames_default()(className, prefix, split && `${prefix}-split`, !!isInputGroup && (dropdownContext == null ? void 0 : dropdownContext.show) && 'show'), ...toggleProps, ...props }, void 0, false, { fileName: DropdownToggle_jsxFileName, lineNumber: 83, columnNumber: 7 }, undefined); }); DropdownToggle_DropdownToggle.displayName = 'DropdownToggle'; DropdownToggle_DropdownToggle.propTypes = DropdownToggle_propTypes; /* harmony default export */ const src_DropdownToggle = (DropdownToggle_DropdownToggle); ;// CONCATENATED MODULE: ./src/Dropdown.tsx var Dropdown_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Dropdown.tsx"; const DropdownHeader = createWithBsPrefix('dropdown-header', { defaultProps: { role: 'heading' } }); const DropdownDivider = createWithBsPrefix('dropdown-divider', { Component: 'hr', defaultProps: { role: 'separator' } }); const DropdownItemText = createWithBsPrefix('dropdown-item-text', { Component: 'span' }); const Dropdown_propTypes = { /** @default 'dropdown' */ bsPrefix: (prop_types_default()).string, /** * Determines the direction and location of the Menu in relation to it's Toggle. */ drop: prop_types_default().oneOf(['up', 'start', 'end', 'down']), as: (prop_types_default()).elementType, /** * Aligns the dropdown menu to the specified side of the Dropdown toggle. You can * also align the menu responsively for breakpoints starting at `sm` and up. * The alignment direction will affect the specified breakpoint or larger. * * *Note: Using responsive alignment will disable Popper usage for positioning.* * * @type {"start"|"end"|{ sm: "start"|"end" }|{ md: "start"|"end" }|{ lg: "start"|"end" }|{ xl: "start"|"end"}|{ xxl: "start"|"end"} } */ align: alignPropType, /** * Whether or not the Dropdown is visible. * * @controllable onToggle */ show: (prop_types_default()).bool, /** * Allow Dropdown to flip in case of an overlapping on the reference element. For more information refer to * Popper.js's flip [docs](https://popper.js.org/docs/v2/modifiers/flip/). * */ flip: (prop_types_default()).bool, /** * A callback fired when the Dropdown wishes to change visibility. Called with the requested * `show` value, the DOM event, and the source that fired it: `'click'`,`'keydown'`,`'rootClose'`, or `'select'`. * * ```js * function( * isOpen: boolean, * event: SyntheticEvent, * metadata: { * source: 'select' | 'click' | 'rootClose' | 'keydown' * } * ): void * ``` * * @controllable show */ onToggle: (prop_types_default()).func, /** * A callback fired when a menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: (prop_types_default()).func, /** * Controls the focus behavior for when the Dropdown is opened. Set to * `true` to always focus the first menu item, `keyboard` to focus only when * navigating via the keyboard, or `false` to disable completely * * The Default behavior is `false` **unless** the Menu has a `role="menu"` * where it will default to `keyboard` to match the recommended [ARIA Authoring practices](https://www.w3.org/TR/wai-aria-practices-1.1/#menubutton). */ focusFirstItemOnShow: prop_types_default().oneOf([false, true, 'keyboard']), /** @private */ navbar: (prop_types_default()).bool, /** * Controls the auto close behaviour of the dropdown when clicking outside of * the button or the list. */ autoClose: prop_types_default().oneOf([true, 'outside', 'inside', false]) }; const Dropdown_defaultProps = { navbar: false, align: 'start', autoClose: true }; const Dropdown_Dropdown = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((pProps, ref) => { const { bsPrefix, drop, show, className, align, onSelect, onToggle, focusFirstItemOnShow, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', navbar: _4, autoClose, ...props } = useUncontrolled(pProps, { show: 'onToggle' }); const isInputGroup = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(InputGroupContext); const prefix = useBootstrapPrefix(bsPrefix, 'dropdown'); const isRTL = useIsRTL(); const isClosingPermitted = source => { // autoClose=false only permits close on button click if (autoClose === false) return source === 'click'; // autoClose=inside doesn't permit close on rootClose if (autoClose === 'inside') return source !== 'rootClose'; // autoClose=outside doesn't permit close on select if (autoClose === 'outside') return source !== 'select'; return true; }; const handleToggle = useEventCallback((nextShow, meta) => { if (meta.originalEvent.currentTarget === document && (meta.source !== 'keydown' || meta.originalEvent.key === 'Escape')) meta.source = 'rootClose'; if (isClosingPermitted(meta.source)) onToggle == null ? void 0 : onToggle(nextShow, meta); }); const alignEnd = align === 'end'; const placement = getDropdownMenuPlacement(alignEnd, drop, isRTL); const contextValue = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ align, drop, isRTL }), [align, drop, isRTL]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_DropdownContext.Provider, { value: contextValue, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Dropdown, { placement: placement, show: show, onSelect: onSelect, onToggle: handleToggle, focusFirstItemOnShow: focusFirstItemOnShow, itemSelector: `.${prefix}-item:not(.disabled):not(:disabled)`, children: isInputGroup ? props.children : /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref, className: classnames_default()(className, show && 'show', (!drop || drop === 'down') && prefix, drop === 'up' && 'dropup', drop === 'end' && 'dropend', drop === 'start' && 'dropstart') }, void 0, false, { fileName: Dropdown_jsxFileName, lineNumber: 205, columnNumber: 13 }, undefined) }, void 0, false, { fileName: Dropdown_jsxFileName, lineNumber: 194, columnNumber: 9 }, undefined) }, void 0, false, { fileName: Dropdown_jsxFileName, lineNumber: 193, columnNumber: 7 }, undefined); }); Dropdown_Dropdown.displayName = 'Dropdown'; Dropdown_Dropdown.propTypes = Dropdown_propTypes; Dropdown_Dropdown.defaultProps = Dropdown_defaultProps; /* harmony default export */ const src_Dropdown = (Object.assign(Dropdown_Dropdown, { Toggle: src_DropdownToggle, Menu: src_DropdownMenu, Item: src_DropdownItem, ItemText: DropdownItemText, Divider: DropdownDivider, Header: DropdownHeader })); ;// CONCATENATED MODULE: ./src/DropdownButton.tsx var DropdownButton_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/DropdownButton.tsx"; const DropdownButton_propTypes = { /** * An html id attribute for the Toggle button, necessary for assistive technologies, such as screen readers. * @type {string} */ id: (prop_types_default()).string, /** An `href` passed to the Toggle component */ href: (prop_types_default()).string, /** An `onClick` handler passed to the Toggle component */ onClick: (prop_types_default()).func, /** The content of the non-toggle Button. */ title: (prop_types_default()).node.isRequired, /** Disables both Buttons */ disabled: (prop_types_default()).bool, /** * Aligns the dropdown menu. * * _see [DropdownMenu](#dropdown-menu-props) for more details_ * * @type {"start"|"end"|{ sm: "start"|"end" }|{ md: "start"|"end" }|{ lg: "start"|"end" }|{ xl: "start"|"end"}|{ xxl: "start"|"end"} } */ align: alignPropType, /** An ARIA accessible role applied to the Menu component. When set to 'menu', The dropdown */ menuRole: (prop_types_default()).string, /** Whether to render the dropdown menu in the DOM before the first time it is shown */ renderMenuOnMount: (prop_types_default()).bool, /** * Which event when fired outside the component will cause it to be closed. * * _see [DropdownMenu](#dropdown-menu-props) for more details_ */ rootCloseEvent: (prop_types_default()).string, /** * Menu color variant. * * Omitting this will use the default light color. */ menuVariant: prop_types_default().oneOf(['dark']), /** @ignore */ bsPrefix: (prop_types_default()).string, /** @ignore */ variant: (prop_types_default()).string, /** @ignore */ size: (prop_types_default()).string }; /** * A convenience component for simple or general use dropdowns. Renders a `Button` toggle and all `children` * are passed directly to the default `Dropdown.Menu`. This component accepts all of * [`Dropdown`'s props](#dropdown-props). * * _All unknown props are passed through to the `Dropdown` component._ Only * the Button `variant`, `size` and `bsPrefix` props are passed to the toggle, * along with menu-related props are passed to the `Dropdown.Menu` */ const DropdownButton = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ title, children, bsPrefix, rootCloseEvent, variant, size, menuRole, renderMenuOnMount, disabled, href, id, menuVariant, ...props }, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Dropdown, { ref: ref, ...props, children: [/*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_DropdownToggle, { id: id, href: href, size: size, variant: variant, disabled: disabled, childBsPrefix: bsPrefix, children: title }, void 0, false, { fileName: DropdownButton_jsxFileName, lineNumber: 109, columnNumber: 7 }, undefined), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_DropdownMenu, { role: menuRole, renderOnMount: renderMenuOnMount, rootCloseEvent: rootCloseEvent, variant: menuVariant, children: children }, void 0, false, { fileName: DropdownButton_jsxFileName, lineNumber: 119, columnNumber: 7 }, undefined)] }, void 0, true, { fileName: DropdownButton_jsxFileName, lineNumber: 108, columnNumber: 5 }, undefined)); DropdownButton.displayName = 'DropdownButton'; DropdownButton.propTypes = DropdownButton_propTypes; /* harmony default export */ const src_DropdownButton = (DropdownButton); ;// CONCATENATED MODULE: ./src/Feedback.tsx var Feedback_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Feedback.tsx"; const Feedback_propTypes = { /** * Specify whether the feedback is for valid or invalid fields * * @type {('valid'|'invalid')} */ type: (prop_types_default()).string, /** Display feedback as a tooltip. */ tooltip: (prop_types_default()).bool, as: (prop_types_default()).elementType }; const Feedback = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef( // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 ({ as: Component = 'div', className, type = 'valid', tooltip = false, ...props }, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref, className: classnames_default()(className, `${type}-${tooltip ? 'tooltip' : 'feedback'}`) }, void 0, false, { fileName: Feedback_jsxFileName, lineNumber: 45, columnNumber: 7 }, undefined)); Feedback.displayName = 'Feedback'; Feedback.propTypes = Feedback_propTypes; /* harmony default export */ const src_Feedback = (Feedback); ;// CONCATENATED MODULE: ./src/FormContext.tsx // TODO const FormContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext({}); /* harmony default export */ const src_FormContext = (FormContext); ;// CONCATENATED MODULE: ./src/FormCheckInput.tsx var FormCheckInput_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormCheckInput.tsx"; const FormCheckInput_propTypes = { /** * @default 'form-check-input' */ bsPrefix: (prop_types_default()).string, /** * The underlying HTML element to use when rendering the FormCheckInput. * * @type {('input'|elementType)} */ as: (prop_types_default()).elementType, /** A HTML id attribute, necessary for proper form accessibility. */ id: (prop_types_default()).string, /** The type of checkable. */ type: prop_types_default().oneOf(['radio', 'checkbox']).isRequired, /** Manually style the input as valid */ isValid: (prop_types_default()).bool, /** Manually style the input as invalid */ isInvalid: (prop_types_default()).bool }; const FormCheckInput = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ id, bsPrefix, className, type = 'checkbox', isValid = false, isInvalid = false, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'input', ...props }, ref) => { const { controlId } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_FormContext); bsPrefix = useBootstrapPrefix(bsPrefix, 'form-check-input'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref, type: type, id: id || controlId, className: classnames_default()(className, bsPrefix, isValid && 'is-valid', isInvalid && 'is-invalid') }, void 0, false, { fileName: FormCheckInput_jsxFileName, lineNumber: 67, columnNumber: 7 }, undefined); }); FormCheckInput.displayName = 'FormCheckInput'; FormCheckInput.propTypes = FormCheckInput_propTypes; /* harmony default export */ const src_FormCheckInput = (FormCheckInput); ;// CONCATENATED MODULE: ./src/FormCheckLabel.tsx var FormCheckLabel_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormCheckLabel.tsx"; const FormCheckLabel_propTypes = { /** * @default 'form-check-label' */ bsPrefix: (prop_types_default()).string, /** The HTML for attribute for associating the label with an input */ htmlFor: (prop_types_default()).string }; const FormCheckLabel = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, htmlFor, ...props }, ref) => { const { controlId } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_FormContext); bsPrefix = useBootstrapPrefix(bsPrefix, 'form-check-label'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("label", { ...props, ref: ref, htmlFor: htmlFor || controlId, className: classnames_default()(className, bsPrefix) }, void 0, false, { fileName: FormCheckLabel_jsxFileName, lineNumber: 31, columnNumber: 7 }, undefined); }); FormCheckLabel.displayName = 'FormCheckLabel'; FormCheckLabel.propTypes = FormCheckLabel_propTypes; /* harmony default export */ const src_FormCheckLabel = (FormCheckLabel); ;// CONCATENATED MODULE: ./src/FormCheck.tsx var FormCheck_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormCheck.tsx"; const FormCheck_propTypes = { /** * @default 'form-check' */ bsPrefix: (prop_types_default()).string, /** * bsPrefix override for the base switch class. * * @default 'form-switch' */ bsSwitchPrefix: (prop_types_default()).string, /** * The FormCheck `ref` will be forwarded to the underlying input element, * which means it will be a DOM node, when resolved. * * @type {ReactRef} * @alias ref */ _ref: (prop_types_default()).any, /** * The underlying HTML element to use when rendering the FormCheck. * * @type {('input'|elementType)} */ as: (prop_types_default()).elementType, /** * A HTML id attribute, necessary for proper form accessibility. * An id is recommended for allowing label clicks to toggle the check control. * * This is **required** when `type="switch"` due to how they are rendered. */ id: (prop_types_default()).string, /** * Provide a function child to manually handle the layout of the FormCheck's inner components. * * ```jsx * <FormCheck> * <FormCheck.Input isInvalid type={radio} /> * <FormCheck.Label>Allow us to contact you?</FormCheck.Label> * <Feedback type="invalid">Yo this is required</Feedback> * </FormCheck> * ``` */ children: (prop_types_default()).node, /** * Groups controls horizontally with other `FormCheck`s. */ inline: (prop_types_default()).bool, /** * Disables the control. */ disabled: (prop_types_default()).bool, /** * `title` attribute for the underlying `FormCheckLabel`. */ title: (prop_types_default()).string, /** * Label for the control. */ label: (prop_types_default()).node, /** * The type of checkable. * @type {('radio' | 'checkbox' | 'switch')} */ type: prop_types_default().oneOf(['radio', 'checkbox', 'switch']), /** Manually style the input as valid */ isValid: (prop_types_default()).bool, /** Manually style the input as invalid */ isInvalid: (prop_types_default()).bool, /** Display feedback as a tooltip. */ feedbackTooltip: (prop_types_default()).bool, /** A message to display when the input is in a validation state */ feedback: (prop_types_default()).node }; const FormCheck = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ id, bsPrefix, bsSwitchPrefix, inline = false, disabled = false, isValid = false, isInvalid = false, feedbackTooltip = false, feedback, feedbackType, className, style, title = '', type = 'checkbox', label, children, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as = 'input', ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'form-check'); bsSwitchPrefix = useBootstrapPrefix(bsSwitchPrefix, 'form-switch'); const { controlId } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_FormContext); const innerFormContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ controlId: id || controlId }), [controlId, id]); const hasLabel = !children && label != null && label !== false || hasChildOfType(children, src_FormCheckLabel); const input = /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_FormCheckInput, { ...props, type: type === 'switch' ? 'checkbox' : type, ref: ref, isValid: isValid, isInvalid: isInvalid, disabled: disabled, as: as }, void 0, false, { fileName: FormCheck_jsxFileName, lineNumber: 161, columnNumber: 9 }, undefined); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_FormContext.Provider, { value: innerFormContext, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { style: style, className: classnames_default()(className, hasLabel && bsPrefix, inline && `${bsPrefix}-inline`, type === 'switch' && bsSwitchPrefix), children: children || /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(jsx_dev_runtime.Fragment, { children: [input, hasLabel && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_FormCheckLabel, { title: title, children: label }, void 0, false, { fileName: FormCheck_jsxFileName, lineNumber: 187, columnNumber: 19 }, undefined), feedback && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Feedback, { type: feedbackType, tooltip: feedbackTooltip, children: feedback }, void 0, false, { fileName: FormCheck_jsxFileName, lineNumber: 190, columnNumber: 19 }, undefined)] }, void 0, true) }, void 0, false, { fileName: FormCheck_jsxFileName, lineNumber: 174, columnNumber: 11 }, undefined) }, void 0, false, { fileName: FormCheck_jsxFileName, lineNumber: 173, columnNumber: 9 }, undefined); }); FormCheck.displayName = 'FormCheck'; FormCheck.propTypes = FormCheck_propTypes; /* harmony default export */ const src_FormCheck = (Object.assign(FormCheck, { Input: src_FormCheckInput, Label: src_FormCheckLabel })); ;// CONCATENATED MODULE: ./src/FormControl.tsx var FormControl_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormControl.tsx"; const FormControl_propTypes = { /** * @default {'form-control'} */ bsPrefix: (prop_types_default()).string, /** * The FormControl `ref` will be forwarded to the underlying input element, * which means unless `as` is a composite component, * it will be a DOM node, when resolved. * * @type {ReactRef} * @alias ref */ _ref: (prop_types_default()).any, /** * Input size variants * * @type {('sm'|'lg')} */ size: (prop_types_default()).string, /** * The size attribute of the underlying HTML element. * Specifies the visible width in characters if `as` is `'input'`. */ htmlSize: (prop_types_default()).number, /** * The underlying HTML element to use when rendering the FormControl. * * @type {('input'|'textarea'|elementType)} */ as: (prop_types_default()).elementType, /** * Render the input as plain text. Generally used along side `readOnly`. */ plaintext: (prop_types_default()).bool, /** Make the control readonly */ readOnly: (prop_types_default()).bool, /** Make the control disabled */ disabled: (prop_types_default()).bool, /** * The `value` attribute of underlying input * * @controllable onChange * */ value: prop_types_default().oneOfType([(prop_types_default()).string, prop_types_default().arrayOf((prop_types_default()).string), (prop_types_default()).number]), /** A callback fired when the `value` prop changes */ onChange: (prop_types_default()).func, /** * The HTML input `type`, which is only relevant if `as` is `'input'` (the default). */ type: (prop_types_default()).string, /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ id: (prop_types_default()).string, /** Add "valid" validation styles to the control */ isValid: (prop_types_default()).bool, /** Add "invalid" validation styles to the control and accompanying label */ isInvalid: (prop_types_default()).bool }; const FormControl = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, type, size, htmlSize, id, className, isValid = false, isInvalid = false, plaintext, readOnly, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'input', ...props }, ref) => { const { controlId } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_FormContext); bsPrefix = useBootstrapPrefix(bsPrefix, 'form-control'); let classes; if (plaintext) { classes = { [`${bsPrefix}-plaintext`]: true }; } else { classes = { [bsPrefix]: true, [`${bsPrefix}-${size}`]: size }; } false ? 0 : void 0; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, type: type, size: htmlSize, ref: ref, readOnly: readOnly, id: id || controlId, className: classnames_default()(className, classes, isValid && `is-valid`, isInvalid && `is-invalid`, type === 'color' && `${bsPrefix}-color`) }, void 0, false, { fileName: FormControl_jsxFileName, lineNumber: 145, columnNumber: 9 }, undefined); }); FormControl.displayName = 'FormControl'; FormControl.propTypes = FormControl_propTypes; /* harmony default export */ const src_FormControl = (Object.assign(FormControl, { Feedback: src_Feedback })); ;// CONCATENATED MODULE: ./src/FormFloating.tsx /* harmony default export */ const FormFloating = (createWithBsPrefix('form-floating')); ;// CONCATENATED MODULE: ./src/FormGroup.tsx var FormGroup_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormGroup.tsx"; const FormGroup_propTypes = { as: (prop_types_default()).elementType, /** * Sets `id` on `<FormControl>` and `htmlFor` on `<FormGroup.Label>`. */ controlId: (prop_types_default()).string, /** * The FormGroup `ref` will be forwarded to the underlying element. * Unless the FormGroup is rendered `as` a composite component, * it will be a DOM node, when resolved. * * @type {ReactRef} * @alias ref */ _ref: (prop_types_default()).any }; const FormGroup = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ controlId, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', ...props }, ref) => { const context = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ controlId }), [controlId]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_FormContext.Provider, { value: context, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref }, void 0, false, { fileName: FormGroup_jsxFileName, lineNumber: 48, columnNumber: 11 }, undefined) }, void 0, false, { fileName: FormGroup_jsxFileName, lineNumber: 47, columnNumber: 9 }, undefined); }); FormGroup.displayName = 'FormGroup'; FormGroup.propTypes = FormGroup_propTypes; /* harmony default export */ const src_FormGroup = (FormGroup); ;// CONCATENATED MODULE: ./src/FormLabel.tsx var FormLabel_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormLabel.tsx"; const FormLabel_propTypes = { /** * @default 'form-label' */ bsPrefix: (prop_types_default()).string, /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ htmlFor: (prop_types_default()).string, /** * Renders the FormLabel as a `<Col>` component (accepting all the same props), * as well as adding additional styling for horizontal forms. */ column: prop_types_default().oneOfType([(prop_types_default()).bool, prop_types_default().oneOf(['sm', 'lg'])]), /** * The FormLabel `ref` will be forwarded to the underlying element. * Unless the FormLabel is rendered `as` a composite component, * it will be a DOM node, when resolved. * * @type {ReactRef} * @alias ref */ _ref: (prop_types_default()).any, /** * Hides the label visually while still allowing it to be * read by assistive technologies. */ visuallyHidden: (prop_types_default()).bool, /** Set a custom element for this component */ as: (prop_types_default()).elementType }; const FormLabel_defaultProps = { column: false, visuallyHidden: false }; const FormLabel = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'label', bsPrefix, column, visuallyHidden, className, htmlFor, ...props }, ref) => { const { controlId } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_FormContext); bsPrefix = useBootstrapPrefix(bsPrefix, 'form-label'); let columnClass = 'col-form-label'; if (typeof column === 'string') columnClass = `${columnClass} ${columnClass}-${column}`; const classes = classnames_default()(className, bsPrefix, visuallyHidden && 'visually-hidden', column && columnClass); false ? 0 : void 0; htmlFor = htmlFor || controlId; if (column) return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Col, { ref: ref, as: "label", className: classes, htmlFor: htmlFor, ...props }, void 0, false, { fileName: FormLabel_jsxFileName, lineNumber: 109, columnNumber: 11 }, undefined); return ( /*#__PURE__*/ // eslint-disable-next-line jsx-a11y/label-has-for, jsx-a11y/label-has-associated-control (0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, className: classes, htmlFor: htmlFor, ...props }, void 0, false, { fileName: FormLabel_jsxFileName, lineNumber: 120, columnNumber: 9 }, undefined) ); }); FormLabel.displayName = 'FormLabel'; FormLabel.propTypes = FormLabel_propTypes; FormLabel.defaultProps = FormLabel_defaultProps; /* harmony default export */ const src_FormLabel = (FormLabel); ;// CONCATENATED MODULE: ./src/FormRange.tsx var FormRange_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormRange.tsx"; const FormRange_propTypes = { /** * @default {'form-range'} */ bsPrefix: (prop_types_default()).string, /** Make the control disabled */ disabled: (prop_types_default()).bool, /** * The `value` attribute of underlying input * * @controllable onChange * */ value: prop_types_default().oneOfType([(prop_types_default()).string, prop_types_default().arrayOf((prop_types_default()).string.isRequired), (prop_types_default()).number]), /** A callback fired when the `value` prop changes */ onChange: (prop_types_default()).func, /** * Uses `controlId` from `<FormGroup>` if not explicitly specified. */ id: (prop_types_default()).string }; const FormRange = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, id, ...props }, ref) => { const { controlId } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_FormContext); bsPrefix = useBootstrapPrefix(bsPrefix, 'form-range'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("input", { ...props, type: "range", ref: ref, className: classnames_default()(className, bsPrefix), id: id || controlId }, void 0, false, { fileName: FormRange_jsxFileName, lineNumber: 48, columnNumber: 7 }, undefined); }); FormRange.displayName = 'FormRange'; FormRange.propTypes = FormRange_propTypes; /* harmony default export */ const src_FormRange = (FormRange); ;// CONCATENATED MODULE: ./src/FormSelect.tsx var FormSelect_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormSelect.tsx"; const FormSelect_propTypes = { /** * @default {'form-select'} */ bsPrefix: (prop_types_default()).string, /** * Size variants * * @type {('sm'|'lg')} */ size: (prop_types_default()).string, /** * The size attribute of the underlying HTML element. * Specifies the number of visible options. */ htmlSize: (prop_types_default()).number, /** Make the control disabled */ disabled: (prop_types_default()).bool, /** * The `value` attribute of underlying input * * @controllable onChange * */ value: prop_types_default().oneOfType([(prop_types_default()).string, prop_types_default().arrayOf((prop_types_default()).string), (prop_types_default()).number]), /** A callback fired when the `value` prop changes */ onChange: (prop_types_default()).func, /** Add "valid" validation styles to the control */ isValid: (prop_types_default()).bool, /** Add "invalid" validation styles to the control and accompanying label */ isInvalid: (prop_types_default()).bool }; const FormSelect = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, size, htmlSize, className, isValid = false, isInvalid = false, id, ...props }, ref) => { const { controlId } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_FormContext); bsPrefix = useBootstrapPrefix(bsPrefix, 'form-select'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("select", { ...props, size: htmlSize, ref: ref, className: classnames_default()(className, bsPrefix, size && `${bsPrefix}-${size}`, isValid && `is-valid`, isInvalid && `is-invalid`), id: id || controlId }, void 0, false, { fileName: FormSelect_jsxFileName, lineNumber: 80, columnNumber: 9 }, undefined); }); FormSelect.displayName = 'FormSelect'; FormSelect.propTypes = FormSelect_propTypes; /* harmony default export */ const src_FormSelect = (FormSelect); ;// CONCATENATED MODULE: ./src/FormText.tsx var FormText_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FormText.tsx"; const FormText_propTypes = { /** @default 'form-text' */ bsPrefix: (prop_types_default()).string, /** * The FormText `ref` will be forwarded to the underlying element. * Unless the FormText is rendered `as` a composite component, * it will be a DOM node, when resolved. * * @type {ReactRef} * @alias ref */ _ref: (prop_types_default()).any, /** * A convenience prop for add the `text-muted` class, * since it's so commonly used here. */ muted: (prop_types_default()).bool, as: (prop_types_default()).elementType }; const FormText = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef( // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 ({ bsPrefix, className, as: Component = 'small', muted, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'form-text'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref, className: classnames_default()(className, bsPrefix, muted && 'text-muted') }, void 0, false, { fileName: FormText_jsxFileName, lineNumber: 48, columnNumber: 9 }, undefined); }); FormText.displayName = 'FormText'; FormText.propTypes = FormText_propTypes; /* harmony default export */ const src_FormText = (FormText); ;// CONCATENATED MODULE: ./src/Switch.tsx var Switch_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Switch.tsx"; const Switch = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_FormCheck, { ...props, ref: ref, type: "switch" }, void 0, false, { fileName: Switch_jsxFileName, lineNumber: 9, columnNumber: 5 }, undefined)); Switch.displayName = 'Switch'; /* harmony default export */ const src_Switch = (Object.assign(Switch, { Input: src_FormCheck.Input, Label: src_FormCheck.Label })); ;// CONCATENATED MODULE: ./src/FloatingLabel.tsx var FloatingLabel_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FloatingLabel.tsx"; const FloatingLabel_propTypes = { as: (prop_types_default()).elementType, /** * Sets `id` on `<FormControl>` and `htmlFor` on `<label>`. */ controlId: (prop_types_default()).string, /** * Form control label. */ label: (prop_types_default()).node.isRequired }; const FloatingLabel = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, children, controlId, label, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'form-floating'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_FormGroup, { ref: ref, className: classnames_default()(className, bsPrefix), controlId: controlId, ...props, children: [children, /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("label", { htmlFor: controlId, children: label }, void 0, false, { fileName: FloatingLabel_jsxFileName, lineNumber: 41, columnNumber: 11 }, undefined)] }, void 0, true, { fileName: FloatingLabel_jsxFileName, lineNumber: 34, columnNumber: 9 }, undefined); }); FloatingLabel.displayName = 'FloatingLabel'; FloatingLabel.propTypes = FloatingLabel_propTypes; /* harmony default export */ const src_FloatingLabel = (FloatingLabel); ;// CONCATENATED MODULE: ./src/Form.tsx var Form_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Form.tsx"; const Form_propTypes = { /** * The Form `ref` will be forwarded to the underlying element, * which means, unless it's rendered `as` a composite component, * it will be a DOM node, when resolved. * * @type {ReactRef} * @alias ref */ _ref: (prop_types_default()).any, /** * Mark a form as having been validated. Setting it to `true` will * toggle any validation styles on the forms elements. */ validated: (prop_types_default()).bool, as: (prop_types_default()).elementType }; const Form = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ className, validated, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'form', ...props }, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref, className: classnames_default()(className, validated && 'was-validated') }, void 0, false, { fileName: Form_jsxFileName, lineNumber: 53, columnNumber: 7 }, undefined)); Form.displayName = 'Form'; Form.propTypes = Form_propTypes; /* harmony default export */ const src_Form = (Object.assign(Form, { Group: src_FormGroup, Control: src_FormControl, Floating: FormFloating, Check: src_FormCheck, Switch: src_Switch, Label: src_FormLabel, Text: src_FormText, Range: src_FormRange, Select: src_FormSelect, FloatingLabel: src_FloatingLabel })); ;// CONCATENATED MODULE: ./src/Container.tsx var Container_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Container.tsx"; const containerSizes = prop_types_default().oneOfType([(prop_types_default()).bool, prop_types_default().oneOf(['sm', 'md', 'lg', 'xl', 'xxl'])]); const Container_propTypes = { /** * @default 'container' */ bsPrefix: (prop_types_default()).string, /** * Allow the Container to fill all of its available horizontal space. * @type {(true|"sm"|"md"|"lg"|"xl"|"xxl")} */ fluid: containerSizes, /** * You can use a custom element for this component */ as: (prop_types_default()).elementType }; const Container_defaultProps = { fluid: false }; const Container = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, fluid, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', className, ...props }, ref) => { const prefix = useBootstrapPrefix(bsPrefix, 'container'); const suffix = typeof fluid === 'string' ? `-${fluid}` : '-fluid'; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, fluid ? `${prefix}${suffix}` : prefix) }, void 0, false, { fileName: Container_jsxFileName, lineNumber: 56, columnNumber: 9 }, undefined); }); Container.displayName = 'Container'; Container.propTypes = Container_propTypes; Container.defaultProps = Container_defaultProps; /* harmony default export */ const src_Container = (Container); ;// CONCATENATED MODULE: ./src/Image.tsx var Image_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Image.tsx"; const Image_propTypes = { /** * @default 'img' */ bsPrefix: (prop_types_default()).string, /** * Sets image as fluid image. */ fluid: (prop_types_default()).bool, /** * Sets image shape as rounded. */ rounded: (prop_types_default()).bool, /** * Sets image shape as circle. */ roundedCircle: (prop_types_default()).bool, /** * Sets image shape as thumbnail. */ thumbnail: (prop_types_default()).bool }; const Image_defaultProps = { fluid: false, rounded: false, roundedCircle: false, thumbnail: false }; const Image_Image = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, fluid, rounded, roundedCircle, thumbnail, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'img'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("img", { // eslint-disable-line jsx-a11y/alt-text ref: ref, ...props, className: classnames_default()(className, fluid && `${bsPrefix}-fluid`, rounded && `rounded`, roundedCircle && `rounded-circle`, thumbnail && `${bsPrefix}-thumbnail`) }, void 0, false, { fileName: Image_jsxFileName, lineNumber: 57, columnNumber: 7 }, undefined); }); Image_Image.displayName = 'Image'; Image_Image.propTypes = Image_propTypes; Image_Image.defaultProps = Image_defaultProps; /* harmony default export */ const src_Image = (Image_Image); ;// CONCATENATED MODULE: ./src/FigureImage.tsx var FigureImage_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/FigureImage.tsx"; const FigureImage_defaultProps = { fluid: true }; const FigureImage = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ className, ...props }, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Image, { ref: ref, ...props, className: classnames_default()(className, 'figure-img') }, void 0, false, { fileName: FigureImage_jsxFileName, lineNumber: 10, columnNumber: 5 }, undefined)); FigureImage.displayName = 'FigureImage'; FigureImage.propTypes = Image_propTypes; FigureImage.defaultProps = FigureImage_defaultProps; /* harmony default export */ const src_FigureImage = (FigureImage); ;// CONCATENATED MODULE: ./src/FigureCaption.tsx const FigureCaption = createWithBsPrefix('figure-caption', { Component: 'figcaption' }); /* harmony default export */ const src_FigureCaption = (FigureCaption); ;// CONCATENATED MODULE: ./src/Figure.tsx const Figure = createWithBsPrefix('figure', { Component: 'figure' }); /* harmony default export */ const src_Figure = (Object.assign(Figure, { Image: src_FigureImage, Caption: src_FigureCaption })); ;// CONCATENATED MODULE: ./src/InputGroup.tsx var InputGroup_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/InputGroup.tsx"; const InputGroupText = createWithBsPrefix('input-group-text', { Component: 'span' }); const InputGroupCheckbox = props => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(InputGroupText, { children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_FormCheckInput, { type: "checkbox", ...props }, void 0, false, { fileName: InputGroup_jsxFileName, lineNumber: 19, columnNumber: 5 }, undefined) }, void 0, false, { fileName: InputGroup_jsxFileName, lineNumber: 18, columnNumber: 3 }, undefined); const InputGroupRadio = props => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(InputGroupText, { children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_FormCheckInput, { type: "radio", ...props }, void 0, false, { fileName: InputGroup_jsxFileName, lineNumber: 25, columnNumber: 5 }, undefined) }, void 0, false, { fileName: InputGroup_jsxFileName, lineNumber: 24, columnNumber: 3 }, undefined); const InputGroup_propTypes = { /** @default 'input-group' */ bsPrefix: (prop_types_default()).string, /** * Control the size of buttons and form elements from the top-level. * * @type {('sm'|'lg')} */ size: (prop_types_default()).string, /** * Handles the input's rounded corners when using form validation. * * Use this when your input group contains both an input and feedback element. */ hasValidation: (prop_types_default()).bool, as: (prop_types_default()).elementType }; /** * * @property {InputGroupText} Text * @property {InputGroupRadio} Radio * @property {InputGroupCheckbox} Checkbox */ const InputGroup = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, size, hasValidation, className, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'input-group'); // Intentionally an empty object. Used in detecting if a dropdown // exists under an input group. const contextValue = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({}), []); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(InputGroupContext.Provider, { value: contextValue, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, bsPrefix, size && `${bsPrefix}-${size}`, hasValidation && 'has-validation') }, void 0, false, { fileName: InputGroup_jsxFileName, lineNumber: 85, columnNumber: 11 }, undefined) }, void 0, false, { fileName: InputGroup_jsxFileName, lineNumber: 84, columnNumber: 9 }, undefined); }); InputGroup.propTypes = InputGroup_propTypes; InputGroup.displayName = 'InputGroup'; /* harmony default export */ const src_InputGroup = (Object.assign(InputGroup, { Text: InputGroupText, Radio: InputGroupRadio, Checkbox: InputGroupCheckbox })); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useMergedRefs.js var useMergedRefs_toFnRef = function toFnRef(ref) { return !ref || typeof ref === 'function' ? ref : function (value) { ref.current = value; }; }; function useMergedRefs_mergeRefs(refA, refB) { var a = useMergedRefs_toFnRef(refA); var b = useMergedRefs_toFnRef(refB); return function (value) { if (a) a(value); if (b) b(value); }; } /** * Create and returns a single callback ref composed from two other Refs. * * ```tsx * const Button = React.forwardRef((props, ref) => { * const [element, attachRef] = useCallbackRef<HTMLButtonElement>(); * const mergedRef = useMergedRefs(ref, attachRef); * * return <button ref={mergedRef} {...props}/> * }) * ``` * * @param refA A Callback or mutable Ref * @param refB A Callback or mutable Ref * @category refs */ function useMergedRefs_useMergedRefs(refA, refB) { return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(function () { return useMergedRefs_mergeRefs(refA, refB); }, [refA, refB]); } /* harmony default export */ const hooks_esm_useMergedRefs = (useMergedRefs_useMergedRefs); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/TabContext.js const TabContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext(null); /* harmony default export */ const esm_TabContext = (TabContext); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/NavItem.js const NavItem_excluded = ["as", "active", "eventKey"]; function NavItem_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function useNavItem({ key, onClick, active, id, role, disabled }) { const parentOnSelect = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_SelectableContext); const navContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_NavContext); let isActive = active; const props = { role }; if (navContext) { if (!role && navContext.role === 'tablist') props.role = 'tab'; const contextControllerId = navContext.getControllerId(key != null ? key : null); const contextControlledId = navContext.getControlledId(key != null ? key : null); // @ts-ignore props[dataAttr('event-key')] = key; props.id = contextControllerId || id; props['aria-controls'] = contextControlledId; isActive = active == null && key != null ? navContext.activeKey === key : active; } if (props.role === 'tab') { if (disabled) { props.tabIndex = -1; props['aria-disabled'] = true; } if (isActive) { props['aria-selected'] = isActive; } else { props.tabIndex = -1; } } props.onClick = useEventCallback_useEventCallback(e => { if (disabled) return; onClick == null ? void 0 : onClick(e); if (key == null) { return; } if (parentOnSelect && !e.isPropagationStopped()) { parentOnSelect(key, e); } }); return [props, { isActive }]; } const NavItem = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((_ref, ref) => { let { as: Component = esm_Button, active, eventKey } = _ref, options = NavItem_objectWithoutPropertiesLoose(_ref, NavItem_excluded); const [props, meta] = useNavItem(Object.assign({ key: makeEventKey(eventKey, options.href), active }, options)); // @ts-ignore props[dataAttr('active')] = meta.isActive; return /*#__PURE__*/(0,jsx_runtime.jsx)(Component, Object.assign({}, options, props, { ref: ref })); }); NavItem.displayName = 'NavItem'; /* harmony default export */ const esm_NavItem = (NavItem); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/Nav.js const Nav_excluded = ["as", "onSelect", "activeKey", "role", "onKeyDown"]; function Nav_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } // eslint-disable-next-line @typescript-eslint/no-empty-function const Nav_noop = () => {}; const EVENT_KEY_ATTR = dataAttr('event-key'); const Nav = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((_ref, ref) => { let { // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', onSelect, activeKey, role, onKeyDown } = _ref, props = Nav_objectWithoutPropertiesLoose(_ref, Nav_excluded); // A ref and forceUpdate for refocus, b/c we only want to trigger when needed // and don't want to reset the set in the effect const forceUpdate = useForceUpdate(); const needsRefocusRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(false); const parentOnSelect = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_SelectableContext); const tabContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_TabContext); let getControlledId, getControllerId; if (tabContext) { role = role || 'tablist'; activeKey = tabContext.activeKey; // TODO: do we need to duplicate these? getControlledId = tabContext.getControlledId; getControllerId = tabContext.getControllerId; } const listNode = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); const getNextActiveTab = offset => { const currentListNode = listNode.current; if (!currentListNode) return null; const items = qsa(currentListNode, `[${EVENT_KEY_ATTR}]:not([aria-disabled=true])`); const activeChild = currentListNode.querySelector('[aria-selected=true]'); if (!activeChild) return null; const index = items.indexOf(activeChild); if (index === -1) return null; let nextIndex = index + offset; if (nextIndex >= items.length) nextIndex = 0; if (nextIndex < 0) nextIndex = items.length - 1; return items[nextIndex]; }; const handleSelect = (key, event) => { if (key == null) return; onSelect == null ? void 0 : onSelect(key, event); parentOnSelect == null ? void 0 : parentOnSelect(key, event); }; const handleKeyDown = event => { onKeyDown == null ? void 0 : onKeyDown(event); if (!tabContext) { return; } let nextActiveChild; switch (event.key) { case 'ArrowLeft': case 'ArrowUp': nextActiveChild = getNextActiveTab(-1); break; case 'ArrowRight': case 'ArrowDown': nextActiveChild = getNextActiveTab(1); break; default: return; } if (!nextActiveChild) return; event.preventDefault(); handleSelect(nextActiveChild.dataset[dataProp('EventKey')] || null, event); needsRefocusRef.current = true; forceUpdate(); }; (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (listNode.current && needsRefocusRef.current) { const activeChild = listNode.current.querySelector(`[${EVENT_KEY_ATTR}][aria-selected=true]`); activeChild == null ? void 0 : activeChild.focus(); } needsRefocusRef.current = false; }); const mergedRef = hooks_esm_useMergedRefs(ref, listNode); return /*#__PURE__*/(0,jsx_runtime.jsx)(esm_SelectableContext.Provider, { value: handleSelect, children: /*#__PURE__*/(0,jsx_runtime.jsx)(esm_NavContext.Provider, { value: { role, // used by NavLink to determine it's role activeKey: makeEventKey(activeKey), getControlledId: getControlledId || Nav_noop, getControllerId: getControllerId || Nav_noop }, children: /*#__PURE__*/(0,jsx_runtime.jsx)(Component, Object.assign({}, props, { onKeyDown: handleKeyDown, ref: mergedRef, role: role })) }) }); }); Nav.displayName = 'Nav'; /* harmony default export */ const esm_Nav = (Object.assign(Nav, { Item: esm_NavItem })); ;// CONCATENATED MODULE: ./src/ListGroupItem.tsx var ListGroupItem_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ListGroupItem.tsx"; const ListGroupItem_propTypes = { /** * @default 'list-group-item' */ bsPrefix: (prop_types_default()).string, /** * Sets contextual classes for list item * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'dark'|'light')} */ variant: (prop_types_default()).string, /** * Marks a ListGroupItem as actionable, applying additional hover, active and disabled styles * for links and buttons. */ action: (prop_types_default()).bool, /** * Sets list item as active */ active: (prop_types_default()).bool, /** * Sets list item state as disabled */ disabled: (prop_types_default()).bool, eventKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]), onClick: (prop_types_default()).func, href: (prop_types_default()).string, /** * You can use a custom element type for this component. For none `action` items, items render as `li`. * For actions the default is an achor or button element depending on whether a `href` is provided. * * @default {'div' | 'a' | 'button'} */ as: (prop_types_default()).elementType }; const ListGroupItem = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, active, disabled, eventKey, className, variant, action, as, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'list-group-item'); const [navItemProps, meta] = useNavItem({ key: makeEventKey(eventKey, props.href), active, ...props }); const handleClick = useEventCallback(event => { if (disabled) { event.preventDefault(); event.stopPropagation(); return; } navItemProps.onClick(event); }); if (disabled && props.tabIndex === undefined) { props.tabIndex = -1; props['aria-disabled'] = true; } // eslint-disable-next-line no-nested-ternary const Component = as || (action ? props.href ? 'a' : 'button' : 'div'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, ...navItemProps, onClick: handleClick, className: classnames_default()(className, bsPrefix, meta.isActive && 'active', disabled && 'disabled', variant && `${bsPrefix}-${variant}`, action && `${bsPrefix}-action`) }, void 0, false, { fileName: ListGroupItem_jsxFileName, lineNumber: 105, columnNumber: 9 }, undefined); }); ListGroupItem.propTypes = ListGroupItem_propTypes; ListGroupItem.displayName = 'ListGroupItem'; /* harmony default export */ const src_ListGroupItem = (ListGroupItem); ;// CONCATENATED MODULE: ./src/ListGroup.tsx var ListGroup_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ListGroup.tsx"; const ListGroup_propTypes = { /** * @default 'list-group' */ bsPrefix: (prop_types_default()).string, /** * Adds a variant to the list-group * * @type {('flush')} */ variant: prop_types_default().oneOf(['flush']), /** * Changes the flow of the list group items from vertical to horizontal. * A value of `null` (the default) sets it to vertical for all breakpoints; * Just including the prop sets it for all breakpoints, while `{sm|md|lg|xl|xxl}` * makes the list group horizontal starting at that breakpoint’s `min-width`. * @type {(true|'sm'|'md'|'lg'|'xl'|'xxl')} */ horizontal: prop_types_default().oneOf([true, 'sm', 'md', 'lg', 'xl', 'xxl']), /** * Generate numbered list items. */ numbered: (prop_types_default()).bool, /** * You can use a custom element type for this component. */ as: (prop_types_default()).elementType }; const ListGroup = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, ref) => { const { className, bsPrefix: initialBsPrefix, variant, horizontal, numbered, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as = 'div', ...controlledProps } = useUncontrolled(props, { activeKey: 'onSelect' }); const bsPrefix = useBootstrapPrefix(initialBsPrefix, 'list-group'); let horizontalVariant; if (horizontal) { horizontalVariant = horizontal === true ? 'horizontal' : `horizontal-${horizontal}`; } false ? 0 : void 0; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Nav, { ref: ref, ...controlledProps, as: as, className: classnames_default()(className, bsPrefix, variant && `${bsPrefix}-${variant}`, horizontalVariant && `${bsPrefix}-${horizontalVariant}`, numbered && `${bsPrefix}-numbered`) }, void 0, false, { fileName: ListGroup_jsxFileName, lineNumber: 81, columnNumber: 7 }, undefined); }); ListGroup.propTypes = ListGroup_propTypes; ListGroup.displayName = 'ListGroup'; /* harmony default export */ const src_ListGroup = (Object.assign(ListGroup, { Item: src_ListGroupItem })); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/scrollbarSize.js var size; function scrollbarSize(recalc) { if (!size && size !== 0 || recalc) { if (canUseDOM) { var scrollDiv = document.createElement('div'); scrollDiv.style.position = 'absolute'; scrollDiv.style.top = '-9999px'; scrollDiv.style.width = '50px'; scrollDiv.style.height = '50px'; scrollDiv.style.overflow = 'scroll'; document.body.appendChild(scrollDiv); size = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); } } return size; } ;// CONCATENATED MODULE: ./node_modules/@restart/hooks/esm/useCallbackRef.js /** * A convenience hook around `useState` designed to be paired with * the component [callback ref](https://reactjs.org/docs/refs-and-the-dom.html#callback-refs) api. * Callback refs are useful over `useRef()` when you need to respond to the ref being set * instead of lazily accessing it in an effect. * * ```ts * const [element, attachRef] = useCallbackRef<HTMLDivElement>() * * useEffect(() => { * if (!element) return * * const calendar = new FullCalendar.Calendar(element) * * return () => { * calendar.destroy() * } * }, [element]) * * return <div ref={attachRef} /> * ``` * * @category refs */ function useCallbackRef_useCallbackRef() { return (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(null); } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/activeElement.js /** * Returns the actively focused element safely. * * @param doc the document to check */ function activeElement(doc) { if (doc === void 0) { doc = ownerDocument(); } // Support: IE 9 only // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { var active = doc.activeElement; // IE11 returns a seemingly empty object in some cases when accessing // document.activeElement from an <iframe> if (!active || !active.nodeName) return null; return active; } catch (e) { /* ie throws if no active element */ return doc.body; } } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useUpdatedRef.js /** * Returns a ref that is immediately updated with the new value * * @param value The Ref value * @category refs */ function useUpdatedRef_useUpdatedRef(value) { var valueRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(value); valueRef.current = value; return valueRef; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/node_modules/@restart/hooks/esm/useWillUnmount.js /** * Attach a callback that fires when a component unmounts * * @param fn Handler to run when the component unmounts * @category effects */ function useWillUnmount_useWillUnmount(fn) { var onUnmount = useUpdatedRef_useUpdatedRef(fn); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(function () { return function () { return onUnmount.current(); }; }, []); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/getScrollbarWidth.js /** * Get the width of the vertical window scrollbar if it's visible */ function getBodyScrollbarWidth(ownerDocument = document) { const window = ownerDocument.defaultView; return Math.abs(window.innerWidth - ownerDocument.documentElement.clientWidth); } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/ModalManager.js const OPEN_DATA_ATTRIBUTE = dataAttr('modal-open'); /** * Manages a stack of Modals as well as ensuring * body scrolling is is disabled and padding accounted for */ class ModalManager { constructor({ ownerDocument, handleContainerOverflow = true, isRTL = false } = {}) { this.handleContainerOverflow = handleContainerOverflow; this.isRTL = isRTL; this.modals = []; this.ownerDocument = ownerDocument; } getScrollbarWidth() { return getBodyScrollbarWidth(this.ownerDocument); } getElement() { return (this.ownerDocument || document).body; } setModalAttributes(_modal) {// For overriding } removeModalAttributes(_modal) {// For overriding } setContainerStyle(containerState) { const style = { overflow: 'hidden' }; // we are only interested in the actual `style` here // because we will override it const paddingProp = this.isRTL ? 'paddingLeft' : 'paddingRight'; const container = this.getElement(); containerState.style = { overflow: container.style.overflow, [paddingProp]: container.style[paddingProp] }; if (containerState.scrollBarWidth) { // use computed style, here to get the real padding // to add our scrollbar width style[paddingProp] = `${parseInt(css(container, paddingProp) || '0', 10) + containerState.scrollBarWidth}px`; } container.setAttribute(OPEN_DATA_ATTRIBUTE, ''); css(container, style); } reset() { [...this.modals].forEach(m => this.remove(m)); } removeContainerStyle(containerState) { const container = this.getElement(); container.removeAttribute(OPEN_DATA_ATTRIBUTE); Object.assign(container.style, containerState.style); } add(modal) { let modalIdx = this.modals.indexOf(modal); if (modalIdx !== -1) { return modalIdx; } modalIdx = this.modals.length; this.modals.push(modal); this.setModalAttributes(modal); if (modalIdx !== 0) { return modalIdx; } this.state = { scrollBarWidth: this.getScrollbarWidth(), style: {} }; if (this.handleContainerOverflow) { this.setContainerStyle(this.state); } return modalIdx; } remove(modal) { const modalIdx = this.modals.indexOf(modal); if (modalIdx === -1) { return; } this.modals.splice(modalIdx, 1); // if that was the last modal in a container, // clean up the container if (!this.modals.length && this.handleContainerOverflow) { this.removeContainerStyle(this.state); } this.removeModalAttributes(modal); } isTopModal(modal) { return !!this.modals.length && this.modals[this.modals.length - 1] === modal; } } /* harmony default export */ const esm_ModalManager = (ModalManager); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/useWaitForDOMRef.js const resolveContainerRef = (ref, document) => { var _ref; if (!canUseDOM) return null; if (ref == null) return (document || ownerDocument()).body; if (typeof ref === 'function') ref = ref(); if (ref && 'current' in ref) ref = ref.current; if ((_ref = ref) != null && _ref.nodeType) return ref || null; return null; }; function useWaitForDOMRef(ref, onResolved) { const window = useWindow(); const [resolvedRef, setRef] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(() => resolveContainerRef(ref, window == null ? void 0 : window.document)); if (!resolvedRef) { const earlyRef = resolveContainerRef(ref); if (earlyRef) setRef(earlyRef); } (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (onResolved && resolvedRef) { onResolved(resolvedRef); } }, [onResolved, resolvedRef]); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { const nextRef = resolveContainerRef(ref); if (nextRef !== resolvedRef) { setRef(nextRef); } }, [ref, resolvedRef]); return resolvedRef; } ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/Modal.js const Modal_excluded = ["show", "role", "className", "style", "children", "backdrop", "keyboard", "onBackdropClick", "onEscapeKeyDown", "transition", "backdropTransition", "autoFocus", "enforceFocus", "restoreFocus", "restoreFocusOptions", "renderDialog", "renderBackdrop", "manager", "container", "onShow", "onHide", "onExit", "onExited", "onExiting", "onEnter", "onEntering", "onEntered"]; function Modal_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /* eslint-disable @typescript-eslint/no-use-before-define, react/prop-types */ let manager; function getManager(window) { if (!manager) manager = new esm_ModalManager({ ownerDocument: window == null ? void 0 : window.document }); return manager; } function useModalManager(provided) { const window = useWindow(); const modalManager = provided || getManager(window); const modal = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)({ dialog: null, backdrop: null }); return Object.assign(modal.current, { add: () => modalManager.add(modal.current), remove: () => modalManager.remove(modal.current), isTopModal: () => modalManager.isTopModal(modal.current), setDialogRef: (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(ref => { modal.current.dialog = ref; }, []), setBackdropRef: (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(ref => { modal.current.backdrop = ref; }, []) }); } const Modal = /*#__PURE__*/(0,external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef)((_ref, ref) => { let { show = false, role = 'dialog', className, style, children, backdrop = true, keyboard = true, onBackdropClick, onEscapeKeyDown, transition, backdropTransition, autoFocus = true, enforceFocus = true, restoreFocus = true, restoreFocusOptions, renderDialog, renderBackdrop = props => /*#__PURE__*/(0,jsx_runtime.jsx)("div", Object.assign({}, props)), manager: providedManager, container: containerRef, onShow, onHide = () => {}, onExit, onExited, onExiting, onEnter, onEntering, onEntered } = _ref, rest = Modal_objectWithoutPropertiesLoose(_ref, Modal_excluded); const container = useWaitForDOMRef(containerRef); const modal = useModalManager(providedManager); const isMounted = useMounted(); const prevShow = usePrevious(show); const [exited, setExited] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(!show); const lastFocusRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useImperativeHandle)(ref, () => modal, [modal]); if (canUseDOM && !prevShow && show) { lastFocusRef.current = activeElement(); } if (!transition && !show && !exited) { setExited(true); } else if (show && exited) { setExited(false); } const handleShow = useEventCallback_useEventCallback(() => { modal.add(); removeKeydownListenerRef.current = esm_listen(document, 'keydown', handleDocumentKeyDown); removeFocusListenerRef.current = esm_listen(document, 'focus', // the timeout is necessary b/c this will run before the new modal is mounted // and so steals focus from it () => setTimeout(handleEnforceFocus), true); if (onShow) { onShow(); } // autofocus after onShow to not trigger a focus event for previous // modals before this one is shown. if (autoFocus) { const currentActiveElement = activeElement(document); if (modal.dialog && currentActiveElement && !contains_contains(modal.dialog, currentActiveElement)) { lastFocusRef.current = currentActiveElement; modal.dialog.focus(); } } }); const handleHide = useEventCallback_useEventCallback(() => { modal.remove(); removeKeydownListenerRef.current == null ? void 0 : removeKeydownListenerRef.current(); removeFocusListenerRef.current == null ? void 0 : removeFocusListenerRef.current(); if (restoreFocus) { var _lastFocusRef$current; // Support: <=IE11 doesn't support `focus()` on svg elements (RB: #917) (_lastFocusRef$current = lastFocusRef.current) == null ? void 0 : _lastFocusRef$current.focus == null ? void 0 : _lastFocusRef$current.focus(restoreFocusOptions); lastFocusRef.current = null; } }); // TODO: try and combine these effects: https://github.com/react-bootstrap/react-overlays/pull/794#discussion_r409954120 // Show logic when: // - show is `true` _and_ `container` has resolved (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (!show || !container) return; handleShow(); }, [show, container, /* should never change: */ handleShow]); // Hide cleanup logic when: // - `exited` switches to true // - component unmounts; (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (!exited) return; handleHide(); }, [exited, handleHide]); useWillUnmount_useWillUnmount(() => { handleHide(); }); // -------------------------------- const handleEnforceFocus = useEventCallback_useEventCallback(() => { if (!enforceFocus || !isMounted() || !modal.isTopModal()) { return; } const currentActiveElement = activeElement(); if (modal.dialog && currentActiveElement && !contains_contains(modal.dialog, currentActiveElement)) { modal.dialog.focus(); } }); const handleBackdropClick = useEventCallback_useEventCallback(e => { if (e.target !== e.currentTarget) { return; } onBackdropClick == null ? void 0 : onBackdropClick(e); if (backdrop === true) { onHide(); } }); const handleDocumentKeyDown = useEventCallback_useEventCallback(e => { if (keyboard && e.keyCode === 27 && modal.isTopModal()) { onEscapeKeyDown == null ? void 0 : onEscapeKeyDown(e); if (!e.defaultPrevented) { onHide(); } } }); const removeFocusListenerRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(); const removeKeydownListenerRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(); const handleHidden = (...args) => { setExited(true); onExited == null ? void 0 : onExited(...args); }; const Transition = transition; if (!container || !(show || Transition && !exited)) { return null; } const dialogProps = Object.assign({ role, ref: modal.setDialogRef, // apparently only works on the dialog role element 'aria-modal': role === 'dialog' ? true : undefined }, rest, { style, className, tabIndex: -1 }); let dialog = renderDialog ? renderDialog(dialogProps) : /*#__PURE__*/(0,jsx_runtime.jsx)("div", Object.assign({}, dialogProps, { children: /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement(children, { role: 'document' }) })); if (Transition) { dialog = /*#__PURE__*/(0,jsx_runtime.jsx)(Transition, { appear: true, unmountOnExit: true, in: !!show, onExit: onExit, onExiting: onExiting, onExited: handleHidden, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, children: dialog }); } let backdropElement = null; if (backdrop) { const BackdropTransition = backdropTransition; backdropElement = renderBackdrop({ ref: modal.setBackdropRef, onClick: handleBackdropClick }); if (BackdropTransition) { backdropElement = /*#__PURE__*/(0,jsx_runtime.jsx)(BackdropTransition, { appear: true, in: !!show, children: backdropElement }); } } return /*#__PURE__*/(0,jsx_runtime.jsx)(jsx_runtime.Fragment, { children: /*#__PURE__*/external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_default().createPortal( /*#__PURE__*/(0,jsx_runtime.jsxs)(jsx_runtime.Fragment, { children: [backdropElement, dialog] }), container) }); }); Modal.displayName = 'Modal'; /* harmony default export */ const esm_Modal = (Object.assign(Modal, { Manager: esm_ModalManager })); ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/hasClass.js /** * Checks if a given element has a CSS class. * * @param element the element * @param className the CSS class name */ function hasClass(element, className) { if (element.classList) return !!className && element.classList.contains(className); return (" " + (element.className.baseVal || element.className) + " ").indexOf(" " + className + " ") !== -1; } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/addClass.js /** * Adds a CSS class to a given element. * * @param element the element * @param className the CSS class name */ function addClass(element, className) { if (element.classList) element.classList.add(className);else if (!hasClass(element, className)) if (typeof element.className === 'string') element.className = element.className + " " + className;else element.setAttribute('class', (element.className && element.className.baseVal || '') + " " + className); } ;// CONCATENATED MODULE: ./node_modules/dom-helpers/esm/removeClass.js function replaceClassName(origClass, classToRemove) { return origClass.replace(new RegExp("(^|\\s)" + classToRemove + "(?:\\s|$)", 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ''); } /** * Removes a CSS class from a given element. * * @param element the element * @param className the CSS class name */ function removeClass(element, className) { if (element.classList) { element.classList.remove(className); } else if (typeof element.className === 'string') { element.className = replaceClassName(element.className, className); } else { element.setAttribute('class', replaceClassName(element.className && element.className.baseVal || '', className)); } } ;// CONCATENATED MODULE: ./src/BootstrapModalManager.tsx const Selector = { FIXED_CONTENT: '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top', STICKY_CONTENT: '.sticky-top', NAVBAR_TOGGLER: '.navbar-toggler' }; class BootstrapModalManager extends esm_ModalManager { adjustAndStore(prop, element, adjust) { const actual = element.style[prop]; // TODO: DOMStringMap and CSSStyleDeclaration aren't strictly compatible // @ts-ignore element.dataset[prop] = actual; css(element, { [prop]: `${parseFloat(css(element, prop)) + adjust}px` }); } restore(prop, element) { const value = element.dataset[prop]; if (value !== undefined) { delete element.dataset[prop]; css(element, { [prop]: value }); } } setContainerStyle(containerState) { super.setContainerStyle(containerState); const container = this.getElement(); addClass(container, 'modal-open'); if (!containerState.scrollBarWidth) return; const paddingProp = this.isRTL ? 'paddingLeft' : 'paddingRight'; const marginProp = this.isRTL ? 'marginLeft' : 'marginRight'; qsa(container, Selector.FIXED_CONTENT).forEach(el => this.adjustAndStore(paddingProp, el, containerState.scrollBarWidth)); qsa(container, Selector.STICKY_CONTENT).forEach(el => this.adjustAndStore(marginProp, el, -containerState.scrollBarWidth)); qsa(container, Selector.NAVBAR_TOGGLER).forEach(el => this.adjustAndStore(marginProp, el, containerState.scrollBarWidth)); } removeContainerStyle(containerState) { super.removeContainerStyle(containerState); const container = this.getElement(); removeClass(container, 'modal-open'); const paddingProp = this.isRTL ? 'paddingLeft' : 'paddingRight'; const marginProp = this.isRTL ? 'marginLeft' : 'marginRight'; qsa(container, Selector.FIXED_CONTENT).forEach(el => this.restore(paddingProp, el)); qsa(container, Selector.STICKY_CONTENT).forEach(el => this.restore(marginProp, el)); qsa(container, Selector.NAVBAR_TOGGLER).forEach(el => this.restore(marginProp, el)); } } let sharedManager; function getSharedManager(options) { if (!sharedManager) sharedManager = new BootstrapModalManager(options); return sharedManager; } /* harmony default export */ const src_BootstrapModalManager = (BootstrapModalManager); ;// CONCATENATED MODULE: ./src/ModalBody.tsx /* harmony default export */ const ModalBody = (createWithBsPrefix('modal-body')); ;// CONCATENATED MODULE: ./src/ModalContext.tsx const ModalContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext({ // eslint-disable-next-line @typescript-eslint/no-empty-function onHide() {} }); /* harmony default export */ const src_ModalContext = (ModalContext); ;// CONCATENATED MODULE: ./src/ModalDialog.tsx var ModalDialog_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ModalDialog.tsx"; const ModalDialog_propTypes = { /** @default 'modal' */ bsPrefix: (prop_types_default()).string, contentClassName: (prop_types_default()).string, /** * Render a large, extra large or small modal. * * @type ('sm'|'lg','xl') */ size: (prop_types_default()).string, /** * Renders a fullscreen modal. Specifying a breakpoint will render the modal * as fullscreen __below__ the breakpoint size. * * @type (true|'sm-down'|'md-down'|'lg-down'|'xl-down'|'xxl-down') */ fullscreen: prop_types_default().oneOfType([(prop_types_default()).bool, (prop_types_default()).string]), /** * Specify whether the Component should be vertically centered */ centered: (prop_types_default()).bool, /** * Allows scrolling the `<Modal.Body>` instead of the entire Modal when overflowing. */ scrollable: (prop_types_default()).bool }; const ModalDialog = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, contentClassName, centered, size, fullscreen, children, scrollable, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'modal'); const dialogClass = `${bsPrefix}-dialog`; const fullScreenClass = typeof fullscreen === 'string' ? `${bsPrefix}-fullscreen-${fullscreen}` : `${bsPrefix}-fullscreen`; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ...props, ref: ref, className: classnames_default()(dialogClass, className, size && `${bsPrefix}-${size}`, centered && `${dialogClass}-centered`, scrollable && `${dialogClass}-scrollable`, fullscreen && fullScreenClass), children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { className: classnames_default()(`${bsPrefix}-content`, contentClassName), children: children }, void 0, false, { fileName: ModalDialog_jsxFileName, lineNumber: 92, columnNumber: 9 }, undefined) }, void 0, false, { fileName: ModalDialog_jsxFileName, lineNumber: 80, columnNumber: 7 }, undefined); }); ModalDialog.displayName = 'ModalDialog'; ModalDialog.propTypes = ModalDialog_propTypes; /* harmony default export */ const src_ModalDialog = (ModalDialog); ;// CONCATENATED MODULE: ./src/ModalFooter.tsx /* harmony default export */ const ModalFooter = (createWithBsPrefix('modal-footer')); ;// CONCATENATED MODULE: ./src/AbstractModalHeader.tsx var AbstractModalHeader_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/AbstractModalHeader.tsx"; const AbstractModalHeader_propTypes = { /** * Provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ closeLabel: (prop_types_default()).string, /** * Sets the variant for close button. */ closeVariant: prop_types_default().oneOf(['white']), /** * Specify whether the Component should contain a close button */ closeButton: (prop_types_default()).bool, /** * A Callback fired when the close button is clicked. If used directly inside * a ModalContext, the onHide will automatically be propagated up * to the parent `onHide`. */ onHide: (prop_types_default()).func }; const AbstractModalHeader_defaultProps = { closeLabel: 'Close', closeButton: false }; const AbstractModalHeader = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ closeLabel, closeVariant, closeButton, onHide, children, ...props }, ref) => { const context = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_ModalContext); const handleClick = useEventCallback(() => { context == null ? void 0 : context.onHide(); onHide == null ? void 0 : onHide(); }); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ref: ref, ...props, children: [children, closeButton && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_CloseButton, { "aria-label": closeLabel, variant: closeVariant, onClick: handleClick }, void 0, false, { fileName: AbstractModalHeader_jsxFileName, lineNumber: 67, columnNumber: 11 }, undefined)] }, void 0, true, { fileName: AbstractModalHeader_jsxFileName, lineNumber: 63, columnNumber: 7 }, undefined); }); AbstractModalHeader.propTypes = AbstractModalHeader_propTypes; AbstractModalHeader.defaultProps = AbstractModalHeader_defaultProps; /* harmony default export */ const src_AbstractModalHeader = (AbstractModalHeader); ;// CONCATENATED MODULE: ./src/ModalHeader.tsx var ModalHeader_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ModalHeader.tsx"; const ModalHeader_propTypes = { /** * @default 'modal-header' */ bsPrefix: (prop_types_default()).string, /** * Provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ closeLabel: (prop_types_default()).string, /** * Sets the variant for close button. */ closeVariant: prop_types_default().oneOf(['white']), /** * Specify whether the Component should contain a close button */ closeButton: (prop_types_default()).bool, /** * A Callback fired when the close button is clicked. If used directly inside * a Modal component, the onHide will automatically be propagated up to the * parent Modal `onHide`. */ onHide: (prop_types_default()).func }; const ModalHeader_defaultProps = { closeLabel: 'Close', closeButton: false }; const ModalHeader = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'modal-header'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_AbstractModalHeader, { ref: ref, ...props, className: classnames_default()(className, bsPrefix) }, void 0, false, { fileName: ModalHeader_jsxFileName, lineNumber: 55, columnNumber: 7 }, undefined); }); ModalHeader.displayName = 'ModalHeader'; ModalHeader.propTypes = ModalHeader_propTypes; ModalHeader.defaultProps = ModalHeader_defaultProps; /* harmony default export */ const src_ModalHeader = (ModalHeader); ;// CONCATENATED MODULE: ./src/ModalTitle.tsx const ModalTitle_DivStyledAsH4 = divWithClassName('h4'); /* harmony default export */ const ModalTitle = (createWithBsPrefix('modal-title', { Component: ModalTitle_DivStyledAsH4 })); ;// CONCATENATED MODULE: ./src/Modal.tsx var Modal_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Modal.tsx"; const Modal_propTypes = { /** * @default 'modal' */ bsPrefix: (prop_types_default()).string, /** * Render a large, extra large or small modal. * When not provided, the modal is rendered with medium (default) size. * @type ('sm'|'lg'|'xl') */ size: (prop_types_default()).string, /** * Renders a fullscreen modal. Specifying a breakpoint will render the modal * as fullscreen __below__ the breakpoint size. * * @type (true|'sm-down'|'md-down'|'lg-down'|'xl-down'|'xxl-down') */ fullscreen: prop_types_default().oneOfType([(prop_types_default()).bool, (prop_types_default()).string]), /** * vertically center the Dialog in the window */ centered: (prop_types_default()).bool, /** * Include a backdrop component. Specify 'static' for a backdrop that doesn't * trigger an "onHide" when clicked. */ backdrop: prop_types_default().oneOf(['static', true, false]), /** * Add an optional extra class name to .modal-backdrop * It could end up looking like class="modal-backdrop foo-modal-backdrop in". */ backdropClassName: (prop_types_default()).string, /** * Close the modal when escape key is pressed */ keyboard: (prop_types_default()).bool, /** * Allows scrolling the `<Modal.Body>` instead of the entire Modal when overflowing. */ scrollable: (prop_types_default()).bool, /** * Open and close the Modal with a slide and fade animation. */ animation: (prop_types_default()).bool, /** * A css class to apply to the Modal dialog DOM node. */ dialogClassName: (prop_types_default()).string, /** * Add an optional extra class name to .modal-content */ contentClassName: (prop_types_default()).string, /** * A Component type that provides the modal content Markup. This is a useful * prop when you want to use your own styles and markup to create a custom * modal component. */ dialogAs: (prop_types_default()).elementType, /** * When `true` The modal will automatically shift focus to itself when it * opens, and replace it to the last focused element when it closes. * Generally this should never be set to false as it makes the Modal less * accessible to assistive technologies, like screen-readers. */ autoFocus: (prop_types_default()).bool, /** * When `true` The modal will prevent focus from leaving the Modal while * open. Consider leaving the default value here, as it is necessary to make * the Modal work well with assistive technologies, such as screen readers. */ enforceFocus: (prop_types_default()).bool, /** * When `true` The modal will restore focus to previously focused element once * modal is hidden */ restoreFocus: (prop_types_default()).bool, /** * Options passed to focus function when `restoreFocus` is set to `true` * * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus#Parameters */ restoreFocusOptions: prop_types_default().shape({ preventScroll: (prop_types_default()).bool }), /** * When `true` The modal will show itself. */ show: (prop_types_default()).bool, /** * A callback fired when the Modal is opening. */ onShow: (prop_types_default()).func, /** * A callback fired when the header closeButton or non-static backdrop is * clicked. Required if either are specified. */ onHide: (prop_types_default()).func, /** * A callback fired when the escape key, if specified in `keyboard`, is pressed. */ onEscapeKeyDown: (prop_types_default()).func, /** * Callback fired before the Modal transitions in */ onEnter: (prop_types_default()).func, /** * Callback fired as the Modal begins to transition in */ onEntering: (prop_types_default()).func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: (prop_types_default()).func, /** * Callback fired right before the Modal transitions out */ onExit: (prop_types_default()).func, /** * Callback fired as the Modal begins to transition out */ onExiting: (prop_types_default()).func, /** * Callback fired after the Modal finishes transitioning out */ onExited: (prop_types_default()).func, /** * A ModalManager instance used to track and manage the state of open * Modals. Useful when customizing how modals interact within a container */ manager: (prop_types_default()).object, /** * @private */ container: (prop_types_default()).any, 'aria-labelledby': (prop_types_default()).any }; const Modal_defaultProps = { show: false, backdrop: true, keyboard: true, autoFocus: true, enforceFocus: true, restoreFocus: true, animation: true, dialogAs: src_ModalDialog }; /* eslint-disable no-use-before-define, react/no-multi-comp */ function DialogTransition(props) { return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Fade, { ...props, timeout: null }, void 0, false, { fileName: Modal_jsxFileName, lineNumber: 235, columnNumber: 10 }, this); } function BackdropTransition(props) { return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Fade, { ...props, timeout: null }, void 0, false, { fileName: Modal_jsxFileName, lineNumber: 239, columnNumber: 10 }, this); } /* eslint-enable no-use-before-define */ const Modal_Modal = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, style, dialogClassName, contentClassName, children, dialogAs: Dialog, 'aria-labelledby': ariaLabelledby, /* BaseModal props */ show, animation, backdrop, keyboard, onEscapeKeyDown, onShow, onHide, container, autoFocus, enforceFocus, restoreFocus, restoreFocusOptions, onEntered, onExit, onExiting, onEnter, onEntering, onExited, backdropClassName, manager: propsManager, ...props }, ref) => { const [modalStyle, setStyle] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)({}); const [animateStaticModal, setAnimateStaticModal] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(false); const waitingForMouseUpRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(false); const ignoreBackdropClickRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(false); const removeStaticModalAnimationRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); const [modal, setModalRef] = useCallbackRef_useCallbackRef(); const mergedRef = esm_useMergedRefs(ref, setModalRef); const handleHide = useEventCallback(onHide); const isRTL = useIsRTL(); bsPrefix = useBootstrapPrefix(bsPrefix, 'modal'); const modalContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ onHide: handleHide }), [handleHide]); function getModalManager() { if (propsManager) return propsManager; return getSharedManager({ isRTL }); } function updateDialogStyle(node) { if (!canUseDOM) return; const containerIsOverflowing = getModalManager().getScrollbarWidth() > 0; const modalIsOverflowing = node.scrollHeight > ownerDocument(node).documentElement.clientHeight; setStyle({ paddingRight: containerIsOverflowing && !modalIsOverflowing ? scrollbarSize() : undefined, paddingLeft: !containerIsOverflowing && modalIsOverflowing ? scrollbarSize() : undefined }); } const handleWindowResize = useEventCallback(() => { if (modal) { updateDialogStyle(modal.dialog); } }); useWillUnmount(() => { esm_removeEventListener(window, 'resize', handleWindowResize); removeStaticModalAnimationRef.current == null ? void 0 : removeStaticModalAnimationRef.current(); }); // We prevent the modal from closing during a drag by detecting where the // the click originates from. If it starts in the modal and then ends outside // don't close. const handleDialogMouseDown = () => { waitingForMouseUpRef.current = true; }; const handleMouseUp = e => { if (waitingForMouseUpRef.current && modal && e.target === modal.dialog) { ignoreBackdropClickRef.current = true; } waitingForMouseUpRef.current = false; }; const handleStaticModalAnimation = () => { setAnimateStaticModal(true); removeStaticModalAnimationRef.current = transitionEnd(modal.dialog, () => { setAnimateStaticModal(false); }); }; const handleStaticBackdropClick = e => { if (e.target !== e.currentTarget) { return; } handleStaticModalAnimation(); }; const handleClick = e => { if (backdrop === 'static') { handleStaticBackdropClick(e); return; } if (ignoreBackdropClickRef.current || e.target !== e.currentTarget) { ignoreBackdropClickRef.current = false; return; } onHide == null ? void 0 : onHide(); }; const handleEscapeKeyDown = e => { if (!keyboard && backdrop === 'static') { // Call preventDefault to stop modal from closing in restart ui, // then play our animation. e.preventDefault(); handleStaticModalAnimation(); } else if (keyboard && onEscapeKeyDown) { onEscapeKeyDown(e); } }; const handleEnter = (node, isAppearing) => { if (node) { node.style.display = 'block'; updateDialogStyle(node); } onEnter == null ? void 0 : onEnter(node, isAppearing); }; const handleExit = node => { removeStaticModalAnimationRef.current == null ? void 0 : removeStaticModalAnimationRef.current(); onExit == null ? void 0 : onExit(node); }; const handleEntering = (node, isAppearing) => { onEntering == null ? void 0 : onEntering(node, isAppearing); // FIXME: This should work even when animation is disabled. esm_addEventListener(window, 'resize', handleWindowResize); }; const handleExited = node => { if (node) node.style.display = ''; // RHL removes it sometimes onExited == null ? void 0 : onExited(node); // FIXME: This should work even when animation is disabled. esm_removeEventListener(window, 'resize', handleWindowResize); }; const renderBackdrop = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(backdropProps => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ...backdropProps, className: classnames_default()(`${bsPrefix}-backdrop`, backdropClassName, !animation && 'show') }, void 0, false, { fileName: Modal_jsxFileName, lineNumber: 430, columnNumber: 11 }, undefined), [animation, backdropClassName, bsPrefix]); const baseModalStyle = { ...style, ...modalStyle }; // Sets `display` always block when `animation` is false if (!animation) { baseModalStyle.display = 'block'; } const renderDialog = dialogProps => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { role: "dialog", ...dialogProps, style: baseModalStyle, className: classnames_default()(className, bsPrefix, animateStaticModal && `${bsPrefix}-static`), onClick: backdrop ? handleClick : undefined, onMouseUp: handleMouseUp, "aria-labelledby": ariaLabelledby, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Dialog, { ...props, onMouseDown: handleDialogMouseDown, className: dialogClassName, contentClassName: contentClassName, children: children }, void 0, false, { fileName: Modal_jsxFileName, lineNumber: 465, columnNumber: 11 }, undefined) }, void 0, false, { fileName: Modal_jsxFileName, lineNumber: 450, columnNumber: 9 }, undefined); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_ModalContext.Provider, { value: modalContext, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Modal, { show: show, ref: mergedRef, backdrop: backdrop, container: container, keyboard: true // Always set true - see handleEscapeKeyDown , autoFocus: autoFocus, enforceFocus: enforceFocus, restoreFocus: restoreFocus, restoreFocusOptions: restoreFocusOptions, onEscapeKeyDown: handleEscapeKeyDown, onShow: onShow, onHide: onHide, onEnter: handleEnter, onEntering: handleEntering, onEntered: onEntered, onExit: handleExit, onExiting: onExiting, onExited: handleExited, manager: getModalManager(), transition: animation ? DialogTransition : undefined, backdropTransition: animation ? BackdropTransition : undefined, renderBackdrop: renderBackdrop, renderDialog: renderDialog }, void 0, false, { fileName: Modal_jsxFileName, lineNumber: 478, columnNumber: 11 }, undefined) }, void 0, false, { fileName: Modal_jsxFileName, lineNumber: 477, columnNumber: 9 }, undefined); }); Modal_Modal.displayName = 'Modal'; Modal_Modal.propTypes = Modal_propTypes; Modal_Modal.defaultProps = Modal_defaultProps; /* harmony default export */ const src_Modal = (Object.assign(Modal_Modal, { Body: ModalBody, Header: src_ModalHeader, Title: ModalTitle, Footer: ModalFooter, Dialog: src_ModalDialog, TRANSITION_DURATION: 300, BACKDROP_TRANSITION_DURATION: 150 })); // EXTERNAL MODULE: ./node_modules/prop-types-extra/lib/all.js var lib_all = __webpack_require__(946); var all_default = /*#__PURE__*/__webpack_require__.n(lib_all); ;// CONCATENATED MODULE: ./src/NavItem.tsx /* harmony default export */ const src_NavItem = (createWithBsPrefix('nav-item')); ;// CONCATENATED MODULE: ./src/NavLink.tsx var NavLink_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/NavLink.tsx"; const NavLink_propTypes = { /** * @default 'nav-link' */ bsPrefix: (prop_types_default()).string, /** * The active state of the NavItem item. */ active: (prop_types_default()).bool, /** * The disabled state of the NavItem item. */ disabled: (prop_types_default()).bool, /** * The ARIA role for the `NavLink`, In the context of a 'tablist' parent Nav, * the role defaults to 'tab' * */ role: (prop_types_default()).string, /** The HTML href attribute for the `NavLink` */ href: (prop_types_default()).string, /** * Uniquely identifies the `NavItem` amongst its siblings, * used to determine and control the active state of the parent `Nav` */ eventKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]), /** @default 'a' */ as: (prop_types_default()).elementType }; const NavLink_defaultProps = { disabled: false }; const NavLink = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, as: Component = esm_Anchor, active, eventKey, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'nav-link'); const [navItemProps, meta] = useNavItem({ key: makeEventKey(eventKey, props.href), active, ...props }); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ...navItemProps, ref: ref, className: classnames_default()(className, bsPrefix, props.disabled && 'disabled', meta.isActive && 'active') }, void 0, false, { fileName: NavLink_jsxFileName, lineNumber: 78, columnNumber: 9 }, undefined); }); NavLink.displayName = 'NavLink'; NavLink.propTypes = NavLink_propTypes; NavLink.defaultProps = NavLink_defaultProps; /* harmony default export */ const src_NavLink = (NavLink); ;// CONCATENATED MODULE: ./src/Nav.tsx var Nav_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Nav.tsx"; const Nav_propTypes = { /** * @default 'nav' */ bsPrefix: (prop_types_default()).string, /** @private */ navbarBsPrefix: (prop_types_default()).string, /** @private */ cardHeaderBsPrefix: (prop_types_default()).string, /** * The visual variant of the nav items. * * @type {('tabs'|'pills')} */ variant: (prop_types_default()).string, /** * Marks the NavItem with a matching `eventKey` (or `href` if present) as active. */ activeKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]), /** * Have all `NavItem`s proportionately fill all available width. */ fill: (prop_types_default()).bool, /** * Have all `NavItem`s evenly fill all available width. * * @type {boolean} */ justify: all_default()((prop_types_default()).bool, ({ justify, navbar }) => justify && navbar ? Error('justify navbar `Nav`s are not supported') : null), /** * A callback fired when a NavItem is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` */ onSelect: (prop_types_default()).func, /** * ARIA role for the Nav, in the context of a TabContainer, the default will * be set to "tablist", but can be overridden by the Nav when set explicitly. * * When the role is "tablist", NavLink focus is managed according to * the ARIA authoring practices for tabs: * https://www.w3.org/TR/2013/WD-wai-aria-practices-20130307/#tabpanel */ role: (prop_types_default()).string, /** * Apply styling an alignment for use in a Navbar. This prop will be set * automatically when the Nav is used inside a Navbar. */ navbar: (prop_types_default()).bool, /** * Enable vertical scrolling within the toggleable contents of a collapsed Navbar. */ navbarScroll: (prop_types_default()).bool, as: (prop_types_default()).elementType, /** @private */ onKeyDown: (prop_types_default()).func }; const Nav_defaultProps = { justify: false, fill: false }; const Nav_Nav = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((uncontrolledProps, ref) => { const { as = 'div', bsPrefix: initialBsPrefix, variant, fill, justify, navbar, navbarScroll, className, activeKey, ...props } = useUncontrolled(uncontrolledProps, { activeKey: 'onSelect' }); const bsPrefix = useBootstrapPrefix(initialBsPrefix, 'nav'); let navbarBsPrefix; let cardHeaderBsPrefix; let isNavbar = false; const navbarContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(NavbarContext); const cardHeaderContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(CardHeaderContext); if (navbarContext) { navbarBsPrefix = navbarContext.bsPrefix; isNavbar = navbar == null ? true : navbar; } else if (cardHeaderContext) { ({ cardHeaderBsPrefix } = cardHeaderContext); } return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Nav, { as: as, ref: ref, activeKey: activeKey, className: classnames_default()(className, { [bsPrefix]: !isNavbar, [`${navbarBsPrefix}-nav`]: isNavbar, [`${navbarBsPrefix}-nav-scroll`]: isNavbar && navbarScroll, [`${cardHeaderBsPrefix}-${variant}`]: !!cardHeaderBsPrefix, [`${bsPrefix}-${variant}`]: !!variant, [`${bsPrefix}-fill`]: fill, [`${bsPrefix}-justified`]: justify }), ...props }, void 0, false, { fileName: Nav_jsxFileName, lineNumber: 143, columnNumber: 5 }, undefined); }); Nav_Nav.displayName = 'Nav'; Nav_Nav.propTypes = Nav_propTypes; Nav_Nav.defaultProps = Nav_defaultProps; /* harmony default export */ const src_Nav = (Object.assign(Nav_Nav, { Item: src_NavItem, Link: src_NavLink })); ;// CONCATENATED MODULE: ./src/NavbarBrand.tsx var NavbarBrand_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/NavbarBrand.tsx"; const NavbarBrand_propTypes = { /** @default 'navbar' */ bsPrefix: (prop_types_default()).string, /** * An href, when provided the Brand will render as an `<a>` element (unless `as` is provided). */ href: (prop_types_default()).string, /** * Set a custom element for this component. */ as: (prop_types_default()).elementType }; const NavbarBrand = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, as, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'navbar-brand'); const Component = as || (props.href ? 'a' : 'span'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref, className: classnames_default()(className, bsPrefix) }, void 0, false, { fileName: NavbarBrand_jsxFileName, lineNumber: 37, columnNumber: 9 }, undefined); }); NavbarBrand.displayName = 'NavbarBrand'; NavbarBrand.propTypes = NavbarBrand_propTypes; /* harmony default export */ const src_NavbarBrand = (NavbarBrand); ;// CONCATENATED MODULE: ./src/NavbarCollapse.tsx var NavbarCollapse_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/NavbarCollapse.tsx"; const NavbarCollapse_propTypes = { /** @default 'navbar-collapse' */ bsPrefix: (prop_types_default()).string }; const NavbarCollapse = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ children, bsPrefix, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'navbar-collapse'); const context = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(NavbarContext); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Collapse, { in: !!(context && context.expanded), ...props, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ref: ref, className: bsPrefix, children: children }, void 0, false, { fileName: NavbarCollapse_jsxFileName, lineNumber: 27, columnNumber: 9 }, undefined) }, void 0, false, { fileName: NavbarCollapse_jsxFileName, lineNumber: 26, columnNumber: 7 }, undefined); }); NavbarCollapse.displayName = 'NavbarCollapse'; NavbarCollapse.propTypes = NavbarCollapse_propTypes; /* harmony default export */ const src_NavbarCollapse = (NavbarCollapse); ;// CONCATENATED MODULE: ./src/NavbarToggle.tsx var NavbarToggle_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/NavbarToggle.tsx"; const NavbarToggle_propTypes = { /** @default 'navbar-toggler' */ bsPrefix: (prop_types_default()).string, /** An accessible ARIA label for the toggler button. */ label: (prop_types_default()).string, /** @private */ onClick: (prop_types_default()).func, /** * The toggle content. When empty, the default toggle will be rendered. */ children: (prop_types_default()).node, as: (prop_types_default()).elementType }; const NavbarToggle_defaultProps = { label: 'Toggle navigation' }; const NavbarToggle = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, children, label, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'button', onClick, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'navbar-toggler'); const { onToggle, expanded } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(NavbarContext) || {}; const handleClick = useEventCallback(e => { if (onClick) onClick(e); if (onToggle) onToggle(); }); if (Component === 'button') { props.type = 'button'; } return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref, onClick: handleClick, "aria-label": label, className: classnames_default()(className, bsPrefix, !expanded && 'collapsed'), children: children || /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { className: `${bsPrefix}-icon` }, void 0, false, { fileName: NavbarToggle_jsxFileName, lineNumber: 77, columnNumber: 22 }, undefined) }, void 0, false, { fileName: NavbarToggle_jsxFileName, lineNumber: 70, columnNumber: 7 }, undefined); }); NavbarToggle.displayName = 'NavbarToggle'; NavbarToggle.propTypes = NavbarToggle_propTypes; NavbarToggle.defaultProps = NavbarToggle_defaultProps; /* harmony default export */ const src_NavbarToggle = (NavbarToggle); ;// CONCATENATED MODULE: ./src/OffcanvasBody.tsx /* harmony default export */ const OffcanvasBody = (createWithBsPrefix('offcanvas-body')); ;// CONCATENATED MODULE: ./src/OffcanvasToggling.tsx var OffcanvasToggling_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/OffcanvasToggling.tsx"; const OffcanvasToggling_propTypes = { /** * Show the component; triggers the fade in or fade out animation */ in: (prop_types_default()).bool, /** * Wait until the first "enter" transition to mount the component (add it to the DOM) */ mountOnEnter: (prop_types_default()).bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: (prop_types_default()).bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ appear: (prop_types_default()).bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: (prop_types_default()).number, /** * Callback fired before the component fades in */ onEnter: (prop_types_default()).func, /** * Callback fired after the component starts to fade in */ onEntering: (prop_types_default()).func, /** * Callback fired after the has component faded in */ onEntered: (prop_types_default()).func, /** * Callback fired before the component fades out */ onExit: (prop_types_default()).func, /** * Callback fired after the component starts to fade out */ onExiting: (prop_types_default()).func, /** * Callback fired after the component has faded out */ onExited: (prop_types_default()).func }; const OffcanvasToggling_defaultProps = { in: false, mountOnEnter: false, unmountOnExit: false, appear: false }; const transitionStyles = { [ENTERING]: 'show', [ENTERED]: 'show' }; const OffcanvasToggling = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, children, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'offcanvas'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_TransitionWrapper, { ref: ref, addEndListener: transitionEndListener, ...props, childRef: children.ref, children: (status, innerProps) => /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement(children, { ...innerProps, className: classnames_default()(className, children.props.className, (status === ENTERING || status === EXITING) && `${bsPrefix}-toggling`, transitionStyles[status]) }) }, void 0, false, { fileName: OffcanvasToggling_jsxFileName, lineNumber: 102, columnNumber: 5 }, undefined); }); OffcanvasToggling.propTypes = OffcanvasToggling_propTypes; OffcanvasToggling.defaultProps = OffcanvasToggling_defaultProps; OffcanvasToggling.displayName = 'OffcanvasToggling'; /* harmony default export */ const src_OffcanvasToggling = (OffcanvasToggling); ;// CONCATENATED MODULE: ./src/OffcanvasHeader.tsx var OffcanvasHeader_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/OffcanvasHeader.tsx"; const OffcanvasHeader_propTypes = { /** * @default 'offcanvas-header' */ bsPrefix: (prop_types_default()).string, /** * Provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ closeLabel: (prop_types_default()).string, /** * Sets the variant for close button. */ closeVariant: prop_types_default().oneOf(['white']), /** * Specify whether the Component should contain a close button */ closeButton: (prop_types_default()).bool, /** * A Callback fired when the close button is clicked. If used directly inside * a Offcanvas component, the onHide will automatically be propagated up to the * parent Offcanvas `onHide`. */ onHide: (prop_types_default()).func }; const OffcanvasHeader_defaultProps = { closeLabel: 'Close', closeButton: false }; const OffcanvasHeader = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'offcanvas-header'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_AbstractModalHeader, { ref: ref, ...props, className: classnames_default()(className, bsPrefix) }, void 0, false, { fileName: OffcanvasHeader_jsxFileName, lineNumber: 55, columnNumber: 7 }, undefined); }); OffcanvasHeader.displayName = 'OffcanvasHeader'; OffcanvasHeader.propTypes = OffcanvasHeader_propTypes; OffcanvasHeader.defaultProps = OffcanvasHeader_defaultProps; /* harmony default export */ const src_OffcanvasHeader = (OffcanvasHeader); ;// CONCATENATED MODULE: ./src/OffcanvasTitle.tsx const OffcanvasTitle_DivStyledAsH5 = divWithClassName('h5'); /* harmony default export */ const OffcanvasTitle = (createWithBsPrefix('offcanvas-title', { Component: OffcanvasTitle_DivStyledAsH5 })); ;// CONCATENATED MODULE: ./src/Offcanvas.tsx var Offcanvas_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Offcanvas.tsx"; const Offcanvas_propTypes = { /** * @default 'offcanvas' */ bsPrefix: (prop_types_default()).string, /** * Include a backdrop component. */ backdrop: (prop_types_default()).bool, /** * Add an optional extra class name to .offcanvas-backdrop. */ backdropClassName: (prop_types_default()).string, /** * Closes the offcanvas when escape key is pressed. */ keyboard: (prop_types_default()).bool, /** * Allow body scrolling while offcanvas is open. */ scroll: (prop_types_default()).bool, /** * Which side of the viewport the offcanvas will appear from. */ placement: prop_types_default().oneOf(['start', 'end', 'top', 'bottom']), /** * When `true` The offcanvas will automatically shift focus to itself when it * opens, and replace it to the last focused element when it closes. * Generally this should never be set to false as it makes the offcanvas less * accessible to assistive technologies, like screen-readers. */ autoFocus: (prop_types_default()).bool, /** * When `true` The offcanvas will prevent focus from leaving the offcanvas while * open. Consider leaving the default value here, as it is necessary to make * the offcanvas work well with assistive technologies, such as screen readers. */ enforceFocus: (prop_types_default()).bool, /** * When `true` The offcanvas will restore focus to previously focused element once * offcanvas is hidden */ restoreFocus: (prop_types_default()).bool, /** * Options passed to focus function when `restoreFocus` is set to `true` * * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus#Parameters */ restoreFocusOptions: prop_types_default().shape({ preventScroll: (prop_types_default()).bool }), /** * When `true` The offcanvas will show itself. */ show: (prop_types_default()).bool, /** * A callback fired when the offcanvas is opening. */ onShow: (prop_types_default()).func, /** * A callback fired when the header closeButton or backdrop is * clicked. Required if either are specified. */ onHide: (prop_types_default()).func, /** * A callback fired when the escape key, if specified in `keyboard`, is pressed. */ onEscapeKeyDown: (prop_types_default()).func, /** * Callback fired before the offcanvas transitions in */ onEnter: (prop_types_default()).func, /** * Callback fired as the offcanvas begins to transition in */ onEntering: (prop_types_default()).func, /** * Callback fired after the offcanvas finishes transitioning in */ onEntered: (prop_types_default()).func, /** * Callback fired right before the offcanvas transitions out */ onExit: (prop_types_default()).func, /** * Callback fired as the offcanvas begins to transition out */ onExiting: (prop_types_default()).func, /** * Callback fired after the offcanvas finishes transitioning out */ onExited: (prop_types_default()).func, /** * @private */ container: (prop_types_default()).any, 'aria-labelledby': (prop_types_default()).string }; const Offcanvas_defaultProps = { show: false, backdrop: true, keyboard: true, scroll: false, autoFocus: true, enforceFocus: true, restoreFocus: true, placement: 'start' }; function Offcanvas_DialogTransition(props) { return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_OffcanvasToggling, { ...props }, void 0, false, { fileName: Offcanvas_jsxFileName, lineNumber: 178, columnNumber: 10 }, this); } function Offcanvas_BackdropTransition(props) { return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Fade, { ...props }, void 0, false, { fileName: Offcanvas_jsxFileName, lineNumber: 182, columnNumber: 10 }, this); } const Offcanvas = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, children, 'aria-labelledby': ariaLabelledby, placement, /* BaseModal props */ show, backdrop, keyboard, scroll, onEscapeKeyDown, onShow, onHide, container, autoFocus, enforceFocus, restoreFocus, restoreFocusOptions, onEntered, onExit, onExiting, onEnter, onEntering, onExited, backdropClassName, manager: propsManager, ...props }, ref) => { const modalManager = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(); bsPrefix = useBootstrapPrefix(bsPrefix, 'offcanvas'); const { onToggle } = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(NavbarContext) || {}; const handleHide = useEventCallback(() => { onToggle == null ? void 0 : onToggle(); onHide == null ? void 0 : onHide(); }); const modalContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ onHide: handleHide }), [handleHide]); function getModalManager() { if (propsManager) return propsManager; if (scroll) { // Have to use a different modal manager since the shared // one handles overflow. if (!modalManager.current) modalManager.current = new src_BootstrapModalManager({ handleContainerOverflow: false }); return modalManager.current; } return getSharedManager(); } const handleEnter = (node, ...args) => { if (node) node.style.visibility = 'visible'; onEnter == null ? void 0 : onEnter(node, ...args); }; const handleExited = (node, ...args) => { if (node) node.style.visibility = ''; onExited == null ? void 0 : onExited(...args); }; const renderBackdrop = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(backdropProps => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ...backdropProps, className: classnames_default()(`${bsPrefix}-backdrop`, backdropClassName) }, void 0, false, { fileName: Offcanvas_jsxFileName, lineNumber: 264, columnNumber: 11 }, undefined), [backdropClassName, bsPrefix]); const renderDialog = dialogProps => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { role: "dialog", ...dialogProps, ...props, className: classnames_default()(className, bsPrefix, `${bsPrefix}-${placement}`), "aria-labelledby": ariaLabelledby, children: children }, void 0, false, { fileName: Offcanvas_jsxFileName, lineNumber: 273, columnNumber: 9 }, undefined); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_ModalContext.Provider, { value: modalContext, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Modal, { show: show, ref: ref, backdrop: backdrop, container: container, keyboard: keyboard, autoFocus: autoFocus, enforceFocus: enforceFocus && !scroll, restoreFocus: restoreFocus, restoreFocusOptions: restoreFocusOptions, onEscapeKeyDown: onEscapeKeyDown, onShow: onShow, onHide: handleHide, onEnter: handleEnter, onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: handleExited, manager: getModalManager(), transition: Offcanvas_DialogTransition, backdropTransition: Offcanvas_BackdropTransition, renderBackdrop: renderBackdrop, renderDialog: renderDialog }, void 0, false, { fileName: Offcanvas_jsxFileName, lineNumber: 290, columnNumber: 11 }, undefined) }, void 0, false, { fileName: Offcanvas_jsxFileName, lineNumber: 289, columnNumber: 9 }, undefined); }); Offcanvas.displayName = 'Offcanvas'; Offcanvas.propTypes = Offcanvas_propTypes; Offcanvas.defaultProps = Offcanvas_defaultProps; /* harmony default export */ const src_Offcanvas = (Object.assign(Offcanvas, { Body: OffcanvasBody, Header: src_OffcanvasHeader, Title: OffcanvasTitle })); ;// CONCATENATED MODULE: ./src/NavbarOffcanvas.tsx var NavbarOffcanvas_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/NavbarOffcanvas.tsx"; const NavbarOffcanvas = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, ref) => { const context = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(NavbarContext); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Offcanvas, { ref: ref, show: !!(context != null && context.expanded), ...props }, void 0, false, { fileName: NavbarOffcanvas_jsxFileName, lineNumber: 10, columnNumber: 12 }, undefined); }); NavbarOffcanvas.displayName = 'NavbarOffcanvas'; /* harmony default export */ const src_NavbarOffcanvas = (NavbarOffcanvas); ;// CONCATENATED MODULE: ./src/Navbar.tsx var Navbar_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Navbar.tsx"; const NavbarText = createWithBsPrefix('navbar-text', { Component: 'span' }); const Navbar_propTypes = { /** @default 'navbar' */ bsPrefix: (prop_types_default()).string, /** * The general visual variant a the Navbar. * Use in combination with the `bg` prop, `background-color` utilities, * or your own background styles. * * @type {('light'|'dark')} */ variant: (prop_types_default()).string, /** * The breakpoint, below which, the Navbar will collapse. * When `true` the Navbar will always be expanded regardless of screen size. */ expand: prop_types_default().oneOf([false, true, 'sm', 'md', 'lg', 'xl', 'xxl']).isRequired, /** * A convenience prop for adding `bg-*` utility classes since they are so commonly used here. * `light` and `dark` are common choices but any `bg-*` class is supported, including any custom ones you might define. * * Pairs nicely with the `variant` prop. */ bg: (prop_types_default()).string, /** * Create a fixed navbar along the top or bottom of the screen, that scrolls with the * page. A convenience prop for the `fixed-*` positioning classes. */ fixed: prop_types_default().oneOf(['top', 'bottom']), /** * Position the navbar at the top of the viewport, but only after scrolling past it. * A convenience prop for the `sticky-top` positioning class. * * __Not supported in <= IE11 and other older browsers without a polyfill__ */ sticky: prop_types_default().oneOf(['top']), /** * Set a custom element for this component. */ as: (prop_types_default()).elementType, /** * A callback fired when the `<Navbar>` body collapses or expands. Fired when * a `<Navbar.Toggle>` is clicked and called with the new `expanded` * boolean value. * * @controllable expanded */ onToggle: (prop_types_default()).func, /** * A callback fired when a descendant of a child `<Nav>` is selected. Should * be used to execute complex closing or other miscellaneous actions desired * after selecting a descendant of `<Nav>`. Does nothing if no `<Nav>` or `<Nav>` * descendants exist. The callback is called with an eventKey, which is a * prop from the selected `<Nav>` descendant, and an event. * * ```js * function ( * eventKey: mixed, * event?: SyntheticEvent * ) * ``` * * For basic closing behavior after all `<Nav>` descendant onSelect events in * mobile viewports, try using collapseOnSelect. * * Note: If you are manually closing the navbar using this `OnSelect` prop, * ensure that you are setting `expanded` to false and not *toggling* between * true and false. */ onSelect: (prop_types_default()).func, /** * Toggles `expanded` to `false` after the onSelect event of a descendant of a * child `<Nav>` fires. Does nothing if no `<Nav>` or `<Nav>` descendants exist. * * Manually controlling `expanded` via the onSelect callback is recommended instead, * for more complex operations that need to be executed after * the `select` event of `<Nav>` descendants. */ collapseOnSelect: (prop_types_default()).bool, /** * Controls the visiblity of the navbar body * * @controllable onToggle */ expanded: (prop_types_default()).bool, /** * The ARIA role for the navbar, will default to 'navigation' for * Navbars whose `as` is something other than `<nav>`. * * @default 'navigation' */ role: (prop_types_default()).string }; const Navbar_defaultProps = { expand: true, variant: 'light', collapseOnSelect: false }; const Navbar = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, ref) => { const { bsPrefix: initialBsPrefix, expand, variant, bg, fixed, sticky, className, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'nav', expanded, onToggle, onSelect, collapseOnSelect, ...controlledProps } = useUncontrolled(props, { expanded: 'onToggle' }); const bsPrefix = useBootstrapPrefix(initialBsPrefix, 'navbar'); const handleCollapse = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)((...args) => { onSelect == null ? void 0 : onSelect(...args); if (collapseOnSelect && expanded) { onToggle == null ? void 0 : onToggle(false); } }, [onSelect, collapseOnSelect, expanded, onToggle]); // will result in some false positives but that seems better // than false negatives. strict `undefined` check allows explicit // "nulling" of the role if the user really doesn't want one if (controlledProps.role === undefined && Component !== 'nav') { controlledProps.role = 'navigation'; } let expandClass = `${bsPrefix}-expand`; if (typeof expand === 'string') expandClass = `${expandClass}-${expand}`; const navbarContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ onToggle: () => onToggle == null ? void 0 : onToggle(!expanded), bsPrefix, expanded: !!expanded }), [bsPrefix, expanded, onToggle]); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(NavbarContext.Provider, { value: navbarContext, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_SelectableContext.Provider, { value: handleCollapse, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...controlledProps, className: classnames_default()(className, bsPrefix, expand && expandClass, variant && `${bsPrefix}-${variant}`, bg && `bg-${bg}`, sticky && `sticky-${sticky}`, fixed && `fixed-${fixed}`) }, void 0, false, { fileName: Navbar_jsxFileName, lineNumber: 201, columnNumber: 11 }, undefined) }, void 0, false, { fileName: Navbar_jsxFileName, lineNumber: 200, columnNumber: 9 }, undefined) }, void 0, false, { fileName: Navbar_jsxFileName, lineNumber: 199, columnNumber: 7 }, undefined); }); Navbar.propTypes = Navbar_propTypes; Navbar.defaultProps = Navbar_defaultProps; Navbar.displayName = 'Navbar'; /* harmony default export */ const src_Navbar = (Object.assign(Navbar, { Brand: src_NavbarBrand, Collapse: src_NavbarCollapse, Offcanvas: src_NavbarOffcanvas, Text: NavbarText, Toggle: src_NavbarToggle })); ;// CONCATENATED MODULE: ./src/NavDropdown.tsx var NavDropdown_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/NavDropdown.tsx"; const NavDropdown_propTypes = { /** * An html id attribute for the Toggle button, necessary for assistive technologies, such as screen readers. * @type {string} */ id: (prop_types_default()).string, /** An `onClick` handler passed to the Toggle component */ onClick: (prop_types_default()).func, /** The content of the non-toggle Button. */ title: (prop_types_default()).node.isRequired, /** Disables the toggle NavLink */ disabled: (prop_types_default()).bool, /** Style the toggle NavLink as active */ active: (prop_types_default()).bool, /** An ARIA accessible role applied to the Menu component. When set to 'menu', The dropdown */ menuRole: (prop_types_default()).string, /** Whether to render the dropdown menu in the DOM before the first time it is shown */ renderMenuOnMount: (prop_types_default()).bool, /** * Which event when fired outside the component will cause it to be closed. * * _see [DropdownMenu](#menu-props) for more details_ */ rootCloseEvent: (prop_types_default()).string, /** * Menu color variant. * * Omitting this will use the default light color. */ menuVariant: prop_types_default().oneOf(['dark']), /** @ignore */ bsPrefix: (prop_types_default()).string }; const NavDropdown = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ id, title, children, bsPrefix, className, rootCloseEvent, menuRole, disabled, active, renderMenuOnMount, menuVariant, ...props }, ref) => { /* NavItem has no additional logic, it's purely presentational. Can set nav item class here to support "as" */ const navItemPrefix = useBootstrapPrefix(undefined, 'nav-item'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Dropdown, { ref: ref, ...props, className: classnames_default()(className, navItemPrefix), children: [/*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Dropdown.Toggle, { id: id, eventKey: null, active: active, disabled: disabled, childBsPrefix: bsPrefix, as: src_NavLink, children: title }, void 0, false, { fileName: NavDropdown_jsxFileName, lineNumber: 92, columnNumber: 11 }, undefined), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Dropdown.Menu, { role: menuRole, renderOnMount: renderMenuOnMount, rootCloseEvent: rootCloseEvent, variant: menuVariant, children: children }, void 0, false, { fileName: NavDropdown_jsxFileName, lineNumber: 103, columnNumber: 11 }, undefined)] }, void 0, true, { fileName: NavDropdown_jsxFileName, lineNumber: 87, columnNumber: 9 }, undefined); }); NavDropdown.displayName = 'NavDropdown'; NavDropdown.propTypes = NavDropdown_propTypes; /* harmony default export */ const src_NavDropdown = (Object.assign(NavDropdown, { Item: src_Dropdown.Item, ItemText: src_Dropdown.ItemText, Divider: src_Dropdown.Divider, Header: src_Dropdown.Header })); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/Overlay.js /** * Built on top of `Popper.js`, the overlay component is * great for custom tooltip overlays. */ const Overlay = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, outerRef) => { const { flip, offset, placement, containerPadding, popperConfig = {}, transition: Transition } = props; const [rootElement, attachRef] = useCallbackRef(); const [arrowElement, attachArrowRef] = useCallbackRef(); const mergedRef = hooks_esm_useMergedRefs(attachRef, outerRef); const container = useWaitForDOMRef(props.container); const target = useWaitForDOMRef(props.target); const [exited, setExited] = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useState)(!props.show); const popper = esm_usePopper(target, rootElement, mergeOptionsWithPopperConfig({ placement, enableEvents: !!props.show, containerPadding: containerPadding || 5, flip, offset, arrowElement, popperConfig })); if (props.show) { if (exited) setExited(false); } else if (!props.transition && !exited) { setExited(true); } const handleHidden = (...args) => { setExited(true); if (props.onExited) { props.onExited(...args); } }; // Don't un-render the overlay while it's transitioning out. const mountOverlay = props.show || Transition && !exited; esm_useRootClose(rootElement, props.onHide, { disabled: !props.rootClose || props.rootCloseDisabled, clickTrigger: props.rootCloseEvent }); if (!mountOverlay) { // Don't bother showing anything if we don't have to. return null; } let child = props.children(Object.assign({}, popper.attributes.popper, { style: popper.styles.popper, ref: mergedRef }), { popper, placement, show: !!props.show, arrowProps: Object.assign({}, popper.attributes.arrow, { style: popper.styles.arrow, ref: attachArrowRef }) }); if (Transition) { const { onExit, onExiting, onEnter, onEntering, onEntered } = props; child = /*#__PURE__*/(0,jsx_runtime.jsx)(Transition, { in: props.show, appear: true, onExit: onExit, onExiting: onExiting, onExited: handleHidden, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, children: child }); } return container ? /*#__PURE__*/external_root_ReactDOM_commonjs2_react_dom_commonjs_react_dom_amd_react_dom_default().createPortal(child, container) : null; }); Overlay.displayName = 'Overlay'; /* harmony default export */ const esm_Overlay = (Overlay); ;// CONCATENATED MODULE: ./src/PopoverHeader.tsx /* harmony default export */ const PopoverHeader = (createWithBsPrefix('popover-header')); ;// CONCATENATED MODULE: ./src/PopoverBody.tsx /* harmony default export */ const PopoverBody = (createWithBsPrefix('popover-body')); ;// CONCATENATED MODULE: ./src/helpers.ts class BsPrefixComponent extends external_root_React_commonjs2_react_commonjs_react_amd_react_.Component {} // Need to use this instead of typeof Component to get proper type checking. function getOverlayDirection(placement, isRTL) { let bsDirection = placement; if (placement === 'left') { bsDirection = isRTL ? 'end' : 'start'; } else if (placement === 'right') { bsDirection = isRTL ? 'start' : 'end'; } return bsDirection; } ;// CONCATENATED MODULE: ./src/Popover.tsx var Popover_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Popover.tsx"; const Popover_propTypes = { /** * @default 'popover' */ bsPrefix: (prop_types_default()).string, /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: (prop_types_default()).string, /** * Sets the direction the Popover is positioned towards. * * > This is generally provided by the `Overlay` component positioning the popover */ placement: prop_types_default().oneOf(['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']), /** * An Overlay injected set of props for positioning the popover arrow. * * > This is generally provided by the `Overlay` component positioning the popover */ arrowProps: prop_types_default().shape({ ref: (prop_types_default()).any, style: (prop_types_default()).object }), /** * When this prop is set, it creates a Popover with a Popover.Body inside * passing the children directly to it */ body: (prop_types_default()).bool, /** @private */ popper: (prop_types_default()).object, /** @private */ show: (prop_types_default()).bool }; const Popover_defaultProps = { placement: 'right' }; const Popover = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, placement, className, style, children, body, arrowProps, popper: _, show: _1, ...props }, ref) => { const decoratedBsPrefix = useBootstrapPrefix(bsPrefix, 'popover'); const isRTL = useIsRTL(); const [primaryPlacement] = (placement == null ? void 0 : placement.split('-')) || []; const bsDirection = getOverlayDirection(primaryPlacement, isRTL); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ref: ref, role: "tooltip", style: style, "x-placement": primaryPlacement, className: classnames_default()(className, decoratedBsPrefix, primaryPlacement && `bs-popover-${bsDirection}`), ...props, children: [/*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { className: "popover-arrow", ...arrowProps }, void 0, false, { fileName: Popover_jsxFileName, lineNumber: 119, columnNumber: 9 }, undefined), body ? /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(PopoverBody, { children: children }, void 0, false, { fileName: Popover_jsxFileName, lineNumber: 120, columnNumber: 17 }, undefined) : children] }, void 0, true, { fileName: Popover_jsxFileName, lineNumber: 107, columnNumber: 7 }, undefined); }); Popover.propTypes = Popover_propTypes; Popover.defaultProps = Popover_defaultProps; /* harmony default export */ const src_Popover = (Object.assign(Popover, { Header: PopoverHeader, Body: PopoverBody, // Default popover offset. // https://github.com/twbs/bootstrap/blob/5c32767e0e0dbac2d934bcdee03719a65d3f1187/js/src/popover.js#L28 POPPER_OFFSET: [0, 8] })); ;// CONCATENATED MODULE: ./src/useOverlayOffset.tsx // This is meant for internal use. // This applies a custom offset to the overlay if it's a popover. function useOverlayOffset() { const overlayRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); const popoverClass = useBootstrapPrefix(undefined, 'popover'); const offset = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ name: 'offset', options: { offset: () => { if (overlayRef.current && hasClass(overlayRef.current, popoverClass)) { return src_Popover.POPPER_OFFSET; } return [0, 0]; } } }), [popoverClass]); return [overlayRef, [offset]]; } ;// CONCATENATED MODULE: ./src/Overlay.tsx var Overlay_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Overlay.tsx"; const Overlay_propTypes = { /** * A component instance, DOM node, or function that returns either. * The `container` element will have the Overlay appended to it via a React portal. */ container: prop_types_default().oneOfType([lib/* componentOrElement */.ax, (prop_types_default()).func]), /** * A component instance, DOM node, or function that returns either. * The overlay will be positioned in relation to the `target` */ target: prop_types_default().oneOfType([lib/* componentOrElement */.ax, (prop_types_default()).func]), /** * Set the visibility of the Overlay */ show: (prop_types_default()).bool, /** * A set of popper options and props passed directly to Popper. */ popperConfig: (prop_types_default()).object, /** * Specify whether the overlay should trigger onHide when the user clicks outside the overlay */ rootClose: (prop_types_default()).bool, /** * Specify event for triggering a "root close" toggle. */ rootCloseEvent: prop_types_default().oneOf(['click', 'mousedown']), /** * A callback invoked by the overlay when it wishes to be hidden. Required if * `rootClose` is specified. */ onHide: (prop_types_default()).func, /** * Animate the entering and exiting of the Overlay. `true` will use the `<Fade>` transition, * or a custom react-transition-group `<Transition>` component can be provided. */ transition: prop_types_default().oneOfType([(prop_types_default()).bool, lib/* elementType */.nm]), /** * Callback fired before the Overlay transitions in */ onEnter: (prop_types_default()).func, /** * Callback fired as the Overlay begins to transition in */ onEntering: (prop_types_default()).func, /** * Callback fired after the Overlay finishes transitioning in */ onEntered: (prop_types_default()).func, /** * Callback fired right before the Overlay transitions out */ onExit: (prop_types_default()).func, /** * Callback fired as the Overlay begins to transition out */ onExiting: (prop_types_default()).func, /** * Callback fired after the Overlay finishes transitioning out */ onExited: (prop_types_default()).func, /** * The placement of the Overlay in relation to it's `target`. */ placement: prop_types_default().oneOf(['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']) }; const Overlay_defaultProps = { transition: src_Fade, rootClose: false, show: false, placement: 'top' }; function wrapRefs(props, arrowProps) { const { ref } = props; const { ref: aRef } = arrowProps; props.ref = ref.__wrapped || (ref.__wrapped = r => ref(safeFindDOMNode(r))); arrowProps.ref = aRef.__wrapped || (aRef.__wrapped = r => aRef(safeFindDOMNode(r))); } const Overlay_Overlay = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ children: overlay, transition, popperConfig = {}, ...outerProps }, outerRef) => { const popperRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)({}); const [ref, modifiers] = useOverlayOffset(); const mergedRef = esm_useMergedRefs(outerRef, ref); const actualTransition = transition === true ? src_Fade : transition || undefined; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Overlay, { ...outerProps, ref: mergedRef, popperConfig: { ...popperConfig, modifiers: modifiers.concat(popperConfig.modifiers || []) }, transition: actualTransition, children: (overlayProps, { arrowProps, placement, popper: popperObj, show }) => { var _popperObj$state, _popperObj$state$modi; wrapRefs(overlayProps, arrowProps); const popper = Object.assign(popperRef.current, { state: popperObj == null ? void 0 : popperObj.state, scheduleUpdate: popperObj == null ? void 0 : popperObj.update, placement, outOfBoundaries: (popperObj == null ? void 0 : (_popperObj$state = popperObj.state) == null ? void 0 : (_popperObj$state$modi = _popperObj$state.modifiersData.hide) == null ? void 0 : _popperObj$state$modi.isReferenceHidden) || false }); if (typeof overlay === 'function') return overlay({ ...overlayProps, placement, show, ...(!transition && show && { className: 'show' }), popper, arrowProps }); return /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement(overlay, { ...overlayProps, placement, arrowProps, popper, className: classnames_default()(overlay.props.className, !transition && show && 'show'), style: { ...overlay.props.style, ...overlayProps.style } }); } }, void 0, false, { fileName: Overlay_jsxFileName, lineNumber: 173, columnNumber: 7 }, undefined); }); Overlay_Overlay.displayName = 'Overlay'; Overlay_Overlay.propTypes = Overlay_propTypes; Overlay_Overlay.defaultProps = Overlay_defaultProps; /* harmony default export */ const src_Overlay = (Overlay_Overlay); ;// CONCATENATED MODULE: ./src/OverlayTrigger.tsx var OverlayTrigger_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/OverlayTrigger.tsx"; function normalizeDelay(delay) { return delay && typeof delay === 'object' ? delay : { show: delay, hide: delay }; } // Simple implementation of mouseEnter and mouseLeave. // React's built version is broken: https://github.com/facebook/react/issues/4251 // for cases when the trigger is disabled and mouseOut/Over can cause flicker // moving from one child element to another. function handleMouseOverOut( // eslint-disable-next-line @typescript-eslint/no-shadow handler, args, relatedNative) { const [e] = args; const target = e.currentTarget; const related = e.relatedTarget || e.nativeEvent[relatedNative]; if ((!related || related !== target) && !contains_contains(target, related)) { handler(...args); } } const triggerType = prop_types_default().oneOf(['click', 'hover', 'focus']); const OverlayTrigger_propTypes = { children: prop_types_default().oneOfType([(prop_types_default()).element, (prop_types_default()).func]).isRequired, /** * Specify which action or actions trigger Overlay visibility * * @type {'hover' | 'click' |'focus' | Array<'hover' | 'click' |'focus'>} */ trigger: prop_types_default().oneOfType([triggerType, prop_types_default().arrayOf(triggerType)]), /** * A millisecond delay amount to show and hide the Overlay once triggered */ delay: prop_types_default().oneOfType([(prop_types_default()).number, prop_types_default().shape({ show: (prop_types_default()).number, hide: (prop_types_default()).number })]), /** * The visibility of the Overlay. `show` is a _controlled_ prop so should be paired * with `onToggle` to avoid breaking user interactions. * * Manually toggling `show` does **not** wait for `delay` to change the visibility. * * @controllable onToggle */ show: (prop_types_default()).bool, /** * The initial visibility state of the Overlay. */ defaultShow: (prop_types_default()).bool, /** * A callback that fires when the user triggers a change in tooltip visibility. * * `onToggle` is called with the desired next `show`, and generally should be passed * back to the `show` prop. `onToggle` fires _after_ the configured `delay` * * @controllable `show` */ onToggle: (prop_types_default()).func, /** The initial flip state of the Overlay. */ flip: (prop_types_default()).bool, /** * An element or text to overlay next to the target. */ overlay: prop_types_default().oneOfType([(prop_types_default()).func, (prop_types_default()).element.isRequired]), /** * A Popper.js config object passed to the the underlying popper instance. */ popperConfig: (prop_types_default()).object, // Overridden props from `<Overlay>`. /** * @private */ target: prop_types_default().oneOf([null]), /** * @private */ onHide: prop_types_default().oneOf([null]), /** * The placement of the Overlay in relation to it's `target`. */ placement: prop_types_default().oneOf(['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']) }; const OverlayTrigger_defaultProps = { defaultShow: false, trigger: ['hover', 'focus'] }; function OverlayTrigger({ trigger, overlay, children, popperConfig = {}, show: propsShow, defaultShow = false, onToggle, delay: propsDelay, placement, flip = placement && placement.indexOf('auto') !== -1, ...props }) { const triggerNodeRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(null); const mergedRef = esm_useMergedRefs(triggerNodeRef, children.ref); const timeout = useTimeout(); const hoverStateRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(''); const [show, setShow] = useUncontrolledProp(propsShow, defaultShow, onToggle); const delay = normalizeDelay(propsDelay); const { onFocus, onBlur, onClick } = typeof children !== 'function' ? external_root_React_commonjs2_react_commonjs_react_amd_react_.Children.only(children).props : {}; const attachRef = r => { mergedRef(safeFindDOMNode(r)); }; const handleShow = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(() => { timeout.clear(); hoverStateRef.current = 'show'; if (!delay.show) { setShow(true); return; } timeout.set(() => { if (hoverStateRef.current === 'show') setShow(true); }, delay.show); }, [delay.show, setShow, timeout]); const handleHide = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(() => { timeout.clear(); hoverStateRef.current = 'hide'; if (!delay.hide) { setShow(false); return; } timeout.set(() => { if (hoverStateRef.current === 'hide') setShow(false); }, delay.hide); }, [delay.hide, setShow, timeout]); const handleFocus = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)((...args) => { handleShow(); onFocus == null ? void 0 : onFocus(...args); }, [handleShow, onFocus]); const handleBlur = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)((...args) => { handleHide(); onBlur == null ? void 0 : onBlur(...args); }, [handleHide, onBlur]); const handleClick = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)((...args) => { setShow(!show); onClick == null ? void 0 : onClick(...args); }, [onClick, setShow, show]); const handleMouseOver = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)((...args) => { handleMouseOverOut(handleShow, args, 'fromElement'); }, [handleShow]); const handleMouseOut = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)((...args) => { handleMouseOverOut(handleHide, args, 'toElement'); }, [handleHide]); const triggers = trigger == null ? [] : [].concat(trigger); const triggerProps = { ref: attachRef }; if (triggers.indexOf('click') !== -1) { triggerProps.onClick = handleClick; } if (triggers.indexOf('focus') !== -1) { triggerProps.onFocus = handleFocus; triggerProps.onBlur = handleBlur; } if (triggers.indexOf('hover') !== -1) { false ? 0 : void 0; triggerProps.onMouseOver = handleMouseOver; triggerProps.onMouseOut = handleMouseOut; } return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(jsx_dev_runtime.Fragment, { children: [typeof children === 'function' ? children(triggerProps) : /*#__PURE__*/(0,external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement)(children, triggerProps), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Overlay, { ...props, show: show, onHide: handleHide, flip: flip, placement: placement, popperConfig: popperConfig, target: triggerNodeRef.current, children: overlay }, void 0, false, { fileName: OverlayTrigger_jsxFileName, lineNumber: 300, columnNumber: 7 }, this)] }, void 0, true); } OverlayTrigger.propTypes = OverlayTrigger_propTypes; OverlayTrigger.defaultProps = OverlayTrigger_defaultProps; /* harmony default export */ const src_OverlayTrigger = (OverlayTrigger); ;// CONCATENATED MODULE: ./src/PageItem.tsx var PageItem_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/PageItem.tsx"; /* eslint-disable react/no-multi-comp */ const PageItem_propTypes = { /** Disables the PageItem */ disabled: (prop_types_default()).bool, /** Styles PageItem as active, and renders a `<span>` instead of an `<a>`. */ active: (prop_types_default()).bool, /** An accessible label indicating the active state.. */ activeLabel: (prop_types_default()).string, /** A callback function for when this component is clicked */ onClick: (prop_types_default()).func }; const PageItem_defaultProps = { active: false, disabled: false, activeLabel: '(current)' }; const PageItem = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ active, disabled, className, style, activeLabel, children, ...props }, ref) => { const Component = active || disabled ? 'span' : esm_Anchor; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("li", { ref: ref, style: style, className: classnames_default()(className, 'page-item', { active, disabled }), children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { className: "page-link", disabled: disabled, ...props, children: [children, active && activeLabel && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { className: "visually-hidden", children: activeLabel }, void 0, false, { fileName: PageItem_jsxFileName, lineNumber: 62, columnNumber: 15 }, undefined)] }, void 0, true, { fileName: PageItem_jsxFileName, lineNumber: 59, columnNumber: 11 }, undefined) }, void 0, false, { fileName: PageItem_jsxFileName, lineNumber: 54, columnNumber: 9 }, undefined); }); PageItem.propTypes = PageItem_propTypes; PageItem.defaultProps = PageItem_defaultProps; PageItem.displayName = 'PageItem'; /* harmony default export */ const src_PageItem = (PageItem); function createButton(name, defaultValue, label = name) { function Button({ children, ...props }) { return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(PageItem, { ...props, children: [/*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { "aria-hidden": "true", children: children || defaultValue }, void 0, false, { fileName: PageItem_jsxFileName, lineNumber: 80, columnNumber: 9 }, this), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { className: "visually-hidden", children: label }, void 0, false, { fileName: PageItem_jsxFileName, lineNumber: 81, columnNumber: 9 }, this)] }, void 0, true, { fileName: PageItem_jsxFileName, lineNumber: 79, columnNumber: 7 }, this); } Button.displayName = name; return Button; } const First = createButton('First', '«'); const Prev = createButton('Prev', '‹', 'Previous'); const Ellipsis = createButton('Ellipsis', '…', 'More'); const Next = createButton('Next', '›'); const Last = createButton('Last', '»'); ;// CONCATENATED MODULE: ./src/Pagination.tsx var Pagination_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Pagination.tsx"; const Pagination_propTypes = { /** * @default 'pagination' * */ bsPrefix: (prop_types_default()).string, /** * Set's the size of all PageItems. * * @type {('sm'|'lg')} */ size: prop_types_default().oneOf(['sm', 'lg']) }; /** * @property {PageItem} Item * @property {PageItem} First * @property {PageItem} Prev * @property {PageItem} Ellipsis * @property {PageItem} Next * @property {PageItem} Last */ const Pagination = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, size, ...props }, ref) => { const decoratedBsPrefix = useBootstrapPrefix(bsPrefix, 'pagination'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("ul", { ref: ref, ...props, className: classnames_default()(className, decoratedBsPrefix, size && `${decoratedBsPrefix}-${size}`) }, void 0, false, { fileName: Pagination_jsxFileName, lineNumber: 43, columnNumber: 7 }, undefined); }); Pagination.propTypes = Pagination_propTypes; Pagination.displayName = 'Pagination'; /* harmony default export */ const src_Pagination = (Object.assign(Pagination, { First: First, Prev: Prev, Ellipsis: Ellipsis, Item: src_PageItem, Next: Next, Last: Last })); ;// CONCATENATED MODULE: ./src/usePlaceholder.ts function usePlaceholder({ animation, bg, bsPrefix, size, ...props }) { bsPrefix = useBootstrapPrefix(bsPrefix, 'placeholder'); const [{ className, ...colProps }] = useCol(props); return { ...colProps, className: classnames_default()(className, animation ? `${bsPrefix}-${animation}` : bsPrefix, size && `${bsPrefix}-${size}`, bg && `bg-${bg}`) }; } ;// CONCATENATED MODULE: ./src/PlaceholderButton.tsx var PlaceholderButton_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/PlaceholderButton.tsx"; const PlaceholderButton_propTypes = { /** * @default 'placeholder' */ bsPrefix: (prop_types_default()).string, /** * Changes the animation of the placeholder. */ animation: prop_types_default().oneOf(['glow', 'wave']), size: prop_types_default().oneOf(['xs', 'sm', 'lg']), /** * Button variant. */ variant: (prop_types_default()).string }; const PlaceholderButton = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, ref) => { const placeholderProps = usePlaceholder(props); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Button, { ...placeholderProps, ref: ref, disabled: true, tabIndex: -1 }, void 0, false, { fileName: PlaceholderButton_jsxFileName, lineNumber: 38, columnNumber: 12 }, undefined); }); PlaceholderButton.displayName = 'PlaceholderButton'; PlaceholderButton.propTypes = PlaceholderButton_propTypes; /* harmony default export */ const src_PlaceholderButton = (PlaceholderButton); ;// CONCATENATED MODULE: ./src/Placeholder.tsx var Placeholder_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Placeholder.tsx"; const Placeholder_propTypes = { /** * @default 'placeholder' */ bsPrefix: (prop_types_default()).string, /** * Changes the animation of the placeholder. * * @type ('glow'|'wave') */ animation: (prop_types_default()).string, /** * Change the background color of the placeholder. * * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'light'|'dark')} */ bg: (prop_types_default()).string, /** * Component size variations. * * @type ('xs'|'sm'|'lg') */ size: (prop_types_default()).string }; const Placeholder = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ as: Component = 'span', ...props }, ref) => { const placeholderProps = usePlaceholder(props); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...placeholderProps, ref: ref }, void 0, false, { fileName: Placeholder_jsxFileName, lineNumber: 42, columnNumber: 14 }, undefined); }); Placeholder.displayName = 'Placeholder'; Placeholder.propTypes = Placeholder_propTypes; /* harmony default export */ const src_Placeholder = (Object.assign(Placeholder, { Button: src_PlaceholderButton })); ;// CONCATENATED MODULE: ./src/ProgressBar.tsx var ProgressBar_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ProgressBar.tsx"; const ROUND_PRECISION = 1000; /** * Validate that children, if any, are instances of `<ProgressBar>`. */ function onlyProgressBar(props, propName, componentName) { const children = props[propName]; if (!children) { return null; } let error = null; external_root_React_commonjs2_react_commonjs_react_amd_react_.Children.forEach(children, child => { if (error) { return; } /** * Compare types in a way that works with libraries that patch and proxy * components like react-hot-loader. * * see https://github.com/gaearon/react-hot-loader#checking-element-types */ // eslint-disable-next-line @typescript-eslint/no-use-before-define const element = /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(ProgressBar, {}, void 0, false, { fileName: ProgressBar_jsxFileName, lineNumber: 50, columnNumber: 21 }, this); if (child.type === element.type) return; const childType = child.type; const childIdentifier = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.isValidElement(child) ? childType.displayName || childType.name || childType : child; error = new Error(`Children of ${componentName} can contain only ProgressBar ` + `components. Found ${childIdentifier}.`); }); return error; } const ProgressBar_propTypes = { /** * Minimum value progress can begin from */ min: (prop_types_default()).number, /** * Current value of progress */ now: (prop_types_default()).number, /** * Maximum value progress can reach */ max: (prop_types_default()).number, /** * Show label that represents visual percentage. * EG. 60% */ label: (prop_types_default()).node, /** * Hide's the label visually. */ visuallyHidden: (prop_types_default()).bool, /** * Uses a gradient to create a striped effect. */ striped: (prop_types_default()).bool, /** * Animate's the stripes from right to left */ animated: (prop_types_default()).bool, /** * @private * @default 'progress-bar' */ bsPrefix: (prop_types_default()).string, /** * Sets the background class of the progress bar. * * @type ('success'|'danger'|'warning'|'info') */ variant: (prop_types_default()).string, /** * Child elements (only allows elements of type <ProgressBar />) */ children: onlyProgressBar, /** * @private */ isChild: (prop_types_default()).bool }; const ProgressBar_defaultProps = { min: 0, max: 100, animated: false, isChild: false, visuallyHidden: false, striped: false }; function getPercentage(now, min, max) { const percentage = (now - min) / (max - min) * 100; return Math.round(percentage * ROUND_PRECISION) / ROUND_PRECISION; } function renderProgressBar({ min, now, max, label, visuallyHidden, striped, animated, className, style, variant, bsPrefix, ...props }, ref) { return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ref: ref, ...props, role: "progressbar", className: classnames_default()(className, `${bsPrefix}-bar`, { [`bg-${variant}`]: variant, [`${bsPrefix}-bar-animated`]: animated, [`${bsPrefix}-bar-striped`]: animated || striped }), style: { width: `${getPercentage(now, min, max)}%`, ...style }, "aria-valuenow": now, "aria-valuemin": min, "aria-valuemax": max, children: visuallyHidden ? /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { className: "visually-hidden", children: label }, void 0, false, { fileName: ProgressBar_jsxFileName, lineNumber: 174, columnNumber: 9 }, this) : label }, void 0, false, { fileName: ProgressBar_jsxFileName, lineNumber: 159, columnNumber: 5 }, this); } renderProgressBar.propTypes = ProgressBar_propTypes; const ProgressBar = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ isChild, ...props }, ref) => { props.bsPrefix = useBootstrapPrefix(props.bsPrefix, 'progress'); if (isChild) { return renderProgressBar(props, ref); } const { min, now, max, label, visuallyHidden, striped, animated, bsPrefix, variant, className, children, ...wrapperProps } = props; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ref: ref, ...wrapperProps, className: classnames_default()(className, bsPrefix), children: children ? map(children, child => /*#__PURE__*/(0,external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement)(child, { isChild: true })) : renderProgressBar({ min, now, max, label, visuallyHidden, striped, animated, bsPrefix, variant }, ref) }, void 0, false, { fileName: ProgressBar_jsxFileName, lineNumber: 208, columnNumber: 7 }, undefined); }); ProgressBar.displayName = 'ProgressBar'; ProgressBar.propTypes = ProgressBar_propTypes; ProgressBar.defaultProps = ProgressBar_defaultProps; /* harmony default export */ const src_ProgressBar = (ProgressBar); ;// CONCATENATED MODULE: ./src/Ratio.tsx var Ratio_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Ratio.tsx"; const Ratio_propTypes = { /** * @default 'ratio' */ bsPrefix: (prop_types_default()).string, /** * This component requires a single child element */ children: (prop_types_default()).element.isRequired, /** * Set the aspect ratio of the embed. A fraction or a percentage can also * be used to create custom aspect ratios. */ aspectRatio: prop_types_default().oneOfType([(prop_types_default()).number, (prop_types_default()).string]) }; const Ratio_defaultProps = { aspectRatio: '1x1' }; function toPercent(num) { if (num <= 0 || num > 100) return '100%'; if (num < 1) return `${num * 100}%`; return `${num}%`; } const Ratio = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, children, aspectRatio, style, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'ratio'); const isCustomRatio = typeof aspectRatio === 'number'; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ref: ref, ...props, style: { ...style, ...(isCustomRatio && { '--bs-aspect-ratio': toPercent(aspectRatio) }) }, className: classnames_default()(bsPrefix, className, !isCustomRatio && `${bsPrefix}-${aspectRatio}`), children: external_root_React_commonjs2_react_commonjs_react_amd_react_.Children.only(children) }, void 0, false, { fileName: Ratio_jsxFileName, lineNumber: 51, columnNumber: 7 }, undefined); }); Ratio.propTypes = Ratio_propTypes; Ratio.defaultProps = Ratio_defaultProps; /* harmony default export */ const src_Ratio = (Ratio); ;// CONCATENATED MODULE: ./src/Row.tsx var Row_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Row.tsx"; const Row_DEVICE_SIZES = ['xxl', 'xl', 'lg', 'md', 'sm', 'xs']; const rowColWidth = prop_types_default().oneOfType([(prop_types_default()).number, (prop_types_default()).string]); const rowColumns = prop_types_default().oneOfType([rowColWidth, prop_types_default().shape({ cols: rowColWidth })]); const Row_propTypes = { /** * @default 'row' */ bsPrefix: (prop_types_default()).string, as: (prop_types_default()).elementType, /** * The number of columns that will fit next to each other on extra small devices (<576px). * Use `auto` to give columns their natural widths. * * @type {(number|'auto'|{ cols: number|'auto' })} */ xs: rowColumns, /** * The number of columns that will fit next to each other on small devices (≥576px). * Use `auto` to give columns their natural widths. * * @type {(number|'auto'|{ cols: number|'auto' })} */ sm: rowColumns, /** * The number of columns that will fit next to each other on medium devices (≥768px). * Use `auto` to give columns their natural widths. * * @type {(number|'auto'|{ cols: number|'auto' })} */ md: rowColumns, /** * The number of columns that will fit next to each other on large devices (≥992px). * Use `auto` to give columns their natural widths. * * @type {(number|'auto'|{ cols: number|'auto' })} */ lg: rowColumns, /** * The number of columns that will fit next to each other on extra large devices (≥1200px). * Use `auto` to give columns their natural widths. * * @type {(number|'auto'|{ cols: number|'auto' })} */ xl: rowColumns, /** * The number of columns that will fit next to each other on extra extra large devices (≥1400px). * Use `auto` to give columns their natural widths. * * @type {(number|'auto'|{ cols: number|'auto' })} */ xxl: rowColumns }; const Row = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', ...props }, ref) => { const decoratedBsPrefix = useBootstrapPrefix(bsPrefix, 'row'); const sizePrefix = `${decoratedBsPrefix}-cols`; const classes = []; Row_DEVICE_SIZES.forEach(brkPoint => { const propValue = props[brkPoint]; delete props[brkPoint]; let cols; if (propValue != null && typeof propValue === 'object') { ({ cols } = propValue); } else { cols = propValue; } const infix = brkPoint !== 'xs' ? `-${brkPoint}` : ''; if (cols != null) classes.push(`${sizePrefix}${infix}-${cols}`); }); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, decoratedBsPrefix, ...classes) }, void 0, false, { fileName: Row_jsxFileName, lineNumber: 139, columnNumber: 7 }, undefined); }); Row.displayName = 'Row'; Row.propTypes = Row_propTypes; /* harmony default export */ const src_Row = (Row); ;// CONCATENATED MODULE: ./src/Spinner.tsx var Spinner_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Spinner.tsx"; const Spinner_propTypes = { /** * @default 'spinner' */ bsPrefix: (prop_types_default()).string, /** * The visual color style of the spinner * * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'light'|'dark')} */ variant: (prop_types_default()).string, /** * Changes the animation style of the spinner. * * @type {('border'|'grow')} * @default true */ animation: prop_types_default().oneOf(['border', 'grow']).isRequired, /** * Component size variations. * * @type {('sm')} */ size: (prop_types_default()).string, /** * This component may be used to wrap child elements or components. */ children: (prop_types_default()).element, /** * An ARIA accessible role applied to the Menu component. This should generally be set to 'status' */ role: (prop_types_default()).string, /** * @default div */ as: (prop_types_default()).elementType }; const Spinner = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, variant, animation, size, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', className, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'spinner'); const bsSpinnerPrefix = `${bsPrefix}-${animation}`; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(className, bsSpinnerPrefix, size && `${bsSpinnerPrefix}-${size}`, variant && `text-${variant}`) }, void 0, false, { fileName: Spinner_jsxFileName, lineNumber: 80, columnNumber: 9 }, undefined); }); Spinner.propTypes = Spinner_propTypes; Spinner.displayName = 'Spinner'; /* harmony default export */ const src_Spinner = (Spinner); ;// CONCATENATED MODULE: ./src/SplitButton.tsx var SplitButton_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/SplitButton.tsx"; const SplitButton_propTypes = { /** * An html id attribute for the Toggle button, necessary for assistive technologies, such as screen readers. * @type {string} * @required */ id: (prop_types_default()).string, /** * Accessible label for the toggle; the value of `title` if not specified. */ toggleLabel: (prop_types_default()).string, /** An `href` passed to the non-toggle Button */ href: (prop_types_default()).string, /** An anchor `target` passed to the non-toggle Button */ target: (prop_types_default()).string, /** An `onClick` handler passed to the non-toggle Button */ onClick: (prop_types_default()).func, /** The content of the non-toggle Button. */ title: (prop_types_default()).node.isRequired, /** A `type` passed to the non-toggle Button */ type: (prop_types_default()).string, /** Disables both Buttons */ disabled: (prop_types_default()).bool, /** * Aligns the dropdown menu. * * _see [DropdownMenu](#dropdown-menu-props) for more details_ * * @type {"start"|"end"|{ sm: "start"|"end" }|{ md: "start"|"end" }|{ lg: "start"|"end" }|{ xl: "start"|"end"}|{ xxl: "start"|"end"} } */ align: alignPropType, /** An ARIA accessible role applied to the Menu component. When set to 'menu', The dropdown */ menuRole: (prop_types_default()).string, /** Whether to render the dropdown menu in the DOM before the first time it is shown */ renderMenuOnMount: (prop_types_default()).bool, /** * Which event when fired outside the component will cause it to be closed. * * _see [DropdownMenu](#dropdown-menu-props) for more details_ */ rootCloseEvent: (prop_types_default()).string, /** @ignore */ bsPrefix: (prop_types_default()).string, /** @ignore */ variant: (prop_types_default()).string, /** @ignore */ size: (prop_types_default()).string }; const SplitButton_defaultProps = { toggleLabel: 'Toggle dropdown', type: 'button' }; /** * A convenience component for simple or general use split button dropdowns. Renders a * `ButtonGroup` containing a `Button` and a `Button` toggle for the `Dropdown`. All `children` * are passed directly to the default `Dropdown.Menu`. This component accepts all of [`Dropdown`'s * props](#dropdown-props). * * _All unknown props are passed through to the `Dropdown` component._ * The Button `variant`, `size` and `bsPrefix` props are passed to the button and toggle, * and menu-related props are passed to the `Dropdown.Menu` */ const SplitButton = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ id, bsPrefix, size, variant, title, type, toggleLabel, children, onClick, href, target, menuRole, renderMenuOnMount, rootCloseEvent, ...props }, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Dropdown, { ref: ref, ...props, as: src_ButtonGroup, children: [/*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Button, { size: size, variant: variant, disabled: props.disabled, bsPrefix: bsPrefix, href: href, target: target, onClick: onClick, type: type, children: title }, void 0, false, { fileName: SplitButton_jsxFileName, lineNumber: 122, columnNumber: 7 }, undefined), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Dropdown.Toggle, { split: true, id: id, size: size, variant: variant, disabled: props.disabled, childBsPrefix: bsPrefix, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("span", { className: "visually-hidden", children: toggleLabel }, void 0, false, { fileName: SplitButton_jsxFileName, lineNumber: 142, columnNumber: 9 }, undefined) }, void 0, false, { fileName: SplitButton_jsxFileName, lineNumber: 134, columnNumber: 7 }, undefined), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Dropdown.Menu, { role: menuRole, renderOnMount: renderMenuOnMount, rootCloseEvent: rootCloseEvent, children: children }, void 0, false, { fileName: SplitButton_jsxFileName, lineNumber: 145, columnNumber: 7 }, undefined)] }, void 0, true, { fileName: SplitButton_jsxFileName, lineNumber: 121, columnNumber: 5 }, undefined)); SplitButton.propTypes = SplitButton_propTypes; SplitButton.defaultProps = SplitButton_defaultProps; SplitButton.displayName = 'SplitButton'; /* harmony default export */ const src_SplitButton = (SplitButton); ;// CONCATENATED MODULE: ./src/SSRProvider.ts /* harmony default export */ const src_SSRProvider = (SSRProvider); ;// CONCATENATED MODULE: ./src/createUtilityClasses.ts function responsivePropType(propType) { return prop_types_default().oneOfType([propType, prop_types_default().shape({ xs: propType, sm: propType, md: propType, lg: propType, xl: propType, xxl: propType })]); } const createUtilityClasses_DEVICE_SIZES = ['xxl', 'xl', 'lg', 'md', 'sm', 'xs']; function createUtilityClassName(utilityValues) { const classes = []; Object.entries(utilityValues).forEach(([utilName, utilValue]) => { if (utilValue != null) { if (typeof utilValue === 'object') { createUtilityClasses_DEVICE_SIZES.forEach(brkPoint => { const bpValue = utilValue[brkPoint]; if (bpValue != null) { const infix = brkPoint !== 'xs' ? `-${brkPoint}` : ''; classes.push(`${utilName}${infix}-${bpValue}`); } }); } else { classes.push(`${utilName}-${utilValue}`); } } }); return classes; } ;// CONCATENATED MODULE: ./src/Stack.tsx var Stack_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Stack.tsx"; const Stack_propTypes = { /** * Change the underlying component CSS base class name and modifier class names prefix. * **This is an escape hatch** for working with heavily customized bootstrap css. * * Defaults to `hstack` if direction is `horizontal` or `vstack` if direction * is `vertical`. * * @default 'hstack | vstack' */ bsPrefix: (prop_types_default()).string, /** * Sets the spacing between each item. Valid values are `0-5`. */ gap: responsivePropType((prop_types_default()).number) }; const Stack = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ as: Component = 'div', bsPrefix, className, direction, gap, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, direction === 'horizontal' ? 'hstack' : 'vstack'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...props, ref: ref, className: classnames_default()(className, bsPrefix, ...createUtilityClassName({ gap })) }, void 0, false, { fileName: Stack_jsxFileName, lineNumber: 51, columnNumber: 9 }, undefined); }); Stack.displayName = 'Stack'; Stack.propTypes = Stack_propTypes; /* harmony default export */ const src_Stack = (Stack); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/NoopTransition.js function NoopTransition({ children, in: inProp, mountOnEnter, unmountOnExit }) { const hasEnteredRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(inProp); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { if (inProp) hasEnteredRef.current = true; }, [inProp]); if (inProp) return children; // not in // // if (!mountOnEnter && !unmountOnExit) { // return children; // } if (unmountOnExit) { return null; } if (!hasEnteredRef.current && mountOnEnter) { return null; } return children; } /* harmony default export */ const esm_NoopTransition = (NoopTransition); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/TabPanel.js const TabPanel_excluded = ["active", "eventKey", "mountOnEnter", "transition", "unmountOnExit"], _excluded2 = ["activeKey", "getControlledId", "getControllerId"], _excluded3 = ["as"]; function TabPanel_objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function useTabPanel(_ref) { let { active, eventKey, mountOnEnter, transition, unmountOnExit } = _ref, props = TabPanel_objectWithoutPropertiesLoose(_ref, TabPanel_excluded); const context = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(esm_TabContext); if (!context) return [props, { eventKey, isActive: active, mountOnEnter, transition, unmountOnExit }]; const { activeKey, getControlledId, getControllerId } = context, rest = TabPanel_objectWithoutPropertiesLoose(context, _excluded2); const key = makeEventKey(eventKey); return [Object.assign({}, props, { id: getControlledId(eventKey), 'aria-labelledby': getControllerId(eventKey) }), { eventKey, isActive: active == null && key != null ? makeEventKey(activeKey) === key : active, transition: transition || rest.transition, mountOnEnter: mountOnEnter != null ? mountOnEnter : rest.mountOnEnter, unmountOnExit: unmountOnExit != null ? unmountOnExit : rest.unmountOnExit }]; } const TabPanel = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef( // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 (_ref2, ref) => { let { as: Component = 'div' } = _ref2, props = TabPanel_objectWithoutPropertiesLoose(_ref2, _excluded3); const [tabPanelProps, { isActive, onEnter, onEntering, onEntered, onExit, onExiting, onExited, mountOnEnter, unmountOnExit, transition: Transition = esm_NoopTransition }] = useTabPanel(props); // We provide an empty the TabContext so `<Nav>`s in `<TabPanel>`s don't // conflict with the top level one. return /*#__PURE__*/(0,jsx_runtime.jsx)(esm_TabContext.Provider, { value: null, children: /*#__PURE__*/(0,jsx_runtime.jsx)(esm_SelectableContext.Provider, { value: null, children: /*#__PURE__*/(0,jsx_runtime.jsx)(Transition, { in: isActive, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: onExited, mountOnEnter: mountOnEnter, unmountOnExit: unmountOnExit, children: /*#__PURE__*/(0,jsx_runtime.jsx)(Component, Object.assign({}, tabPanelProps, { ref: ref, role: "tabpanel", hidden: !isActive, "aria-hidden": !isActive })) }) }) }); }); TabPanel.displayName = 'TabPanel'; /* harmony default export */ const esm_TabPanel = (TabPanel); ;// CONCATENATED MODULE: ./node_modules/@restart/ui/esm/Tabs.js const Tabs = props => { const { id: userId, generateChildId: generateCustomChildId, onSelect: propsOnSelect, activeKey: propsActiveKey, defaultActiveKey, transition, mountOnEnter, unmountOnExit, children } = props; const [activeKey, onSelect] = useUncontrolledProp(propsActiveKey, defaultActiveKey, propsOnSelect); const id = useSSRSafeId(userId); const generateChildId = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => generateCustomChildId || ((key, type) => id ? `${id}-${type}-${key}` : null), [id, generateCustomChildId]); const tabContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ onSelect, activeKey, transition, mountOnEnter: mountOnEnter || false, unmountOnExit: unmountOnExit || false, getControlledId: key => generateChildId(key, 'tabpane'), getControllerId: key => generateChildId(key, 'tab') }), [onSelect, activeKey, transition, mountOnEnter, unmountOnExit, generateChildId]); return /*#__PURE__*/(0,jsx_runtime.jsx)(esm_TabContext.Provider, { value: tabContext, children: /*#__PURE__*/(0,jsx_runtime.jsx)(esm_SelectableContext.Provider, { value: onSelect || null, children: children }) }); }; Tabs.Panel = esm_TabPanel; /* harmony default export */ const esm_Tabs = (Tabs); ;// CONCATENATED MODULE: ./src/getTabTransitionComponent.ts function getTabTransitionComponent(transition) { if (typeof transition === 'boolean') { return transition ? src_Fade : undefined; } return transition; } ;// CONCATENATED MODULE: ./src/TabContainer.tsx var TabContainer_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/TabContainer.tsx"; const TabContainer_propTypes = { /** * HTML id attribute, required if no `generateChildId` prop * is specified. * * @type {string} */ id: (prop_types_default()).string, /** * Sets a default animation strategy for all children `<TabPane>`s. * Defaults to `<Fade>` animation; else, use `false` to disable, or a * custom react-transition-group `<Transition/>` component. * * @type {{Transition | false}} * @default {Fade} */ transition: prop_types_default().oneOfType([prop_types_default().oneOf([false]), (prop_types_default()).elementType]), /** * Wait until the first "enter" transition to mount tabs (add them to the DOM) */ mountOnEnter: (prop_types_default()).bool, /** * Unmount tabs (remove it from the DOM) when they are no longer visible */ unmountOnExit: (prop_types_default()).bool, /** * A function that takes an `eventKey` and `type` and returns a unique id for * child tab `<NavItem>`s and `<TabPane>`s. The function _must_ be a pure * function, meaning it should always return the _same_ id for the same set * of inputs. The default value requires that an `id` to be set for the * `<TabContainer>`. * * The `type` argument will either be `"tab"` or `"pane"`. * * @defaultValue (eventKey, type) => `${props.id}-${type}-${eventKey}` */ generateChildId: (prop_types_default()).func, /** * A callback fired when a tab is selected. * * @controllable activeKey */ onSelect: (prop_types_default()).func, /** * The `eventKey` of the currently active tab. * * @controllable onSelect */ activeKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]) }; const TabContainer = ({ transition, ...props }) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Tabs, { ...props, transition: getTabTransitionComponent(transition) }, void 0, false, { fileName: TabContainer_jsxFileName, lineNumber: 71, columnNumber: 3 }, undefined); TabContainer.propTypes = TabContainer_propTypes; TabContainer.displayName = 'TabContainer'; /* harmony default export */ const src_TabContainer = (TabContainer); ;// CONCATENATED MODULE: ./src/TabContent.tsx /* harmony default export */ const TabContent = (createWithBsPrefix('tab-content')); ;// CONCATENATED MODULE: ./src/TabPane.tsx var TabPane_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/TabPane.tsx"; const TabPane_propTypes = { /** * @default 'tab-pane' */ bsPrefix: (prop_types_default()).string, as: (prop_types_default()).elementType, /** * A key that associates the `TabPane` with it's controlling `NavLink`. */ eventKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]), /** * Toggles the active state of the TabPane, this is generally controlled by a * TabContainer. */ active: (prop_types_default()).bool, /** * Use animation when showing or hiding `<TabPane>`s. Defaults to `<Fade>` * animation, else use `false` to disable or a react-transition-group * `<Transition/>` component. */ transition: prop_types_default().oneOfType([(prop_types_default()).bool, (prop_types_default()).elementType]), /** * Transition onEnter callback when animation is not `false` */ onEnter: (prop_types_default()).func, /** * Transition onEntering callback when animation is not `false` */ onEntering: (prop_types_default()).func, /** * Transition onEntered callback when animation is not `false` */ onEntered: (prop_types_default()).func, /** * Transition onExit callback when animation is not `false` */ onExit: (prop_types_default()).func, /** * Transition onExiting callback when animation is not `false` */ onExiting: (prop_types_default()).func, /** * Transition onExited callback when animation is not `false` */ onExited: (prop_types_default()).func, /** * Wait until the first "enter" transition to mount the tab (add it to the DOM) */ mountOnEnter: (prop_types_default()).bool, /** * Unmount the tab (remove it from the DOM) when it is no longer visible */ unmountOnExit: (prop_types_default()).bool, /** @ignore * */ id: (prop_types_default()).string, /** @ignore * */ 'aria-labelledby': (prop_types_default()).string }; const TabPane = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, transition, ...props }, ref) => { const [{ className, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', ...rest }, { isActive, onEnter, onEntering, onEntered, onExit, onExiting, onExited, mountOnEnter, unmountOnExit, transition: Transition = esm_NoopTransition }] = useTabPanel({ ...props, transition: getTabTransitionComponent(transition) }); const prefix = useBootstrapPrefix(bsPrefix, 'tab-pane'); // We provide an empty the TabContext so `<Nav>`s in `<TabPanel>`s don't // conflict with the top level one. return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_TabContext.Provider, { value: null, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_SelectableContext.Provider, { value: null, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Transition, { in: isActive, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered, onExit: onExit, onExiting: onExiting, onExited: onExited, mountOnEnter: mountOnEnter, unmountOnExit: unmountOnExit, children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ...rest, ref: ref, className: classnames_default()(className, prefix, isActive && 'active') }, void 0, false, { fileName: TabPane_jsxFileName, lineNumber: 146, columnNumber: 15 }, undefined) }, void 0, false, { fileName: TabPane_jsxFileName, lineNumber: 135, columnNumber: 13 }, undefined) }, void 0, false, { fileName: TabPane_jsxFileName, lineNumber: 134, columnNumber: 11 }, undefined) }, void 0, false, { fileName: TabPane_jsxFileName, lineNumber: 133, columnNumber: 9 }, undefined); }); TabPane.displayName = 'TabPane'; TabPane.propTypes = TabPane_propTypes; /* harmony default export */ const src_TabPane = (TabPane); ;// CONCATENATED MODULE: ./src/Tab.tsx /* eslint-disable react/no-unused-prop-types */ const Tab_propTypes = { eventKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]), /** * Content for the tab title. */ title: (prop_types_default()).node.isRequired, /** * The disabled state of the tab. */ disabled: (prop_types_default()).bool, /** * Class to pass to the underlying nav link. */ tabClassName: (prop_types_default()).string }; const Tab = () => { throw new Error('ReactBootstrap: The `Tab` component is not meant to be rendered! ' + "It's an abstract component that is only valid as a direct Child of the `Tabs` Component. " + 'For custom tabs components use TabPane and TabsContainer directly'); // Needed otherwise docs error out. return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(jsx_dev_runtime.Fragment, {}, void 0, false); }; Tab.propTypes = Tab_propTypes; /* harmony default export */ const src_Tab = (Object.assign(Tab, { Container: src_TabContainer, Content: TabContent, Pane: src_TabPane })); ;// CONCATENATED MODULE: ./src/Table.tsx var Table_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Table.tsx"; const Table_propTypes = { /** * @default 'table' */ bsPrefix: (prop_types_default()).string, /** * Adds zebra-striping to any table row within the `<tbody>`. */ striped: (prop_types_default()).bool, /** * Adds borders on all sides of the table and cells. */ bordered: (prop_types_default()).bool, /** * Removes all borders on the table and cells, including table header. */ borderless: (prop_types_default()).bool, /** * Enable a hover state on table rows within a `<tbody>`. */ hover: (prop_types_default()).bool, /** * Make tables more compact by cutting cell padding in half by setting * size as `sm`. */ size: (prop_types_default()).string, /** * Invert the colors of the table — with light text on dark backgrounds * by setting variant as `dark`. */ variant: (prop_types_default()).string, /** * Responsive tables allow tables to be scrolled horizontally with ease. * Across every breakpoint, use `responsive` for horizontally * scrolling tables. Responsive tables are wrapped automatically in a `div`. * Use `responsive="sm"`, `responsive="md"`, `responsive="lg"`, or * `responsive="xl"` as needed to create responsive tables up to * a particular breakpoint. From that breakpoint and up, the table will * behave normally and not scroll horizontally. */ responsive: prop_types_default().oneOfType([(prop_types_default()).bool, (prop_types_default()).string]) }; const Table = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, striped, bordered, borderless, hover, size, variant, responsive, ...props }, ref) => { const decoratedBsPrefix = useBootstrapPrefix(bsPrefix, 'table'); const classes = classnames_default()(className, decoratedBsPrefix, variant && `${decoratedBsPrefix}-${variant}`, size && `${decoratedBsPrefix}-${size}`, striped && `${decoratedBsPrefix}-striped`, bordered && `${decoratedBsPrefix}-bordered`, borderless && `${decoratedBsPrefix}-borderless`, hover && `${decoratedBsPrefix}-hover`); const table = /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("table", { ...props, className: classes, ref: ref }, void 0, false, { fileName: Table_jsxFileName, lineNumber: 98, columnNumber: 19 }, undefined); if (responsive) { let responsiveClass = `${decoratedBsPrefix}-responsive`; if (typeof responsive === 'string') { responsiveClass = `${responsiveClass}-${responsive}`; } return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { className: responsiveClass, children: table }, void 0, false, { fileName: Table_jsxFileName, lineNumber: 105, columnNumber: 14 }, undefined); } return table; }); Table.propTypes = Table_propTypes; /* harmony default export */ const src_Table = (Table); ;// CONCATENATED MODULE: ./src/Tabs.tsx var Tabs_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Tabs.tsx"; const Tabs_propTypes = { /** * Mark the Tab with a matching `eventKey` as active. * * @controllable onSelect */ activeKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]), /** The default active key that is selected on start */ defaultActiveKey: prop_types_default().oneOfType([(prop_types_default()).string, (prop_types_default()).number]), /** * Navigation style * * @type {('tabs'| 'pills')} */ variant: (prop_types_default()).string, /** * Sets a default animation strategy for all children `<TabPane>`s.<tbcont * * Defaults to `<Fade>` animation, else use `false` to disable or a * react-transition-group `<Transition/>` component. * * @type {Transition | false} * @default {Fade} */ transition: prop_types_default().oneOfType([prop_types_default().oneOf([false]), (prop_types_default()).elementType]), /** * HTML id attribute, required if no `generateChildId` prop * is specified. * * @type {string} */ id: (prop_types_default()).string, /** * Callback fired when a Tab is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * @controllable activeKey */ onSelect: (prop_types_default()).func, /** * Wait until the first "enter" transition to mount tabs (add them to the DOM) */ mountOnEnter: (prop_types_default()).bool, /** * Unmount tabs (remove it from the DOM) when it is no longer visible */ unmountOnExit: (prop_types_default()).bool }; const Tabs_defaultProps = { variant: 'tabs', mountOnEnter: false, unmountOnExit: false }; function getDefaultActiveKey(children) { let defaultActiveKey; forEach(children, child => { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } function renderTab(child) { const { title, eventKey, disabled, tabClassName, id } = child.props; if (title == null) { return null; } return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_NavItem, { as: "li", role: "presentation", children: /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_NavLink, { as: "button", type: "button", eventKey: eventKey, disabled: disabled, id: id, className: tabClassName, children: title }, void 0, false, { fileName: Tabs_jsxFileName, lineNumber: 112, columnNumber: 7 }, this) }, void 0, false, { fileName: Tabs_jsxFileName, lineNumber: 111, columnNumber: 5 }, this); } const Tabs_Tabs = props => { const { id, onSelect, transition, mountOnEnter, unmountOnExit, children, activeKey = getDefaultActiveKey(children), ...controlledProps } = useUncontrolled(props, { activeKey: 'onSelect' }); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(esm_Tabs, { id: id, activeKey: activeKey, onSelect: onSelect, transition: getTabTransitionComponent(transition), mountOnEnter: mountOnEnter, unmountOnExit: unmountOnExit, children: [/*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Nav, { ...controlledProps, role: "tablist", as: "ul", children: map(children, renderTab) }, void 0, false, { fileName: Tabs_jsxFileName, lineNumber: 149, columnNumber: 7 }, undefined), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(TabContent, { children: map(children, child => { const childProps = { ...child.props }; delete childProps.title; delete childProps.disabled; delete childProps.tabClassName; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_TabPane, { ...childProps }, void 0, false, { fileName: Tabs_jsxFileName, lineNumber: 161, columnNumber: 18 }, undefined); }) }, void 0, false, { fileName: Tabs_jsxFileName, lineNumber: 153, columnNumber: 7 }, undefined)] }, void 0, true, { fileName: Tabs_jsxFileName, lineNumber: 141, columnNumber: 5 }, undefined); }; Tabs_Tabs.propTypes = Tabs_propTypes; Tabs_Tabs.defaultProps = Tabs_defaultProps; Tabs_Tabs.displayName = 'Tabs'; /* harmony default export */ const src_Tabs = (Tabs_Tabs); ;// CONCATENATED MODULE: ./src/ToastFade.tsx var ToastFade_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ToastFade.tsx"; const ToastFade_fadeStyles = { [ENTERING]: 'showing', [EXITING]: 'showing show' }; const ToastFade = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, ref) => /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Fade, { ...props, ref: ref, transitionClasses: ToastFade_fadeStyles }, void 0, false, { fileName: ToastFade_jsxFileName, lineNumber: 14, columnNumber: 3 }, undefined)); ToastFade.displayName = 'ToastFade'; /* harmony default export */ const src_ToastFade = (ToastFade); ;// CONCATENATED MODULE: ./src/ToastContext.tsx const ToastContext = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.createContext({ // eslint-disable-next-line @typescript-eslint/no-empty-function onClose() {} }); /* harmony default export */ const src_ToastContext = (ToastContext); ;// CONCATENATED MODULE: ./src/ToastHeader.tsx var ToastHeader_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ToastHeader.tsx"; const ToastHeader_propTypes = { bsPrefix: (prop_types_default()).string, /** * Provides an accessible label for the close * button. It is used for Assistive Technology when the label text is not * readable. */ closeLabel: (prop_types_default()).string, /** * Sets the variant for close button. */ closeVariant: prop_types_default().oneOf(['white']), /** * Specify whether the Component should contain a close button */ closeButton: (prop_types_default()).bool }; const ToastHeader_defaultProps = { closeLabel: 'Close', closeButton: true }; const ToastHeader = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, closeLabel, closeVariant, closeButton, className, children, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'toast-header'); const context = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useContext)(src_ToastContext); const handleClick = useEventCallback(e => { context == null ? void 0 : context.onClose == null ? void 0 : context.onClose(e); }); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ref: ref, ...props, className: classnames_default()(bsPrefix, className), children: [children, closeButton && /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_CloseButton, { "aria-label": closeLabel, variant: closeVariant, onClick: handleClick, "data-dismiss": "toast" }, void 0, false, { fileName: ToastHeader_jsxFileName, lineNumber: 72, columnNumber: 11 }, undefined)] }, void 0, true, { fileName: ToastHeader_jsxFileName, lineNumber: 68, columnNumber: 7 }, undefined); }); ToastHeader.displayName = 'ToastHeader'; ToastHeader.propTypes = ToastHeader_propTypes; ToastHeader.defaultProps = ToastHeader_defaultProps; /* harmony default export */ const src_ToastHeader = (ToastHeader); ;// CONCATENATED MODULE: ./src/ToastBody.tsx /* harmony default export */ const ToastBody = (createWithBsPrefix('toast-body')); ;// CONCATENATED MODULE: ./src/Toast.tsx var Toast_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Toast.tsx"; const Toast_propTypes = { /** * @default 'toast' */ bsPrefix: (prop_types_default()).string, /** * Apply a CSS fade transition to the toast */ animation: (prop_types_default()).bool, /** * Auto hide the toast */ autohide: (prop_types_default()).bool, /** * Delay hiding the toast (ms) */ delay: (prop_types_default()).number, /** * A Callback fired when the close button is clicked. */ onClose: (prop_types_default()).func, /** * When `true` The modal will show itself. */ show: (prop_types_default()).bool, /** * A `react-transition-group` Transition component used to animate the Toast on dismissal. */ transition: (prop_types_default()).elementType, /** * Sets Toast background * * @type {('primary'|'secondary'|'success'|'danger'|'warning'|'info'|'dark'|'light')} */ bg: (prop_types_default()).string }; const Toast = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, className, transition: Transition = src_ToastFade, show = true, animation = true, delay = 5000, autohide = false, onClose, bg, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'toast'); // We use refs for these, because we don't want to restart the autohide // timer in case these values change. const delayRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(delay); const onCloseRef = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useRef)(onClose); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { delayRef.current = delay; onCloseRef.current = onClose; }, [delay, onClose]); const autohideTimeout = useTimeout(); const autohideToast = !!(autohide && show); const autohideFunc = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useCallback)(() => { if (autohideToast) { onCloseRef.current == null ? void 0 : onCloseRef.current(); } }, [autohideToast]); (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useEffect)(() => { // Only reset timer if show or autohide changes. autohideTimeout.set(autohideFunc, delayRef.current); }, [autohideTimeout, autohideFunc]); const toastContext = (0,external_root_React_commonjs2_react_commonjs_react_amd_react_.useMemo)(() => ({ onClose }), [onClose]); const hasAnimation = !!(Transition && animation); const toast = /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ...props, ref: ref, className: classnames_default()(bsPrefix, className, bg && `bg-${bg}`, !hasAnimation && (show ? 'show' : 'hide')), role: "alert", "aria-live": "assertive", "aria-atomic": "true" }, void 0, false, { fileName: Toast_jsxFileName, lineNumber: 125, columnNumber: 9 }, undefined); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_ToastContext.Provider, { value: toastContext, children: hasAnimation && Transition ? /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Transition, { in: show, unmountOnExit: true, children: toast }, void 0, false, { fileName: Toast_jsxFileName, lineNumber: 143, columnNumber: 13 }, undefined) : toast }, void 0, false, { fileName: Toast_jsxFileName, lineNumber: 141, columnNumber: 9 }, undefined); }); Toast.propTypes = Toast_propTypes; Toast.displayName = 'Toast'; /* harmony default export */ const src_Toast = (Object.assign(Toast, { Body: ToastBody, Header: src_ToastHeader })); ;// CONCATENATED MODULE: ./src/ToastContainer.tsx var ToastContainer_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ToastContainer.tsx"; const ToastContainer_propTypes = { /** * @default 'toast-container' */ bsPrefix: (prop_types_default()).string, /** * Where the toasts will be placed within the container. */ position: prop_types_default().oneOf(['top-start', 'top-center', 'top-end', 'middle-start', 'middle-center', 'middle-end', 'bottom-start', 'bottom-center', 'bottom-end']) }; const positionClasses = { 'top-start': 'top-0 start-0', 'top-center': 'top-0 start-50 translate-middle-x', 'top-end': 'top-0 end-0', 'middle-start': 'top-50 start-0 translate-middle-y', 'middle-center': 'top-50 start-50 translate-middle', 'middle-end': 'top-50 end-0 translate-middle-y', 'bottom-start': 'bottom-0 start-0', 'bottom-center': 'bottom-0 start-50 translate-middle-x', 'bottom-end': 'bottom-0 end-0' }; const ToastContainer = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, position, className, // Need to define the default "as" during prop destructuring to be compatible with styled-components github.com/react-bootstrap/react-bootstrap/issues/3595 as: Component = 'div', ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'toast-container'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(Component, { ref: ref, ...props, className: classnames_default()(bsPrefix, position && `position-absolute ${positionClasses[position]}`, className) }, void 0, false, { fileName: ToastContainer_jsxFileName, lineNumber: 76, columnNumber: 7 }, undefined); }); ToastContainer.displayName = 'ToastContainer'; ToastContainer.propTypes = ToastContainer_propTypes; /* harmony default export */ const src_ToastContainer = (ToastContainer); ;// CONCATENATED MODULE: ./src/ToggleButton.tsx var ToggleButton_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ToggleButton.tsx"; const ToggleButton_noop = () => undefined; const ToggleButton_propTypes = { /** * @default 'btn-check' */ bsPrefix: (prop_types_default()).string, /** * The `<input>` element `type` */ type: prop_types_default().oneOf(['checkbox', 'radio']), /** * The HTML input name, used to group like checkboxes or radio buttons together * semantically */ name: (prop_types_default()).string, /** * The checked state of the input, managed by `<ToggleButtonGroup>` automatically */ checked: (prop_types_default()).bool, /** * The disabled state of both the label and input */ disabled: (prop_types_default()).bool, /** * `id` is required for button clicks to toggle input. */ id: (prop_types_default()).string.isRequired, /** * A callback fired when the underlying input element changes. This is passed * directly to the `<input>` so shares the same signature as a native `onChange` event. */ onChange: (prop_types_default()).func, /** * The value of the input, should be unique amongst it's siblings when nested in a * `ToggleButtonGroup`. */ value: prop_types_default().oneOfType([(prop_types_default()).string, prop_types_default().arrayOf((prop_types_default()).string.isRequired), (prop_types_default()).number]).isRequired, /** * A ref attached to the `<input>` element * @type {ReactRef} */ inputRef: prop_types_default().oneOfType([(prop_types_default()).func, (prop_types_default()).any]) }; const ToggleButton = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, name, className, checked, type, onChange, value, disabled, id, inputRef, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'btn-check'); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(jsx_dev_runtime.Fragment, { children: [/*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("input", { className: bsPrefix, name: name, type: type, value: value, ref: inputRef, autoComplete: "off", checked: !!checked, disabled: !!disabled, onChange: onChange || ToggleButton_noop, id: id }, void 0, false, { fileName: ToggleButton_jsxFileName, lineNumber: 98, columnNumber: 9 }, undefined), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_Button, { ...props, ref: ref, className: classnames_default()(className, disabled && 'disabled'), type: undefined, as: "label", htmlFor: id }, void 0, false, { fileName: ToggleButton_jsxFileName, lineNumber: 110, columnNumber: 9 }, undefined)] }, void 0, true); }); ToggleButton.propTypes = ToggleButton_propTypes; ToggleButton.displayName = 'ToggleButton'; /* harmony default export */ const src_ToggleButton = (ToggleButton); ;// CONCATENATED MODULE: ./src/ToggleButtonGroup.tsx var ToggleButtonGroup_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/ToggleButtonGroup.tsx"; const ToggleButtonGroup_propTypes = { /** * An HTML `<input>` name for each child button. * * __Required if `type` is set to `'radio'`__ */ name: (prop_types_default()).string, /** * The value, or array of values, of the active (pressed) buttons * * @controllable onChange */ value: (prop_types_default()).any, /** * Callback fired when a button is pressed, depending on whether the `type` * is `'radio'` or `'checkbox'`, `onChange` will be called with the value or * array of active values * * @controllable value */ onChange: (prop_types_default()).func, /** * The input `type` of the rendered buttons, determines the toggle behavior * of the buttons */ type: prop_types_default().oneOf(['checkbox', 'radio']).isRequired, /** * Sets the size for all Buttons in the group. * * @type ('sm'|'lg') */ size: (prop_types_default()).string, /** Make the set of Buttons appear vertically stacked. */ vertical: (prop_types_default()).bool }; const ToggleButtonGroup_defaultProps = { type: 'radio', vertical: false }; const ToggleButtonGroup = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef((props, ref) => { const { children, type, name, value, onChange, ...controlledProps } = useUncontrolled(props, { value: 'onChange' }); const getValues = () => value == null ? [] : [].concat(value); const handleToggle = (inputVal, event) => { if (!onChange) { return; } const values = getValues(); const isActive = values.indexOf(inputVal) !== -1; if (type === 'radio') { if (!isActive && onChange) onChange(inputVal, event); return; } if (isActive) { onChange(values.filter(n => n !== inputVal), event); } else { onChange([...values, inputVal], event); } }; !(type !== 'radio' || !!name) ? false ? 0 : browser_default()(false) : void 0; return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)(src_ButtonGroup, { ...controlledProps, ref: ref, children: map(children, child => { const values = getValues(); const { value: childVal, onChange: childOnChange } = child.props; const handler = e => handleToggle(childVal, e); return /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.cloneElement(child, { type, name: child.name || name, checked: values.indexOf(childVal) !== -1, onChange: src_createChainedFunction(childOnChange, handler) }); }) }, void 0, false, { fileName: ToggleButtonGroup_jsxFileName, lineNumber: 123, columnNumber: 5 }, undefined); }); ToggleButtonGroup.propTypes = ToggleButtonGroup_propTypes; ToggleButtonGroup.defaultProps = ToggleButtonGroup_defaultProps; /* harmony default export */ const src_ToggleButtonGroup = (Object.assign(ToggleButtonGroup, { Button: src_ToggleButton })); ;// CONCATENATED MODULE: ./src/Tooltip.tsx var Tooltip_jsxFileName = "/Users/kyletsang/Documents/Kyle/Code/react-bootstrap/src/Tooltip.tsx"; const Tooltip_propTypes = { /** * @default 'tooltip' */ bsPrefix: (prop_types_default()).string, /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: (prop_types_default()).string, /** * Sets the direction the Tooltip is positioned towards. * * > This is generally provided by the `Overlay` component positioning the tooltip */ placement: prop_types_default().oneOf(['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']), /** * An Overlay injected set of props for positioning the tooltip arrow. * * > This is generally provided by the `Overlay` component positioning the tooltip * * @type {{ ref: ReactRef, style: Object }} */ arrowProps: prop_types_default().shape({ ref: (prop_types_default()).any, style: (prop_types_default()).object }), /** @private */ popper: (prop_types_default()).object, /** @private */ show: (prop_types_default()).any }; const Tooltip_defaultProps = { placement: 'right' }; const Tooltip = /*#__PURE__*/external_root_React_commonjs2_react_commonjs_react_amd_react_.forwardRef(({ bsPrefix, placement, className, style, children, arrowProps, popper: _, show: _2, ...props }, ref) => { bsPrefix = useBootstrapPrefix(bsPrefix, 'tooltip'); const isRTL = useIsRTL(); const [primaryPlacement] = (placement == null ? void 0 : placement.split('-')) || []; const bsDirection = getOverlayDirection(primaryPlacement, isRTL); return /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { ref: ref, style: style, role: "tooltip", "x-placement": primaryPlacement, className: classnames_default()(className, bsPrefix, `bs-tooltip-${bsDirection}`), ...props, children: [/*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { className: "tooltip-arrow", ...arrowProps }, void 0, false, { fileName: Tooltip_jsxFileName, lineNumber: 107, columnNumber: 9 }, undefined), /*#__PURE__*/(0,jsx_dev_runtime.jsxDEV)("div", { className: `${bsPrefix}-inner`, children: children }, void 0, false, { fileName: Tooltip_jsxFileName, lineNumber: 108, columnNumber: 9 }, undefined)] }, void 0, true, { fileName: Tooltip_jsxFileName, lineNumber: 99, columnNumber: 7 }, undefined); }); Tooltip.propTypes = Tooltip_propTypes; Tooltip.defaultProps = Tooltip_defaultProps; Tooltip.displayName = 'Tooltip'; /* harmony default export */ const src_Tooltip = (Tooltip); ;// CONCATENATED MODULE: ./src/index.tsx })(); /******/ return __webpack_exports__; /******/ })() ; });
/** @license React vundefined * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ (function(){'use strict';(function(c,y){"object"===typeof exports&&"undefined"!==typeof module?y(exports):"function"===typeof define&&define.amd?define(["exports"],y):(c=c||self,y(c.React={}))})(this,function(c){function y(a){if(null===a||"object"!==typeof a)return null;a=X&&a[X]||a["@@iterator"];return"function"===typeof a?a:null}function z(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,f=1;f<arguments.length;f++)b+="&args[]="+encodeURIComponent(arguments[f]);return"Minified React error #"+ a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function w(a,b,f){this.props=a;this.context=b;this.refs=Y;this.updater=f||Z}function aa(){}function L(a,b,f){this.props=a;this.context=b;this.refs=Y;this.updater=f||Z}function ba(a,b,f){var l,e={},c=null,k=null;if(null!=b)for(l in void 0!==b.ref&&(k=b.ref),void 0!==b.key&&(c=""+b.key),b)ca.call(b,l)&&!da.hasOwnProperty(l)&&(e[l]=b[l]);var p=arguments.length-2;if(1===p)e.children= f;else if(1<p){for(var h=Array(p),d=0;d<p;d++)h[d]=arguments[d+2];e.children=h}if(a&&a.defaultProps)for(l in p=a.defaultProps,p)void 0===e[l]&&(e[l]=p[l]);return{$$typeof:x,type:a,key:c,ref:k,props:e,_owner:M.current}}function ua(a,b){return{$$typeof:x,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function N(a){return"object"===typeof a&&null!==a&&a.$$typeof===x}function va(a){var b={"=":"=0",":":"=2"};return"$"+a.replace(/[=:]/g,function(a){return b[a]})}function O(a,b){return"object"=== typeof a&&null!==a&&null!=a.key?va(""+a.key):b.toString(36)}function C(a,b,f,l,e){var c=typeof a;if("undefined"===c||"boolean"===c)a=null;var k=!1;if(null===a)k=!0;else switch(c){case "string":case "number":k=!0;break;case "object":switch(a.$$typeof){case x:case ea:k=!0}}if(k)return k=a,e=e(k),a=""===l?"."+O(k,0):l,fa(e)?(f="",null!=a&&(f=a.replace(ha,"$&/")+"/"),C(e,b,f,"",function(a){return a})):null!=e&&(N(e)&&(e=ua(e,f+(!e.key||k&&k.key===e.key?"":(""+e.key).replace(ha,"$&/")+"/")+a)),b.push(e)), 1;k=0;l=""===l?".":l+":";if(fa(a))for(var d=0;d<a.length;d++){c=a[d];var h=l+O(c,d);k+=C(c,b,f,h,e)}else if(h=y(a),"function"===typeof h)for(a=h.call(a),d=0;!(c=a.next()).done;)c=c.value,h=l+O(c,d++),k+=C(c,b,f,h,e);else if("object"===c)throw b=""+a,Error(z(31,"[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b));return k}function D(a,b,f){if(null==a)return a;var c=[],e=0;C(a,c,"","",function(a){return b.call(f,a,e++)});return c}function wa(a){if(-1===a._status){var b=a._result; b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b});-1===a._status&&(a._status=0,a._result=b)}if(1===a._status)return a._result.default;throw a._result;}function P(a,b){var f=a.length;a.push(b);a:for(;0<f;){var c=f-1>>>1,e=a[c];if(0<E(e,b))a[c]=b,a[f]=e,f=c;else break a}}function q(a){return 0===a.length?null:a[0]}function F(a){if(0===a.length)return null;var b=a[0],f=a.pop();if(f!==b){a[0]=f;a:for(var c= 0,e=a.length,d=e>>>1;c<d;){var k=2*(c+1)-1,p=a[k],h=k+1,g=a[h];if(0>E(p,f))h<e&&0>E(g,p)?(a[c]=g,a[h]=f,c=h):(a[c]=p,a[k]=f,c=k);else if(h<e&&0>E(g,f))a[c]=g,a[h]=f,c=h;else break a}}return b}function E(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}function Q(a){for(var b=q(t);null!==b;){if(null===b.callback)F(t);else if(b.startTime<=a)F(t),b.sortIndex=b.expirationTime,P(r,b);else break;b=q(t)}}function R(a){A=!1;Q(a);if(!u)if(null!==q(r))u=!0,S(T);else{var b=q(t);null!==b&&U(R,b.startTime- a)}}function T(a,b){u=!1;A&&(A=!1,ia(B),B=-1);G=!0;var c=g;try{Q(b);for(n=q(r);null!==n&&(!(n.expirationTime>b)||a&&!ja());){var l=n.callback;if("function"===typeof l){n.callback=null;g=n.priorityLevel;var e=l(n.expirationTime<=b);b=v();"function"===typeof e?n.callback=e:n===q(r)&&F(r);Q(b)}else F(r);n=q(r)}if(null!==n)var d=!0;else{var k=q(t);null!==k&&U(R,k.startTime-b);d=!1}return d}finally{n=null,g=c,G=!1}}function ja(){return v()-ka<la?!1:!0}function S(a){H=a;I||(I=!0,J())}function U(a,b){B= ma(function(){a(v())},b)}var x=60103,ea=60106;c.Fragment=60107;c.StrictMode=60108;c.Profiler=60114;var na=60109,oa=60110,pa=60112;c.Suspense=60113;c.SuspenseList=60120;var qa=60115,ra=60116;if("function"===typeof Symbol&&Symbol.for){var d=Symbol.for;x=d("react.element");ea=d("react.portal");c.Fragment=d("react.fragment");c.StrictMode=d("react.strict_mode");c.Profiler=d("react.profiler");na=d("react.provider");oa=d("react.context");pa=d("react.forward_ref");c.Suspense=d("react.suspense");c.SuspenseList= d("react.suspense_list");qa=d("react.memo");ra=d("react.lazy")}var X="function"===typeof Symbol&&Symbol.iterator,xa=Object.prototype.hasOwnProperty,V=Object.assign||function(a,b){if(null==a)throw new TypeError("Object.assign target cannot be null or undefined");for(var c=Object(a),d=1;d<arguments.length;d++){var e=arguments[d];if(null!=e){var g=void 0;e=Object(e);for(g in e)xa.call(e,g)&&(c[g]=e[g])}}return c},Z={isMounted:function(a){return!1},enqueueForceUpdate:function(a,b,c){},enqueueReplaceState:function(a, b,c,d){},enqueueSetState:function(a,b,c,d){}},Y={};w.prototype.isReactComponent={};w.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error(z(85));this.updater.enqueueSetState(this,a,b,"setState")};w.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};aa.prototype=w.prototype;d=L.prototype=new aa;d.constructor=L;V(d,w.prototype);d.isPureReactComponent=!0;var fa=Array.isArray,ca=Object.prototype.hasOwnProperty,M={current:null}, da={key:!0,ref:!0,__self:!0,__source:!0},ha=/\/+/g,m={current:null},K={transition:0};if("object"===typeof performance&&"function"===typeof performance.now){var ya=performance;var v=function(){return ya.now()}}else{var sa=Date,za=sa.now();v=function(){return sa.now()-za}}var r=[],t=[],Aa=1,n=null,g=3,G=!1,u=!1,A=!1,ma="function"===typeof setTimeout?setTimeout:null,ia="function"===typeof clearTimeout?clearTimeout:null,ta="undefined"!==typeof setImmediate?setImmediate:null;"undefined"!==typeof navigator&& void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var I=!1,H=null,B=-1,la=5,ka=-1,W=function(){if(null!==H){var a=v();ka=a;var b=!0;try{b=H(!0,a)}finally{b?J():(I=!1,H=null)}}else I=!1};if("function"===typeof ta)var J=function(){ta(W)};else if("undefined"!==typeof MessageChannel){d=new MessageChannel;var Ba=d.port2;d.port1.onmessage=W;J=function(){Ba.postMessage(null)}}else J=function(){ma(W,0)};d={ReactCurrentDispatcher:m, ReactCurrentOwner:M,ReactCurrentBatchConfig:K,assign:V,Scheduler:{__proto__:null,unstable_ImmediatePriority:1,unstable_UserBlockingPriority:2,unstable_NormalPriority:3,unstable_IdlePriority:5,unstable_LowPriority:4,unstable_runWithPriority:function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=g;g=a;try{return b()}finally{g=c}},unstable_next:function(a){switch(g){case 1:case 2:case 3:var b=3;break;default:b=g}var c=g;g=b;try{return a()}finally{g=c}},unstable_scheduleCallback:function(a, b,c){var d=v();"object"===typeof c&&null!==c?(c=c.delay,c="number"===typeof c&&0<c?d+c:d):c=d;switch(a){case 1:var e=-1;break;case 2:e=250;break;case 5:e=1073741823;break;case 4:e=1E4;break;default:e=5E3}e=c+e;a={id:Aa++,callback:b,priorityLevel:a,startTime:c,expirationTime:e,sortIndex:-1};c>d?(a.sortIndex=c,P(t,a),null===q(r)&&a===q(t)&&(A?(ia(B),B=-1):A=!0,U(R,c-d))):(a.sortIndex=e,P(r,a),u||G||(u=!0,S(T)));return a},unstable_cancelCallback:function(a){a.callback=null},unstable_wrapCallback:function(a){var b= g;return function(){var c=g;g=b;try{return a.apply(this,arguments)}finally{g=c}}},unstable_getCurrentPriorityLevel:function(){return g},unstable_shouldYield:ja,unstable_requestPaint:function(){},unstable_continueExecution:function(){u||G||(u=!0,S(T))},unstable_pauseExecution:function(){},unstable_getFirstCallbackNode:function(){return q(r)},get unstable_now(){return v},unstable_forceFrameRate:function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"): la=0<a?Math.floor(1E3/a):5},unstable_Profiling:null}};c.Children={map:D,forEach:function(a,b,c){D(a,function(){b.apply(this,arguments)},c)},count:function(a){var b=0;D(a,function(){b++});return b},toArray:function(a){return D(a,function(a){return a})||[]},only:function(a){if(!N(a))throw Error(z(143));return a}};c.Component=w;c.PureComponent=L;c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=d;c.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error(z(267,a));var d=V({},a.props),e=a.key, f=a.ref,k=a._owner;if(null!=b){void 0!==b.ref&&(f=b.ref,k=M.current);void 0!==b.key&&(e=""+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(h in b)ca.call(b,h)&&!da.hasOwnProperty(h)&&(d[h]=void 0===b[h]&&void 0!==g?g[h]:b[h])}var h=arguments.length-2;if(1===h)d.children=c;else if(1<h){g=Array(h);for(var m=0;m<h;m++)g[m]=arguments[m+2];d.children=g}return{$$typeof:x,type:a.type,key:e,ref:f,props:d,_owner:k}};c.createContext=function(a){a={$$typeof:oa,_currentValue:a,_currentValue2:a, _threadCount:0,Provider:null,Consumer:null};a.Provider={$$typeof:na,_context:a};return a.Consumer=a};c.createElement=ba;c.createFactory=function(a){var b=ba.bind(null,a);b.type=a;return b};c.createRef=function(){return{current:null}};c.forwardRef=function(a){return{$$typeof:pa,render:a}};c.isValidElement=N;c.lazy=function(a){return{$$typeof:ra,_payload:{_status:-1,_result:a},_init:wa}};c.memo=function(a,b){return{$$typeof:qa,type:a,compare:void 0===b?null:b}};c.startTransition=function(a){var b=K.transition; K.transition=1;try{a()}finally{K.transition=b}};c.unstable_act=function(a){throw Error(z(406));};c.unstable_useOpaqueIdentifier=function(){return m.current.useOpaqueIdentifier()};c.useCallback=function(a,b){return m.current.useCallback(a,b)};c.useContext=function(a){return m.current.useContext(a)};c.useDebugValue=function(a,b){};c.useDeferredValue=function(a){return m.current.useDeferredValue(a)};c.useEffect=function(a,b){return m.current.useEffect(a,b)};c.useImperativeHandle=function(a,b,c){return m.current.useImperativeHandle(a, b,c)};c.useLayoutEffect=function(a,b){return m.current.useLayoutEffect(a,b)};c.useMemo=function(a,b){return m.current.useMemo(a,b)};c.useReducer=function(a,b,c){return m.current.useReducer(a,b,c)};c.useRef=function(a){return m.current.useRef(a)};c.useState=function(a){return m.current.useState(a)};c.useTransition=function(){return m.current.useTransition()};c.version="18.0.0-baff3f200-20210921"}); })();
/*! JointJS v3.3.0 (2021-01-15) - JavaScript diagramming library This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ this.joint = this.joint || {}; this.joint.shapes = this.joint.shapes || {}; (function (exports, Element_mjs, Link_mjs) { 'use strict'; var Entity = Element_mjs.Element.define('erd.Entity', { size: { width: 150, height: 60 }, attrs: { '.outer': { fill: '#2ECC71', stroke: '#27AE60', 'stroke-width': 2, points: '100,0 100,60 0,60 0,0' }, '.inner': { fill: '#2ECC71', stroke: '#27AE60', 'stroke-width': 2, points: '95,5 95,55 5,55 5,5', display: 'none' }, text: { text: 'Entity', 'font-family': 'Arial', 'font-size': 14, 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', 'text-anchor': 'middle' } } }, { markup: '<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>', }); var WeakEntity = Entity.define('erd.WeakEntity', { attrs: { '.inner': { display: 'auto' }, text: { text: 'Weak Entity' } } }); var Relationship = Element_mjs.Element.define('erd.Relationship', { size: { width: 80, height: 80 }, attrs: { '.outer': { fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2, points: '40,0 80,40 40,80 0,40' }, '.inner': { fill: '#3498DB', stroke: '#2980B9', 'stroke-width': 2, points: '40,5 75,40 40,75 5,40', display: 'none' }, text: { text: 'Relationship', 'font-family': 'Arial', 'font-size': 12, 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', 'text-anchor': 'middle' } } }, { markup: '<g class="rotatable"><g class="scalable"><polygon class="outer"/><polygon class="inner"/></g><text/></g>', }); var IdentifyingRelationship = Relationship.define('erd.IdentifyingRelationship', { attrs: { '.inner': { display: 'auto' }, text: { text: 'Identifying' } } }); var Attribute = Element_mjs.Element.define('erd.Attribute', { size: { width: 100, height: 50 }, attrs: { 'ellipse': { transform: 'translate(50, 25)' }, '.outer': { stroke: '#D35400', 'stroke-width': 2, cx: 0, cy: 0, rx: 50, ry: 25, fill: '#E67E22' }, '.inner': { stroke: '#D35400', 'stroke-width': 2, cx: 0, cy: 0, rx: 45, ry: 20, fill: '#E67E22', display: 'none' }, text: { 'font-family': 'Arial', 'font-size': 14, 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', 'text-anchor': 'middle' } } }, { markup: '<g class="rotatable"><g class="scalable"><ellipse class="outer"/><ellipse class="inner"/></g><text/></g>', }); var Multivalued = Attribute.define('erd.Multivalued', { attrs: { '.inner': { display: 'block' }, text: { text: 'multivalued' } } }); var Derived = Attribute.define('erd.Derived', { attrs: { '.outer': { 'stroke-dasharray': '3,5' }, text: { text: 'derived' } } }); var Key = Attribute.define('erd.Key', { attrs: { ellipse: { 'stroke-width': 4 }, text: { text: 'key', 'font-weight': '800', 'text-decoration': 'underline' } } }); var Normal = Attribute.define('erd.Normal', { attrs: { text: { text: 'Normal' }} }); var ISA = Element_mjs.Element.define('erd.ISA', { type: 'erd.ISA', size: { width: 100, height: 50 }, attrs: { polygon: { points: '0,0 50,50 100,0', fill: '#F1C40F', stroke: '#F39C12', 'stroke-width': 2 }, text: { text: 'ISA', 'font-size': 18, 'ref-x': .5, 'ref-y': .3, 'y-alignment': 'middle', 'text-anchor': 'middle' } } }, { markup: '<g class="rotatable"><g class="scalable"><polygon/></g><text/></g>', }); var Line = Link_mjs.Link.define('erd.Line', {}, { cardinality: function(value) { this.set('labels', [{ position: -20, attrs: { text: { dy: -8, text: value }}}]); } }); exports.Attribute = Attribute; exports.Derived = Derived; exports.Entity = Entity; exports.ISA = ISA; exports.IdentifyingRelationship = IdentifyingRelationship; exports.Key = Key; exports.Line = Line; exports.Multivalued = Multivalued; exports.Normal = Normal; exports.Relationship = Relationship; exports.WeakEntity = WeakEntity; }(this.joint.shapes.erd = this.joint.shapes.erd || {}, joint.dia, joint.dia));
/*! * DevExtreme (dx.messages.ja.js) * Version: 17.2.18 * Build date: Fri Dec 03 2021 * * Copyright (c) 2012 - 2021 Developer Express Inc. ALL RIGHTS RESERVED * Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/ */ "use strict"; ! function(root, factory) { if ("function" === typeof define && define.amd) { define(function(require) { factory(require("devextreme/localization")) }) } else { if ("object" === typeof module && module.exports) { factory(require("devextreme/localization")) } else { factory(DevExpress.localization) } } }(this, function(localization) { localization.loadMessages({ ja: { Yes: "はい", No: "いいえ", Cancel: "キャンセル", Clear: "クリア", Done: "完了", Loading: "読み込み中…", Select: "選択…", Search: "検索", Back: "戻る", OK: "OK", "dxCollectionWidget-noDataText": "表示するデータがありません。", "validation-required": "必須", "validation-required-formatted": "{0} は必須です。", "validation-numeric": "数値を指定してください。", "validation-numeric-formatted": "{0} は数値でなければいけません。", "validation-range": "値が範囲外です", "validation-range-formatted": "{0} の長さが正しくありません。", "validation-stringLength": "値の長さが正しくありません。", "validation-stringLength-formatted": "{0} の長さが正しくありません", "validation-custom": "値が無効です。", "validation-custom-formatted": "{0} が無効です。", "validation-compare": "値が一致しません。", "validation-compare-formatted": " {0} が一致しません。", "validation-pattern": "値がパターンと一致しません", "validation-pattern-formatted": "{0} がパターンと一致しません", "validation-email": "電子メール アドレスが無効です。", "validation-email-formatted": "{0} が無効です。", "validation-mask": "値が無効です。", "dxLookup-searchPlaceholder": "最低文字数: {0}", "dxList-pullingDownText": "引っ張って更新…", "dxList-pulledDownText": "指を離して更新…", "dxList-refreshingText": "更新中…", "dxList-pageLoadingText": "読み込み中…", "dxList-nextButtonText": "もっと表示する", "dxList-selectAll": "すべてを選択", "dxListEditDecorator-delete": "削除", "dxListEditDecorator-more": "もっと", "dxScrollView-pullingDownText": "引っ張って更新…", "dxScrollView-pulledDownText": "指を離して更新…", "dxScrollView-refreshingText": "更新中…", "dxScrollView-reachBottomText": "読み込み中", "dxDateBox-simulatedDataPickerTitleTime": "時刻を選択してください。", "dxDateBox-simulatedDataPickerTitleDate": "日付を選択してください。", "dxDateBox-simulatedDataPickerTitleDateTime": "日付と時刻を選択してください。", "dxDateBox-validation-datetime": "日付または時刻を指定してください。", "dxFileUploader-selectFile": "ファイルを選択", "dxFileUploader-dropFile": "またはファイルをこちらにドロップしてください。", "dxFileUploader-bytes": "バイト", "dxFileUploader-kb": "kb", "dxFileUploader-Mb": "Mb", "dxFileUploader-Gb": "Gb", "dxFileUploader-upload": "アップロード", "dxFileUploader-uploaded": "アップロード済み", "dxFileUploader-readyToUpload": "アップロードの準備中", "dxFileUploader-uploadFailedMessage": "アップロードに失敗しました", "dxRangeSlider-ariaFrom": "から", "dxRangeSlider-ariaTill": "まで", "dxSwitch-onText": "オン", "dxSwitch-offText": "オフ", "dxForm-optionalMark": "任意", "dxForm-requiredMessage": "{0} は必須フィールドです", "dxNumberBox-invalidValueMessage": "数値を指定してください。", "dxDataGrid-columnChooserTitle": "列の選択", "dxDataGrid-columnChooserEmptyText": "隠したい列のヘッダーをここにドラッグしてください。", "dxDataGrid-groupContinuesMessage": "次ページに続く", "dxDataGrid-groupContinuedMessage": "前ページから続く", "dxDataGrid-groupHeaderText": "この列でグループ化", "dxDataGrid-ungroupHeaderText": "グループ解除", "dxDataGrid-ungroupAllText": "すべてのグループを解除", "dxDataGrid-editingEditRow": "編集", "dxDataGrid-editingSaveRowChanges": "保存", "dxDataGrid-editingCancelRowChanges": "キャンセル", "dxDataGrid-editingDeleteRow": "削除", "dxDataGrid-editingUndeleteRow": "復元", "dxDataGrid-editingConfirmDeleteMessage": "このレコードを削 除してもよろしいですか?", "dxDataGrid-validationCancelChanges": "変更をキャンセル", "dxDataGrid-groupPanelEmptyText": "グループ化したい列のヘッダーをここにドラッグしてください。", "dxDataGrid-noDataText": "データがありません", "dxDataGrid-searchPanelPlaceholder": "検索", "dxDataGrid-filterRowShowAllText": "(すべて)", "dxDataGrid-filterRowResetOperationText": "リセット", "dxDataGrid-filterRowOperationEquals": "指定の値に等しい", "dxDataGrid-filterRowOperationNotEquals": "指定の値に等しくない", "dxDataGrid-filterRowOperationLess": "指定の値より小さい", "dxDataGrid-filterRowOperationLessOrEquals": "指定の値以下", "dxDataGrid-filterRowOperationGreater": "指定の値より大きい", "dxDataGrid-filterRowOperationGreaterOrEquals": "指定の値以上", "dxDataGrid-filterRowOperationStartsWith": "指定の値で始まる", "dxDataGrid-filterRowOperationContains": "指定の値を含む", "dxDataGrid-filterRowOperationNotContains": "指定の値を含まない", "dxDataGrid-filterRowOperationEndsWith": "指定の値で終わる", "dxDataGrid-filterRowOperationBetween": "~から~の間", "dxDataGrid-filterRowOperationBetweenStartText": "開始値", "dxDataGrid-filterRowOperationBetweenEndText": "終了値", "dxDataGrid-applyFilterText": "フィルターを適用", "dxDataGrid-trueText": "true", "dxDataGrid-falseText": "false", "dxDataGrid-sortingAscendingText": "昇順に並べ替え", "dxDataGrid-sortingDescendingText": "降順に並べ替え", "dxDataGrid-sortingClearText": "並べ替えをクリア", "dxDataGrid-editingSaveAllChanges": "変更を保存", "dxDataGrid-editingCancelAllChanges": "変更を破棄", "dxDataGrid-editingAddRow": "行を追加", "dxDataGrid-summaryMin": "Min: {0}", "dxDataGrid-summaryMinOtherColumn": "{1} の最小は {0}", "dxDataGrid-summaryMax": "Max: {0}", "dxDataGrid-summaryMaxOtherColumn": "{1} の最小は {0}", "dxDataGrid-summaryAvg": "Avg: {0}", "dxDataGrid-summaryAvgOtherColumn": "{1} の平均は {0}", "dxDataGrid-summarySum": "合計: {0}", "dxDataGrid-summarySumOtherColumn": "{1} の合計は {0}", "dxDataGrid-summaryCount": "総数: {0}", "dxDataGrid-columnFixingFix": "固定", "dxDataGrid-columnFixingUnfix": "固定の解除", "dxDataGrid-columnFixingLeftPosition": "左に固定", "dxDataGrid-columnFixingRightPosition": "右に固定", "dxDataGrid-exportTo": "エクスポート", "dxDataGrid-exportToExcel": "Excel ファイルにエクスポート", "dxDataGrid-excelFormat": "Excel ファイル", "dxDataGrid-selectedRows": "選択された行", "dxDataGrid-exportAll": "すべてのデータをエクスポート", "dxDataGrid-exportSelectedRows": "選択された行をエクスポート", "dxDataGrid-headerFilterEmptyValue": "(空白)", "dxDataGrid-headerFilterOK": "OK", "dxDataGrid-headerFilterCancel": "キャンセル", "dxDataGrid-ariaColumn": "列", "dxDataGrid-ariaValue": "値", "dxDataGrid-ariaFilterCell": "フィルター セル", "dxDataGrid-ariaCollapse": "折りたたむ", "dxDataGrid-ariaExpand": "展開", "dxDataGrid-ariaDataGrid": "データ グリッド", "dxDataGrid-ariaSearchInGrid": "データ グリッド内で検索", "dxDataGrid-ariaSelectAll": "すべてを選択", "dxDataGrid-ariaSelectRow": "行の選択", "dxTreeList-ariaTreeList": "ツリー リスト", "dxTreeList-editingAddRowToNode": "追加", "dxPager-infoText": "ページ {0} / {1} ({2} アイテム)", "dxPager-pagesCountText": "/", "dxPivotGrid-grandTotal": "総計", "dxPivotGrid-total": "{0} 合計", "dxPivotGrid-fieldChooserTitle": "フィールドの選択", "dxPivotGrid-showFieldChooser": "フィールドの選択を表示", "dxPivotGrid-expandAll": "すべて展開", "dxPivotGrid-collapseAll": "すべて折りたたむ", "dxPivotGrid-sortColumnBySummary": 'この列で "{0}" を並べ替え', "dxPivotGrid-sortRowBySummary": "この行で {0} を並べ替え", "dxPivotGrid-removeAllSorting": "すべての並べ替えを削除", "dxPivotGrid-dataNotAvailable": "N/A", "dxPivotGrid-rowFields": "行のフィールド", "dxPivotGrid-columnFields": "列のフィールド", "dxPivotGrid-dataFields": "データ  フィールド", "dxPivotGrid-filterFields": "フィルター フィールド", "dxPivotGrid-allFields": "すべてのフィールド", "dxPivotGrid-columnFieldArea": "列フィールドをこちらへドラッグ&ドロップ", "dxPivotGrid-dataFieldArea": "データ フィールドをこちらへドラッグ&ドロップ", "dxPivotGrid-rowFieldArea": "行フィールドをこちらへドラッグ&ドロップ", "dxPivotGrid-filterFieldArea": "フィルター フィールドをこちらへドラッグ&ドロップ", "dxScheduler-editorLabelTitle": "件名", "dxScheduler-editorLabelStartDate": "開始時刻", "dxScheduler-editorLabelEndDate": "終了時刻", "dxScheduler-editorLabelDescription": "説明", "dxScheduler-editorLabelRecurrence": "リピート", "dxScheduler-openAppointment": "オープンの予定", "dxScheduler-recurrenceNever": "無効", "dxScheduler-recurrenceDaily": "日間毎日", "dxScheduler-recurrenceWeekly": "毎週", "dxScheduler-recurrenceMonthly": "毎月", "dxScheduler-recurrenceYearly": "毎年", "dxScheduler-recurrenceEvery": "リピートの頻度", "dxScheduler-recurrenceEnd": "リピートの終了日", "dxScheduler-recurrenceAfter": "次の発生回数後に終了", "dxScheduler-recurrenceOn": "リピート解除の日付", "dxScheduler-recurrenceRepeatDaily": "日後", "dxScheduler-recurrenceRepeatWeekly": "週間後", "dxScheduler-recurrenceRepeatMonthly": "カ月後", "dxScheduler-recurrenceRepeatYearly": "年後", "dxScheduler-switcherDay": "日ビュー", "dxScheduler-switcherWeek": "週ビュー", "dxScheduler-switcherWorkWeek": "稼働週ビュー", "dxScheduler-switcherMonth": "月ビュー", "dxScheduler-switcherTimelineDay": "タイムライン 日ビュー", "dxScheduler-switcherTimelineWeek": "タイムライン 週ビュー", "dxScheduler-switcherTimelineWorkWeek": "タイムライン 稼働週ビュー", "dxScheduler-switcherTimelineMonth": "タイムライン 月ビュー", "dxScheduler-switcherAgenda": "予定一覧", "dxScheduler-recurrenceRepeatOnDate": "次の日付に終了", "dxScheduler-recurrenceRepeatCount": "出現", "dxScheduler-allDay": "終日イベント", "dxScheduler-confirmRecurrenceEditMessage": "この予定のみを編集しますか、または定期的な予定を編集しますか?", "dxScheduler-confirmRecurrenceDeleteMessage": "この予定のみを削除しますか、または定期的な予定を削除しますか?", "dxScheduler-confirmRecurrenceEditSeries": "定期的なアイテムを編集", "dxScheduler-confirmRecurrenceDeleteSeries": "定期的なアイテムを削除", "dxScheduler-confirmRecurrenceEditOccurrence": "予定を編集", "dxScheduler-confirmRecurrenceDeleteOccurrence": "予定を削除", "dxScheduler-noTimezoneTitle": "時間帯なし", "dxScheduler-moreAppointments": "その他 {0} つ選択", "dxCalendar-todayButtonText": "今日", "dxCalendar-ariaWidgetName": "カレンダー", "dxColorView-ariaRed": "赤", "dxColorView-ariaGreen": "緑", "dxColorView-ariaBlue": "青", "dxColorView-ariaAlpha": "透明度", "dxColorView-ariaHex": "色コード", "dxTagBox-selected": "{0} つ選択済み", "dxTagBox-allSelected": "すべて選択済み ({0})", "dxTagBox-moreSelected": "その他 {0} つ選択", "vizExport-printingButtonText": "印刷", "vizExport-titleMenuText": "エクスポート / 印刷", "vizExport-exportButtonText": "{0} ファイル", "dxFilterBuilder-and": "And", "dxFilterBuilder-or": "Or", "dxFilterBuilder-notAnd": "Not And", "dxFilterBuilder-notOr": "Not Or", "dxFilterBuilder-addCondition": "条件の追加", "dxFilterBuilder-addGroup": "グループの追加", "dxFilterBuilder-enterValueText": "値を入力", "dxFilterBuilder-filterOperationEquals": "指定の値に等しい", "dxFilterBuilder-filterOperationNotEquals": "指定の値に等しくない", "dxFilterBuilder-filterOperationLess": "指定の値より小さい", "dxFilterBuilder-filterOperationLessOrEquals": "指定の値以下", "dxFilterBuilder-filterOperationGreater": "指定の値より大きい", "dxFilterBuilder-filterOperationGreaterOrEquals": "指定の値以上", "dxFilterBuilder-filterOperationStartsWith": "指定の値で始まる", "dxFilterBuilder-filterOperationContains": "指定の値を含む", "dxFilterBuilder-filterOperationNotContains": "指定の値を含まない", "dxFilterBuilder-filterOperationEndsWith": "指定の値で終わる", "dxFilterBuilder-filterOperationIsBlank": "空白である", "dxFilterBuilder-filterOperationIsNotBlank": "空白ではない" } }) });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ColorUtils_1 = require("./Utils/ColorUtils"); var Utils_1 = require("./Utils/Utils"); var Absorber = (function () { function Absorber(container, options, position) { var _a, _b; this.container = container; this.initialPosition = position; this.options = options; var size = options.size.value * container.retina.pixelRatio; var random = typeof options.size.random === "boolean" ? options.size.random : options.size.random.enable; var minSize = typeof options.size.random === "boolean" ? 1 : options.size.random.minimumValue; if (random) { size = Utils_1.Utils.randomInRange(minSize, size); } this.opacity = this.options.opacity; this.size = size * container.retina.pixelRatio; this.mass = size * options.size.density; this.limit = options.size.limit; var color = typeof options.color === "string" ? { value: options.color } : options.color; this.color = (_a = ColorUtils_1.ColorUtils.colorToRgb(color)) !== null && _a !== void 0 ? _a : { b: 0, g: 0, r: 0, }; this.position = (_b = this.initialPosition) !== null && _b !== void 0 ? _b : this.calcPosition(); } Absorber.prototype.attract = function (particle) { var container = this.container; var dx = this.position.x - (particle.position.x + particle.offset.x); var dy = this.position.y - (particle.position.y + particle.offset.y); var distance = Math.sqrt(Math.abs(dx * dx + dy * dy)); var angle = Math.atan2(dx, dy) * (180 / Math.PI); var acceleration = this.mass / Math.pow(distance, 2); if (distance < this.size + particle.size.value) { var remove = false; var sizeFactor = particle.size.value * 0.033; if (this.size > particle.size.value && distance < this.size - particle.size.value) { container.particles.remove(particle); remove = true; } else { particle.size.value -= sizeFactor; particle.velocity.horizontal += Math.sin(angle * (Math.PI / 180)) * acceleration; particle.velocity.vertical += Math.cos(angle * (Math.PI / 180)) * acceleration; } if (this.limit === undefined || this.size < this.limit) { this.size += sizeFactor; } this.mass += sizeFactor * this.options.size.density; return !remove; } else { particle.velocity.horizontal += Math.sin(angle * (Math.PI / 180)) * acceleration; particle.velocity.vertical += Math.cos(angle * (Math.PI / 180)) * acceleration; return true; } }; Absorber.prototype.resize = function () { var initialPosition = this.initialPosition; this.position = initialPosition && Utils_1.Utils.isPointInside(initialPosition, this.container.canvas.size) ? initialPosition : this.calcPosition(); }; Absorber.prototype.draw = function () { var container = this.container; container.canvas.drawAbsorber(this); }; Absorber.prototype.calcPosition = function () { var _a; var container = this.container; var percentPosition = (_a = this.options.position) !== null && _a !== void 0 ? _a : { x: Math.random() * 100, y: Math.random() * 100, }; return { x: percentPosition.x / 100 * container.canvas.size.width, y: percentPosition.y / 100 * container.canvas.size.height, }; }; return Absorber; }()); exports.Absorber = Absorber;
/*! pako 2.0.1 https://github.com/nodeca/pako @license (MIT AND Zlib) */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.pako = factory()); }(this, (function () { 'use strict'; // It isn't worth it to make additional optimizations as in original. // Small size is preferable. // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var adler32 = function adler32(adler, buf, len, pos) { var s1 = adler & 0xffff | 0, s2 = adler >>> 16 & 0xffff | 0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = s1 + buf[pos++] | 0; s2 = s2 + s1 | 0; } while (--n); s1 %= 65521; s2 %= 65521; } return s1 | s2 << 16 | 0; }; var adler32_1 = adler32; // So write code to minimize size - no pregenerated tables // and array tools dependencies. // (C) 1995-2013 Jean-loup Gailly and Mark Adler // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // Use ordinary array, since untyped makes no boost here var makeTable = function makeTable() { var c, table = []; for (var n = 0; n < 256; n++) { c = n; for (var k = 0; k < 8; k++) { c = c & 1 ? 0xEDB88320 ^ c >>> 1 : c >>> 1; } table[n] = c; } return table; }; // Create table on load. Just 255 signed longs. Not a problem. var crcTable = new Uint32Array(makeTable()); var crc32 = function crc32(crc, buf, len, pos) { var t = crcTable; var end = pos + len; crc ^= -1; for (var i = pos; i < end; i++) { crc = crc >>> 8 ^ t[(crc ^ buf[i]) & 0xFF]; } return crc ^ -1; // >>> 0; }; var crc32_1 = crc32; // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ var inffast = function inflate_fast(strm, start) { var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ var state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24 /*here.bits*/ ; hold >>>= op; bits -= op; op = here >>> 16 & 0xff /*here.op*/ ; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff /*here.val*/ ; } else if (op & 16) { /* length base */ len = here & 0xffff /*here.val*/ ; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & (1 << op) - 1; hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24 /*here.bits*/ ; hold >>>= op; bits -= op; op = here >>> 16 & 0xff /*here.op*/ ; if (op & 16) { /* distance base */ dist = here & 0xffff /*here.val*/ ; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & (1 << op) - 1; //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff) + ( /*here.val*/ hold & (1 << op) - 1)]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff) + ( /*here.val*/ hold & (1 << op) - 1)]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = _in < last ? 5 + (last - _in) : 5 - (_in - last); strm.avail_out = _out < end ? 257 + (end - _out) : 257 - (_out - end); state.hold = hold; state.bits = bits; return; }; // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = new Uint16Array([ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0]); var lext = new Uint8Array([ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78]); var dbase = new Uint16Array([ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0]); var dext = new Uint8Array([ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64]); var inflate_table = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // let shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = 1 << 24 | 64 << 16 | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = 1 << 24 | 64 << 16 | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { return 1; } /* process all codes and make table entries */ for (;;) { /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << len - drop; fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = here_bits << 24 | here_op << 16 | here_val | 0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << len - 1; while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if (type === LENS && used > ENOUGH_LENS || type === DISTS && used > ENOUGH_DISTS) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = root << 24 | curr << 16 | next - table_index | 0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = len - drop << 24 | 64 << 16 | 0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; var inftrees = inflate_table; // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var constants = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var CODES$1 = 0; var LENS$1 = 1; var DISTS$1 = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_FINISH = constants.Z_FINISH, Z_BLOCK = constants.Z_BLOCK, Z_TREES = constants.Z_TREES, Z_OK = constants.Z_OK, Z_STREAM_END = constants.Z_STREAM_END, Z_NEED_DICT = constants.Z_NEED_DICT, Z_STREAM_ERROR = constants.Z_STREAM_ERROR, Z_DATA_ERROR = constants.Z_DATA_ERROR, Z_MEM_ERROR = constants.Z_MEM_ERROR, Z_BUF_ERROR = constants.Z_BUF_ERROR, Z_DEFLATED = constants.Z_DEFLATED; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD$1 = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS$1 = 852; var ENOUGH_DISTS$1 = 592; //const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; var zswap32 = function zswap32(q) { return (q >>> 24 & 0xff) + (q >>> 8 & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24); }; function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new Uint16Array(320); /* temporary storage for code lengths */ this.work = new Uint16Array(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new Int32Array(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } var inflateResetKeep = function inflateResetKeep(strm) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } var state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null /*Z_NULL*/ ; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS$1); state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS$1); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; }; var inflateReset = function inflateReset(strm) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } var state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); }; var inflateReset2 = function inflateReset2(strm, windowBits) { var wrap; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } var state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); }; var inflateInit2 = function inflateInit2(strm, windowBits) { if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ var state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null /*Z_NULL*/ ; var ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null /*Z_NULL*/ ; } return ret; }; var inflateInit = function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); }; /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate var fixedtables = function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { lenfix = new Int32Array(512); distfix = new Int32Array(32); /* literal/length table */ var sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inftrees(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inftrees(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; }; /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ var updatewindow = function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new Uint8Array(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { state.window.set(src.subarray(end - state.wsize, end), 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); state.window.set(src.subarray(end - copy, end), 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; }; var inflate = function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //let last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary variable for NEED_BITS var order = /* permutation of code lengths */ new Uint8Array([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); if (!strm || !strm.state || !strm.output || !strm.input && strm.avail_in !== 0) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.wrap & 2 && hold === 0x8b1f) { /* gzip header */ state.check = 0 /*crc32(0L, Z_NULL, 0)*/ ; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = hold >>> 8 & 0xff; state.check = crc32_1(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff) << /*BITS(8)*/ 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD$1; break; } if ((hold & 0x0f) !== /*BITS(4)*/ Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD$1; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f) + /*BITS(4)*/ 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD$1; break; } // !!! pako patch. Force use `options.windowBits` if passed. // Required to always use max window size by default. state.dmax = 1 << state.wbits; //state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ; state.mode = hold & 0x200 ? DICTID : TYPE$1; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD$1; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD$1; break; } if (state.head) { state.head.text = hold >> 8 & 1; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = hold >>> 8 & 0xff; state.check = crc32_1(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = hold >>> 8 & 0xff; hbuf[2] = hold >>> 16 & 0xff; hbuf[3] = hold >>> 24 & 0xff; state.check = crc32_1(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = hold & 0xff; state.head.os = hold >> 8; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = hold >>> 8 & 0xff; state.check = crc32_1(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = hold >>> 8 & 0xff; state.check = crc32_1(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null /*Z_NULL*/ ; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more convenient processing later state.head.extra = new Uint8Array(state.head.extra_len); } state.head.extra.set(input.subarray(next, // extra field is limited to 65536 bytes // - no need for additional size check next + copy), /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32_1(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && state.length < 65536 /*state.head.name_max*/ ) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32_1(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && state.length < 65536 /*state.head.comm_max*/ ) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32_1(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD$1; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = state.flags >> 9 & 1; state.head.done = true; } strm.adler = state.check = 0; state.mode = TYPE$1; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = zswap32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ; state.mode = TYPE$1; /* falls through */ case TYPE$1: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = hold & 0x01 /*BITS(1)*/ ; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch (hold & 0x03) { /*BITS(2)*/ case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD$1; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== (hold >>> 16 ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD$1; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- output.set(input.subarray(next, next + copy), put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE$1; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f) + /*BITS(5)*/ 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f) + /*BITS(5)*/ 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f) + /*BITS(4)*/ 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD$1; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = hold & 0x07; //BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = { bits: state.lenbits }; ret = inftrees(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD$1; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & (1 << state.lenbits) - 1]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = here >>> 16 & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD$1; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03); //BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07); //BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f); //BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD$1; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD$1) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD$1; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = { bits: state.lenbits }; ret = inftrees(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD$1; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = { bits: state.distbits }; ret = inftrees(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD$1; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inffast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE$1) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & (1 << state.lenbits) - 1]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = here >>> 16 & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> /*BITS(last.bits + last.op)*/ last_bits)]; here_bits = here >>> 24; here_op = here >>> 16 & 0xff; here_val = here & 0xffff; if (last_bits + here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE$1; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD$1; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & (1 << state.extra) - 1 /*BITS(state.extra)*/ ; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & (1 << state.distbits) - 1]; /*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = here >>> 16 & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & (1 << last_bits + last_op) - 1) >> /*BITS(last.bits + last.op)*/ last_bits)]; here_bits = here >>> 24; here_op = here >>> 16 & 0xff; here_val = here & 0xffff; if (last_bits + here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD$1; break; } state.offset = here_val; state.extra = here_op & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & (1 << state.extra) - 1 /*BITS(state.extra)*/ ; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD$1; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD$1; break; } // (!) This block is disabled in zlib defaults, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' instead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out); } _out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too if ((state.flags ? hold : zswap32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD$1; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD$1; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD$1: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || _out !== strm.avail_out && state.mode < BAD$1 && (state.mode < CHECK || flush !== Z_FINISH)) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE$1 ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if ((_in === 0 && _out === 0 || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; }; var inflateEnd = function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/ ) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; }; var inflateGetHeader = function inflateGetHeader(strm, head) { /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } var state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; }; var inflateSetDictionary = function inflateSetDictionary(strm, dictionary) { var dictLength = dictionary.length; var state; var dictid; var ret; /* check state */ if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */ ) { return Z_STREAM_ERROR; } state = strm.state; if (state.wrap !== 0 && state.mode !== DICT) { return Z_STREAM_ERROR; } /* check for correct dictionary identifier */ if (state.mode === DICT) { dictid = 1; /* adler32(0, null, 0)*/ /* dictid = adler32(dictid, dictionary, dictLength); */ dictid = adler32_1(dictid, dictionary, dictLength, 0); if (dictid !== state.check) { return Z_DATA_ERROR; } } /* copy dictionary to window using updatewindow(), which will amend the existing dictionary if appropriate */ ret = updatewindow(strm, dictionary, dictLength, dictLength); if (ret) { state.mode = MEM; return Z_MEM_ERROR; } state.havedict = 1; // Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; }; var inflateReset_1 = inflateReset; var inflateReset2_1 = inflateReset2; var inflateResetKeep_1 = inflateResetKeep; var inflateInit_1 = inflateInit; var inflateInit2_1 = inflateInit2; var inflate_2 = inflate; var inflateEnd_1 = inflateEnd; var inflateGetHeader_1 = inflateGetHeader; var inflateSetDictionary_1 = inflateSetDictionary; var inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ var inflate_1 = { inflateReset: inflateReset_1, inflateReset2: inflateReset2_1, inflateResetKeep: inflateResetKeep_1, inflateInit: inflateInit_1, inflateInit2: inflateInit2_1, inflate: inflate_2, inflateEnd: inflateEnd_1, inflateGetHeader: inflateGetHeader_1, inflateSetDictionary: inflateSetDictionary_1, inflateInfo: inflateInfo }; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var _has = function _has(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }; var assign = function assign(obj /*from1, from2, from3, ...*/ ) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (_typeof(source) !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (_has(source, p)) { obj[p] = source[p]; } } } return obj; }; // Join array of chunks to single array. var flattenChunks = function flattenChunks(chunks) { // calculate data length var len = 0; for (var i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length; } // join chunks var result = new Uint8Array(len); for (var _i = 0, pos = 0, _l = chunks.length; _i < _l; _i++) { var chunk = chunks[_i]; result.set(chunk, pos); pos += chunk.length; } return result; }; var common = { assign: assign, flattenChunks: flattenChunks }; // String encode/decode helpers // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safari // var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new Uint8Array(256); for (var q = 0; q < 256; q++) { _utf8len[q] = q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1; } _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start // convert string to array (typed, when possible) var string2buf = function string2buf(str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new Uint8Array(buf_len); // convert for (i = 0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && m_pos + 1 < str_len) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + (c - 0xd800 << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | c >>> 6; buf[i++] = 0x80 | c & 0x3f; } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | c >>> 12; buf[i++] = 0x80 | c >>> 6 & 0x3f; buf[i++] = 0x80 | c & 0x3f; } else { /* four bytes */ buf[i++] = 0xf0 | c >>> 18; buf[i++] = 0x80 | c >>> 12 & 0x3f; buf[i++] = 0x80 | c >>> 6 & 0x3f; buf[i++] = 0x80 | c & 0x3f; } } return buf; }; // Helper var buf2binstring = function buf2binstring(buf, len) { // On Chrome, the arguments in a function call that are allowed is `65534`. // If the length of the buffer is smaller than that, we can use this optimization, // otherwise we will take a slower path. if (len < 65534) { if (buf.subarray && STR_APPLY_UIA_OK) { return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len)); } } var result = ''; for (var i = 0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; }; // convert array to string var buf2string = function buf2string(buf, max) { var i, out; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len * 2); for (out = 0, i = 0; i < len;) { var c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } var c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = c << 6 | buf[i++] & 0x3f; c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | c >> 10 & 0x3ff; utf16buf[out++] = 0xdc00 | c & 0x3ff; } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); var utf8border = function utf8border(buf, max) { max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found var pos = max - 1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means buffer is too small, // return max too. if (pos === 0) { return max; } return pos + _utf8len[buf[pos]] > max ? pos : max; }; var strings = { string2buf: string2buf, buf2string: buf2string, utf8border: utf8border }; // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. var messages = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ 1: 'stream end', /* Z_STREAM_END 1 */ 0: '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = '' /*Z_NULL*/ ; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2 /*Z_UNKNOWN*/ ; /* adler32 value of the uncompressed data */ this.adler = 0; } var zstream = ZStream; // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } var gzheader = GZheader; var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = constants.Z_NO_FLUSH, Z_FINISH$1 = constants.Z_FINISH, Z_OK$1 = constants.Z_OK, Z_STREAM_END$1 = constants.Z_STREAM_END, Z_NEED_DICT$1 = constants.Z_NEED_DICT, Z_STREAM_ERROR$1 = constants.Z_STREAM_ERROR, Z_DATA_ERROR$1 = constants.Z_DATA_ERROR, Z_MEM_ERROR$1 = constants.Z_MEM_ERROR; /* ===========================================================================*/ /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overridden. **/ /** * Inflate.result -> Uint8Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * - `dictionary` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * const pako = require('pako') * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9]) * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * const inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ function Inflate(options) { this.options = common.assign({ chunkSize: 1024 * 64, windowBits: 15, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if (opt.windowBits > 15 && opt.windowBits < 48) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = inflate_1.inflateInit2(this.strm, opt.windowBits); if (status !== Z_OK$1) { throw new Error(messages[status]); } this.header = new gzheader(); inflate_1.inflateGetHeader(this.strm, this.header); // Setup dictionary if (opt.dictionary) { // Convert data if needed if (typeof opt.dictionary === 'string') { opt.dictionary = strings.string2buf(opt.dictionary); } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { opt.dictionary = new Uint8Array(opt.dictionary); } if (opt.raw) { //In raw mode we need to set the dictionary early status = inflate_1.inflateSetDictionary(this.strm, opt.dictionary); if (status !== Z_OK$1) { throw new Error(messages[status]); } } } } /** * Inflate#push(data[, flush_mode]) -> Boolean * - data (Uint8Array|ArrayBuffer): input data * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH, * `true` means Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. If end of stream detected, * [[Inflate#onEnd]] will be called. * * `flush_mode` is not needed for normal operation, because end of stream * detected automatically. You may try to use it for advanced things, but * this functionality was not tested. * * On fail call [[Inflate#onEnd]] with error code and return false. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function (data, flush_mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var dictionary = this.options.dictionary; var status, _flush_mode, last_avail_out; if (this.ended) return false; if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;else _flush_mode = flush_mode === true ? Z_FINISH$1 : Z_NO_FLUSH; // Convert data if needed if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; for (;;) { if (strm.avail_out === 0) { strm.output = new Uint8Array(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = inflate_1.inflate(strm, _flush_mode); if (status === Z_NEED_DICT$1 && dictionary) { status = inflate_1.inflateSetDictionary(strm, dictionary); if (status === Z_OK$1) { status = inflate_1.inflate(strm, _flush_mode); } else if (status === Z_DATA_ERROR$1) { // Replace code with more verbose status = Z_NEED_DICT$1; } } // Skip snyc markers if more data follows and not raw mode while (strm.avail_in > 0 && status === Z_STREAM_END$1 && strm.state.wrap > 0 && data[strm.next_in] !== 0) { inflate_1.inflateReset(strm); status = inflate_1.inflate(strm, _flush_mode); } switch (status) { case Z_STREAM_ERROR$1: case Z_DATA_ERROR$1: case Z_NEED_DICT$1: case Z_MEM_ERROR$1: this.onEnd(status); this.ended = true; return false; } // Remember real `avail_out` value, because we may patch out buffer content // to align utf8 strings boundaries. last_avail_out = strm.avail_out; if (strm.next_out) { if (strm.avail_out === 0 || status === Z_STREAM_END$1) { if (this.options.to === 'string') { var next_out_utf8 = strings.utf8border(strm.output, strm.next_out); var tail = strm.next_out - next_out_utf8; var utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail & realign counters strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0); this.onData(utf8str); } else { this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out)); } } } // Must repeat iteration if out buffer is full if (status === Z_OK$1 && last_avail_out === 0) continue; // Finalize if end of stream reached. if (status === Z_STREAM_END$1) { status = inflate_1.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return true; } if (strm.avail_in === 0) break; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|String): output data. When string output requested, * each chunk will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH). By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function (status) { // On success - join if (status === Z_OK$1) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = common.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|String * - data (Uint8Array): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * const pako = require('pako'); * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9])); * let output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate$1(input, options) { var inflator = new Inflate(options); inflator.push(input); // That will never happens, if you don't cheat with options :) if (inflator.err) throw inflator.msg || messages[inflator.err]; return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|String * - data (Uint8Array): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate$1(input, options); } /** * ungzip(data[, options]) -> Uint8Array|String * - data (Uint8Array): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ var inflate_1$1 = { Inflate: Inflate, inflate: inflate$1, inflateRaw: inflateRaw, ungzip: inflate$1, constants: constants }; return inflate_1$1; })));
/** * Tom Select v1.4.1 * Licensed under the Apache License, Version 2.0 (the "License"); */ import TomSelect from '../../tom-select.js'; /** * Plugin: "restore_on_backspace" (Tom Select) * Copyright (c) contributors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. * */ TomSelect.define('restore_on_backspace', function (options) { var self = this; options.text = options.text || function (option) { return option[self.settings.labelField]; }; self.on('item_remove', function (value) { if (self.control_input.value.trim() === '') { var option = self.options[value]; if (option) { self.setTextboxValue(options.text.call(self, option)); } } }); }); //# sourceMappingURL=plugin.js.map
import{g as n}from"./p-e0b6c512.js";let e;const r=()=>{if("undefined"==typeof window)return new Map;if(!e){const n=window;n.Ionicons=n.Ionicons||{},e=n.Ionicons.map=n.Ionicons.map||new Map}return e},t=n=>{const e=r();Object.keys(n).forEach((r=>e.set(r,n[r])))},i=n=>{let e=u(n.src);if(e)return e;if(e=o(n.name,n.icon,n.mode,n.ios,n.md),e)return s(e);if(n.icon){if(e=u(n.icon),e)return e;if(e=u(n.icon[n.mode]),e)return e}return null},s=e=>r().get(e)||n(`svg/${e}.svg`),o=(n,e,r,t,i)=>(r="ios"===(r&&a(r))?"ios":"md",t&&"ios"===r?n=a(t):i&&"md"===r?n=a(i):(n||!e||f(e)||(n=e),l(n)&&(n=a(n))),l(n)&&""!==n.trim()?""!==n.replace(/[a-z]|-|\d/gi,"")?null:n:null),u=n=>l(n)&&(n=n.trim(),f(n))?n:null,f=n=>n.length>0&&/(\/|\.)/.test(n),l=n=>"string"==typeof n,a=n=>n.toLowerCase();export{t as a,o as b,i as g,l as i}
var test = require('tape'); var JWT = require('jsonwebtoken'); var secret = 'NeverShareYourSecret'; var server = require('./custom_parameters_server.js'); var cookie_options = '; Max-Age=31536000;'; //' Expires=Mon, 18 Jul 2016 05:29:45 GMT; Secure; HttpOnly'; // Those tests are the same as cookie-test and url-token-test but with custom parameters in cookie or URL test("Attempt to access restricted content using inVALID Cookie Token - custom parameters", function(t) { var token = JWT.sign({ id: 123, "name": "Charlie" }, 'badsecret'); var options = { method: "POST", url: "/privado", headers: { cookie: "customCookieKey=" + token } }; console.log(options); server.inject(options, function(response) { t.equal(response.statusCode, 401, "Invalid token should error!"); t.end(); }); }); test("Attempt to access restricted content with VALID Token but malformed Cookie - custom parameters", function(t) { var token = JWT.sign({ id: 123, "name": "Charlie" }, secret); var options = { method: "POST", url: "/privado", headers: { cookie: token } }; // server.inject lets us simulate an http request server.inject(options, function(response) { t.equal(response.statusCode, 400, "Valid Token but inVALID COOKIE should fial!"); t.end(); }); }); test("Access restricted content with VALID Token Cookie - custom parameters", function(t) { var token = JWT.sign({ id: 123, "name": "Charlie" }, secret); var options = { method: "POST", url: "/privado", headers: { cookie: "customCookieKey=" + token } }; // server.inject lets us simulate an http request server.inject(options, function(response) { t.equal(response.statusCode, 200, "VALID COOKIE Token should succeed!"); t.end(); }); }); test("Access restricted content with VALID Token Cookie (With Options!) - custom parameters", function(t) { var token = JWT.sign({ id: 123, "name": "Charlie" }, secret); var options = { method: "POST", url: "/privado", headers: { cookie: "customCookieKey=" + token + cookie_options } }; // console.log(' - - - - - - - - - - - - - - - OPTIONS:') // console.log(options); // server.inject lets us simulate an http request server.inject(options, function(response) { // console.log(' - - - - - - - - - - - - - - - response:') // console.log(response); t.equal(response.statusCode, 200, "VALID COOKIE Token (With Options!) should succeed!"); t.end(); }); }); /** Regressions Tests for https://github.com/dwyl/hapi-auth-jwt2/issues/65 **/ // supply valid Token Auth Header but invalid Cookie // should succeed because Auth Header is first test("Authorization Header should take precedence over any cookie - custom parameters", function(t) { var token = JWT.sign({ id: 123, "name": "Charlie" }, secret); var options = { method: "POST", url: "/privado", headers: { authorization: "MyAuthScheme " + token, cookie: "customCookieKey=malformed.token" + cookie_options } }; server.inject(options, function(response) { // console.log(' - - - - - - - - - - - - - - - response:') // console.log(response); t.equal(response.statusCode, 200, "Ignores cookie when Auth Header is set"); t.end(); }); }); // valid google analytics cookie but invalid auth header token // see: https://github.com/dwyl/hapi-auth-jwt2/issues/65#issuecomment-124791842 test("Valid Google Analytics cookie should be ignored - custom parameters", function(t) { var GA = "gwcm=%7B%22expires%22%3Anull%2C%22clabel%22%3A%22SbNVCILRtFcQwcrE6gM%22%2C%22backoff%22%3A1437241242%7D; _ga=GA1.2.1363734468.1432273334"; var token = JWT.sign({ id: 123, "name": "Charlie" }, secret); var options = { method: "POST", url: "/privado", headers: { authorization: "MyAuthScheme " + token, cookie: GA } }; server.inject(options, function(response) { t.equal(response.statusCode, 200, "Ignores Google Analytics Cookie"); t.end(); }); }); test("Valid Google Analytics cookie should be ignored (BAD Header Token) - custom parameters", function(t) { var GA = "gwcm=%7B%22expires%22%3Anull%2C%22clabel%22%3A%22SbNVCILRtFcQwcrE6gM%22%2C%22backoff%22%3A1437241242%7D; _ga=GA1.2.1363734468.1432273334"; var token = JWT.sign({ id: 123, "name": "Charlie" }, 'invalid'); var options = { method: "POST", url: "/privado", headers: { authorization: "MyAuthScheme " + token, cookie: GA } }; server.inject(options, function(response) { t.equal(response.statusCode, 401, "Ignores GA but Invalid Auth Header still rejected"); t.end(); }); }); // Supply a VALID Token in Cookie A-N-D valid GA in Cookie!! test("Valid Google Analytics cookie should be ignored (BAD Header Token) - custom parameters", function(t) { var GA = "gwcm=%7B%22expires%22%3Anull%2C%22clabel%22%3A%22SbNVCILRtFcQwcrE6gM%22%2C%22backoff%22%3A1437241242%7D; _ga=GA1.2.1363734468.1432273334"; var token = JWT.sign({ id: 123, "name": "Charlie" }, secret); var options = { method: "POST", url: "/privado", headers: { cookie: "customCookieKey=" + token + '; ' + GA } }; server.inject(options, function(response) { t.equal(response.statusCode, 200, "Valid Cookie Token Succeeds (Ignores GA)"); t.end(); }); }); test("Attempt to access restricted content (with an INVALID URL Token) - custom parameters", function(t) { var token = "?customUrlKey=my.invalid.token"; var options = { method: "POST", url: "/privado" + token }; // server.inject lets us simulate an http request server.inject(options, function(response) { t.equal(response.statusCode, 401, "INVALID Token should fail"); t.end(); }); }); test("Try using an incorrect secret to sign the JWT - custom parameters", function(t) { // use the token as the 'authorization' header in requests var token = JWT.sign({ id: 123, "name": "Charlie" }, 'incorrectSecret'); token = "?customUrlKey=" + token; // console.log(" - - - - - - token - - - - -") // console.log(token); var options = { method: "POST", url: "/privado" + token }; // server.inject lets us simulate an http request server.inject(options, function(response) { t.equal(response.statusCode, 401, "URL Token signed with incorrect key fails"); t.end(); }); }); test("URL Token is well formed but is allowed=false so should be denied - custom parameters", function(t) { // use the token as the 'authorization' header in requests // var token = jwt.sign({ "id": 1 ,"name":"Old Greg" }, 'incorrectSecret'); var token = JWT.sign({ id: 321, "name": "Old Gregg" }, secret); token = "?customUrlKey=" + token; var options = { method: "POST", url: "/privado" + token }; // server.inject lets us simulate an http request server.inject(options, function(response) { t.equal(response.statusCode, 401, "User is Denied"); t.end(); }); }); test("Access restricted content (with VALID Token) - custom parameters", function(t) { // use the token as the 'authorization' header in requests var token = JWT.sign({ id: 123, "name": "Charlie" }, secret); token = "?customUrlKey=" + token; var options = { method: "POST", url: "/privado" + token }; // server.inject lets us simulate an http request server.inject(options, function(response) { t.equal(response.statusCode, 200, "VALID Token should succeed!"); t.end(); }); }); test("Attempt to access restricted content using inVALID header tokenType - custom parameters", function(t) { var token = JWT.sign({ id: 123, "name": "Charlie" }, 'badsecret'); var options = { method: "POST", url: "/privado", headers: { Authorization: "InvalidAuthScheme " + token } }; server.inject(options, function(response) { t.equal(response.statusCode, 401, "Invalid token should error!"); t.end(); }); }); test("Access restricted content (with VALID Token and header tokenType) - custom parameters", function(t) { var token = JWT.sign({ id: 123, "name": "Charlie" }, secret); var options = { method: "POST", url: "/privado", headers: { Authorization: "MyAuthScheme " + token } }; server.inject(options, function(response) { t.equal(response.statusCode, 200, "VALID Token should succeed!"); t.end(); }); });