code
stringlengths
2
1.05M
/** * Module dependencies. */ var express = require('express'), http = require('http'), path = require('path'), mongoose = require('mongoose'), config = require('./config'), routes = require('./routes/routes'); // connect to local mongodb database mongoose.connect('mongodb://' + config.MONGODB_IP + ':' + config.MONGODB_PORT + '/' + config.MONGODB_DATABASE_NAME, function(err) { if (!err) { //console.log('【日志】连接到数据库:' + config.MONGODB_DATABASE_NAME); } else { throw err; } }); //attach lister to connected event mongoose.connection.once('connected', function() { console.log('【日志】连接到数据库:' + config.MONGODB_DATABASE_NAME); }); var app = express(); // 修改文件后缀 app.engine('.html', require('ejs').__express); app.set('view engine', 'html'); // 所有环境 app.set('port', process.env.PORT || config.WEB_SERVER_PORT); app.set('views', path.join(__dirname, 'views')); app.use(express.favicon(__dirname + '/public/icon/favicon.ico')); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('your secret here')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // 只用于开发环境 if ('development' == app.get('env')) { app.use(express.errorHandler()); } // 只用于生产环境 if ('production' == app.get('env')) { } http.createServer(app).listen(app.get('port'), function() { console.log('【日志】Express server listening on port' + app.get('port')); }); // 路由 routes(app);
export default { env: 'dev' };
var xyz = require('xyz-utils') var tmp = [0, 0, 0] var tmp1 = [0, 0, 0] var tmpRGBM = [0, 0, 0, 0] const clamp = require('clamp') module.exports = xyzToRGBM function xyzToRGBM (xyzArray) { var pixelCount = xyzArray.length / 3 var ret = new Uint8Array(pixelCount * 4) for (var i = 0; i < pixelCount; i++) { tmp[0] = xyzArray[i * 3] tmp[1] = xyzArray[i * 3 + 1] tmp[2] = xyzArray[i * 3 + 2] xyz.toRGB(tmp, tmp1) // xyz to rgb encode(tmp1, tmpRGBM) // rgb to rgbm ret[i * 4] = tmpRGBM[0] ret[i * 4 + 1] = tmpRGBM[1] ret[i * 4 + 2] = tmpRGBM[2] ret[i * 4 + 3] = tmpRGBM[3] } return ret } function encode (color, out) { if (!out) out = [ 0, 0, 0, 0 ] var minB = 0.000001 var coeff = 1 / 6 var r = color[0] * coeff var g = color[1] * coeff var b = color[2] * coeff var a = clamp(Math.max(Math.max(r, g), Math.max(b, minB)), 0.0, 1.0) a = Math.ceil(a * 255.0) / 255.0 out[0] = clamp(Math.ceil(r / a * 255), 0, 255) out[1] = clamp(Math.ceil(g / a * 255), 0, 255) out[2] = clamp(Math.ceil(b / a * 255), 0, 255) out[3] = clamp(Math.ceil(a * 255), 0, 255) return out }
exports.strength = { "1": "cjersov3s14fu01832cku6ivc", "2": "cjertinv814oj0183jx107b9u", "3": "cjertith714om0183tr2huxiw", "4": "cjertj05014or0183we74xnsb", "5": "cjertj34914ov0183sl7kmqm1", "6": "cjertj5ol14p10183cmzat5y9", "7": "cjertj8a814p60183av1hlcty", "8": "cjertjbqr14pc0183uo7656p7", "9": "cjertjebc14ph0183025ls377" }; exports.intelligence = { "1": "cjertjj9i14pm01835g18maaz", "2": "cjertjmjt14pq01838b9o4h92", "3": "cjertjpvq14px0183ff0j6i8o", "4": "cjertjspz14q00183gypv8iaa", "5": "cjertjy5i14q70183vq4en94t", "6": "cjertk2k914qa0183zxqjv2q3", "7": "cjertk64814qe0183s8gtzive", "8": "cjertkf4i14qj0183iafpggqn", "9": "cjertkih114qm01833ztywguw" }; exports.special = { "1": "cjertkmfs14qr0183zvz5p90r", "2": "cjertkqcd14qv01833umx8bs6", "3": "cjertkthm14r10183p8ymqv7a", "4": "cjertkxl714r401837ddh78bw", "5": "cjertl0i914r80183y161rfvw", "6": "cjertl3mj14rc018322rxbnb3", "7": "cjertl7pv14rg01835d77dxcm", "8": "cjertlb0h14rj0183wfrkgp4x", "9": "cjertleik14rm01837rde1qzn" }; exports.trait = { "Hero": "cjes4rlte16z90183tpe0zwp8", "Villain": "cjes4ro4e16zc0183wukhv8yy", "Blue Lantern": "cjes4rtu116zg0183b2u6zvqh", "Green Lantern": "cjes4s2gj16zk0183uon6d2qy", "Indigo Tribe": "cjes4s9rt16zo0183dblaykto", "Orange Lantern": "cjes4sgpd16zs0183ri5sae4f", "Red Lantern": "cjes4smq216zw01834711alj5", "Sinestro Corps": "cjes4ssvn17000183imycm8h7", "Star Sapphire": "cjes4sz0t17030183x780qp5t", "White Lantern": "cjes4t5r617070183n5f60a53", "Black Lantern": "cjes4tna6170b0183yxydoxc8", "Scout Regiment": "cjes4ufa5170g0183ne60w0n5", "Garrison Regiment": "cjes4ulp5170k0183wz5ewix6", "Military Police Regiment": "cjes4ushb170o0183gqvjd1pr", "Titan": "cjes4v11x170t0183yn2ripoe", "Cadet Corps": "cjes4vgkg170x0183kj04xyew", "Human": "cjf8iuklm49ie0183uw7s0iq4" };
exports.addDays = function(date, days) { var newDate = new Date(date); newDate.setDate(newDate.getDate() + days); return newDate; }
import '../styles.css';
'use strict'; // resolved via hbsfy transform module.exports = require('./svg.hbs');
// TYPE <groups/info> TEST("The groups's identifier is returned.", function(Query) { var example = {}; var db = Query.mkdb(); var auth = Query.auth(db); var id = Query.post(["db/",db,"/groups"],example,auth).id(); var id2 = Query.get(["db/",db,"/groups/",id,"/info"],auth).id(); return Assert.areEqual(id,id2); }); TEST("The group's label is returned if available.", function(Query) { var example = { "label" : "Associates" }; var db = Query.mkdb(); var auth = Query.auth(db); var id = Query.post(["db/",db,"/groups"],example,auth).id(); var label = Query.get(["db/",db,"/groups/",id,"/info"],auth).then(function(d) { return d.label; }); return Assert.areEqual(example.label,label); }); TEST("The group's access levels are returned.", function(Query) { var example = { "audience" : { "moderate" : "anyone" } }; var db = Query.mkdb(); var auth = Query.auth(db); var id = Query.post(["db/",db,"/groups"],example,auth).id(); var access = Query.get(["db/",db,"/groups/",id,"/info"]).then(function(d) { return d.access; }); return Assert.areEqual([ "view", "list", "moderate" ], access); }); TEST("The group's member count is returned.", function(Query) { var example = { "label" : "Associates" }; var db = Query.mkdb(); var auth = Query.auth(db); var id = Query.post(["db/",db,"/groups"],example,auth).id(); return Query.post(["db/",db,"/groups/",id,"/add"],[auth.id],auth).then(function(){ return Query.get(["db/",db,"/groups/",id,"/info"],auth).then(function(d,s,r) { return Assert.areEqual(1, d.count); }); }); }); TEST("The group's member count requires 'list' access.", function(Query) { var example = { "label" : "Associates", "audience" : { "view" : "anyone" } }; var db = Query.mkdb(); var auth = Query.auth(db); var id = Query.post(["db/",db,"/groups"],example,auth).id(); return Query.post(["db/",db,"/groups/",id,"/add"],[auth.id],auth).then(function(){ return Query.get(["db/",db,"/groups/",id,"/info"]).then(function(d,s,r) { return Assert.areEqual(null, d.count); }); }); });
/** * Copyright 2013-2014 Academe Computing Ltd * Released under the MIT license * Author: Jason Judge <jason@academe.co.uk> * Version: 1.2.1 */ /** * jquery.maxsubmit.js * * Checks how many parameters a form is going to submit, and * gives the user a chance to cancel if it exceeds a set number. * PHP5.3+ has limits set by default on the number of POST parameters * that will be accepted. Parameters beyond that number, usually 1000, * will be silently discarded. This can have nasty side-effects in some * applications, such as editiong shop products with many variations * against a product, which can result in well over 1000 submitted * parameters (looking at you WooCommerce). This aims to provide some * level of protection. * */ (function($) { /** * Set a trigger on a form to pop up a warning if the fields to be submitted * exceed a specified maximum. * Usage: $('form#selector').maxSubmit({options}); */ $.fn.maxSubmit = function(options) { // this.each() is the wrapper for each form. return this.each(function() { var settings = $.extend({ // The maximum number of parameters the form will be allowed to submit // before the user is issued a confirm (OK/Cancel) dialogue. max_count: 1000, // The message given to the user to confirm they want to submit anyway. // Can use {max_count} as a placeholder for the permitted maximum // and {form_count} for the counted form items. max_exceeded_message: 'This form has too many fields for the server to accept.\n' + ' Data may be lost if you submit. Are you sure you want to go ahead?', // The function that will display the confirm message. // Replace this with something fancy such as jquery.ui if you wish. confirm_display: function(form_count) { if (typeof(form_count) === 'undefined') form_count = ''; return confirm( settings .max_exceeded_message .replace("{max_count}", settings.max_count) .replace("{form_count}", form_count) ); } }, options); // Form elements will be passed in, so we need to trigger on // an attempt to submit that form. // First check we do have a form. if ($(this).is("form")) { $(this).on('submit', function(e) { // We have a form, so count up the form items that will be // submitted to the server. // For now, add one for the submit button. var form_count = $(this).maxSubmitCount() + 1; if (form_count > settings.max_count) { // If the user cancels, then abort the form submit. if (!settings.confirm_display(form_count)) return false; } // Allow the submit to go ahead. return true; }); } // Support chaining. return this; }); }; /** * Count the number of fields that will be posted in a form. * If return_elements is true, then an array of elements will be returned * instead of the count. This is handy for testing. * TODO: elements without names will not be submitted. * Another approach may be to get all input fields at once using $("form :input") * then knock out the ones that we don't want. That would keep the same order as the * items would be submitted. */ $.fn.maxSubmitCount = function(return_elements) { // Text fields and submit buttons will all post one parameter. // Find the textareas. // These will count as one post parameter each. var fields = $('textarea:enabled[name]', this).toArray(); // Find the basic textual input fields (text, email, number, date and similar). // These will count as one post parameter each. // We deal with checkboxes, radio buttons sparately. // Checkboxes will post only if checked, so exclude any that are not checked. // There may be multiple form submit buttons, but only one will be posted with the // form, assuming the form has been submitted by the user with a button. // An image submit will post two fields - an x and y coordinate. fields = fields.concat( $('input:enabled[name]', this) // Data items that are handled later. .not("[type='checkbox']:not(:checked)") .not("[type='radio']") .not("[type='file']") .not("[type='reset']") // Submit form items. .not("[type='submit']") .not("[type='button']") .not("[type='image']") .toArray() ); // Single-select lists will always post one value. fields = fields.concat( $('select:enabled[name]', this) .not('[multiple]') .toArray() ); // Multi-select lists will post one parameter for each selected option. // The parent select is $(this).parent() with its name being $(this).parent().attr('name') $('select[multiple]:enabled[name] option:selected', this).each(function() { // We collect all the options that have been selected. fields = fields.concat(this); }); // Each radio button group will post one parameter. // We assume all checked radio buttons will be posted. fields = fields.concat( $('input:enabled:radio:checked', this) .toArray() ); // TODO: provide an option to return an array of objects containing the form field names, // types and values, in a form that can be compared to what is actually posted. if (typeof(return_elements) === 'undefined') return_elements = false; if (return_elements === true) { // Return the full list of elements for analysis. return fields; } else { // Just return the number of elements matched. return fields.length; } }; }(jQuery));
define(['src/components/cpu', 'src/components/memory'], function(CPU, Memory) { var Atari; Atari = { CPU: CPU, Memory: Memory, init: function init() { this.attachMemory(); }, attachMemory: function attachMemory() { CPU.memory = Memory; } }; Atari.init(); // 38 F8 78 A2 01 A0 02 A9 69 AD 00 00 AD 01 00 BD 01 00 B9 02 00 A1 09 B1 0A Atari.CPU.memory.data = [ 0x38, // SEC 0xF8, // SED 0x78, // SEI 0xA2, 0x01, // LDX #$01 0xA0, 0x02, // LDY #$02 0xA9, 0x69, // LDA #$69 0xAD, 0x00, 0x00, // LDA $00 0xAD, 0x01, 0x00, // LDA $0001 0xBD, 0x01, 0x00, // LDA $01,X 0xB9, 0x02, 0x00, // LDA $02,Y 0xA1, 0x09, // LDA ($09,X) 0xB1, 0x0A // LDA ($0A),Y ]; return Atari; });
'use strict'; /* SQL Challenges framework Version: 5.0 as of SQL3 Build, check, reset */ var workspaceDirectory = '/home/codio/workspace/'; var sqlDir = workspaceDirectory + '.guides/sqltests/'; // var workspaceDirectory = '/Volumes/Seagate Backup Plus Drive/htdocs/MySQL/CodioSQL.Units/sqlx/'; // var sqlDir = workspaceDirectory + '.guides/sqltests/'; var mysql = require('mysql'), fs = require('fs'), errorLogs = require('./fw-errorLogs.js'); // Globals var tasksArr, connection, count = 0, db; // MySQL function connectTo(db) { connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'codio', database : db }); connection.connect(); } // Test environment function test(){ // console.log(count); // console.log(`Testing: ${tasksArr[count][1]}. Task: ${count+1}`); if (count < tasksArr.length) { var query = tasksArr[count][1]; return new Promise(function(resolve, reject){ connectTo(db); connection.query(query, function(err, rows, fields) { if (err) errorLogs.queryMismatch(count+1, tasksArr[count][0]); // console.log(rows); count++; test(); }); }); } else { console.log('Well done!'); process.exit(0); } } // Reset environment function reset(){ if (count < tasksArr.length) { var query = tasksArr[count][1]; return new Promise(function(resolve, reject){ connectTo(db); connection.query(query, function(err, rows, fields) { if (err) errorLogs.resetFailed(tasksArr[count][0]); // console.log(rows); count++; reset(); }); }); } else { errorLogs.reset(tasksArr[count-1][0]); } } // Init exports.init = function(tasks, dbName) { tasksArr = tasks, db = dbName; test(); } exports.reset = function(tasks, dbName) { tasksArr = tasks, db = dbName; reset(); }
module.exports = function ({ canvas, onPan, onZoom, onRotate }) { let prevX = 0 let prevY = 0 canvas.addEventListener('mousemove', ({clientX, clientY, buttons, which}) => { if ((buttons | which | 0) & 1) { onRotate( (clientX - prevX) / window.innerWidth, (prevY - clientY) / window.innerHeight) prevX = clientX prevY = clientY } }) canvas.addEventListener('mousedown', ({clientX, clientY, buttons, which}) => { if ((buttons | which | 0) & 1) { prevX = clientX prevY = clientY } }) canvas.addEventListener('wheel', (ev) => { ev.preventDefault() let s = ev.deltaY || 0 switch (ev.deltaMode) { case 1: s *= 16 break case 2: s *= window.innerHeight break } onZoom(s / window.innerHeight) }) // TODO handle touch events }
var express = require('express') var router = express.Router() var path = require('path') var debug = require('debug')('app:' + path.basename(__filename).replace('.js', '')) var request = require('request') var entu = require('./entu') // GET requests/offers listing router.get('/:type', function(req, res, next) { if(req.params.type === 'requests') { var page_id = 654 var help_group = 650 var help_type = 'request' } else if(req.params.type === 'offers') { var page_id = 655 var help_group = 651 var help_type = 'offer' } else { res.redirect('/help/requests') return } entu.get_entities(help_group, 'request', null, null, function(error, requests) { if(error) return next(error) res.render('help', { requests: requests, show_add: (req.signedCookies.auth_id && req.signedCookies.auth_token), help_type: help_type }) }) }) // Create request/offer router.post('/:type', function(req, res, next) { if(!req.signedCookies.auth_id || !req.signedCookies.auth_token) { res.status(403).send() return } if(req.params.type === 'requests') { var page_id = 654 var help_group = 650 var help_type = 'request' } else if(req.params.type === 'offers') { var page_id = 655 var help_group = 651 var help_type = 'offer' } else { res.status(403).send() return } var properties = req.body properties['person'] = req.signedCookies.auth_id entu.add(help_group, 'request', properties, req.signedCookies.auth_id, req.signedCookies.auth_token, function(error, new_id) { if(error) return next(error) entu.make_public(new_id, req.signedCookies.auth_id, req.signedCookies.auth_token, function(error, response) { if(error) return next(error) res.status(200).send(response) }) }) }) module.exports = router
(function(){ angular.module('app') .directive('newNote', function() { return { templateUrl: "new-note.html", scope: { notes: '=' }, controller: NewNoteController }; function NewNoteController($scope, NoteService) { $scope.blankNote = null; $scope.createNote = createNote; $scope.saveNote = saveNote; function createNote() { $scope.blankNote = NoteService.createBlankNote(); } function saveNote() { if ($scope.blankNote && ($scope.blankNote.title.length > 0 || $scope.blankNote.content.length > 0)) { NoteService.saveNote($scope.blankNote).then(function(savedNote) { $scope.notes.unshift(savedNote); }); } $scope.blankNote = null; } } }) ; })();
//嘉福客服模块 var jfCustomerService = { init: function (service, token) {//初始化 if (!$("#MEIQIA-PANEL-HOLDER").length > 0) { var isIosProduct = 0; //判断是不是可能出现位移的页面 function jfServiceInit(visibility) { jfServiceSwitch(visibility); if (browser.os.iOS && $('html').hasClass('ovfHiden') && $('body').hasClass('ovfHiden')) { //解决ios10的在详情页聊天移位问题。 isIosProduct = 1; $(document).scrollTop(0); } } function jfServiceSwitch(visibility) { if (visibility === 'visible') { if (isIosProduct) { //解决ios10的在详情页聊天移位问题。 $('html').removeClass('ovfHiden'); $('body').removeClass('ovfHiden') } $('#MEIQIA-PANEL-HOLDER').show().removeClass('hide').addClass('show'); setTimeout( function () { $('#MEIQIA-PANEL-HOLDER').removeClass('show'); } , 300); } else { // 你可以根据自己的需求编写相应的代码 $('#MEIQIA-PANEL-HOLDER').addClass('hide').css('left', 0).css('z-index', 600); setTimeout( function () { $('#MEIQIA-PANEL-HOLDER').hide(); } , 300); if (isIosProduct) { //解决ios10的在详情页聊天移位问题。 $('html').addClass('ovfHiden'); $('body').addClass('ovfHiden'); $(document).scrollTop(0); } } } (function (m, ei, q, i, a, j, s) { m[i] = m[i] || function () { (m[i].a = m[i].a || []).push(arguments) }; j = ei.createElement(q); s = ei.getElementsByTagName(q)[0]; j.async = true; j.charset = 'UTF-8'; j.src = '//static.meiqia.com/dist/meiqia.js'; s.parentNode.insertBefore(j, s); })(window, document, 'script', '_MEIQIA'); _MEIQIA('entId', '39750'); // 在这里开启手动模式(必须紧跟美洽的嵌入代码) _MEIQIA('manualInit'); // 你可以自己的代码中选择合适的时机来调用手动初始化 _MEIQIA('withoutBtn');//不使用插件按钮 _MEIQIA('allSet', jfServiceInit);//初始设置 _MEIQIA('getPanelVisibility', jfServiceSwitch);//改变状态后设置 _MEIQIA('init');//初始化 //指定客服 _MEIQIA('assign', { groupToken: token }); //用户信息导入 _MEIQIA('metadata', service); } }, click: function () { //导入使用 _MEIQIA('showPanel') } }; //嘉福客服模块结束
var system = require('system'); var page = require('webpage').create(); var fs = require('fs'); if (system.args.length === 3) { console.log('Usage: snap.js <some URL> <view port width> <target image name>'); phantom.exit(); } var url = system.args[1]; var image_name = system.args[3]; var view_port_width = system.args[2]; page.viewportSize = { width: view_port_width, height: 1500}; page.settings = { loadImages: true, javascriptEnabled: true }; // If you want to use additional phantomjs commands, place them here page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.17'; // You can place custom headers here, example below. // page.customHeaders = { // 'X-Candy-OVERRIDE': 'https://api.live.bbc.co.uk/' // }; // If you want to set a cookie, just add your details below in the following way. // phantom.addCookie({ // 'name': 'ckns_policy', // 'value': '111', // 'domain': '.bbc.co.uk' // }); // phantom.addCookie({ // 'name': 'locserv', // 'value': '1#l1#i=6691484:n=Oxford+Circus:h=e@w1#i=8:p=London@d1#1=l:2=e:3=e:4=2@n1#r=40', // 'domain': '.bbc.co.uk' // }); page.open(url, function(status) { if (status === 'success') { window.setTimeout(function() { console.log('Snapping ' + url + ' at width ' + view_port_width); page.render(image_name); phantom.exit(); }, 3000); } else { console.log('Error with page ' + url); phantom.exit(); } });
/******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ var parentJsonpFunction = window["webpackJsonp"]; /******/ window["webpackJsonp"] = function webpackJsonpCallback(chunkIds, moreModules) { /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0, callbacks = []; /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) /******/ callbacks.push.apply(callbacks, installedChunks[chunkId]); /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules); /******/ while(callbacks.length) /******/ callbacks.shift().call(null, __webpack_require__); /******/ if(moreModules[0]) { /******/ installedModules[0] = 0; /******/ return __webpack_require__(0); /******/ } /******/ }; /******/ var parentHotUpdateCallback = this["webpackHotUpdate"]; /******/ this["webpackHotUpdate"] = /******/ function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars /******/ hotAddUpdateChunk(chunkId, moreModules); /******/ if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); /******/ } /******/ /******/ function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars /******/ var head = document.getElementsByTagName("head")[0]; /******/ var script = document.createElement("script"); /******/ script.type = "text/javascript"; /******/ script.charset = "utf-8"; /******/ script.src = __webpack_require__.p + "" + chunkId + "." + hotCurrentHash + ".hot-update.js"; /******/ head.appendChild(script); /******/ } /******/ /******/ function hotDownloadManifest(callback) { // eslint-disable-line no-unused-vars /******/ if(typeof XMLHttpRequest === "undefined") /******/ return callback(new Error("No browser support")); /******/ try { /******/ var request = new XMLHttpRequest(); /******/ var requestPath = __webpack_require__.p + "" + hotCurrentHash + ".hot-update.json"; /******/ request.open("GET", requestPath, true); /******/ request.timeout = 10000; /******/ request.send(null); /******/ } catch(err) { /******/ return callback(err); /******/ } /******/ request.onreadystatechange = function() { /******/ if(request.readyState !== 4) return; /******/ if(request.status === 0) { /******/ // timeout /******/ callback(new Error("Manifest request to " + requestPath + " timed out.")); /******/ } else if(request.status === 404) { /******/ // no update available /******/ callback(); /******/ } else if(request.status !== 200 && request.status !== 304) { /******/ // other failure /******/ callback(new Error("Manifest request to " + requestPath + " failed.")); /******/ } else { /******/ // success /******/ try { /******/ var update = JSON.parse(request.responseText); /******/ } catch(e) { /******/ callback(e); /******/ return; /******/ } /******/ callback(null, update); /******/ } /******/ }; /******/ } /******/ /******/ /******/ /******/ // Copied from https://github.com/facebook/react/blob/bef45b0/src/shared/utils/canDefineProperty.js /******/ var canDefineProperty = false; /******/ try { /******/ Object.defineProperty({}, "x", { /******/ get: function() {} /******/ }); /******/ canDefineProperty = true; /******/ } catch(x) { /******/ // IE will fail on defineProperty /******/ } /******/ /******/ var hotApplyOnUpdate = true; /******/ var hotCurrentHash = "4fdab2f3d5915072bfb1"; // eslint-disable-line no-unused-vars /******/ var hotCurrentModuleData = {}; /******/ var hotCurrentParents = []; // eslint-disable-line no-unused-vars /******/ /******/ function hotCreateRequire(moduleId) { // eslint-disable-line no-unused-vars /******/ var me = installedModules[moduleId]; /******/ if(!me) return __webpack_require__; /******/ var fn = function(request) { /******/ if(me.hot.active) { /******/ if(installedModules[request]) { /******/ if(installedModules[request].parents.indexOf(moduleId) < 0) /******/ installedModules[request].parents.push(moduleId); /******/ if(me.children.indexOf(request) < 0) /******/ me.children.push(request); /******/ } else hotCurrentParents = [moduleId]; /******/ } else { /******/ console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId); /******/ hotCurrentParents = []; /******/ } /******/ return __webpack_require__(request); /******/ }; /******/ for(var name in __webpack_require__) { /******/ if(Object.prototype.hasOwnProperty.call(__webpack_require__, name)) { /******/ if(canDefineProperty) { /******/ Object.defineProperty(fn, name, (function(name) { /******/ return { /******/ configurable: true, /******/ enumerable: true, /******/ get: function() { /******/ return __webpack_require__[name]; /******/ }, /******/ set: function(value) { /******/ __webpack_require__[name] = value; /******/ } /******/ }; /******/ }(name))); /******/ } else { /******/ fn[name] = __webpack_require__[name]; /******/ } /******/ } /******/ } /******/ /******/ function ensure(chunkId, callback) { /******/ if(hotStatus === "ready") /******/ hotSetStatus("prepare"); /******/ hotChunksLoading++; /******/ __webpack_require__.e(chunkId, function() { /******/ try { /******/ callback.call(null, fn); /******/ } finally { /******/ finishChunkLoading(); /******/ } /******/ /******/ function finishChunkLoading() { /******/ hotChunksLoading--; /******/ if(hotStatus === "prepare") { /******/ if(!hotWaitingFilesMap[chunkId]) { /******/ hotEnsureUpdateChunk(chunkId); /******/ } /******/ if(hotChunksLoading === 0 && hotWaitingFiles === 0) { /******/ hotUpdateDownloaded(); /******/ } /******/ } /******/ } /******/ }); /******/ } /******/ if(canDefineProperty) { /******/ Object.defineProperty(fn, "e", { /******/ enumerable: true, /******/ value: ensure /******/ }); /******/ } else { /******/ fn.e = ensure; /******/ } /******/ return fn; /******/ } /******/ /******/ function hotCreateModule(moduleId) { // eslint-disable-line no-unused-vars /******/ var hot = { /******/ // private stuff /******/ _acceptedDependencies: {}, /******/ _declinedDependencies: {}, /******/ _selfAccepted: false, /******/ _selfDeclined: false, /******/ _disposeHandlers: [], /******/ /******/ // Module API /******/ active: true, /******/ accept: function(dep, callback) { /******/ if(typeof dep === "undefined") /******/ hot._selfAccepted = true; /******/ else if(typeof dep === "function") /******/ hot._selfAccepted = dep; /******/ else if(typeof dep === "object") /******/ for(var i = 0; i < dep.length; i++) /******/ hot._acceptedDependencies[dep[i]] = callback; /******/ else /******/ hot._acceptedDependencies[dep] = callback; /******/ }, /******/ decline: function(dep) { /******/ if(typeof dep === "undefined") /******/ hot._selfDeclined = true; /******/ else if(typeof dep === "number") /******/ hot._declinedDependencies[dep] = true; /******/ else /******/ for(var i = 0; i < dep.length; i++) /******/ hot._declinedDependencies[dep[i]] = true; /******/ }, /******/ dispose: function(callback) { /******/ hot._disposeHandlers.push(callback); /******/ }, /******/ addDisposeHandler: function(callback) { /******/ hot._disposeHandlers.push(callback); /******/ }, /******/ removeDisposeHandler: function(callback) { /******/ var idx = hot._disposeHandlers.indexOf(callback); /******/ if(idx >= 0) hot._disposeHandlers.splice(idx, 1); /******/ }, /******/ /******/ // Management API /******/ check: hotCheck, /******/ apply: hotApply, /******/ status: function(l) { /******/ if(!l) return hotStatus; /******/ hotStatusHandlers.push(l); /******/ }, /******/ addStatusHandler: function(l) { /******/ hotStatusHandlers.push(l); /******/ }, /******/ removeStatusHandler: function(l) { /******/ var idx = hotStatusHandlers.indexOf(l); /******/ if(idx >= 0) hotStatusHandlers.splice(idx, 1); /******/ }, /******/ /******/ //inherit from previous dispose call /******/ data: hotCurrentModuleData[moduleId] /******/ }; /******/ return hot; /******/ } /******/ /******/ var hotStatusHandlers = []; /******/ var hotStatus = "idle"; /******/ /******/ function hotSetStatus(newStatus) { /******/ hotStatus = newStatus; /******/ for(var i = 0; i < hotStatusHandlers.length; i++) /******/ hotStatusHandlers[i].call(null, newStatus); /******/ } /******/ /******/ // while downloading /******/ var hotWaitingFiles = 0; /******/ var hotChunksLoading = 0; /******/ var hotWaitingFilesMap = {}; /******/ var hotRequestedFilesMap = {}; /******/ var hotAvailibleFilesMap = {}; /******/ var hotCallback; /******/ /******/ // The update info /******/ var hotUpdate, hotUpdateNewHash; /******/ /******/ function toModuleId(id) { /******/ var isNumber = (+id) + "" === id; /******/ return isNumber ? +id : id; /******/ } /******/ /******/ function hotCheck(apply, callback) { /******/ if(hotStatus !== "idle") throw new Error("check() is only allowed in idle status"); /******/ if(typeof apply === "function") { /******/ hotApplyOnUpdate = false; /******/ callback = apply; /******/ } else { /******/ hotApplyOnUpdate = apply; /******/ callback = callback || function(err) { /******/ if(err) throw err; /******/ }; /******/ } /******/ hotSetStatus("check"); /******/ hotDownloadManifest(function(err, update) { /******/ if(err) return callback(err); /******/ if(!update) { /******/ hotSetStatus("idle"); /******/ callback(null, null); /******/ return; /******/ } /******/ /******/ hotRequestedFilesMap = {}; /******/ hotAvailibleFilesMap = {}; /******/ hotWaitingFilesMap = {}; /******/ for(var i = 0; i < update.c.length; i++) /******/ hotAvailibleFilesMap[update.c[i]] = true; /******/ hotUpdateNewHash = update.h; /******/ /******/ hotSetStatus("prepare"); /******/ hotCallback = callback; /******/ hotUpdate = {}; /******/ for(var chunkId in installedChunks) /******/ { // eslint-disable-line no-lone-blocks /******/ /*globals chunkId */ /******/ hotEnsureUpdateChunk(chunkId); /******/ } /******/ if(hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0) { /******/ hotUpdateDownloaded(); /******/ } /******/ }); /******/ } /******/ /******/ function hotAddUpdateChunk(chunkId, moreModules) { // eslint-disable-line no-unused-vars /******/ if(!hotAvailibleFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) /******/ return; /******/ hotRequestedFilesMap[chunkId] = false; /******/ for(var moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ hotUpdate[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(--hotWaitingFiles === 0 && hotChunksLoading === 0) { /******/ hotUpdateDownloaded(); /******/ } /******/ } /******/ /******/ function hotEnsureUpdateChunk(chunkId) { /******/ if(!hotAvailibleFilesMap[chunkId]) { /******/ hotWaitingFilesMap[chunkId] = true; /******/ } else { /******/ hotRequestedFilesMap[chunkId] = true; /******/ hotWaitingFiles++; /******/ hotDownloadUpdateChunk(chunkId); /******/ } /******/ } /******/ /******/ function hotUpdateDownloaded() { /******/ hotSetStatus("ready"); /******/ var callback = hotCallback; /******/ hotCallback = null; /******/ if(!callback) return; /******/ if(hotApplyOnUpdate) { /******/ hotApply(hotApplyOnUpdate, callback); /******/ } else { /******/ var outdatedModules = []; /******/ for(var id in hotUpdate) { /******/ if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) { /******/ outdatedModules.push(toModuleId(id)); /******/ } /******/ } /******/ callback(null, outdatedModules); /******/ } /******/ } /******/ /******/ function hotApply(options, callback) { /******/ if(hotStatus !== "ready") throw new Error("apply() is only allowed in ready status"); /******/ if(typeof options === "function") { /******/ callback = options; /******/ options = {}; /******/ } else if(options && typeof options === "object") { /******/ callback = callback || function(err) { /******/ if(err) throw err; /******/ }; /******/ } else { /******/ options = {}; /******/ callback = callback || function(err) { /******/ if(err) throw err; /******/ }; /******/ } /******/ /******/ function getAffectedStuff(module) { /******/ var outdatedModules = [module]; /******/ var outdatedDependencies = {}; /******/ /******/ var queue = outdatedModules.slice(); /******/ while(queue.length > 0) { /******/ var moduleId = queue.pop(); /******/ var module = installedModules[moduleId]; /******/ if(!module || module.hot._selfAccepted) /******/ continue; /******/ if(module.hot._selfDeclined) { /******/ return new Error("Aborted because of self decline: " + moduleId); /******/ } /******/ if(moduleId === 0) { /******/ return; /******/ } /******/ for(var i = 0; i < module.parents.length; i++) { /******/ var parentId = module.parents[i]; /******/ var parent = installedModules[parentId]; /******/ if(parent.hot._declinedDependencies[moduleId]) { /******/ return new Error("Aborted because of declined dependency: " + moduleId + " in " + parentId); /******/ } /******/ if(outdatedModules.indexOf(parentId) >= 0) continue; /******/ if(parent.hot._acceptedDependencies[moduleId]) { /******/ if(!outdatedDependencies[parentId]) /******/ outdatedDependencies[parentId] = []; /******/ addAllToSet(outdatedDependencies[parentId], [moduleId]); /******/ continue; /******/ } /******/ delete outdatedDependencies[parentId]; /******/ outdatedModules.push(parentId); /******/ queue.push(parentId); /******/ } /******/ } /******/ /******/ return [outdatedModules, outdatedDependencies]; /******/ } /******/ /******/ function addAllToSet(a, b) { /******/ for(var i = 0; i < b.length; i++) { /******/ var item = b[i]; /******/ if(a.indexOf(item) < 0) /******/ a.push(item); /******/ } /******/ } /******/ /******/ // at begin all updates modules are outdated /******/ // the "outdated" status can propagate to parents if they don't accept the children /******/ var outdatedDependencies = {}; /******/ var outdatedModules = []; /******/ var appliedUpdate = {}; /******/ for(var id in hotUpdate) { /******/ if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) { /******/ var moduleId = toModuleId(id); /******/ var result = getAffectedStuff(moduleId); /******/ if(!result) { /******/ if(options.ignoreUnaccepted) /******/ continue; /******/ hotSetStatus("abort"); /******/ return callback(new Error("Aborted because " + moduleId + " is not accepted")); /******/ } /******/ if(result instanceof Error) { /******/ hotSetStatus("abort"); /******/ return callback(result); /******/ } /******/ appliedUpdate[moduleId] = hotUpdate[moduleId]; /******/ addAllToSet(outdatedModules, result[0]); /******/ for(var moduleId in result[1]) { /******/ if(Object.prototype.hasOwnProperty.call(result[1], moduleId)) { /******/ if(!outdatedDependencies[moduleId]) /******/ outdatedDependencies[moduleId] = []; /******/ addAllToSet(outdatedDependencies[moduleId], result[1][moduleId]); /******/ } /******/ } /******/ } /******/ } /******/ /******/ // Store self accepted outdated modules to require them later by the module system /******/ var outdatedSelfAcceptedModules = []; /******/ for(var i = 0; i < outdatedModules.length; i++) { /******/ var moduleId = outdatedModules[i]; /******/ if(installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted) /******/ outdatedSelfAcceptedModules.push({ /******/ module: moduleId, /******/ errorHandler: installedModules[moduleId].hot._selfAccepted /******/ }); /******/ } /******/ /******/ // Now in "dispose" phase /******/ hotSetStatus("dispose"); /******/ var queue = outdatedModules.slice(); /******/ while(queue.length > 0) { /******/ var moduleId = queue.pop(); /******/ var module = installedModules[moduleId]; /******/ if(!module) continue; /******/ /******/ var data = {}; /******/ /******/ // Call dispose handlers /******/ var disposeHandlers = module.hot._disposeHandlers; /******/ for(var j = 0; j < disposeHandlers.length; j++) { /******/ var cb = disposeHandlers[j]; /******/ cb(data); /******/ } /******/ hotCurrentModuleData[moduleId] = data; /******/ /******/ // disable module (this disables requires from this module) /******/ module.hot.active = false; /******/ /******/ // remove module from cache /******/ delete installedModules[moduleId]; /******/ /******/ // remove "parents" references from all children /******/ for(var j = 0; j < module.children.length; j++) { /******/ var child = installedModules[module.children[j]]; /******/ if(!child) continue; /******/ var idx = child.parents.indexOf(moduleId); /******/ if(idx >= 0) { /******/ child.parents.splice(idx, 1); /******/ } /******/ } /******/ } /******/ /******/ // remove outdated dependency from module children /******/ for(var moduleId in outdatedDependencies) { /******/ if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) { /******/ var module = installedModules[moduleId]; /******/ var moduleOutdatedDependencies = outdatedDependencies[moduleId]; /******/ for(var j = 0; j < moduleOutdatedDependencies.length; j++) { /******/ var dependency = moduleOutdatedDependencies[j]; /******/ var idx = module.children.indexOf(dependency); /******/ if(idx >= 0) module.children.splice(idx, 1); /******/ } /******/ } /******/ } /******/ /******/ // Not in "apply" phase /******/ hotSetStatus("apply"); /******/ /******/ hotCurrentHash = hotUpdateNewHash; /******/ /******/ // insert new code /******/ for(var moduleId in appliedUpdate) { /******/ if(Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { /******/ modules[moduleId] = appliedUpdate[moduleId]; /******/ } /******/ } /******/ /******/ // call accept handlers /******/ var error = null; /******/ for(var moduleId in outdatedDependencies) { /******/ if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) { /******/ var module = installedModules[moduleId]; /******/ var moduleOutdatedDependencies = outdatedDependencies[moduleId]; /******/ var callbacks = []; /******/ for(var i = 0; i < moduleOutdatedDependencies.length; i++) { /******/ var dependency = moduleOutdatedDependencies[i]; /******/ var cb = module.hot._acceptedDependencies[dependency]; /******/ if(callbacks.indexOf(cb) >= 0) continue; /******/ callbacks.push(cb); /******/ } /******/ for(var i = 0; i < callbacks.length; i++) { /******/ var cb = callbacks[i]; /******/ try { /******/ cb(outdatedDependencies); /******/ } catch(err) { /******/ if(!error) /******/ error = err; /******/ } /******/ } /******/ } /******/ } /******/ /******/ // Load self accepted modules /******/ for(var i = 0; i < outdatedSelfAcceptedModules.length; i++) { /******/ var item = outdatedSelfAcceptedModules[i]; /******/ var moduleId = item.module; /******/ hotCurrentParents = [moduleId]; /******/ try { /******/ __webpack_require__(moduleId); /******/ } catch(err) { /******/ if(typeof item.errorHandler === "function") { /******/ try { /******/ item.errorHandler(err); /******/ } catch(err) { /******/ if(!error) /******/ error = err; /******/ } /******/ } else if(!error) /******/ error = err; /******/ } /******/ } /******/ /******/ // handle errors in accept handlers and self accepted module load /******/ if(error) { /******/ hotSetStatus("fail"); /******/ return callback(error); /******/ } /******/ /******/ hotSetStatus("idle"); /******/ callback(null, outdatedModules); /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // "0" means "already loaded" /******/ // Array means "loading", array contains callbacks /******/ var installedChunks = { /******/ 1:0 /******/ }; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false, /******/ hot: hotCreateModule(moduleId), /******/ parents: hotCurrentParents, /******/ children: [] /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId)); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // This file contains only the entry chunk. /******/ // The chunk loading function for additional chunks /******/ __webpack_require__.e = function requireEnsure(chunkId, callback) { /******/ // "0" is the signal for "already loaded" /******/ if(installedChunks[chunkId] === 0) /******/ return callback.call(null, __webpack_require__); /******/ /******/ // an array means "currently loading". /******/ if(installedChunks[chunkId] !== undefined) { /******/ installedChunks[chunkId].push(callback); /******/ } else { /******/ // start chunk loading /******/ installedChunks[chunkId] = [callback]; /******/ var head = document.getElementsByTagName('head')[0]; /******/ var script = document.createElement('script'); /******/ script.type = 'text/javascript'; /******/ script.charset = 'utf-8'; /******/ script.async = true; /******/ /******/ script.src = __webpack_require__.p + "" + chunkId + "." + ({"0":"app"}[chunkId]||chunkId) + "." + hotCurrentHash + ".js"; /******/ head.appendChild(script); /******/ } /******/ }; /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ // __webpack_hash__ /******/ __webpack_require__.h = function() { return hotCurrentHash; }; /******/ /******/ // Load entry module and return exports /******/ return hotCreateRequire(0)(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(88); __webpack_require__(265); __webpack_require__(303); module.exports = __webpack_require__(276); /***/ }, /* 1 */, /* 2 */, /* 3 */, /* 4 */, /* 5 */, /* 6 */, /* 7 */, /* 8 */, /* 9 */, /* 10 */, /* 11 */, /* 12 */, /* 13 */, /* 14 */, /* 15 */, /* 16 */, /* 17 */, /* 18 */, /* 19 */, /* 20 */, /* 21 */, /* 22 */, /* 23 */, /* 24 */, /* 25 */, /* 26 */, /* 27 */, /* 28 */, /* 29 */, /* 30 */, /* 31 */, /* 32 */, /* 33 */, /* 34 */, /* 35 */, /* 36 */, /* 37 */, /* 38 */, /* 39 */, /* 40 */, /* 41 */, /* 42 */, /* 43 */, /* 44 */, /* 45 */, /* 46 */, /* 47 */, /* 48 */, /* 49 */, /* 50 */, /* 51 */, /* 52 */, /* 53 */, /* 54 */, /* 55 */, /* 56 */, /* 57 */, /* 58 */, /* 59 */, /* 60 */, /* 61 */, /* 62 */, /* 63 */, /* 64 */, /* 65 */, /* 66 */, /* 67 */, /* 68 */, /* 69 */, /* 70 */, /* 71 */, /* 72 */, /* 73 */, /* 74 */, /* 75 */, /* 76 */, /* 77 */, /* 78 */, /* 79 */, /* 80 */, /* 81 */, /* 82 */, /* 83 */, /* 84 */, /* 85 */, /* 86 */, /* 87 */, /* 88 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(89); /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var _assign = __webpack_require__(90); var ReactChildren = __webpack_require__(91); var ReactComponent = __webpack_require__(104); var ReactPureComponent = __webpack_require__(107); var ReactClass = __webpack_require__(108); var ReactDOMFactories = __webpack_require__(110); var ReactElement = __webpack_require__(95); var ReactPropTypes = __webpack_require__(116); var ReactVersion = __webpack_require__(117); var onlyChild = __webpack_require__(118); var warning = __webpack_require__(97); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (true) { var ReactElementValidator = __webpack_require__(111); createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; if (true) { var warned = false; __spread = function () { true ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0; warned = true; return _assign.apply(null, arguments); }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, PureComponent: ReactPureComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; module.exports = React; /***/ }, /* 90 */ /***/ function(module, exports) { 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var PooledClass = __webpack_require__(92); var ReactElement = __webpack_require__(95); var emptyFunction = __webpack_require__(98); var traverseAllChildren = __webpack_require__(101); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.foreach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.map * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.count * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.toarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * * */ 'use strict'; var _prodInvariant = __webpack_require__(93); var invariant = __webpack_require__(94); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? true ? invariant(false, 'Trying to release an instance into a pool of a different type.') : _prodInvariant('25') : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances. * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { // Casting as any so that flow ignores the actual implementation and trusts // it to match the type we declared var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; /***/ }, /* 93 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * WARNING: DO NOT manually require this module. * This is a replacement for `invariant(...)` used by the error code system * and will _only_ be required by the corresponding babel pass. * It always throws. */ function reactProdInvariant(code) { var argCount = arguments.length - 1; var message = 'Minified React error #' + code + '; visit ' + 'http://facebook.github.io/react/docs/error-decoder.html?invariant=' + code; for (var argIdx = 0; argIdx < argCount; argIdx++) { message += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); } message += ' for the full message or use the non-minified dev environment' + ' for full errors and additional helpful warnings.'; var error = new Error(message); error.name = 'Invariant Violation'; error.framesToPop = 1; // we don't care about reactProdInvariant's own frame throw error; } module.exports = reactProdInvariant; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (true) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); 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; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _assign = __webpack_require__(90); var ReactCurrentOwner = __webpack_require__(96); var warning = __webpack_require__(97); var canDefineProperty = __webpack_require__(99); var hasOwnProperty = Object.prototype.hasOwnProperty; var REACT_ELEMENT_TYPE = __webpack_require__(100); var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; function hasValidRef(config) { if (true) { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { if (true) { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; true ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; true ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName) : void 0; } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (true) { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createelement */ ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } if (true) { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (true) { if (key || ref) { if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; /** * Return a function that produces ReactElements of a given type. * See https://facebook.github.io/react/docs/top-level-api.html#react.createfactory */ ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; /** * Clone and return a new ReactElement using element as the starting point. * See https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement */ ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * Verifies the object is a ReactElement. * See https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; /***/ }, /* 96 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyFunction = __webpack_require__(98); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (true) { (function () { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; })(); } module.exports = warning; /***/ }, /* 98 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * * */ 'use strict'; var canDefineProperty = false; if (true) { try { // $FlowFixMe https://github.com/facebook/flow/issues/285 Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /***/ }, /* 100 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; module.exports = REACT_ELEMENT_TYPE; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var _prodInvariant = __webpack_require__(93); var ReactCurrentOwner = __webpack_require__(96); var REACT_ELEMENT_TYPE = __webpack_require__(100); var getIteratorFn = __webpack_require__(102); var invariant = __webpack_require__(94); var KeyEscapeUtils = __webpack_require__(103); var warning = __webpack_require__(97); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * This is inlined from ReactElement since this file is shared between * isomorphic and renderers. We could extract this to a * */ /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || // The following is inlined from ReactElement. This means we can optimize // some checks. React Fiber also inlines this logic for similar purposes. type === 'object' && children.$$typeof === REACT_ELEMENT_TYPE) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (true) { var mapsAsChildrenAddendum = ''; if (ReactCurrentOwner.current) { var mapsAsChildrenOwnerName = ReactCurrentOwner.current.getName(); if (mapsAsChildrenOwnerName) { mapsAsChildrenAddendum = ' Check the render method of `' + mapsAsChildrenOwnerName + '`.'; } } true ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.%s', mapsAsChildrenAddendum) : void 0; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (true) { addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? true ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : _prodInvariant('31', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /***/ }, /* 102 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }, /* 103 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var _prodInvariant = __webpack_require__(93); var ReactNoopUpdateQueue = __webpack_require__(105); var canDefineProperty = __webpack_require__(99); var emptyObject = __webpack_require__(106); var invariant = __webpack_require__(94); var warning = __webpack_require__(97); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? true ? invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0; this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (true) { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { true ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var warning = __webpack_require__(97); function warnNoop(publicInstance, callerName) { if (true) { var constructor = publicInstance.constructor; true ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, constructor && (constructor.displayName || constructor.name) || 'ReactClass') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnNoop(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if (true) { Object.freeze(emptyObject); } module.exports = emptyObject; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var _assign = __webpack_require__(90); var ReactComponent = __webpack_require__(104); var ReactNoopUpdateQueue = __webpack_require__(105); var emptyObject = __webpack_require__(106); /** * Base class helpers for the updating state of a component. */ function ReactPureComponent(props, context, updater) { // Duplicated from ReactComponent. this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } function ComponentDummy() {} ComponentDummy.prototype = ReactComponent.prototype; ReactPureComponent.prototype = new ComponentDummy(); ReactPureComponent.prototype.constructor = ReactPureComponent; // Avoid an extra prototype jump for these methods. _assign(ReactPureComponent.prototype, ReactComponent.prototype); ReactPureComponent.prototype.isPureReactComponent = true; module.exports = ReactPureComponent; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var _prodInvariant = __webpack_require__(93), _assign = __webpack_require__(90); var ReactComponent = __webpack_require__(104); var ReactElement = __webpack_require__(95); var ReactPropTypeLocationNames = __webpack_require__(109); var ReactNoopUpdateQueue = __webpack_require__(105); var emptyObject = __webpack_require__(106); var invariant = __webpack_require__(94); var warning = __webpack_require__(97); var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if (true) { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if (true) { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if (true) { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but only in __DEV__ true ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0; } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === 'OVERRIDE_BASE') ? true ? invariant(false, 'ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.', name) : _prodInvariant('73', name) : void 0; } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { !(specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED') ? true ? invariant(false, 'ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('74', name) : void 0; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (true) { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; true ? warning(isMixinValid, '%s: You\'re attempting to include a mixin that is either null ' + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec) : void 0; } return; } !(typeof spec !== 'function') ? true ? invariant(false, 'ReactClass: You\'re attempting to use a component class or function as a mixin. Instead, just use a regular object.') : _prodInvariant('75') : void 0; !!ReactElement.isValidElement(spec) ? true ? invariant(false, 'ReactClass: You\'re attempting to use a component as a mixin. Instead, just use a regular object.') : _prodInvariant('76') : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY')) ? true ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.', specPolicy, name) : _prodInvariant('77', specPolicy, name) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (true) { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; !!isReserved ? true ? invariant(false, 'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.', name) : _prodInvariant('78', name) : void 0; var isInherited = name in Constructor; !!isInherited ? true ? invariant(false, 'ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.', name) : _prodInvariant('79', name) : void 0; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? true ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : _prodInvariant('80') : void 0; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? true ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.', key) : _prodInvariant('81', key) : void 0; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (true) { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { true ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0; } else if (!args.length) { true ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : void 0; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback, 'replaceState'); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); } }; var ReactClassComponent = function () {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function (props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (true) { true ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0; } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (true) { // We allow auto-mocks to proceed as if they're returning null. if (initialState === undefined && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? true ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : _prodInvariant('82', Constructor.displayName || 'ReactCompositeComponent') : void 0; this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (true) { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? true ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : _prodInvariant('83') : void 0; if (true) { true ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : void 0; true ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * * */ 'use strict'; var ReactPropTypeLocationNames = {}; if (true) { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var ReactElement = __webpack_require__(95); /** * Create a factory that creates HTML tag elements. * * @private */ var createDOMFactory = ReactElement.createFactory; if (true) { var ReactElementValidator = __webpack_require__(111); createDOMFactory = ReactElementValidator.createFactory; } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = { a: createDOMFactory('a'), abbr: createDOMFactory('abbr'), address: createDOMFactory('address'), area: createDOMFactory('area'), article: createDOMFactory('article'), aside: createDOMFactory('aside'), audio: createDOMFactory('audio'), b: createDOMFactory('b'), base: createDOMFactory('base'), bdi: createDOMFactory('bdi'), bdo: createDOMFactory('bdo'), big: createDOMFactory('big'), blockquote: createDOMFactory('blockquote'), body: createDOMFactory('body'), br: createDOMFactory('br'), button: createDOMFactory('button'), canvas: createDOMFactory('canvas'), caption: createDOMFactory('caption'), cite: createDOMFactory('cite'), code: createDOMFactory('code'), col: createDOMFactory('col'), colgroup: createDOMFactory('colgroup'), data: createDOMFactory('data'), datalist: createDOMFactory('datalist'), dd: createDOMFactory('dd'), del: createDOMFactory('del'), details: createDOMFactory('details'), dfn: createDOMFactory('dfn'), dialog: createDOMFactory('dialog'), div: createDOMFactory('div'), dl: createDOMFactory('dl'), dt: createDOMFactory('dt'), em: createDOMFactory('em'), embed: createDOMFactory('embed'), fieldset: createDOMFactory('fieldset'), figcaption: createDOMFactory('figcaption'), figure: createDOMFactory('figure'), footer: createDOMFactory('footer'), form: createDOMFactory('form'), h1: createDOMFactory('h1'), h2: createDOMFactory('h2'), h3: createDOMFactory('h3'), h4: createDOMFactory('h4'), h5: createDOMFactory('h5'), h6: createDOMFactory('h6'), head: createDOMFactory('head'), header: createDOMFactory('header'), hgroup: createDOMFactory('hgroup'), hr: createDOMFactory('hr'), html: createDOMFactory('html'), i: createDOMFactory('i'), iframe: createDOMFactory('iframe'), img: createDOMFactory('img'), input: createDOMFactory('input'), ins: createDOMFactory('ins'), kbd: createDOMFactory('kbd'), keygen: createDOMFactory('keygen'), label: createDOMFactory('label'), legend: createDOMFactory('legend'), li: createDOMFactory('li'), link: createDOMFactory('link'), main: createDOMFactory('main'), map: createDOMFactory('map'), mark: createDOMFactory('mark'), menu: createDOMFactory('menu'), menuitem: createDOMFactory('menuitem'), meta: createDOMFactory('meta'), meter: createDOMFactory('meter'), nav: createDOMFactory('nav'), noscript: createDOMFactory('noscript'), object: createDOMFactory('object'), ol: createDOMFactory('ol'), optgroup: createDOMFactory('optgroup'), option: createDOMFactory('option'), output: createDOMFactory('output'), p: createDOMFactory('p'), param: createDOMFactory('param'), picture: createDOMFactory('picture'), pre: createDOMFactory('pre'), progress: createDOMFactory('progress'), q: createDOMFactory('q'), rp: createDOMFactory('rp'), rt: createDOMFactory('rt'), ruby: createDOMFactory('ruby'), s: createDOMFactory('s'), samp: createDOMFactory('samp'), script: createDOMFactory('script'), section: createDOMFactory('section'), select: createDOMFactory('select'), small: createDOMFactory('small'), source: createDOMFactory('source'), span: createDOMFactory('span'), strong: createDOMFactory('strong'), style: createDOMFactory('style'), sub: createDOMFactory('sub'), summary: createDOMFactory('summary'), sup: createDOMFactory('sup'), table: createDOMFactory('table'), tbody: createDOMFactory('tbody'), td: createDOMFactory('td'), textarea: createDOMFactory('textarea'), tfoot: createDOMFactory('tfoot'), th: createDOMFactory('th'), thead: createDOMFactory('thead'), time: createDOMFactory('time'), title: createDOMFactory('title'), tr: createDOMFactory('tr'), track: createDOMFactory('track'), u: createDOMFactory('u'), ul: createDOMFactory('ul'), 'var': createDOMFactory('var'), video: createDOMFactory('video'), wbr: createDOMFactory('wbr'), // SVG circle: createDOMFactory('circle'), clipPath: createDOMFactory('clipPath'), defs: createDOMFactory('defs'), ellipse: createDOMFactory('ellipse'), g: createDOMFactory('g'), image: createDOMFactory('image'), line: createDOMFactory('line'), linearGradient: createDOMFactory('linearGradient'), mask: createDOMFactory('mask'), path: createDOMFactory('path'), pattern: createDOMFactory('pattern'), polygon: createDOMFactory('polygon'), polyline: createDOMFactory('polyline'), radialGradient: createDOMFactory('radialGradient'), rect: createDOMFactory('rect'), stop: createDOMFactory('stop'), svg: createDOMFactory('svg'), text: createDOMFactory('text'), tspan: createDOMFactory('tspan') }; module.exports = ReactDOMFactories; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactCurrentOwner = __webpack_require__(96); var ReactComponentTreeHook = __webpack_require__(112); var ReactElement = __webpack_require__(95); var checkReactTypeSpec = __webpack_require__(113); var canDefineProperty = __webpack_require__(99); var getIteratorFn = __webpack_require__(102); var warning = __webpack_require__(97); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = ' Check the top-level render call using <' + parentName + '>.'; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var memoizer = ownerHasKeyUseWarning.uniqueKey || (ownerHasKeyUseWarning.uniqueKey = {}); var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (memoizer[currentComponentErrorInfo]) { return; } memoizer[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } true ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.%s', currentComponentErrorInfo, childOwner, ReactComponentTreeHook.getCurrentStackAddendum(element)) : void 0; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkReactTypeSpec(componentClass.propTypes, element.props, 'prop', name, element, null); } if (typeof componentClass.getDefaultProps === 'function') { true ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { true ? warning(false, 'React.createElement: type should not be null, undefined, boolean, or ' + 'number. It should be a string (for DOM elements) or a ReactClass ' + '(for composite components).%s', getDeclarationErrorAddendum()) : void 0; } var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if (true) { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { true ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var _prodInvariant = __webpack_require__(93); var ReactCurrentOwner = __webpack_require__(96); var invariant = __webpack_require__(94); var warning = __webpack_require__(97); function isNative(fn) { // Based on isNative() from Lodash var funcToString = Function.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; var reIsNative = RegExp('^' + funcToString // Take an example native function source for comparison .call(hasOwnProperty) // Strip regex characters so we can use it for regex .replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') // Remove hasOwnProperty from the template to make it generic .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); try { var source = funcToString.call(fn); return reIsNative.test(source); } catch (err) { return false; } } var canUseCollections = // Array.from typeof Array.from === 'function' && // Map typeof Map === 'function' && isNative(Map) && // Map.prototype.keys Map.prototype != null && typeof Map.prototype.keys === 'function' && isNative(Map.prototype.keys) && // Set typeof Set === 'function' && isNative(Set) && // Set.prototype.keys Set.prototype != null && typeof Set.prototype.keys === 'function' && isNative(Set.prototype.keys); var setItem; var getItem; var removeItem; var getItemIDs; var addRoot; var removeRoot; var getRootIDs; if (canUseCollections) { var itemMap = new Map(); var rootIDSet = new Set(); setItem = function (id, item) { itemMap.set(id, item); }; getItem = function (id) { return itemMap.get(id); }; removeItem = function (id) { itemMap['delete'](id); }; getItemIDs = function () { return Array.from(itemMap.keys()); }; addRoot = function (id) { rootIDSet.add(id); }; removeRoot = function (id) { rootIDSet['delete'](id); }; getRootIDs = function () { return Array.from(rootIDSet.keys()); }; } else { var itemByKey = {}; var rootByKey = {}; // Use non-numeric keys to prevent V8 performance issues: // https://github.com/facebook/react/pull/7232 var getKeyFromID = function (id) { return '.' + id; }; var getIDFromKey = function (key) { return parseInt(key.substr(1), 10); }; setItem = function (id, item) { var key = getKeyFromID(id); itemByKey[key] = item; }; getItem = function (id) { var key = getKeyFromID(id); return itemByKey[key]; }; removeItem = function (id) { var key = getKeyFromID(id); delete itemByKey[key]; }; getItemIDs = function () { return Object.keys(itemByKey).map(getIDFromKey); }; addRoot = function (id) { var key = getKeyFromID(id); rootByKey[key] = true; }; removeRoot = function (id) { var key = getKeyFromID(id); delete rootByKey[key]; }; getRootIDs = function () { return Object.keys(rootByKey).map(getIDFromKey); }; } var unmountedIDs = []; function purgeDeep(id) { var item = getItem(id); if (item) { var childIDs = item.childIDs; removeItem(id); childIDs.forEach(purgeDeep); } } function describeComponentFrame(name, source, ownerName) { return '\n in ' + (name || 'Unknown') + (source ? ' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + ')' : ownerName ? ' (created by ' + ownerName + ')' : ''); } function getDisplayName(element) { if (element == null) { return '#empty'; } else if (typeof element === 'string' || typeof element === 'number') { return '#text'; } else if (typeof element.type === 'string') { return element.type; } else { return element.type.displayName || element.type.name || 'Unknown'; } } function describeID(id) { var name = ReactComponentTreeHook.getDisplayName(id); var element = ReactComponentTreeHook.getElement(id); var ownerID = ReactComponentTreeHook.getOwnerID(id); var ownerName; if (ownerID) { ownerName = ReactComponentTreeHook.getDisplayName(ownerID); } true ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0; return describeComponentFrame(name, element && element._source, ownerName); } var ReactComponentTreeHook = { onSetChildren: function (id, nextChildIDs) { var item = getItem(id); !item ? true ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.childIDs = nextChildIDs; for (var i = 0; i < nextChildIDs.length; i++) { var nextChildID = nextChildIDs[i]; var nextChild = getItem(nextChildID); !nextChild ? true ? invariant(false, 'Expected hook events to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('140') : void 0; !(nextChild.childIDs != null || typeof nextChild.element !== 'object' || nextChild.element == null) ? true ? invariant(false, 'Expected onSetChildren() to fire for a container child before its parent includes it in onSetChildren().') : _prodInvariant('141') : void 0; !nextChild.isMounted ? true ? invariant(false, 'Expected onMountComponent() to fire for the child before its parent includes it in onSetChildren().') : _prodInvariant('71') : void 0; if (nextChild.parentID == null) { nextChild.parentID = id; // TODO: This shouldn't be necessary but mounting a new root during in // componentWillMount currently causes not-yet-mounted components to // be purged from our tree data so their parent id is missing. } !(nextChild.parentID === id) ? true ? invariant(false, 'Expected onBeforeMountComponent() parent and onSetChildren() to be consistent (%s has parents %s and %s).', nextChildID, nextChild.parentID, id) : _prodInvariant('142', nextChildID, nextChild.parentID, id) : void 0; } }, onBeforeMountComponent: function (id, element, parentID) { var item = { element: element, parentID: parentID, text: null, childIDs: [], isMounted: false, updateCount: 0 }; setItem(id, item); }, onBeforeUpdateComponent: function (id, element) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.element = element; }, onMountComponent: function (id) { var item = getItem(id); !item ? true ? invariant(false, 'Item must have been set') : _prodInvariant('144') : void 0; item.isMounted = true; var isRoot = item.parentID === 0; if (isRoot) { addRoot(id); } }, onUpdateComponent: function (id) { var item = getItem(id); if (!item || !item.isMounted) { // We may end up here as a result of setState() in componentWillUnmount(). // In this case, ignore the element. return; } item.updateCount++; }, onUnmountComponent: function (id) { var item = getItem(id); if (item) { // We need to check if it exists. // `item` might not exist if it is inside an error boundary, and a sibling // error boundary child threw while mounting. Then this instance never // got a chance to mount, but it still gets an unmounting event during // the error boundary cleanup. item.isMounted = false; var isRoot = item.parentID === 0; if (isRoot) { removeRoot(id); } } unmountedIDs.push(id); }, purgeUnmountedComponents: function () { if (ReactComponentTreeHook._preventPurging) { // Should only be used for testing. return; } for (var i = 0; i < unmountedIDs.length; i++) { var id = unmountedIDs[i]; purgeDeep(id); } unmountedIDs.length = 0; }, isMounted: function (id) { var item = getItem(id); return item ? item.isMounted : false; }, getCurrentStackAddendum: function (topElement) { var info = ''; if (topElement) { var name = getDisplayName(topElement); var owner = topElement._owner; info += describeComponentFrame(name, topElement._source, owner && owner.getName()); } var currentOwner = ReactCurrentOwner.current; var id = currentOwner && currentOwner._debugID; info += ReactComponentTreeHook.getStackAddendumByID(id); return info; }, getStackAddendumByID: function (id) { var info = ''; while (id) { info += describeID(id); id = ReactComponentTreeHook.getParentID(id); } return info; }, getChildIDs: function (id) { var item = getItem(id); return item ? item.childIDs : []; }, getDisplayName: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element) { return null; } return getDisplayName(element); }, getElement: function (id) { var item = getItem(id); return item ? item.element : null; }, getOwnerID: function (id) { var element = ReactComponentTreeHook.getElement(id); if (!element || !element._owner) { return null; } return element._owner._debugID; }, getParentID: function (id) { var item = getItem(id); return item ? item.parentID : null; }, getSource: function (id) { var item = getItem(id); var element = item ? item.element : null; var source = element != null ? element._source : null; return source; }, getText: function (id) { var element = ReactComponentTreeHook.getElement(id); if (typeof element === 'string') { return element; } else if (typeof element === 'number') { return '' + element; } else { return null; } }, getUpdateCount: function (id) { var item = getItem(id); return item ? item.updateCount : 0; }, getRootIDs: getRootIDs, getRegisteredIDs: getItemIDs }; module.exports = ReactComponentTreeHook; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = __webpack_require__(93); var ReactPropTypeLocationNames = __webpack_require__(109); var ReactPropTypesSecret = __webpack_require__(115); var invariant = __webpack_require__(94); var warning = __webpack_require__(97); var ReactComponentTreeHook; if (typeof process !== 'undefined' && ({"NODE_ENV":"development"}) && ("development") === 'test') { // Temporary hack. // Inline requires don't work well with Jest: // https://github.com/facebook/react/issues/7240 // Remove the inline requires when we don't need them anymore: // https://github.com/facebook/react/pull/7178 ReactComponentTreeHook = __webpack_require__(112); } var loggedTypeFailures = {}; /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?object} element The React element that is being type-checked * @param {?number} debugID The React component instance that is being type-checked * @private */ function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { for (var typeSpecName in typeSpecs) { if (typeSpecs.hasOwnProperty(typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof typeSpecs[typeSpecName] === 'function') ? true ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : _prodInvariant('84', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName) : void 0; error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } true ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], typeSpecName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var componentStackInfo = ''; if (true) { if (!ReactComponentTreeHook) { ReactComponentTreeHook = __webpack_require__(112); } if (debugID !== null) { componentStackInfo = ReactComponentTreeHook.getStackAddendumByID(debugID); } else if (element !== null) { componentStackInfo = ReactComponentTreeHook.getCurrentStackAddendum(element); } } true ? warning(false, 'Failed %s type: %s%s', location, error.message, componentStackInfo) : void 0; } } } } module.exports = checkReactTypeSpec; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(114))) /***/ }, /* 114 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 115 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var ReactElement = __webpack_require__(95); var ReactPropTypeLocationNames = __webpack_require__(109); var ReactPropTypesSecret = __webpack_require__(115); var emptyFunction = __webpack_require__(98); var getIteratorFn = __webpack_require__(102); var warning = __webpack_require__(97); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (true) { var manualPropTypeCallCache = {}; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (true) { if (secret !== ReactPropTypesSecret && typeof console !== 'undefined') { var cacheKey = componentName + ':' + propName; if (!manualPropTypeCallCache[cacheKey]) { true ? warning(false, 'You are manually calling a React.PropTypes validation ' + 'function for the `%s` prop on `%s`. This is deprecated ' + 'and will not work in production with the next major version. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.', propFullName, componentName) : void 0; manualPropTypeCallCache[cacheKey] = true; } } } if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + locationName + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + locationName + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!ReactElement.isValidElement(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { true ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { true ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunction.thatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new PropTypeError('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } module.exports = ReactPropTypes; /***/ }, /* 117 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; module.exports = '15.4.1'; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { /** * 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. * */ 'use strict'; var _prodInvariant = __webpack_require__(93); var ReactElement = __webpack_require__(95); var invariant = __webpack_require__(94); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? true ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild; /***/ }, /* 119 */, /* 120 */, /* 121 */, /* 122 */, /* 123 */, /* 124 */, /* 125 */, /* 126 */, /* 127 */, /* 128 */, /* 129 */, /* 130 */, /* 131 */, /* 132 */, /* 133 */, /* 134 */, /* 135 */, /* 136 */, /* 137 */, /* 138 */, /* 139 */, /* 140 */, /* 141 */, /* 142 */, /* 143 */, /* 144 */, /* 145 */, /* 146 */, /* 147 */, /* 148 */, /* 149 */, /* 150 */, /* 151 */, /* 152 */, /* 153 */, /* 154 */, /* 155 */, /* 156 */, /* 157 */, /* 158 */, /* 159 */, /* 160 */, /* 161 */, /* 162 */, /* 163 */, /* 164 */, /* 165 */, /* 166 */, /* 167 */, /* 168 */, /* 169 */, /* 170 */, /* 171 */, /* 172 */, /* 173 */, /* 174 */, /* 175 */, /* 176 */, /* 177 */, /* 178 */, /* 179 */, /* 180 */, /* 181 */, /* 182 */, /* 183 */, /* 184 */, /* 185 */, /* 186 */, /* 187 */, /* 188 */, /* 189 */, /* 190 */, /* 191 */, /* 192 */, /* 193 */, /* 194 */, /* 195 */, /* 196 */, /* 197 */, /* 198 */, /* 199 */, /* 200 */, /* 201 */, /* 202 */, /* 203 */, /* 204 */, /* 205 */, /* 206 */, /* 207 */, /* 208 */, /* 209 */, /* 210 */, /* 211 */, /* 212 */, /* 213 */, /* 214 */, /* 215 */, /* 216 */, /* 217 */, /* 218 */, /* 219 */, /* 220 */, /* 221 */, /* 222 */, /* 223 */, /* 224 */, /* 225 */, /* 226 */, /* 227 */, /* 228 */, /* 229 */, /* 230 */, /* 231 */, /* 232 */, /* 233 */, /* 234 */, /* 235 */, /* 236 */, /* 237 */, /* 238 */, /* 239 */, /* 240 */, /* 241 */, /* 242 */, /* 243 */, /* 244 */, /* 245 */, /* 246 */, /* 247 */, /* 248 */, /* 249 */, /* 250 */, /* 251 */, /* 252 */, /* 253 */, /* 254 */, /* 255 */, /* 256 */, /* 257 */, /* 258 */, /* 259 */, /* 260 */, /* 261 */, /* 262 */, /* 263 */, /* 264 */, /* 265 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.connect = exports.connectAdvanced = exports.Provider = undefined; var _Provider = __webpack_require__(266); var _Provider2 = _interopRequireDefault(_Provider); var _connectAdvanced = __webpack_require__(269); var _connectAdvanced2 = _interopRequireDefault(_connectAdvanced); var _connect = __webpack_require__(273); var _connect2 = _interopRequireDefault(_connect); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.Provider = _Provider2.default; exports.connectAdvanced = _connectAdvanced2.default; exports.connect = _connect2.default; /***/ }, /* 266 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = undefined; var _react = __webpack_require__(88); var _storeShape = __webpack_require__(267); var _storeShape2 = _interopRequireDefault(_storeShape); var _warning = __webpack_require__(268); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var didWarnAboutReceivingStore = false; function warnAboutReceivingStore() { if (didWarnAboutReceivingStore) { return; } didWarnAboutReceivingStore = true; (0, _warning2.default)('<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/reactjs/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.'); } var Provider = function (_Component) { _inherits(Provider, _Component); Provider.prototype.getChildContext = function getChildContext() { return { store: this.store }; }; function Provider(props, context) { _classCallCheck(this, Provider); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.store = props.store; return _this; } Provider.prototype.render = function render() { return _react.Children.only(this.props.children); }; return Provider; }(_react.Component); exports.default = Provider; if (true) { Provider.prototype.componentWillReceiveProps = function (nextProps) { var store = this.store; var nextStore = nextProps.store; if (store !== nextStore) { warnAboutReceivingStore(); } }; } Provider.propTypes = { store: _storeShape2.default.isRequired, children: _react.PropTypes.element.isRequired }; Provider.childContextTypes = { store: _storeShape2.default.isRequired }; Provider.displayName = 'Provider'; /***/ }, /* 267 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(88); exports.default = _react.PropTypes.shape({ subscribe: _react.PropTypes.func.isRequired, dispatch: _react.PropTypes.func.isRequired, getState: _react.PropTypes.func.isRequired }); /***/ }, /* 268 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.default = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 269 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = connectAdvanced; var _hoistNonReactStatics = __webpack_require__(270); var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(88); var _Subscription = __webpack_require__(272); var _Subscription2 = _interopRequireDefault(_Subscription); var _storeShape = __webpack_require__(267); var _storeShape2 = _interopRequireDefault(_storeShape); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var hotReloadingVersion = 0; function connectAdvanced( /* selectorFactory is a func that is responsible for returning the selector function used to compute new props from state, props, and dispatch. For example: export default connectAdvanced((dispatch, options) => (state, props) => ({ thing: state.things[props.thingId], saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)), }))(YourComponent) Access to dispatch is provided to the factory so selectorFactories can bind actionCreators outside of their selector as an optimization. Options passed to connectAdvanced are passed to the selectorFactory, along with displayName and WrappedComponent, as the second argument. Note that selectorFactory is responsible for all caching/memoization of inbound and outbound props. Do not use connectAdvanced directly without memoizing results between calls to your selector, otherwise the Connect component will re-render on every state or props change. */ selectorFactory) { var _contextTypes, _childContextTypes; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$getDisplayName = _ref.getDisplayName, getDisplayName = _ref$getDisplayName === undefined ? function (name) { return 'ConnectAdvanced(' + name + ')'; } : _ref$getDisplayName, _ref$methodName = _ref.methodName, methodName = _ref$methodName === undefined ? 'connectAdvanced' : _ref$methodName, _ref$renderCountProp = _ref.renderCountProp, renderCountProp = _ref$renderCountProp === undefined ? undefined : _ref$renderCountProp, _ref$shouldHandleStat = _ref.shouldHandleStateChanges, shouldHandleStateChanges = _ref$shouldHandleStat === undefined ? true : _ref$shouldHandleStat, _ref$storeKey = _ref.storeKey, storeKey = _ref$storeKey === undefined ? 'store' : _ref$storeKey, _ref$withRef = _ref.withRef, withRef = _ref$withRef === undefined ? false : _ref$withRef, connectOptions = _objectWithoutProperties(_ref, ['getDisplayName', 'methodName', 'renderCountProp', 'shouldHandleStateChanges', 'storeKey', 'withRef']); var subscriptionKey = storeKey + 'Subscription'; var version = hotReloadingVersion++; var contextTypes = (_contextTypes = {}, _contextTypes[storeKey] = _storeShape2.default, _contextTypes[subscriptionKey] = _react.PropTypes.instanceOf(_Subscription2.default), _contextTypes); var childContextTypes = (_childContextTypes = {}, _childContextTypes[subscriptionKey] = _react.PropTypes.instanceOf(_Subscription2.default), _childContextTypes); return function wrapWithConnect(WrappedComponent) { (0, _invariant2.default)(typeof WrappedComponent == 'function', 'You must pass a component to the function returned by ' + ('connect. Instead received ' + WrappedComponent)); var wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component'; var displayName = getDisplayName(wrappedComponentName); var selectorFactoryOptions = _extends({}, connectOptions, { getDisplayName: getDisplayName, methodName: methodName, renderCountProp: renderCountProp, shouldHandleStateChanges: shouldHandleStateChanges, storeKey: storeKey, withRef: withRef, displayName: displayName, wrappedComponentName: wrappedComponentName, WrappedComponent: WrappedComponent }); var Connect = function (_Component) { _inherits(Connect, _Component); function Connect(props, context) { _classCallCheck(this, Connect); var _this = _possibleConstructorReturn(this, _Component.call(this, props, context)); _this.version = version; _this.state = {}; _this.renderCount = 0; _this.store = _this.props[storeKey] || _this.context[storeKey]; _this.parentSub = props[subscriptionKey] || context[subscriptionKey]; _this.setWrappedInstance = _this.setWrappedInstance.bind(_this); (0, _invariant2.default)(_this.store, 'Could not find "' + storeKey + '" in either the context or ' + ('props of "' + displayName + '". ') + 'Either wrap the root component in a <Provider>, ' + ('or explicitly pass "' + storeKey + '" as a prop to "' + displayName + '".')); // make sure `getState` is properly bound in order to avoid breaking // custom store implementations that rely on the store's context _this.getState = _this.store.getState.bind(_this.store); _this.initSelector(); _this.initSubscription(); return _this; } Connect.prototype.getChildContext = function getChildContext() { var _ref2; return _ref2 = {}, _ref2[subscriptionKey] = this.subscription, _ref2; }; Connect.prototype.componentDidMount = function componentDidMount() { if (!shouldHandleStateChanges) return; // componentWillMount fires during server side rendering, but componentDidMount and // componentWillUnmount do not. Because of this, trySubscribe happens during ...didMount. // Otherwise, unsubscription would never take place during SSR, causing a memory leak. // To handle the case where a child component may have triggered a state change by // dispatching an action in its componentWillMount, we have to re-run the select and maybe // re-render. this.subscription.trySubscribe(); this.selector.run(this.props); if (this.selector.shouldComponentUpdate) this.forceUpdate(); }; Connect.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { this.selector.run(nextProps); }; Connect.prototype.shouldComponentUpdate = function shouldComponentUpdate() { return this.selector.shouldComponentUpdate; }; Connect.prototype.componentWillUnmount = function componentWillUnmount() { if (this.subscription) this.subscription.tryUnsubscribe(); // these are just to guard against extra memory leakage if a parent element doesn't // dereference this instance properly, such as an async callback that never finishes this.subscription = null; this.store = null; this.parentSub = null; this.selector.run = function () {}; }; Connect.prototype.getWrappedInstance = function getWrappedInstance() { (0, _invariant2.default)(withRef, 'To access the wrapped instance, you need to specify ' + ('{ withRef: true } in the options argument of the ' + methodName + '() call.')); return this.wrappedInstance; }; Connect.prototype.setWrappedInstance = function setWrappedInstance(ref) { this.wrappedInstance = ref; }; Connect.prototype.initSelector = function initSelector() { var dispatch = this.store.dispatch; var getState = this.getState; var sourceSelector = selectorFactory(dispatch, selectorFactoryOptions); // wrap the selector in an object that tracks its results between runs var selector = this.selector = { shouldComponentUpdate: true, props: sourceSelector(getState(), this.props), run: function runComponentSelector(props) { try { var nextProps = sourceSelector(getState(), props); if (selector.error || nextProps !== selector.props) { selector.shouldComponentUpdate = true; selector.props = nextProps; selector.error = null; } } catch (error) { selector.shouldComponentUpdate = true; selector.error = error; } } }; }; Connect.prototype.initSubscription = function initSubscription() { var _this2 = this; if (shouldHandleStateChanges) { (function () { var subscription = _this2.subscription = new _Subscription2.default(_this2.store, _this2.parentSub); var dummyState = {}; subscription.onStateChange = function onStateChange() { this.selector.run(this.props); if (!this.selector.shouldComponentUpdate) { subscription.notifyNestedSubs(); } else { this.componentDidUpdate = function componentDidUpdate() { this.componentDidUpdate = undefined; subscription.notifyNestedSubs(); }; this.setState(dummyState); } }.bind(_this2); })(); } }; Connect.prototype.isSubscribed = function isSubscribed() { return Boolean(this.subscription) && this.subscription.isSubscribed(); }; Connect.prototype.addExtraProps = function addExtraProps(props) { if (!withRef && !renderCountProp) return props; // make a shallow copy so that fields added don't leak to the original selector. // this is especially important for 'ref' since that's a reference back to the component // instance. a singleton memoized selector would then be holding a reference to the // instance, preventing the instance from being garbage collected, and that would be bad var withExtras = _extends({}, props); if (withRef) withExtras.ref = this.setWrappedInstance; if (renderCountProp) withExtras[renderCountProp] = this.renderCount++; return withExtras; }; Connect.prototype.render = function render() { var selector = this.selector; selector.shouldComponentUpdate = false; if (selector.error) { throw selector.error; } else { return (0, _react.createElement)(WrappedComponent, this.addExtraProps(selector.props)); } }; return Connect; }(_react.Component); Connect.WrappedComponent = WrappedComponent; Connect.displayName = displayName; Connect.childContextTypes = childContextTypes; Connect.contextTypes = contextTypes; Connect.propTypes = contextTypes; if (true) { Connect.prototype.componentWillUpdate = function componentWillUpdate() { // We are hot reloading! if (this.version !== version) { this.version = version; this.initSelector(); if (this.subscription) this.subscription.tryUnsubscribe(); this.initSubscription(); if (shouldHandleStateChanges) this.subscription.trySubscribe(); } }; } return (0, _hoistNonReactStatics2.default)(Connect, WrappedComponent); }; } /***/ }, /* 270 */ /***/ function(module, exports) { /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, arguments: true, arity: true }; var isGetOwnPropertySymbolsAvailable = typeof Object.getOwnPropertySymbols === 'function'; module.exports = function hoistNonReactStatics(targetComponent, sourceComponent, customStatics) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var keys = Object.getOwnPropertyNames(sourceComponent); /* istanbul ignore else */ if (isGetOwnPropertySymbolsAvailable) { keys = keys.concat(Object.getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { if (!REACT_STATICS[keys[i]] && !KNOWN_STATICS[keys[i]] && (!customStatics || !customStatics[keys[i]])) { try { targetComponent[keys[i]] = sourceComponent[keys[i]]; } catch (error) { } } } } return targetComponent; }; /***/ }, /* 271 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * 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 (true) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }, /* 272 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // encapsulates the subscription logic for connecting a component to the redux store, as // well as nesting subscriptions of descendant components, so that we can ensure the // ancestor components re-render before descendants var CLEARED = null; var nullListeners = { notify: function notify() {} }; function createListenerCollection() { // the current/next pattern is copied from redux's createStore code. // TODO: refactor+expose that code to be reusable here? var current = []; var next = []; return { clear: function clear() { next = CLEARED; current = CLEARED; }, notify: function notify() { var listeners = current = next; for (var i = 0; i < listeners.length; i++) { listeners[i](); } }, subscribe: function subscribe(listener) { var isSubscribed = true; if (next === current) next = current.slice(); next.push(listener); return function unsubscribe() { if (!isSubscribed || current === CLEARED) return; isSubscribed = false; if (next === current) next = current.slice(); next.splice(next.indexOf(listener), 1); }; } }; } var Subscription = function () { function Subscription(store, parentSub) { _classCallCheck(this, Subscription); this.store = store; this.parentSub = parentSub; this.unsubscribe = null; this.listeners = nullListeners; } Subscription.prototype.addNestedSub = function addNestedSub(listener) { this.trySubscribe(); return this.listeners.subscribe(listener); }; Subscription.prototype.notifyNestedSubs = function notifyNestedSubs() { this.listeners.notify(); }; Subscription.prototype.isSubscribed = function isSubscribed() { return Boolean(this.unsubscribe); }; Subscription.prototype.trySubscribe = function trySubscribe() { if (!this.unsubscribe) { // this.onStateChange is set by connectAdvanced.initSubscription() this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.onStateChange) : this.store.subscribe(this.onStateChange); this.listeners = createListenerCollection(); } }; Subscription.prototype.tryUnsubscribe = function tryUnsubscribe() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; this.listeners.clear(); this.listeners = nullListeners; } }; return Subscription; }(); exports.default = Subscription; /***/ }, /* 273 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.createConnect = createConnect; var _connectAdvanced = __webpack_require__(269); var _connectAdvanced2 = _interopRequireDefault(_connectAdvanced); var _shallowEqual = __webpack_require__(274); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); var _mapDispatchToProps = __webpack_require__(275); var _mapDispatchToProps2 = _interopRequireDefault(_mapDispatchToProps); var _mapStateToProps = __webpack_require__(299); var _mapStateToProps2 = _interopRequireDefault(_mapStateToProps); var _mergeProps = __webpack_require__(300); var _mergeProps2 = _interopRequireDefault(_mergeProps); var _selectorFactory = __webpack_require__(301); var _selectorFactory2 = _interopRequireDefault(_selectorFactory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /* connect is a facade over connectAdvanced. It turns its args into a compatible selectorFactory, which has the signature: (dispatch, options) => (nextState, nextOwnProps) => nextFinalProps connect passes its args to connectAdvanced as options, which will in turn pass them to selectorFactory each time a Connect component instance is instantiated or hot reloaded. selectorFactory returns a final props selector from its mapStateToProps, mapStateToPropsFactories, mapDispatchToProps, mapDispatchToPropsFactories, mergeProps, mergePropsFactories, and pure args. The resulting final props selector is called by the Connect component instance whenever it receives new props or store state. */ function match(arg, factories, name) { for (var i = factories.length - 1; i >= 0; i--) { var result = factories[i](arg); if (result) return result; } return function (dispatch, options) { throw new Error('Invalid value of type ' + typeof arg + ' for ' + name + ' argument when connecting component ' + options.wrappedComponentName + '.'); }; } function strictEqual(a, b) { return a === b; } // createConnect with default args builds the 'official' connect behavior. Calling it with // different options opens up some testing and extensibility scenarios function createConnect() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$connectHOC = _ref.connectHOC, connectHOC = _ref$connectHOC === undefined ? _connectAdvanced2.default : _ref$connectHOC, _ref$mapStateToPropsF = _ref.mapStateToPropsFactories, mapStateToPropsFactories = _ref$mapStateToPropsF === undefined ? _mapStateToProps2.default : _ref$mapStateToPropsF, _ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories, mapDispatchToPropsFactories = _ref$mapDispatchToPro === undefined ? _mapDispatchToProps2.default : _ref$mapDispatchToPro, _ref$mergePropsFactor = _ref.mergePropsFactories, mergePropsFactories = _ref$mergePropsFactor === undefined ? _mergeProps2.default : _ref$mergePropsFactor, _ref$selectorFactory = _ref.selectorFactory, selectorFactory = _ref$selectorFactory === undefined ? _selectorFactory2.default : _ref$selectorFactory; return function connect(mapStateToProps, mapDispatchToProps, mergeProps) { var _ref2 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, _ref2$pure = _ref2.pure, pure = _ref2$pure === undefined ? true : _ref2$pure, _ref2$areStatesEqual = _ref2.areStatesEqual, areStatesEqual = _ref2$areStatesEqual === undefined ? strictEqual : _ref2$areStatesEqual, _ref2$areOwnPropsEqua = _ref2.areOwnPropsEqual, areOwnPropsEqual = _ref2$areOwnPropsEqua === undefined ? _shallowEqual2.default : _ref2$areOwnPropsEqua, _ref2$areStatePropsEq = _ref2.areStatePropsEqual, areStatePropsEqual = _ref2$areStatePropsEq === undefined ? _shallowEqual2.default : _ref2$areStatePropsEq, _ref2$areMergedPropsE = _ref2.areMergedPropsEqual, areMergedPropsEqual = _ref2$areMergedPropsE === undefined ? _shallowEqual2.default : _ref2$areMergedPropsE, extraOptions = _objectWithoutProperties(_ref2, ['pure', 'areStatesEqual', 'areOwnPropsEqual', 'areStatePropsEqual', 'areMergedPropsEqual']); var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps'); var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps'); var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps'); return connectHOC(selectorFactory, _extends({ // used in error messages methodName: 'connect', // used to compute Connect's displayName from the wrapped component's displayName. getDisplayName: function getDisplayName(name) { return 'Connect(' + name + ')'; }, // if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes shouldHandleStateChanges: Boolean(mapStateToProps), // passed through to selectorFactory initMapStateToProps: initMapStateToProps, initMapDispatchToProps: initMapDispatchToProps, initMergeProps: initMergeProps, pure: pure, areStatesEqual: areStatesEqual, areOwnPropsEqual: areOwnPropsEqual, areStatePropsEqual: areStatePropsEqual, areMergedPropsEqual: areMergedPropsEqual }, extraOptions)); }; } exports.default = createConnect(); /***/ }, /* 274 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports.default = shallowEqual; var hasOwn = Object.prototype.hasOwnProperty; function shallowEqual(a, b) { if (a === b) return true; var countA = 0; var countB = 0; for (var key in a) { if (hasOwn.call(a, key) && a[key] !== b[key]) return false; countA++; } for (var _key in b) { if (hasOwn.call(b, _key)) countB++; } return countA === countB; } /***/ }, /* 275 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.whenMapDispatchToPropsIsFunction = whenMapDispatchToPropsIsFunction; exports.whenMapDispatchToPropsIsMissing = whenMapDispatchToPropsIsMissing; exports.whenMapDispatchToPropsIsObject = whenMapDispatchToPropsIsObject; var _redux = __webpack_require__(276); var _wrapMapToProps = __webpack_require__(297); function whenMapDispatchToPropsIsFunction(mapDispatchToProps) { return typeof mapDispatchToProps === 'function' ? (0, _wrapMapToProps.wrapMapToPropsFunc)(mapDispatchToProps, 'mapDispatchToProps') : undefined; } function whenMapDispatchToPropsIsMissing(mapDispatchToProps) { return !mapDispatchToProps ? (0, _wrapMapToProps.wrapMapToPropsConstant)(function (dispatch) { return { dispatch: dispatch }; }) : undefined; } function whenMapDispatchToPropsIsObject(mapDispatchToProps) { return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? (0, _wrapMapToProps.wrapMapToPropsConstant)(function (dispatch) { return (0, _redux.bindActionCreators)(mapDispatchToProps, dispatch); }) : undefined; } exports.default = [whenMapDispatchToPropsIsFunction, whenMapDispatchToPropsIsMissing, whenMapDispatchToPropsIsObject]; /***/ }, /* 276 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(277); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(292); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(294); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(295); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(296); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(293); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (("development") !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /***/ }, /* 277 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(278); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(288); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 278 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(279), getPrototype = __webpack_require__(285), isObjectLike = __webpack_require__(287); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }, /* 279 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(280), getRawTag = __webpack_require__(283), objectToString = __webpack_require__(284); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }, /* 280 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(281); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 281 */ /***/ function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(282); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }, /* 282 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 283 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(280); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }, /* 284 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }, /* 285 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(286); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 286 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 287 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 288 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(289); /***/ }, /* 289 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, module) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(291); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root; /* global window */ if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof global !== 'undefined') { root = global; } else if (true) { root = module; } else { root = Function('return this')(); } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(290)(module))) /***/ }, /* 290 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 291 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }, /* 292 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(277); var _isPlainObject = __webpack_require__(278); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(293); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (true) { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (true) { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (true) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 293 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 294 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 295 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(296); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 296 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 297 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.wrapMapToPropsConstant = wrapMapToPropsConstant; exports.getDependsOnOwnProps = getDependsOnOwnProps; exports.wrapMapToPropsFunc = wrapMapToPropsFunc; var _verifyPlainObject = __webpack_require__(298); var _verifyPlainObject2 = _interopRequireDefault(_verifyPlainObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function wrapMapToPropsConstant(getConstant) { return function initConstantSelector(dispatch, options) { var constant = getConstant(dispatch, options); function constantSelector() { return constant; } constantSelector.dependsOnOwnProps = false; return constantSelector; }; } // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args // to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine // whether mapToProps needs to be invoked when props have changed. // // A length of one signals that mapToProps does not depend on props from the parent component. // A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and // therefore not reporting its length accurately.. function getDependsOnOwnProps(mapToProps) { return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1; } // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction, // this function wraps mapToProps in a proxy function which does several things: // // * Detects whether the mapToProps function being called depends on props, which // is used by selectorFactory to decide if it should reinvoke on props changes. // // * On first call, handles mapToProps if returns another function, and treats that // new function as the true mapToProps for subsequent calls. // // * On first call, verifies the first result is a plain object, in order to warn // the developer that their mapToProps function is not returning a valid result. // function wrapMapToPropsFunc(mapToProps, methodName) { return function initProxySelector(dispatch, _ref) { var displayName = _ref.displayName; var proxy = function mapToPropsProxy(stateOrDispatch, ownProps) { return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch); }; proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps); proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) { proxy.mapToProps = mapToProps; var props = proxy(stateOrDispatch, ownProps); if (typeof props === 'function') { proxy.mapToProps = props; proxy.dependsOnOwnProps = getDependsOnOwnProps(props); props = proxy(stateOrDispatch, ownProps); } if (true) (0, _verifyPlainObject2.default)(props, displayName, methodName); return props; }; return proxy; }; } /***/ }, /* 298 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = verifyPlainObject; var _isPlainObject = __webpack_require__(278); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(268); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function verifyPlainObject(value, displayName, methodName) { if (!(0, _isPlainObject2.default)(value)) { (0, _warning2.default)(methodName + '() in ' + displayName + ' must return a plain object. Instead received ' + value + '.'); } } /***/ }, /* 299 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.whenMapStateToPropsIsFunction = whenMapStateToPropsIsFunction; exports.whenMapStateToPropsIsMissing = whenMapStateToPropsIsMissing; var _wrapMapToProps = __webpack_require__(297); function whenMapStateToPropsIsFunction(mapStateToProps) { return typeof mapStateToProps === 'function' ? (0, _wrapMapToProps.wrapMapToPropsFunc)(mapStateToProps, 'mapStateToProps') : undefined; } function whenMapStateToPropsIsMissing(mapStateToProps) { return !mapStateToProps ? (0, _wrapMapToProps.wrapMapToPropsConstant)(function () { return {}; }) : undefined; } exports.default = [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing]; /***/ }, /* 300 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.defaultMergeProps = defaultMergeProps; exports.wrapMergePropsFunc = wrapMergePropsFunc; exports.whenMergePropsIsFunction = whenMergePropsIsFunction; exports.whenMergePropsIsOmitted = whenMergePropsIsOmitted; var _verifyPlainObject = __webpack_require__(298); var _verifyPlainObject2 = _interopRequireDefault(_verifyPlainObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function defaultMergeProps(stateProps, dispatchProps, ownProps) { return _extends({}, ownProps, stateProps, dispatchProps); } function wrapMergePropsFunc(mergeProps) { return function initMergePropsProxy(dispatch, _ref) { var displayName = _ref.displayName, pure = _ref.pure, areMergedPropsEqual = _ref.areMergedPropsEqual; var hasRunOnce = false; var mergedProps = void 0; return function mergePropsProxy(stateProps, dispatchProps, ownProps) { var nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps); if (hasRunOnce) { if (!pure || !areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps; } else { hasRunOnce = true; mergedProps = nextMergedProps; if (true) (0, _verifyPlainObject2.default)(mergedProps, displayName, 'mergeProps'); } return mergedProps; }; }; } function whenMergePropsIsFunction(mergeProps) { return typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : undefined; } function whenMergePropsIsOmitted(mergeProps) { return !mergeProps ? function () { return defaultMergeProps; } : undefined; } exports.default = [whenMergePropsIsFunction, whenMergePropsIsOmitted]; /***/ }, /* 301 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.impureFinalPropsSelectorFactory = impureFinalPropsSelectorFactory; exports.pureFinalPropsSelectorFactory = pureFinalPropsSelectorFactory; exports.default = finalPropsSelectorFactory; var _verifySubselectors = __webpack_require__(302); var _verifySubselectors2 = _interopRequireDefault(_verifySubselectors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function impureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch) { return function impureFinalPropsSelector(state, ownProps) { return mergeProps(mapStateToProps(state, ownProps), mapDispatchToProps(dispatch, ownProps), ownProps); }; } function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, _ref) { var areStatesEqual = _ref.areStatesEqual, areOwnPropsEqual = _ref.areOwnPropsEqual, areStatePropsEqual = _ref.areStatePropsEqual; var hasRunAtLeastOnce = false; var state = void 0; var ownProps = void 0; var stateProps = void 0; var dispatchProps = void 0; var mergedProps = void 0; function handleFirstCall(firstState, firstOwnProps) { state = firstState; ownProps = firstOwnProps; stateProps = mapStateToProps(state, ownProps); dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); hasRunAtLeastOnce = true; return mergedProps; } function handleNewPropsAndNewState() { stateProps = mapStateToProps(state, ownProps); if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleNewProps() { if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps); if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps); mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleNewState() { var nextStateProps = mapStateToProps(state, ownProps); var statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps); stateProps = nextStateProps; if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps); return mergedProps; } function handleSubsequentCalls(nextState, nextOwnProps) { var propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps); var stateChanged = !areStatesEqual(nextState, state); state = nextState; ownProps = nextOwnProps; if (propsChanged && stateChanged) return handleNewPropsAndNewState(); if (propsChanged) return handleNewProps(); if (stateChanged) return handleNewState(); return mergedProps; } return function pureFinalPropsSelector(nextState, nextOwnProps) { return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps); }; } // TODO: Add more comments // If pure is true, the selector returned by selectorFactory will memoize its results, // allowing connectAdvanced's shouldComponentUpdate to return false if final // props have not changed. If false, the selector will always return a new // object and shouldComponentUpdate will always return true. function finalPropsSelectorFactory(dispatch, _ref2) { var initMapStateToProps = _ref2.initMapStateToProps, initMapDispatchToProps = _ref2.initMapDispatchToProps, initMergeProps = _ref2.initMergeProps, options = _objectWithoutProperties(_ref2, ['initMapStateToProps', 'initMapDispatchToProps', 'initMergeProps']); var mapStateToProps = initMapStateToProps(dispatch, options); var mapDispatchToProps = initMapDispatchToProps(dispatch, options); var mergeProps = initMergeProps(dispatch, options); if (true) { (0, _verifySubselectors2.default)(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName); } var selectorFactory = options.pure ? pureFinalPropsSelectorFactory : impureFinalPropsSelectorFactory; return selectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options); } /***/ }, /* 302 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = verifySubselectors; var _warning = __webpack_require__(268); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function verify(selector, methodName, displayName) { if (!selector) { throw new Error('Unexpected value for ' + methodName + ' in ' + displayName + '.'); } else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') { if (!selector.hasOwnProperty('dependsOnOwnProps')) { (0, _warning2.default)('The selector for ' + methodName + ' of ' + displayName + ' did not specify a value for dependsOnOwnProps.'); } } } function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, displayName) { verify(mapStateToProps, 'mapStateToProps', displayName); verify(mapDispatchToProps, 'mapDispatchToProps', displayName); verify(mergeProps, 'mergeProps', displayName); } /***/ }, /* 303 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.createMemoryHistory = exports.hashHistory = exports.browserHistory = exports.applyRouterMiddleware = exports.formatPattern = exports.useRouterHistory = exports.match = exports.routerShape = exports.locationShape = exports.RouterContext = exports.createRoutes = exports.Route = exports.Redirect = exports.IndexRoute = exports.IndexRedirect = exports.withRouter = exports.IndexLink = exports.Link = exports.Router = undefined; var _RouteUtils = __webpack_require__(304); Object.defineProperty(exports, 'createRoutes', { enumerable: true, get: function get() { return _RouteUtils.createRoutes; } }); var _PropTypes = __webpack_require__(305); Object.defineProperty(exports, 'locationShape', { enumerable: true, get: function get() { return _PropTypes.locationShape; } }); Object.defineProperty(exports, 'routerShape', { enumerable: true, get: function get() { return _PropTypes.routerShape; } }); var _PatternUtils = __webpack_require__(306); Object.defineProperty(exports, 'formatPattern', { enumerable: true, get: function get() { return _PatternUtils.formatPattern; } }); var _Router2 = __webpack_require__(307); var _Router3 = _interopRequireDefault(_Router2); var _Link2 = __webpack_require__(323); var _Link3 = _interopRequireDefault(_Link2); var _IndexLink2 = __webpack_require__(324); var _IndexLink3 = _interopRequireDefault(_IndexLink2); var _withRouter2 = __webpack_require__(325); var _withRouter3 = _interopRequireDefault(_withRouter2); var _IndexRedirect2 = __webpack_require__(326); var _IndexRedirect3 = _interopRequireDefault(_IndexRedirect2); var _IndexRoute2 = __webpack_require__(328); var _IndexRoute3 = _interopRequireDefault(_IndexRoute2); var _Redirect2 = __webpack_require__(327); var _Redirect3 = _interopRequireDefault(_Redirect2); var _Route2 = __webpack_require__(329); var _Route3 = _interopRequireDefault(_Route2); var _RouterContext2 = __webpack_require__(319); var _RouterContext3 = _interopRequireDefault(_RouterContext2); var _match2 = __webpack_require__(330); var _match3 = _interopRequireDefault(_match2); var _useRouterHistory2 = __webpack_require__(343); var _useRouterHistory3 = _interopRequireDefault(_useRouterHistory2); var _applyRouterMiddleware2 = __webpack_require__(344); var _applyRouterMiddleware3 = _interopRequireDefault(_applyRouterMiddleware2); var _browserHistory2 = __webpack_require__(345); var _browserHistory3 = _interopRequireDefault(_browserHistory2); var _hashHistory2 = __webpack_require__(353); var _hashHistory3 = _interopRequireDefault(_hashHistory2); var _createMemoryHistory2 = __webpack_require__(332); var _createMemoryHistory3 = _interopRequireDefault(_createMemoryHistory2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.Router = _Router3.default; /* components */ exports.Link = _Link3.default; exports.IndexLink = _IndexLink3.default; exports.withRouter = _withRouter3.default; /* components (configuration) */ exports.IndexRedirect = _IndexRedirect3.default; exports.IndexRoute = _IndexRoute3.default; exports.Redirect = _Redirect3.default; exports.Route = _Route3.default; /* utils */ exports.RouterContext = _RouterContext3.default; exports.match = _match3.default; exports.useRouterHistory = _useRouterHistory3.default; exports.applyRouterMiddleware = _applyRouterMiddleware3.default; /* histories */ exports.browserHistory = _browserHistory3.default; exports.hashHistory = _hashHistory3.default; exports.createMemoryHistory = _createMemoryHistory3.default; /***/ }, /* 304 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.isReactChildren = isReactChildren; exports.createRouteFromReactElement = createRouteFromReactElement; exports.createRoutesFromReactChildren = createRoutesFromReactChildren; exports.createRoutes = createRoutes; var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isValidChild(object) { return object == null || _react2.default.isValidElement(object); } function isReactChildren(object) { return isValidChild(object) || Array.isArray(object) && object.every(isValidChild); } function createRoute(defaultProps, props) { return _extends({}, defaultProps, props); } function createRouteFromReactElement(element) { var type = element.type; var route = createRoute(type.defaultProps, element.props); if (route.children) { var childRoutes = createRoutesFromReactChildren(route.children, route); if (childRoutes.length) route.childRoutes = childRoutes; delete route.children; } return route; } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ function createRoutesFromReactChildren(children, parentRoute) { var routes = []; _react2.default.Children.forEach(children, function (element) { if (_react2.default.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute); if (route) routes.push(route); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (routes && !Array.isArray(routes)) { routes = [routes]; } return routes; } /***/ }, /* 305 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.locationShape = exports.routerShape = undefined; var _react = __webpack_require__(88); var func = _react.PropTypes.func, object = _react.PropTypes.object, shape = _react.PropTypes.shape, string = _react.PropTypes.string; var routerShape = exports.routerShape = shape({ push: func.isRequired, replace: func.isRequired, go: func.isRequired, goBack: func.isRequired, goForward: func.isRequired, setRouteLeaveHook: func.isRequired, isActive: func.isRequired }); var locationShape = exports.locationShape = shape({ pathname: string.isRequired, search: string.isRequired, state: object, action: string.isRequired, key: string }); /***/ }, /* 306 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compilePattern = compilePattern; exports.matchPattern = matchPattern; exports.getParamNames = getParamNames; exports.getParams = getParams; exports.formatPattern = formatPattern; var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function _compilePattern(pattern) { var regexpSource = ''; var paramNames = []; var tokens = []; var match = void 0, lastIndex = 0, matcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|\*\*|\*|\(|\)/g; while (match = matcher.exec(pattern)) { if (match.index !== lastIndex) { tokens.push(pattern.slice(lastIndex, match.index)); regexpSource += escapeRegExp(pattern.slice(lastIndex, match.index)); } if (match[1]) { regexpSource += '([^/]+)'; paramNames.push(match[1]); } else if (match[0] === '**') { regexpSource += '(.*)'; paramNames.push('splat'); } else if (match[0] === '*') { regexpSource += '(.*?)'; paramNames.push('splat'); } else if (match[0] === '(') { regexpSource += '(?:'; } else if (match[0] === ')') { regexpSource += ')?'; } tokens.push(match[0]); lastIndex = matcher.lastIndex; } if (lastIndex !== pattern.length) { tokens.push(pattern.slice(lastIndex, pattern.length)); regexpSource += escapeRegExp(pattern.slice(lastIndex, pattern.length)); } return { pattern: pattern, regexpSource: regexpSource, paramNames: paramNames, tokens: tokens }; } var CompiledPatternsCache = Object.create(null); function compilePattern(pattern) { if (!CompiledPatternsCache[pattern]) CompiledPatternsCache[pattern] = _compilePattern(pattern); return CompiledPatternsCache[pattern]; } /** * Attempts to match a pattern on the given pathname. Patterns may use * the following special characters: * * - :paramName Matches a URL segment up to the next /, ?, or #. The * captured string is considered a "param" * - () Wraps a segment of the URL that is optional * - * Consumes (non-greedy) all characters up to the next * character in the pattern, or to the end of the URL if * there is none * - ** Consumes (greedy) all characters up to the next character * in the pattern, or to the end of the URL if there is none * * The function calls callback(error, matched) when finished. * The return value is an object with the following properties: * * - remainingPathname * - paramNames * - paramValues */ function matchPattern(pattern, pathname) { // Ensure pattern starts with leading slash for consistency with pathname. if (pattern.charAt(0) !== '/') { pattern = '/' + pattern; } var _compilePattern2 = compilePattern(pattern), regexpSource = _compilePattern2.regexpSource, paramNames = _compilePattern2.paramNames, tokens = _compilePattern2.tokens; if (pattern.charAt(pattern.length - 1) !== '/') { regexpSource += '/?'; // Allow optional path separator at end. } // Special-case patterns like '*' for catch-all routes. if (tokens[tokens.length - 1] === '*') { regexpSource += '$'; } var match = pathname.match(new RegExp('^' + regexpSource, 'i')); if (match == null) { return null; } var matchedPath = match[0]; var remainingPathname = pathname.substr(matchedPath.length); if (remainingPathname) { // Require that the match ends at a path separator, if we didn't match // the full path, so any remaining pathname is a new path segment. if (matchedPath.charAt(matchedPath.length - 1) !== '/') { return null; } // If there is a remaining pathname, treat the path separator as part of // the remaining pathname for properly continuing the match. remainingPathname = '/' + remainingPathname; } return { remainingPathname: remainingPathname, paramNames: paramNames, paramValues: match.slice(1).map(function (v) { return v && decodeURIComponent(v); }) }; } function getParamNames(pattern) { return compilePattern(pattern).paramNames; } function getParams(pattern, pathname) { var match = matchPattern(pattern, pathname); if (!match) { return null; } var paramNames = match.paramNames, paramValues = match.paramValues; var params = {}; paramNames.forEach(function (paramName, index) { params[paramName] = paramValues[index]; }); return params; } /** * Returns a version of the given pattern with params interpolated. Throws * if there is a dynamic segment of the pattern for which there is no param. */ function formatPattern(pattern, params) { params = params || {}; var _compilePattern3 = compilePattern(pattern), tokens = _compilePattern3.tokens; var parenCount = 0, pathname = '', splatIndex = 0, parenHistory = []; var token = void 0, paramName = void 0, paramValue = void 0; for (var i = 0, len = tokens.length; i < len; ++i) { token = tokens[i]; if (token === '*' || token === '**') { paramValue = Array.isArray(params.splat) ? params.splat[splatIndex++] : params.splat; !(paramValue != null || parenCount > 0) ? true ? (0, _invariant2.default)(false, 'Missing splat #%s for path "%s"', splatIndex, pattern) : (0, _invariant2.default)(false) : void 0; if (paramValue != null) pathname += encodeURI(paramValue); } else if (token === '(') { parenHistory[parenCount] = ''; parenCount += 1; } else if (token === ')') { var parenText = parenHistory.pop(); parenCount -= 1; if (parenCount) parenHistory[parenCount - 1] += parenText;else pathname += parenText; } else if (token.charAt(0) === ':') { paramName = token.substring(1); paramValue = params[paramName]; !(paramValue != null || parenCount > 0) ? true ? (0, _invariant2.default)(false, 'Missing "%s" parameter for path "%s"', paramName, pattern) : (0, _invariant2.default)(false) : void 0; if (paramValue == null) { if (parenCount) { parenHistory[parenCount - 1] = ''; var curTokenIdx = tokens.indexOf(token); var tokensSubset = tokens.slice(curTokenIdx, tokens.length); var nextParenIdx = -1; for (var _i = 0; _i < tokensSubset.length; _i++) { if (tokensSubset[_i] == ')') { nextParenIdx = _i; break; } } !(nextParenIdx > 0) ? true ? (0, _invariant2.default)(false, 'Path "%s" is missing end paren at segment "%s"', pattern, tokensSubset.join('')) : (0, _invariant2.default)(false) : void 0; // jump to ending paren i = curTokenIdx + nextParenIdx - 1; } } else if (parenCount) parenHistory[parenCount - 1] += encodeURIComponent(paramValue);else pathname += encodeURIComponent(paramValue); } else { if (parenCount) parenHistory[parenCount - 1] += token;else pathname += token; } } !(parenCount <= 0) ? true ? (0, _invariant2.default)(false, 'Path "%s" is missing end paren', pattern) : (0, _invariant2.default)(false) : void 0; return pathname.replace(/\/+/g, '/'); } /***/ }, /* 307 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _createTransitionManager2 = __webpack_require__(308); var _createTransitionManager3 = _interopRequireDefault(_createTransitionManager2); var _InternalPropTypes = __webpack_require__(318); var _RouterContext = __webpack_require__(319); var _RouterContext2 = _interopRequireDefault(_RouterContext); var _RouteUtils = __webpack_require__(304); var _RouterUtils = __webpack_require__(322); var _routerWarning = __webpack_require__(309); var _routerWarning2 = _interopRequireDefault(_routerWarning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var _React$PropTypes = _react2.default.PropTypes, func = _React$PropTypes.func, object = _React$PropTypes.object; /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RouterContext> with all the props * it needs each time the URL changes. */ var Router = _react2.default.createClass({ displayName: 'Router', propTypes: { history: object, children: _InternalPropTypes.routes, routes: _InternalPropTypes.routes, // alias for children render: func, createElement: func, onError: func, onUpdate: func, // PRIVATE: For client-side rehydration of server match. matchContext: object }, getDefaultProps: function getDefaultProps() { return { render: function render(props) { return _react2.default.createElement(_RouterContext2.default, props); } }; }, getInitialState: function getInitialState() { return { location: null, routes: null, params: null, components: null }; }, handleError: function handleError(error) { if (this.props.onError) { this.props.onError.call(this, error); } else { // Throw errors by default so we don't silently swallow them! throw error; // This error probably occurred in getChildRoutes or getComponents. } }, createRouterObject: function createRouterObject(state) { var matchContext = this.props.matchContext; if (matchContext) { return matchContext.router; } var history = this.props.history; return (0, _RouterUtils.createRouterObject)(history, this.transitionManager, state); }, createTransitionManager: function createTransitionManager() { var matchContext = this.props.matchContext; if (matchContext) { return matchContext.transitionManager; } var history = this.props.history; var _props = this.props, routes = _props.routes, children = _props.children; !history.getCurrentLocation ? true ? (0, _invariant2.default)(false, 'You have provided a history object created with history v2.x or ' + 'earlier. This version of React Router is only compatible with v3 ' + 'history objects. Please upgrade to history v3.x.') : (0, _invariant2.default)(false) : void 0; return (0, _createTransitionManager3.default)(history, (0, _RouteUtils.createRoutes)(routes || children)); }, componentWillMount: function componentWillMount() { var _this = this; this.transitionManager = this.createTransitionManager(); this.router = this.createRouterObject(this.state); this._unlisten = this.transitionManager.listen(function (error, state) { if (error) { _this.handleError(error); } else { // Keep the identity of this.router because of a caveat in ContextUtils: // they only work if the object identity is preserved. (0, _RouterUtils.assignRouterState)(_this.router, state); _this.setState(state, _this.props.onUpdate); } }); }, /* istanbul ignore next: sanity check */ componentWillReceiveProps: function componentWillReceiveProps(nextProps) { true ? (0, _routerWarning2.default)(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : void 0; true ? (0, _routerWarning2.default)((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : void 0; }, componentWillUnmount: function componentWillUnmount() { if (this._unlisten) this._unlisten(); }, render: function render() { var _state = this.state, location = _state.location, routes = _state.routes, params = _state.params, components = _state.components; var _props2 = this.props, createElement = _props2.createElement, render = _props2.render, props = _objectWithoutProperties(_props2, ['createElement', 'render']); if (location == null) return null; // Async match // Only forward non-Router-specific props to routing context, as those are // the only ones that might be custom routing context props. Object.keys(Router.propTypes).forEach(function (propType) { return delete props[propType]; }); return render(_extends({}, props, { router: this.router, location: location, routes: routes, params: params, components: components, createElement: createElement })); } }); exports.default = Router; module.exports = exports['default']; /***/ }, /* 308 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = createTransitionManager; var _routerWarning = __webpack_require__(309); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _computeChangedRoutes2 = __webpack_require__(311); var _computeChangedRoutes3 = _interopRequireDefault(_computeChangedRoutes2); var _TransitionUtils = __webpack_require__(312); var _isActive2 = __webpack_require__(314); var _isActive3 = _interopRequireDefault(_isActive2); var _getComponents = __webpack_require__(315); var _getComponents2 = _interopRequireDefault(_getComponents); var _matchRoutes = __webpack_require__(317); var _matchRoutes2 = _interopRequireDefault(_matchRoutes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function hasAnyProperties(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return true; }return false; } function createTransitionManager(history, routes) { var state = {}; // Signature should be (location, indexOnly), but needs to support (path, // query, indexOnly) function isActive(location, indexOnly) { location = history.createLocation(location); return (0, _isActive3.default)(location, indexOnly, state.location, state.routes, state.params); } var partialNextState = void 0; function match(location, callback) { if (partialNextState && partialNextState.location === location) { // Continue from where we left off. finishMatch(partialNextState, callback); } else { (0, _matchRoutes2.default)(routes, location, function (error, nextState) { if (error) { callback(error); } else if (nextState) { finishMatch(_extends({}, nextState, { location: location }), callback); } else { callback(); } }); } } function finishMatch(nextState, callback) { var _computeChangedRoutes = (0, _computeChangedRoutes3.default)(state, nextState), leaveRoutes = _computeChangedRoutes.leaveRoutes, changeRoutes = _computeChangedRoutes.changeRoutes, enterRoutes = _computeChangedRoutes.enterRoutes; (0, _TransitionUtils.runLeaveHooks)(leaveRoutes, state); // Tear down confirmation hooks for left routes leaveRoutes.filter(function (route) { return enterRoutes.indexOf(route) === -1; }).forEach(removeListenBeforeHooksForRoute); // change and enter hooks are run in series (0, _TransitionUtils.runChangeHooks)(changeRoutes, state, nextState, function (error, redirectInfo) { if (error || redirectInfo) return handleErrorOrRedirect(error, redirectInfo); (0, _TransitionUtils.runEnterHooks)(enterRoutes, nextState, finishEnterHooks); }); function finishEnterHooks(error, redirectInfo) { if (error || redirectInfo) return handleErrorOrRedirect(error, redirectInfo); // TODO: Fetch components after state is updated. (0, _getComponents2.default)(nextState, function (error, components) { if (error) { callback(error); } else { // TODO: Make match a pure function and have some other API // for "match and update state". callback(null, null, state = _extends({}, nextState, { components: components })); } }); } function handleErrorOrRedirect(error, redirectInfo) { if (error) callback(error);else callback(null, redirectInfo); } } var RouteGuid = 1; function getRouteID(route) { var create = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return route.__id__ || create && (route.__id__ = RouteGuid++); } var RouteHooks = Object.create(null); function getRouteHooksForRoutes(routes) { return routes.map(function (route) { return RouteHooks[getRouteID(route)]; }).filter(function (hook) { return hook; }); } function transitionHook(location, callback) { (0, _matchRoutes2.default)(routes, location, function (error, nextState) { if (nextState == null) { // TODO: We didn't actually match anything, but hang // onto error/nextState so we don't have to matchRoutes // again in the listen callback. callback(); return; } // Cache some state here so we don't have to // matchRoutes() again in the listen callback. partialNextState = _extends({}, nextState, { location: location }); var hooks = getRouteHooksForRoutes((0, _computeChangedRoutes3.default)(state, partialNextState).leaveRoutes); var result = void 0; for (var i = 0, len = hooks.length; result == null && i < len; ++i) { // Passing the location arg here indicates to // the user that this is a transition hook. result = hooks[i](location); } callback(result); }); } /* istanbul ignore next: untestable with Karma */ function beforeUnloadHook() { // Synchronously check to see if any route hooks want // to prevent the current window/tab from closing. if (state.routes) { var hooks = getRouteHooksForRoutes(state.routes); var message = void 0; for (var i = 0, len = hooks.length; typeof message !== 'string' && i < len; ++i) { // Passing no args indicates to the user that this is a // beforeunload hook. We don't know the next location. message = hooks[i](); } return message; } } var unlistenBefore = void 0, unlistenBeforeUnload = void 0; function removeListenBeforeHooksForRoute(route) { var routeID = getRouteID(route); if (!routeID) { return; } delete RouteHooks[routeID]; if (!hasAnyProperties(RouteHooks)) { // teardown transition & beforeunload hooks if (unlistenBefore) { unlistenBefore(); unlistenBefore = null; } if (unlistenBeforeUnload) { unlistenBeforeUnload(); unlistenBeforeUnload = null; } } } /** * Registers the given hook function to run before leaving the given route. * * During a normal transition, the hook function receives the next location * as its only argument and can return either a prompt message (string) to show the user, * to make sure they want to leave the page; or `false`, to prevent the transition. * Any other return value will have no effect. * * During the beforeunload event (in browsers) the hook receives no arguments. * In this case it must return a prompt message to prevent the transition. * * Returns a function that may be used to unbind the listener. */ function listenBeforeLeavingRoute(route, hook) { var thereWereNoRouteHooks = !hasAnyProperties(RouteHooks); var routeID = getRouteID(route, true); RouteHooks[routeID] = hook; if (thereWereNoRouteHooks) { // setup transition & beforeunload hooks unlistenBefore = history.listenBefore(transitionHook); if (history.listenBeforeUnload) unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook); } return function () { removeListenBeforeHooksForRoute(route); }; } /** * This is the API for stateful environments. As the location * changes, we update state and call the listener. We can also * gracefully handle errors and redirects. */ function listen(listener) { function historyListener(location) { if (state.location === location) { listener(null, state); } else { match(location, function (error, redirectLocation, nextState) { if (error) { listener(error); } else if (redirectLocation) { history.replace(redirectLocation); } else if (nextState) { listener(null, nextState); } else { true ? (0, _routerWarning2.default)(false, 'Location "%s" did not match any routes', location.pathname + location.search + location.hash) : void 0; } }); } } // TODO: Only use a single history listener. Otherwise we'll end up with // multiple concurrent calls to match. // Set up the history listener first in case the initial match redirects. var unsubscribe = history.listen(historyListener); if (state.location) { // Picking up on a matchContext. listener(null, state); } else { historyListener(history.getCurrentLocation()); } return unsubscribe; } return { isActive: isActive, match: match, listenBeforeLeavingRoute: listenBeforeLeavingRoute, listen: listen }; } module.exports = exports['default']; /***/ }, /* 309 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = routerWarning; exports._resetWarned = _resetWarned; var _warning = __webpack_require__(310); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var warned = {}; function routerWarning(falseToWarn, message) { // Only issue deprecation warnings once. if (message.indexOf('deprecated') !== -1) { if (warned[message]) { return; } warned[message] = true; } message = '[react-router] ' + message; for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } _warning2.default.apply(undefined, [falseToWarn, message].concat(args)); } function _resetWarned() { warned = {}; } /***/ }, /* 310 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (true) { 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 (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }, /* 311 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _PatternUtils = __webpack_require__(306); function routeParamsChanged(route, prevState, nextState) { if (!route.path) return false; var paramNames = (0, _PatternUtils.getParamNames)(route.path); return paramNames.some(function (paramName) { return prevState.params[paramName] !== nextState.params[paramName]; }); } /** * Returns an object of { leaveRoutes, changeRoutes, enterRoutes } determined by * the change from prevState to nextState. We leave routes if either * 1) they are not in the next state or 2) they are in the next state * but their params have changed (i.e. /users/123 => /users/456). * * leaveRoutes are ordered starting at the leaf route of the tree * we're leaving up to the common parent route. enterRoutes are ordered * from the top of the tree we're entering down to the leaf route. * * changeRoutes are any routes that didn't leave or enter during * the transition. */ function computeChangedRoutes(prevState, nextState) { var prevRoutes = prevState && prevState.routes; var nextRoutes = nextState.routes; var leaveRoutes = void 0, changeRoutes = void 0, enterRoutes = void 0; if (prevRoutes) { (function () { var parentIsLeaving = false; leaveRoutes = prevRoutes.filter(function (route) { if (parentIsLeaving) { return true; } else { var isLeaving = nextRoutes.indexOf(route) === -1 || routeParamsChanged(route, prevState, nextState); if (isLeaving) parentIsLeaving = true; return isLeaving; } }); // onLeave hooks start at the leaf route. leaveRoutes.reverse(); enterRoutes = []; changeRoutes = []; nextRoutes.forEach(function (route) { var isNew = prevRoutes.indexOf(route) === -1; var paramsChanged = leaveRoutes.indexOf(route) !== -1; if (isNew || paramsChanged) enterRoutes.push(route);else changeRoutes.push(route); }); })(); } else { leaveRoutes = []; changeRoutes = []; enterRoutes = nextRoutes; } return { leaveRoutes: leaveRoutes, changeRoutes: changeRoutes, enterRoutes: enterRoutes }; } exports.default = computeChangedRoutes; module.exports = exports['default']; /***/ }, /* 312 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.runEnterHooks = runEnterHooks; exports.runChangeHooks = runChangeHooks; exports.runLeaveHooks = runLeaveHooks; var _AsyncUtils = __webpack_require__(313); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PendingHooks = function PendingHooks() { var _this = this; _classCallCheck(this, PendingHooks); this.hooks = []; this.add = function (hook) { return _this.hooks.push(hook); }; this.remove = function (hook) { return _this.hooks = _this.hooks.filter(function (h) { return h !== hook; }); }; this.has = function (hook) { return _this.hooks.indexOf(hook) !== -1; }; this.clear = function () { return _this.hooks = []; }; }; var enterHooks = new PendingHooks(); var changeHooks = new PendingHooks(); function createTransitionHook(hook, route, asyncArity, pendingHooks) { var isSync = hook.length < asyncArity; var transitionHook = function transitionHook() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } hook.apply(route, args); if (isSync) { var callback = args[args.length - 1]; // Assume hook executes synchronously and // automatically call the callback. callback(); } }; pendingHooks.add(transitionHook); return transitionHook; } function getEnterHooks(routes) { return routes.reduce(function (hooks, route) { if (route.onEnter) hooks.push(createTransitionHook(route.onEnter, route, 3, enterHooks)); return hooks; }, []); } function getChangeHooks(routes) { return routes.reduce(function (hooks, route) { if (route.onChange) hooks.push(createTransitionHook(route.onChange, route, 4, changeHooks)); return hooks; }, []); } function runTransitionHooks(length, iter, callback) { if (!length) { callback(); return; } var redirectInfo = void 0; function replace(location) { redirectInfo = location; } (0, _AsyncUtils.loopAsync)(length, function (index, next, done) { iter(index, replace, function (error) { if (error || redirectInfo) { done(error, redirectInfo); // No need to continue. } else { next(); } }); }, callback); } /** * Runs all onEnter hooks in the given array of routes in order * with onEnter(nextState, replace, callback) and calls * callback(error, redirectInfo) when finished. The first hook * to use replace short-circuits the loop. * * If a hook needs to run asynchronously, it may use the callback * function. However, doing so will cause the transition to pause, * which could lead to a non-responsive UI if the hook is slow. */ function runEnterHooks(routes, nextState, callback) { enterHooks.clear(); var hooks = getEnterHooks(routes); return runTransitionHooks(hooks.length, function (index, replace, next) { var wrappedNext = function wrappedNext() { if (enterHooks.has(hooks[index])) { next(); enterHooks.remove(hooks[index]); } }; hooks[index](nextState, replace, wrappedNext); }, callback); } /** * Runs all onChange hooks in the given array of routes in order * with onChange(prevState, nextState, replace, callback) and calls * callback(error, redirectInfo) when finished. The first hook * to use replace short-circuits the loop. * * If a hook needs to run asynchronously, it may use the callback * function. However, doing so will cause the transition to pause, * which could lead to a non-responsive UI if the hook is slow. */ function runChangeHooks(routes, state, nextState, callback) { changeHooks.clear(); var hooks = getChangeHooks(routes); return runTransitionHooks(hooks.length, function (index, replace, next) { var wrappedNext = function wrappedNext() { if (changeHooks.has(hooks[index])) { next(); changeHooks.remove(hooks[index]); } }; hooks[index](state, nextState, replace, wrappedNext); }, callback); } /** * Runs all onLeave hooks in the given array of routes in order. */ function runLeaveHooks(routes, prevState) { for (var i = 0, len = routes.length; i < len; ++i) { if (routes[i].onLeave) routes[i].onLeave.call(routes[i], prevState); } } /***/ }, /* 313 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports.loopAsync = loopAsync; exports.mapAsync = mapAsync; function loopAsync(turns, work, callback) { var currentTurn = 0, isDone = false; var sync = false, hasNext = false, doneArgs = void 0; function done() { isDone = true; if (sync) { // Iterate instead of recursing if possible. doneArgs = [].concat(Array.prototype.slice.call(arguments)); return; } callback.apply(this, arguments); } function next() { if (isDone) { return; } hasNext = true; if (sync) { // Iterate instead of recursing if possible. return; } sync = true; while (!isDone && currentTurn < turns && hasNext) { hasNext = false; work.call(this, currentTurn++, next, done); } sync = false; if (isDone) { // This means the loop finished synchronously. callback.apply(this, doneArgs); return; } if (currentTurn >= turns && hasNext) { isDone = true; callback(); } } next(); } function mapAsync(array, work, callback) { var length = array.length; var values = []; if (length === 0) return callback(null, values); var isDone = false, doneCount = 0; function done(index, error, value) { if (isDone) return; if (error) { isDone = true; callback(error); } else { values[index] = value; isDone = ++doneCount === length; if (isDone) callback(null, values); } } array.forEach(function (item, index) { work(item, index, function (error, value) { done(index, error, value); }); }); } /***/ }, /* 314 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = 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; }; exports.default = isActive; var _PatternUtils = __webpack_require__(306); function deepEqual(a, b) { if (a == b) return true; if (a == null || b == null) return false; if (Array.isArray(a)) { return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return deepEqual(item, b[index]); }); } if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') { for (var p in a) { if (!Object.prototype.hasOwnProperty.call(a, p)) { continue; } if (a[p] === undefined) { if (b[p] !== undefined) { return false; } } else if (!Object.prototype.hasOwnProperty.call(b, p)) { return false; } else if (!deepEqual(a[p], b[p])) { return false; } } return true; } return String(a) === String(b); } /** * Returns true if the current pathname matches the supplied one, net of * leading and trailing slash normalization. This is sufficient for an * indexOnly route match. */ function pathIsActive(pathname, currentPathname) { // Normalize leading slash for consistency. Leading slash on pathname has // already been normalized in isActive. See caveat there. if (currentPathname.charAt(0) !== '/') { currentPathname = '/' + currentPathname; } // Normalize the end of both path names too. Maybe `/foo/` shouldn't show // `/foo` as active, but in this case, we would already have failed the // match. if (pathname.charAt(pathname.length - 1) !== '/') { pathname += '/'; } if (currentPathname.charAt(currentPathname.length - 1) !== '/') { currentPathname += '/'; } return currentPathname === pathname; } /** * Returns true if the given pathname matches the active routes and params. */ function routeIsActive(pathname, routes, params) { var remainingPathname = pathname, paramNames = [], paramValues = []; // for...of would work here but it's probably slower post-transpilation. for (var i = 0, len = routes.length; i < len; ++i) { var route = routes[i]; var pattern = route.path || ''; if (pattern.charAt(0) === '/') { remainingPathname = pathname; paramNames = []; paramValues = []; } if (remainingPathname !== null && pattern) { var matched = (0, _PatternUtils.matchPattern)(pattern, remainingPathname); if (matched) { remainingPathname = matched.remainingPathname; paramNames = [].concat(paramNames, matched.paramNames); paramValues = [].concat(paramValues, matched.paramValues); } else { remainingPathname = null; } if (remainingPathname === '') { // We have an exact match on the route. Just check that all the params // match. // FIXME: This doesn't work on repeated params. return paramNames.every(function (paramName, index) { return String(paramValues[index]) === String(params[paramName]); }); } } } return false; } /** * Returns true if all key/value pairs in the given query are * currently active. */ function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null; if (query == null) return true; return deepEqual(query, activeQuery); } /** * Returns true if a <Link> to the given pathname/query combination is * currently active. */ function isActive(_ref, indexOnly, currentLocation, routes, params) { var pathname = _ref.pathname, query = _ref.query; if (currentLocation == null) return false; // TODO: This is a bit ugly. It keeps around support for treating pathnames // without preceding slashes as absolute paths, but possibly also works // around the same quirks with basenames as in matchRoutes. if (pathname.charAt(0) !== '/') { pathname = '/' + pathname; } if (!pathIsActive(pathname, currentLocation.pathname)) { // The path check is necessary and sufficient for indexOnly, but otherwise // we still need to check the routes. if (indexOnly || !routeIsActive(pathname, routes, params)) { return false; } } return queryIsActive(query, currentLocation.query); } module.exports = exports['default']; /***/ }, /* 315 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _AsyncUtils = __webpack_require__(313); var _PromiseUtils = __webpack_require__(316); function getComponentsForRoute(nextState, route, callback) { if (route.component || route.components) { callback(null, route.component || route.components); return; } var getComponent = route.getComponent || route.getComponents; if (getComponent) { var componentReturn = getComponent.call(route, nextState, callback); if ((0, _PromiseUtils.isPromise)(componentReturn)) componentReturn.then(function (component) { return callback(null, component); }, callback); } else { callback(); } } /** * Asynchronously fetches all components needed for the given router * state and calls callback(error, components) when finished. * * Note: This operation may finish synchronously if no routes have an * asynchronous getComponents method. */ function getComponents(nextState, callback) { (0, _AsyncUtils.mapAsync)(nextState.routes, function (route, index, callback) { getComponentsForRoute(nextState, route, callback); }, callback); } exports.default = getComponents; module.exports = exports['default']; /***/ }, /* 316 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.isPromise = isPromise; function isPromise(obj) { return obj && typeof obj.then === 'function'; } /***/ }, /* 317 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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; }; exports.default = matchRoutes; var _AsyncUtils = __webpack_require__(313); var _PromiseUtils = __webpack_require__(316); var _PatternUtils = __webpack_require__(306); var _routerWarning = __webpack_require__(309); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _RouteUtils = __webpack_require__(304); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getChildRoutes(route, location, paramNames, paramValues, callback) { if (route.childRoutes) { return [null, route.childRoutes]; } if (!route.getChildRoutes) { return []; } var sync = true, result = void 0; var partialNextState = { location: location, params: createParams(paramNames, paramValues) }; var childRoutesReturn = route.getChildRoutes(partialNextState, function (error, childRoutes) { childRoutes = !error && (0, _RouteUtils.createRoutes)(childRoutes); if (sync) { result = [error, childRoutes]; return; } callback(error, childRoutes); }); if ((0, _PromiseUtils.isPromise)(childRoutesReturn)) childRoutesReturn.then(function (childRoutes) { return callback(null, (0, _RouteUtils.createRoutes)(childRoutes)); }, callback); sync = false; return result; // Might be undefined. } function getIndexRoute(route, location, paramNames, paramValues, callback) { if (route.indexRoute) { callback(null, route.indexRoute); } else if (route.getIndexRoute) { var partialNextState = { location: location, params: createParams(paramNames, paramValues) }; var indexRoutesReturn = route.getIndexRoute(partialNextState, function (error, indexRoute) { callback(error, !error && (0, _RouteUtils.createRoutes)(indexRoute)[0]); }); if ((0, _PromiseUtils.isPromise)(indexRoutesReturn)) indexRoutesReturn.then(function (indexRoute) { return callback(null, (0, _RouteUtils.createRoutes)(indexRoute)[0]); }, callback); } else if (route.childRoutes) { (function () { var pathless = route.childRoutes.filter(function (childRoute) { return !childRoute.path; }); (0, _AsyncUtils.loopAsync)(pathless.length, function (index, next, done) { getIndexRoute(pathless[index], location, paramNames, paramValues, function (error, indexRoute) { if (error || indexRoute) { var routes = [pathless[index]].concat(Array.isArray(indexRoute) ? indexRoute : [indexRoute]); done(error, routes); } else { next(); } }); }, function (err, routes) { callback(null, routes); }); })(); } else { callback(); } } function assignParams(params, paramNames, paramValues) { return paramNames.reduce(function (params, paramName, index) { var paramValue = paramValues && paramValues[index]; if (Array.isArray(params[paramName])) { params[paramName].push(paramValue); } else if (paramName in params) { params[paramName] = [params[paramName], paramValue]; } else { params[paramName] = paramValue; } return params; }, params); } function createParams(paramNames, paramValues) { return assignParams({}, paramNames, paramValues); } function matchRouteDeep(route, location, remainingPathname, paramNames, paramValues, callback) { var pattern = route.path || ''; if (pattern.charAt(0) === '/') { remainingPathname = location.pathname; paramNames = []; paramValues = []; } // Only try to match the path if the route actually has a pattern, and if // we're not just searching for potential nested absolute paths. if (remainingPathname !== null && pattern) { try { var matched = (0, _PatternUtils.matchPattern)(pattern, remainingPathname); if (matched) { remainingPathname = matched.remainingPathname; paramNames = [].concat(paramNames, matched.paramNames); paramValues = [].concat(paramValues, matched.paramValues); } else { remainingPathname = null; } } catch (error) { callback(error); } // By assumption, pattern is non-empty here, which is the prerequisite for // actually terminating a match. if (remainingPathname === '') { var _ret2 = function () { var match = { routes: [route], params: createParams(paramNames, paramValues) }; getIndexRoute(route, location, paramNames, paramValues, function (error, indexRoute) { if (error) { callback(error); } else { if (Array.isArray(indexRoute)) { var _match$routes; true ? (0, _routerWarning2.default)(indexRoute.every(function (route) { return !route.path; }), 'Index routes should not have paths') : void 0; (_match$routes = match.routes).push.apply(_match$routes, indexRoute); } else if (indexRoute) { true ? (0, _routerWarning2.default)(!indexRoute.path, 'Index routes should not have paths') : void 0; match.routes.push(indexRoute); } callback(null, match); } }); return { v: void 0 }; }(); if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v; } } if (remainingPathname != null || route.childRoutes) { // Either a) this route matched at least some of the path or b) // we don't have to load this route's children asynchronously. In // either case continue checking for matches in the subtree. var onChildRoutes = function onChildRoutes(error, childRoutes) { if (error) { callback(error); } else if (childRoutes) { // Check the child routes to see if any of them match. matchRoutes(childRoutes, location, function (error, match) { if (error) { callback(error); } else if (match) { // A child route matched! Augment the match and pass it up the stack. match.routes.unshift(route); callback(null, match); } else { callback(); } }, remainingPathname, paramNames, paramValues); } else { callback(); } }; var result = getChildRoutes(route, location, paramNames, paramValues, onChildRoutes); if (result) { onChildRoutes.apply(undefined, result); } } else { callback(); } } /** * Asynchronously matches the given location to a set of routes and calls * callback(error, state) when finished. The state object will have the * following properties: * * - routes An array of routes that matched, in hierarchical order * - params An object of URL parameters * * Note: This operation may finish synchronously if no routes have an * asynchronous getChildRoutes method. */ function matchRoutes(routes, location, callback, remainingPathname) { var paramNames = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; var paramValues = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; if (remainingPathname === undefined) { // TODO: This is a little bit ugly, but it works around a quirk in history // that strips the leading slash from pathnames when using basenames with // trailing slashes. if (location.pathname.charAt(0) !== '/') { location = _extends({}, location, { pathname: '/' + location.pathname }); } remainingPathname = location.pathname; } (0, _AsyncUtils.loopAsync)(routes.length, function (index, next, done) { matchRouteDeep(routes[index], location, remainingPathname, paramNames, paramValues, function (error, match) { if (error || match) { done(error, match); } else { next(); } }); }, callback); } module.exports = exports['default']; /***/ }, /* 318 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.routes = exports.route = exports.components = exports.component = exports.history = undefined; exports.falsy = falsy; var _react = __webpack_require__(88); var func = _react.PropTypes.func, object = _react.PropTypes.object, arrayOf = _react.PropTypes.arrayOf, oneOfType = _react.PropTypes.oneOfType, element = _react.PropTypes.element, shape = _react.PropTypes.shape, string = _react.PropTypes.string; function falsy(props, propName, componentName) { if (props[propName]) return new Error('<' + componentName + '> should not have a "' + propName + '" prop'); } var history = exports.history = shape({ listen: func.isRequired, push: func.isRequired, replace: func.isRequired, go: func.isRequired, goBack: func.isRequired, goForward: func.isRequired }); var component = exports.component = oneOfType([func, string]); var components = exports.components = oneOfType([component, object]); var route = exports.route = oneOfType([object, element]); var routes = exports.routes = oneOfType([route, arrayOf(route)]); /***/ }, /* 319 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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 _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _getRouteParams = __webpack_require__(320); var _getRouteParams2 = _interopRequireDefault(_getRouteParams); var _ContextUtils = __webpack_require__(321); var _RouteUtils = __webpack_require__(304); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _React$PropTypes = _react2.default.PropTypes, array = _React$PropTypes.array, func = _React$PropTypes.func, object = _React$PropTypes.object; /** * A <RouterContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ var RouterContext = _react2.default.createClass({ displayName: 'RouterContext', mixins: [(0, _ContextUtils.ContextProvider)('router')], propTypes: { router: object.isRequired, location: object.isRequired, routes: array.isRequired, params: object.isRequired, components: array.isRequired, createElement: func.isRequired }, getDefaultProps: function getDefaultProps() { return { createElement: _react2.default.createElement }; }, childContextTypes: { router: object.isRequired }, getChildContext: function getChildContext() { return { router: this.props.router }; }, createElement: function createElement(component, props) { return component == null ? null : this.props.createElement(component, props); }, render: function render() { var _this = this; var _props = this.props, location = _props.location, routes = _props.routes, params = _props.params, components = _props.components, router = _props.router; var element = null; if (components) { element = components.reduceRight(function (element, components, index) { if (components == null) return element; // Don't create new children; use the grandchildren. var route = routes[index]; var routeParams = (0, _getRouteParams2.default)(route, params); var props = { location: location, params: params, route: route, router: router, routeParams: routeParams, routes: routes }; if ((0, _RouteUtils.isReactChildren)(element)) { props.children = element; } else if (element) { for (var prop in element) { if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop]; } } if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object') { var elements = {}; for (var key in components) { if (Object.prototype.hasOwnProperty.call(components, key)) { // Pass through the key as a prop to createElement to allow // custom createElement functions to know which named component // they're rendering, for e.g. matching up to fetched data. elements[key] = _this.createElement(components[key], _extends({ key: key }, props)); } } return elements; } return _this.createElement(components, props); }, element); } !(element === null || element === false || _react2.default.isValidElement(element)) ? true ? (0, _invariant2.default)(false, 'The root route must render a single element') : (0, _invariant2.default)(false) : void 0; return element; } }); exports.default = RouterContext; module.exports = exports['default']; /***/ }, /* 320 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _PatternUtils = __webpack_require__(306); /** * Extracts an object of params the given route cares about from * the given params object. */ function getRouteParams(route, params) { var routeParams = {}; if (!route.path) return routeParams; (0, _PatternUtils.getParamNames)(route.path).forEach(function (p) { if (Object.prototype.hasOwnProperty.call(params, p)) { routeParams[p] = params[p]; } }); return routeParams; } exports.default = getRouteParams; module.exports = exports['default']; /***/ }, /* 321 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ContextProvider = ContextProvider; exports.ContextSubscriber = ContextSubscriber; var _react = __webpack_require__(88); // Works around issues with context updates failing to propagate. // Caveat: the context value is expected to never change its identity. // https://github.com/facebook/react/issues/2517 // https://github.com/reactjs/react-router/issues/470 var contextProviderShape = _react.PropTypes.shape({ subscribe: _react.PropTypes.func.isRequired, eventIndex: _react.PropTypes.number.isRequired }); function makeContextName(name) { return '@@contextSubscriber/' + name; } function ContextProvider(name) { var _childContextTypes, _ref2; var contextName = makeContextName(name); var listenersKey = contextName + '/listeners'; var eventIndexKey = contextName + '/eventIndex'; var subscribeKey = contextName + '/subscribe'; return _ref2 = { childContextTypes: (_childContextTypes = {}, _childContextTypes[contextName] = contextProviderShape.isRequired, _childContextTypes), getChildContext: function getChildContext() { var _ref; return _ref = {}, _ref[contextName] = { eventIndex: this[eventIndexKey], subscribe: this[subscribeKey] }, _ref; }, componentWillMount: function componentWillMount() { this[listenersKey] = []; this[eventIndexKey] = 0; }, componentWillReceiveProps: function componentWillReceiveProps() { this[eventIndexKey]++; }, componentDidUpdate: function componentDidUpdate() { var _this = this; this[listenersKey].forEach(function (listener) { return listener(_this[eventIndexKey]); }); } }, _ref2[subscribeKey] = function (listener) { var _this2 = this; // No need to immediately call listener here. this[listenersKey].push(listener); return function () { _this2[listenersKey] = _this2[listenersKey].filter(function (item) { return item !== listener; }); }; }, _ref2; } function ContextSubscriber(name) { var _contextTypes, _ref4; var contextName = makeContextName(name); var lastRenderedEventIndexKey = contextName + '/lastRenderedEventIndex'; var handleContextUpdateKey = contextName + '/handleContextUpdate'; var unsubscribeKey = contextName + '/unsubscribe'; return _ref4 = { contextTypes: (_contextTypes = {}, _contextTypes[contextName] = contextProviderShape, _contextTypes), getInitialState: function getInitialState() { var _ref3; if (!this.context[contextName]) { return {}; } return _ref3 = {}, _ref3[lastRenderedEventIndexKey] = this.context[contextName].eventIndex, _ref3; }, componentDidMount: function componentDidMount() { if (!this.context[contextName]) { return; } this[unsubscribeKey] = this.context[contextName].subscribe(this[handleContextUpdateKey]); }, componentWillReceiveProps: function componentWillReceiveProps() { var _setState; if (!this.context[contextName]) { return; } this.setState((_setState = {}, _setState[lastRenderedEventIndexKey] = this.context[contextName].eventIndex, _setState)); }, componentWillUnmount: function componentWillUnmount() { if (!this[unsubscribeKey]) { return; } this[unsubscribeKey](); this[unsubscribeKey] = null; } }, _ref4[handleContextUpdateKey] = function (eventIndex) { if (eventIndex !== this.state[lastRenderedEventIndexKey]) { var _setState2; this.setState((_setState2 = {}, _setState2[lastRenderedEventIndexKey] = eventIndex, _setState2)); } }, _ref4; } /***/ }, /* 322 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.createRouterObject = createRouterObject; exports.assignRouterState = assignRouterState; function createRouterObject(history, transitionManager, state) { var router = _extends({}, history, { setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute, isActive: transitionManager.isActive }); return assignRouterState(router, state); } function assignRouterState(router, _ref) { var location = _ref.location, params = _ref.params, routes = _ref.routes; router.location = location; router.params = params; router.routes = routes; return router; } /***/ }, /* 323 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _PropTypes = __webpack_require__(305); var _ContextUtils = __webpack_require__(321); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var _React$PropTypes = _react2.default.PropTypes, bool = _React$PropTypes.bool, object = _React$PropTypes.object, string = _React$PropTypes.string, func = _React$PropTypes.func, oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function resolveToLocation(to, router) { return typeof to === 'function' ? to(router.location) : to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = _react2.default.createClass({ displayName: 'Link', mixins: [(0, _ContextUtils.ContextSubscriber)('router')], contextTypes: { router: _PropTypes.routerShape }, propTypes: { to: oneOfType([string, object, func]), query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; var router = this.context.router; !router ? true ? (0, _invariant2.default)(false, '<Link>s rendered outside of a router context cannot navigate.') : (0, _invariant2.default)(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); router.push(resolveToLocation(this.props.to, router)); }, render: function render() { var _props = this.props, to = _props.to, activeClassName = _props.activeClassName, activeStyle = _props.activeStyle, onlyActiveOnIndex = _props.onlyActiveOnIndex, props = _objectWithoutProperties(_props, ['to', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); // Ignore if rendered outside the context of router to simplify unit testing. var router = this.context.router; if (router) { // If user does not specify a `to` prop, return an empty anchor tag. if (to == null) { return _react2.default.createElement('a', props); } var toLocation = resolveToLocation(to, router); props.href = router.createHref(toLocation); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(toLocation, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return _react2.default.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); exports.default = Link; module.exports = exports['default']; /***/ }, /* 324 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _Link = __webpack_require__(323); var _Link2 = _interopRequireDefault(_Link); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = _react2.default.createClass({ displayName: 'IndexLink', render: function render() { return _react2.default.createElement(_Link2.default, _extends({}, this.props, { onlyActiveOnIndex: true })); } }); exports.default = IndexLink; module.exports = exports['default']; /***/ }, /* 325 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = withRouter; var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _hoistNonReactStatics = __webpack_require__(270); var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics); var _ContextUtils = __webpack_require__(321); var _PropTypes = __webpack_require__(305); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = _react2.default.createClass({ displayName: 'WithRouter', mixins: [(0, _ContextUtils.ContextSubscriber)('router')], contextTypes: { router: _PropTypes.routerShape }, propTypes: { router: _PropTypes.routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? true ? (0, _invariant2.default)(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : (0, _invariant2.default)(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; var params = router.params, location = router.location, routes = router.routes; var props = _extends({}, this.props, { router: router, params: params, location: location, routes: routes }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return _react2.default.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return (0, _hoistNonReactStatics2.default)(WithRouter, WrappedComponent); } module.exports = exports['default']; /***/ }, /* 326 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _routerWarning = __webpack_require__(309); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _Redirect = __webpack_require__(327); var _Redirect2 = _interopRequireDefault(_Redirect); var _InternalPropTypes = __webpack_require__(318); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _React$PropTypes = _react2.default.PropTypes, string = _React$PropTypes.string, object = _React$PropTypes.object; /** * An <IndexRedirect> is used to redirect from an indexRoute. */ /* eslint-disable react/require-render-return */ var IndexRedirect = _react2.default.createClass({ displayName: 'IndexRedirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _Redirect2.default.createRouteFromReactElement(element); } else { true ? (0, _routerWarning2.default)(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0; } } }, propTypes: { to: string.isRequired, query: object, state: object, onEnter: _InternalPropTypes.falsy, children: _InternalPropTypes.falsy }, /* istanbul ignore next: sanity check */ render: function render() { true ? true ? (0, _invariant2.default)(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : (0, _invariant2.default)(false) : void 0; } }); exports.default = IndexRedirect; module.exports = exports['default']; /***/ }, /* 327 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _RouteUtils = __webpack_require__(304); var _PatternUtils = __webpack_require__(306); var _InternalPropTypes = __webpack_require__(318); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _React$PropTypes = _react2.default.PropTypes, string = _React$PropTypes.string, object = _React$PropTypes.object; /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ /* eslint-disable react/require-render-return */ var Redirect = _react2.default.createClass({ displayName: 'Redirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element) { var route = (0, _RouteUtils.createRouteFromReactElement)(element); if (route.from) route.path = route.from; route.onEnter = function (nextState, replace) { var location = nextState.location, params = nextState.params; var pathname = void 0; if (route.to.charAt(0) === '/') { pathname = (0, _PatternUtils.formatPattern)(route.to, params); } else if (!route.to) { pathname = location.pathname; } else { var routeIndex = nextState.routes.indexOf(route); var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1); var pattern = parentPattern.replace(/\/*$/, '/') + route.to; pathname = (0, _PatternUtils.formatPattern)(pattern, params); } replace({ pathname: pathname, query: route.query || location.query, state: route.state || location.state }); }; return route; }, getRoutePattern: function getRoutePattern(routes, routeIndex) { var parentPattern = ''; for (var i = routeIndex; i >= 0; i--) { var route = routes[i]; var pattern = route.path || ''; parentPattern = pattern.replace(/\/*$/, '/') + parentPattern; if (pattern.indexOf('/') === 0) break; } return '/' + parentPattern; } }, propTypes: { path: string, from: string, // Alias for path to: string.isRequired, query: object, state: object, onEnter: _InternalPropTypes.falsy, children: _InternalPropTypes.falsy }, /* istanbul ignore next: sanity check */ render: function render() { true ? true ? (0, _invariant2.default)(false, '<Redirect> elements are for router configuration only and should not be rendered') : (0, _invariant2.default)(false) : void 0; } }); exports.default = Redirect; module.exports = exports['default']; /***/ }, /* 328 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _routerWarning = __webpack_require__(309); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _RouteUtils = __webpack_require__(304); var _InternalPropTypes = __webpack_require__(318); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var func = _react2.default.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ /* eslint-disable react/require-render-return */ var IndexRoute = _react2.default.createClass({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = (0, _RouteUtils.createRouteFromReactElement)(element); } else { true ? (0, _routerWarning2.default)(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0; } } }, propTypes: { path: _InternalPropTypes.falsy, component: _InternalPropTypes.component, components: _InternalPropTypes.components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { true ? true ? (0, _invariant2.default)(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : (0, _invariant2.default)(false) : void 0; } }); exports.default = IndexRoute; module.exports = exports['default']; /***/ }, /* 329 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _RouteUtils = __webpack_require__(304); var _InternalPropTypes = __webpack_require__(318); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _React$PropTypes = _react2.default.PropTypes, string = _React$PropTypes.string, func = _React$PropTypes.func; /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ /* eslint-disable react/require-render-return */ var Route = _react2.default.createClass({ displayName: 'Route', statics: { createRouteFromReactElement: _RouteUtils.createRouteFromReactElement }, propTypes: { path: string, component: _InternalPropTypes.component, components: _InternalPropTypes.components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { true ? true ? (0, _invariant2.default)(false, '<Route> elements are for router configuration only and should not be rendered') : (0, _invariant2.default)(false) : void 0; } }); exports.default = Route; module.exports = exports['default']; /***/ }, /* 330 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _Actions = __webpack_require__(331); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _createMemoryHistory = __webpack_require__(332); var _createMemoryHistory2 = _interopRequireDefault(_createMemoryHistory); var _createTransitionManager = __webpack_require__(308); var _createTransitionManager2 = _interopRequireDefault(_createTransitionManager); var _RouteUtils = __webpack_require__(304); var _RouterUtils = __webpack_require__(322); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /** * A high-level API to be used for server-side rendering. * * This function matches a location to a set of routes and calls * callback(error, redirectLocation, renderProps) when finished. * * Note: You probably don't want to use this in a browser unless you're using * server-side rendering with async routes. */ function match(_ref, callback) { var history = _ref.history, routes = _ref.routes, location = _ref.location, options = _objectWithoutProperties(_ref, ['history', 'routes', 'location']); !(history || location) ? true ? (0, _invariant2.default)(false, 'match needs a history or a location') : (0, _invariant2.default)(false) : void 0; history = history ? history : (0, _createMemoryHistory2.default)(options); var transitionManager = (0, _createTransitionManager2.default)(history, (0, _RouteUtils.createRoutes)(routes)); if (location) { // Allow match({ location: '/the/path', ... }) location = history.createLocation(location); } else { location = history.getCurrentLocation(); } transitionManager.match(location, function (error, redirectLocation, nextState) { var renderProps = void 0; if (nextState) { var router = (0, _RouterUtils.createRouterObject)(history, transitionManager, nextState); renderProps = _extends({}, nextState, { router: router, matchContext: { transitionManager: transitionManager, router: router } }); } callback(error, redirectLocation && history.createLocation(redirectLocation, _Actions.REPLACE), renderProps); }); } exports.default = match; module.exports = exports['default']; /***/ }, /* 331 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; /** * Indicates that navigation was caused by a call to history.push. */ var PUSH = exports.PUSH = 'PUSH'; /** * Indicates that navigation was caused by a call to history.replace. */ var REPLACE = exports.REPLACE = 'REPLACE'; /** * Indicates that navigation was caused by some other action such * as using a browser's back/forward buttons and/or manually manipulating * the URL in a browser's location bar. This is the default. * * See https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate * for more information. */ var POP = exports.POP = 'POP'; /***/ }, /* 332 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = createMemoryHistory; var _useQueries = __webpack_require__(333); var _useQueries2 = _interopRequireDefault(_useQueries); var _useBasename = __webpack_require__(339); var _useBasename2 = _interopRequireDefault(_useBasename); var _createMemoryHistory = __webpack_require__(340); var _createMemoryHistory2 = _interopRequireDefault(_createMemoryHistory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createMemoryHistory(options) { // signatures and type checking differ between `useQueries` and // `createMemoryHistory`, have to create `memoryHistory` first because // `useQueries` doesn't understand the signature var memoryHistory = (0, _createMemoryHistory2.default)(options); var createHistory = function createHistory() { return memoryHistory; }; var history = (0, _useQueries2.default)((0, _useBasename2.default)(createHistory))(options); return history; } module.exports = exports['default']; /***/ }, /* 333 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _queryString = __webpack_require__(334); var _runTransitionHook = __webpack_require__(336); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _LocationUtils = __webpack_require__(337); var _PathUtils = __webpack_require__(338); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultStringifyQuery = function defaultStringifyQuery(query) { return (0, _queryString.stringify)(query).replace(/%20/g, '+'); }; var defaultParseQueryString = _queryString.parse; /** * Returns a new createHistory function that may be used to create * history objects that know how to handle URL queries. */ var useQueries = function useQueries(createHistory) { return function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var history = createHistory(options); var stringifyQuery = options.stringifyQuery; var parseQueryString = options.parseQueryString; if (typeof stringifyQuery !== 'function') stringifyQuery = defaultStringifyQuery; if (typeof parseQueryString !== 'function') parseQueryString = defaultParseQueryString; var decodeQuery = function decodeQuery(location) { if (!location) return location; if (location.query == null) location.query = parseQueryString(location.search.substring(1)); return location; }; var encodeQuery = function encodeQuery(location, query) { if (query == null) return location; var object = typeof location === 'string' ? (0, _PathUtils.parsePath)(location) : location; var queryString = stringifyQuery(query); var search = queryString ? '?' + queryString : ''; return _extends({}, object, { search: search }); }; // Override all read methods with query-aware versions. var getCurrentLocation = function getCurrentLocation() { return decodeQuery(history.getCurrentLocation()); }; var listenBefore = function listenBefore(hook) { return history.listenBefore(function (location, callback) { return (0, _runTransitionHook2.default)(hook, decodeQuery(location), callback); }); }; var listen = function listen(listener) { return history.listen(function (location) { return listener(decodeQuery(location)); }); }; // Override all write methods with query-aware versions. var push = function push(location) { return history.push(encodeQuery(location, location.query)); }; var replace = function replace(location) { return history.replace(encodeQuery(location, location.query)); }; var createPath = function createPath(location) { return history.createPath(encodeQuery(location, location.query)); }; var createHref = function createHref(location) { return history.createHref(encodeQuery(location, location.query)); }; var createLocation = function createLocation(location) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var newLocation = history.createLocation.apply(history, [encodeQuery(location, location.query)].concat(args)); if (location.query) newLocation.query = (0, _LocationUtils.createQuery)(location.query); return decodeQuery(newLocation); }; return _extends({}, history, { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, push: push, replace: replace, createPath: createPath, createHref: createHref, createLocation: createLocation }); }; }; exports.default = useQueries; /***/ }, /* 334 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strictUriEncode = __webpack_require__(335); var objectAssign = __webpack_require__(90); function encode(value, opts) { if (opts.encode) { return opts.strict ? strictUriEncode(value) : encodeURIComponent(value); } return value; } exports.extract = function (str) { return str.split('?')[1] || ''; }; exports.parse = function (str) { // Create an object with no prototype // https://github.com/sindresorhus/query-string/issues/47 var ret = Object.create(null); if (typeof str !== 'string') { return ret; } str = str.trim().replace(/^(\?|#|&)/, ''); if (!str) { return ret; } str.split('&').forEach(function (param) { var parts = param.replace(/\+/g, ' ').split('='); // Firefox (pre 40) decodes `%3D` to `=` // https://github.com/sindresorhus/query-string/pull/37 var key = parts.shift(); var val = parts.length > 0 ? parts.join('=') : undefined; key = decodeURIComponent(key); // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeURIComponent(val); if (ret[key] === undefined) { ret[key] = val; } else if (Array.isArray(ret[key])) { ret[key].push(val); } else { ret[key] = [ret[key], val]; } }); return ret; }; exports.stringify = function (obj, opts) { var defaults = { encode: true, strict: true }; opts = objectAssign(defaults, opts); return obj ? Object.keys(obj).sort().map(function (key) { var val = obj[key]; if (val === undefined) { return ''; } if (val === null) { return encode(key, opts); } if (Array.isArray(val)) { var result = []; val.slice().forEach(function (val2) { if (val2 === undefined) { return; } if (val2 === null) { result.push(encode(key, opts)); } else { result.push(encode(key, opts) + '=' + encode(val2, opts)); } }); return result.join('&'); } return encode(key, opts) + '=' + encode(val, opts); }).filter(function (x) { return x.length > 0; }).join('&') : ''; }; /***/ }, /* 335 */ /***/ function(module, exports) { 'use strict'; module.exports = function (str) { return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); }; /***/ }, /* 336 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _warning = __webpack_require__(310); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var runTransitionHook = function runTransitionHook(hook, location, callback) { var result = hook(location, callback); if (hook.length < 2) { // Assume the hook runs synchronously and automatically // call the callback with the return value. callback(result); } else { true ? (0, _warning2.default)(result === undefined, 'You should not "return" in a transition hook with a callback argument; ' + 'call the callback instead') : void 0; } }; exports.default = runTransitionHook; /***/ }, /* 337 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.locationsAreEqual = exports.statesAreEqual = exports.createLocation = exports.createQuery = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _warning = __webpack_require__(310); var _warning2 = _interopRequireDefault(_warning); var _PathUtils = __webpack_require__(338); var _Actions = __webpack_require__(331); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createQuery = exports.createQuery = function createQuery(props) { return _extends(Object.create(null), props); }; var createLocation = exports.createLocation = function createLocation() { var input = arguments.length <= 0 || arguments[0] === undefined ? '/' : arguments[0]; var action = arguments.length <= 1 || arguments[1] === undefined ? _Actions.POP : arguments[1]; var key = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; var object = typeof input === 'string' ? (0, _PathUtils.parsePath)(input) : input; true ? (0, _warning2.default)(!object.path, 'Location descriptor objects should have a `pathname`, not a `path`.') : void 0; var pathname = object.pathname || '/'; var search = object.search || ''; var hash = object.hash || ''; var state = object.state; return { pathname: pathname, search: search, hash: hash, state: state, action: action, key: key }; }; var isDate = function isDate(object) { return Object.prototype.toString.call(object) === '[object Date]'; }; var statesAreEqual = exports.statesAreEqual = function statesAreEqual(a, b) { if (a === b) return true; var typeofA = typeof a === 'undefined' ? 'undefined' : _typeof(a); var typeofB = typeof b === 'undefined' ? 'undefined' : _typeof(b); if (typeofA !== typeofB) return false; !(typeofA !== 'function') ? true ? (0, _invariant2.default)(false, 'You must not store functions in location state') : (0, _invariant2.default)(false) : void 0; // Not the same object, but same type. if (typeofA === 'object') { !!(isDate(a) && isDate(b)) ? true ? (0, _invariant2.default)(false, 'You must not store Date objects in location state') : (0, _invariant2.default)(false) : void 0; if (!Array.isArray(a)) { var keysofA = Object.keys(a); var keysofB = Object.keys(b); return keysofA.length === keysofB.length && keysofA.every(function (key) { return statesAreEqual(a[key], b[key]); }); } return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return statesAreEqual(item, b[index]); }); } // All other serializable types (string, number, boolean) // should be strict equal. return false; }; var locationsAreEqual = exports.locationsAreEqual = function locationsAreEqual(a, b) { return a.key === b.key && // a.action === b.action && // Different action !== location change. a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && statesAreEqual(a.state, b.state); }; /***/ }, /* 338 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.createPath = exports.parsePath = exports.getQueryStringValueFromPath = exports.stripQueryStringValueFromPath = exports.addQueryStringValueToPath = undefined; var _warning = __webpack_require__(310); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var addQueryStringValueToPath = exports.addQueryStringValueToPath = function addQueryStringValueToPath(path, key, value) { var _parsePath = parsePath(path); var pathname = _parsePath.pathname; var search = _parsePath.search; var hash = _parsePath.hash; return createPath({ pathname: pathname, search: search + (search.indexOf('?') === -1 ? '?' : '&') + key + '=' + value, hash: hash }); }; var stripQueryStringValueFromPath = exports.stripQueryStringValueFromPath = function stripQueryStringValueFromPath(path, key) { var _parsePath2 = parsePath(path); var pathname = _parsePath2.pathname; var search = _parsePath2.search; var hash = _parsePath2.hash; return createPath({ pathname: pathname, search: search.replace(new RegExp('([?&])' + key + '=[a-zA-Z0-9]+(&?)'), function (match, prefix, suffix) { return prefix === '?' ? prefix : suffix; }), hash: hash }); }; var getQueryStringValueFromPath = exports.getQueryStringValueFromPath = function getQueryStringValueFromPath(path, key) { var _parsePath3 = parsePath(path); var search = _parsePath3.search; var match = search.match(new RegExp('[?&]' + key + '=([a-zA-Z0-9]+)')); return match && match[1]; }; var extractPath = function extractPath(string) { var match = string.match(/^(https?:)?\/\/[^\/]*/); return match == null ? string : string.substring(match[0].length); }; var parsePath = exports.parsePath = function parsePath(path) { var pathname = extractPath(path); var search = ''; var hash = ''; true ? (0, _warning2.default)(path === pathname, 'A path must be pathname + search + hash only, not a full URL like "%s"', path) : void 0; var hashIndex = pathname.indexOf('#'); if (hashIndex !== -1) { hash = pathname.substring(hashIndex); pathname = pathname.substring(0, hashIndex); } var searchIndex = pathname.indexOf('?'); if (searchIndex !== -1) { search = pathname.substring(searchIndex); pathname = pathname.substring(0, searchIndex); } if (pathname === '') pathname = '/'; return { pathname: pathname, search: search, hash: hash }; }; var createPath = exports.createPath = function createPath(location) { if (location == null || typeof location === 'string') return location; var basename = location.basename; var pathname = location.pathname; var search = location.search; var hash = location.hash; var path = (basename || '') + pathname; if (search && search !== '?') path += search; if (hash) path += hash; return path; }; /***/ }, /* 339 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _runTransitionHook = __webpack_require__(336); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _PathUtils = __webpack_require__(338); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var useBasename = function useBasename(createHistory) { return function () { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var history = createHistory(options); var basename = options.basename; var addBasename = function addBasename(location) { if (!location) return location; if (basename && location.basename == null) { if (location.pathname.indexOf(basename) === 0) { location.pathname = location.pathname.substring(basename.length); location.basename = basename; if (location.pathname === '') location.pathname = '/'; } else { location.basename = ''; } } return location; }; var prependBasename = function prependBasename(location) { if (!basename) return location; var object = typeof location === 'string' ? (0, _PathUtils.parsePath)(location) : location; var pname = object.pathname; var normalizedBasename = basename.slice(-1) === '/' ? basename : basename + '/'; var normalizedPathname = pname.charAt(0) === '/' ? pname.slice(1) : pname; var pathname = normalizedBasename + normalizedPathname; return _extends({}, object, { pathname: pathname }); }; // Override all read methods with basename-aware versions. var getCurrentLocation = function getCurrentLocation() { return addBasename(history.getCurrentLocation()); }; var listenBefore = function listenBefore(hook) { return history.listenBefore(function (location, callback) { return (0, _runTransitionHook2.default)(hook, addBasename(location), callback); }); }; var listen = function listen(listener) { return history.listen(function (location) { return listener(addBasename(location)); }); }; // Override all write methods with basename-aware versions. var push = function push(location) { return history.push(prependBasename(location)); }; var replace = function replace(location) { return history.replace(prependBasename(location)); }; var createPath = function createPath(location) { return history.createPath(prependBasename(location)); }; var createHref = function createHref(location) { return history.createHref(prependBasename(location)); }; var createLocation = function createLocation(location) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return addBasename(history.createLocation.apply(history, [prependBasename(location)].concat(args))); }; return _extends({}, history, { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, push: push, replace: replace, createPath: createPath, createHref: createHref, createLocation: createLocation }); }; }; exports.default = useBasename; /***/ }, /* 340 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _warning = __webpack_require__(310); var _warning2 = _interopRequireDefault(_warning); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _LocationUtils = __webpack_require__(337); var _PathUtils = __webpack_require__(338); var _createHistory = __webpack_require__(341); var _createHistory2 = _interopRequireDefault(_createHistory); var _Actions = __webpack_require__(331); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createStateStorage = function createStateStorage(entries) { return entries.filter(function (entry) { return entry.state; }).reduce(function (memo, entry) { memo[entry.key] = entry.state; return memo; }, {}); }; var createMemoryHistory = function createMemoryHistory() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (Array.isArray(options)) { options = { entries: options }; } else if (typeof options === 'string') { options = { entries: [options] }; } var getCurrentLocation = function getCurrentLocation() { var entry = entries[current]; var path = (0, _PathUtils.createPath)(entry); var key = void 0, state = void 0; if (entry.key) { key = entry.key; state = readState(key); } var init = (0, _PathUtils.parsePath)(path); return (0, _LocationUtils.createLocation)(_extends({}, init, { state: state }), undefined, key); }; var canGo = function canGo(n) { var index = current + n; return index >= 0 && index < entries.length; }; var go = function go(n) { if (!n) return; if (!canGo(n)) { true ? (0, _warning2.default)(false, 'Cannot go(%s) there is not enough history', n) : void 0; return; } current += n; var currentLocation = getCurrentLocation(); // Change action to POP history.transitionTo(_extends({}, currentLocation, { action: _Actions.POP })); }; var pushLocation = function pushLocation(location) { current += 1; if (current < entries.length) entries.splice(current); entries.push(location); saveState(location.key, location.state); }; var replaceLocation = function replaceLocation(location) { entries[current] = location; saveState(location.key, location.state); }; var history = (0, _createHistory2.default)(_extends({}, options, { getCurrentLocation: getCurrentLocation, pushLocation: pushLocation, replaceLocation: replaceLocation, go: go })); var _options = options; var entries = _options.entries; var current = _options.current; if (typeof entries === 'string') { entries = [entries]; } else if (!Array.isArray(entries)) { entries = ['/']; } entries = entries.map(function (entry) { return (0, _LocationUtils.createLocation)(entry); }); if (current == null) { current = entries.length - 1; } else { !(current >= 0 && current < entries.length) ? true ? (0, _invariant2.default)(false, 'Current index must be >= 0 and < %s, was %s', entries.length, current) : (0, _invariant2.default)(false) : void 0; } var storage = createStateStorage(entries); var saveState = function saveState(key, state) { return storage[key] = state; }; var readState = function readState(key) { return storage[key]; }; return _extends({}, history, { canGo: canGo }); }; exports.default = createMemoryHistory; /***/ }, /* 341 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _AsyncUtils = __webpack_require__(342); var _PathUtils = __webpack_require__(338); var _runTransitionHook = __webpack_require__(336); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _Actions = __webpack_require__(331); var _LocationUtils = __webpack_require__(337); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createHistory = function createHistory() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var getCurrentLocation = options.getCurrentLocation; var getUserConfirmation = options.getUserConfirmation; var pushLocation = options.pushLocation; var replaceLocation = options.replaceLocation; var go = options.go; var keyLength = options.keyLength; var currentLocation = void 0; var pendingLocation = void 0; var beforeListeners = []; var listeners = []; var allKeys = []; var getCurrentIndex = function getCurrentIndex() { if (pendingLocation && pendingLocation.action === _Actions.POP) return allKeys.indexOf(pendingLocation.key); if (currentLocation) return allKeys.indexOf(currentLocation.key); return -1; }; var updateLocation = function updateLocation(nextLocation) { var currentIndex = getCurrentIndex(); currentLocation = nextLocation; if (currentLocation.action === _Actions.PUSH) { allKeys = [].concat(allKeys.slice(0, currentIndex + 1), [currentLocation.key]); } else if (currentLocation.action === _Actions.REPLACE) { allKeys[currentIndex] = currentLocation.key; } listeners.forEach(function (listener) { return listener(currentLocation); }); }; var listenBefore = function listenBefore(listener) { beforeListeners.push(listener); return function () { return beforeListeners = beforeListeners.filter(function (item) { return item !== listener; }); }; }; var listen = function listen(listener) { listeners.push(listener); return function () { return listeners = listeners.filter(function (item) { return item !== listener; }); }; }; var confirmTransitionTo = function confirmTransitionTo(location, callback) { (0, _AsyncUtils.loopAsync)(beforeListeners.length, function (index, next, done) { (0, _runTransitionHook2.default)(beforeListeners[index], location, function (result) { return result != null ? done(result) : next(); }); }, function (message) { if (getUserConfirmation && typeof message === 'string') { getUserConfirmation(message, function (ok) { return callback(ok !== false); }); } else { callback(message !== false); } }); }; var transitionTo = function transitionTo(nextLocation) { if (currentLocation && (0, _LocationUtils.locationsAreEqual)(currentLocation, nextLocation) || pendingLocation && (0, _LocationUtils.locationsAreEqual)(pendingLocation, nextLocation)) return; // Nothing to do pendingLocation = nextLocation; confirmTransitionTo(nextLocation, function (ok) { if (pendingLocation !== nextLocation) return; // Transition was interrupted during confirmation pendingLocation = null; if (ok) { // Treat PUSH to same path like REPLACE to be consistent with browsers if (nextLocation.action === _Actions.PUSH) { var prevPath = (0, _PathUtils.createPath)(currentLocation); var nextPath = (0, _PathUtils.createPath)(nextLocation); if (nextPath === prevPath && (0, _LocationUtils.statesAreEqual)(currentLocation.state, nextLocation.state)) nextLocation.action = _Actions.REPLACE; } if (nextLocation.action === _Actions.POP) { updateLocation(nextLocation); } else if (nextLocation.action === _Actions.PUSH) { if (pushLocation(nextLocation) !== false) updateLocation(nextLocation); } else if (nextLocation.action === _Actions.REPLACE) { if (replaceLocation(nextLocation) !== false) updateLocation(nextLocation); } } else if (currentLocation && nextLocation.action === _Actions.POP) { var prevIndex = allKeys.indexOf(currentLocation.key); var nextIndex = allKeys.indexOf(nextLocation.key); if (prevIndex !== -1 && nextIndex !== -1) go(prevIndex - nextIndex); // Restore the URL } }); }; var push = function push(input) { return transitionTo(createLocation(input, _Actions.PUSH)); }; var replace = function replace(input) { return transitionTo(createLocation(input, _Actions.REPLACE)); }; var goBack = function goBack() { return go(-1); }; var goForward = function goForward() { return go(1); }; var createKey = function createKey() { return Math.random().toString(36).substr(2, keyLength || 6); }; var createHref = function createHref(location) { return (0, _PathUtils.createPath)(location); }; var createLocation = function createLocation(location, action) { var key = arguments.length <= 2 || arguments[2] === undefined ? createKey() : arguments[2]; return (0, _LocationUtils.createLocation)(location, action, key); }; return { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, transitionTo: transitionTo, push: push, replace: replace, go: go, goBack: goBack, goForward: goForward, createKey: createKey, createPath: _PathUtils.createPath, createHref: createHref, createLocation: createLocation }; }; exports.default = createHistory; /***/ }, /* 342 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; var loopAsync = exports.loopAsync = function loopAsync(turns, work, callback) { var currentTurn = 0, isDone = false; var isSync = false, hasNext = false, doneArgs = void 0; var done = function done() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } isDone = true; if (isSync) { // Iterate instead of recursing if possible. doneArgs = args; return; } callback.apply(undefined, args); }; var next = function next() { if (isDone) return; hasNext = true; if (isSync) return; // Iterate instead of recursing if possible. isSync = true; while (!isDone && currentTurn < turns && hasNext) { hasNext = false; work(currentTurn++, next, done); } isSync = false; if (isDone) { // This means the loop finished synchronously. callback.apply(undefined, doneArgs); return; } if (currentTurn >= turns && hasNext) { isDone = true; callback(); } }; next(); }; /***/ }, /* 343 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = useRouterHistory; var _useQueries = __webpack_require__(333); var _useQueries2 = _interopRequireDefault(_useQueries); var _useBasename = __webpack_require__(339); var _useBasename2 = _interopRequireDefault(_useBasename); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function useRouterHistory(createHistory) { return function (options) { var history = (0, _useQueries2.default)((0, _useBasename2.default)(createHistory))(options); return history; }; } module.exports = exports['default']; /***/ }, /* 344 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(88); var _react2 = _interopRequireDefault(_react); var _RouterContext = __webpack_require__(319); var _RouterContext2 = _interopRequireDefault(_RouterContext); var _routerWarning = __webpack_require__(309); var _routerWarning2 = _interopRequireDefault(_routerWarning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } if (true) { middlewares.forEach(function (middleware, index) { true ? (0, _routerWarning2.default)(middleware.renderRouterContext || middleware.renderRouteComponent, 'The middleware specified at index ' + index + ' does not appear to be ' + 'a valid React Router middleware.') : void 0; }); } var withContext = middlewares.map(function (middleware) { return middleware.renderRouterContext; }).filter(Boolean); var withComponent = middlewares.map(function (middleware) { return middleware.renderRouteComponent; }).filter(Boolean); var makeCreateElement = function makeCreateElement() { var baseCreateElement = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _react.createElement; return function (Component, props) { return withComponent.reduceRight(function (previous, renderRouteComponent) { return renderRouteComponent(previous, props); }, baseCreateElement(Component, props)); }; }; return function (renderProps) { return withContext.reduceRight(function (previous, renderRouterContext) { return renderRouterContext(previous, renderProps); }, _react2.default.createElement(_RouterContext2.default, _extends({}, renderProps, { createElement: makeCreateElement(renderProps.createElement) }))); }; }; module.exports = exports['default']; /***/ }, /* 345 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createBrowserHistory = __webpack_require__(346); var _createBrowserHistory2 = _interopRequireDefault(_createBrowserHistory); var _createRouterHistory = __webpack_require__(352); var _createRouterHistory2 = _interopRequireDefault(_createRouterHistory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _createRouterHistory2.default)(_createBrowserHistory2.default); module.exports = exports['default']; /***/ }, /* 346 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _ExecutionEnvironment = __webpack_require__(347); var _BrowserProtocol = __webpack_require__(348); var BrowserProtocol = _interopRequireWildcard(_BrowserProtocol); var _RefreshProtocol = __webpack_require__(351); var RefreshProtocol = _interopRequireWildcard(_RefreshProtocol); var _DOMUtils = __webpack_require__(349); var _createHistory = __webpack_require__(341); var _createHistory2 = _interopRequireDefault(_createHistory); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Creates and returns a history object that uses HTML5's history API * (pushState, replaceState, and the popstate event) to manage history. * This is the recommended method of managing history in browsers because * it provides the cleanest URLs. * * Note: In browsers that do not support the HTML5 history API full * page reloads will be used to preserve clean URLs. You can force this * behavior using { forceRefresh: true } in options. */ var createBrowserHistory = function createBrowserHistory() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; !_ExecutionEnvironment.canUseDOM ? true ? (0, _invariant2.default)(false, 'Browser history needs a DOM') : (0, _invariant2.default)(false) : void 0; var useRefresh = options.forceRefresh || !(0, _DOMUtils.supportsHistory)(); var Protocol = useRefresh ? RefreshProtocol : BrowserProtocol; var getUserConfirmation = Protocol.getUserConfirmation; var getCurrentLocation = Protocol.getCurrentLocation; var pushLocation = Protocol.pushLocation; var replaceLocation = Protocol.replaceLocation; var go = Protocol.go; var history = (0, _createHistory2.default)(_extends({ getUserConfirmation: getUserConfirmation }, options, { getCurrentLocation: getCurrentLocation, pushLocation: pushLocation, replaceLocation: replaceLocation, go: go })); var listenerCount = 0, stopListener = void 0; var startListener = function startListener(listener, before) { if (++listenerCount === 1) stopListener = BrowserProtocol.startListener(history.transitionTo); var unlisten = before ? history.listenBefore(listener) : history.listen(listener); return function () { unlisten(); if (--listenerCount === 0) stopListener(); }; }; var listenBefore = function listenBefore(listener) { return startListener(listener, true); }; var listen = function listen(listener) { return startListener(listener, false); }; return _extends({}, history, { listenBefore: listenBefore, listen: listen }); }; exports.default = createBrowserHistory; /***/ }, /* 347 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var canUseDOM = exports.canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /***/ }, /* 348 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.go = exports.replaceLocation = exports.pushLocation = exports.startListener = exports.getUserConfirmation = exports.getCurrentLocation = undefined; var _LocationUtils = __webpack_require__(337); var _DOMUtils = __webpack_require__(349); var _DOMStateStorage = __webpack_require__(350); var _PathUtils = __webpack_require__(338); var _ExecutionEnvironment = __webpack_require__(347); var PopStateEvent = 'popstate'; var HashChangeEvent = 'hashchange'; var needsHashchangeListener = _ExecutionEnvironment.canUseDOM && !(0, _DOMUtils.supportsPopstateOnHashchange)(); var _createLocation = function _createLocation(historyState) { var key = historyState && historyState.key; return (0, _LocationUtils.createLocation)({ pathname: window.location.pathname, search: window.location.search, hash: window.location.hash, state: key ? (0, _DOMStateStorage.readState)(key) : undefined }, undefined, key); }; var getCurrentLocation = exports.getCurrentLocation = function getCurrentLocation() { var historyState = void 0; try { historyState = window.history.state || {}; } catch (error) { // IE 11 sometimes throws when accessing window.history.state // See https://github.com/ReactTraining/history/pull/289 historyState = {}; } return _createLocation(historyState); }; var getUserConfirmation = exports.getUserConfirmation = function getUserConfirmation(message, callback) { return callback(window.confirm(message)); }; // eslint-disable-line no-alert var startListener = exports.startListener = function startListener(listener) { var handlePopState = function handlePopState(event) { if (event.state !== undefined) // Ignore extraneous popstate events in WebKit listener(_createLocation(event.state)); }; (0, _DOMUtils.addEventListener)(window, PopStateEvent, handlePopState); var handleUnpoppedHashChange = function handleUnpoppedHashChange() { return listener(getCurrentLocation()); }; if (needsHashchangeListener) { (0, _DOMUtils.addEventListener)(window, HashChangeEvent, handleUnpoppedHashChange); } return function () { (0, _DOMUtils.removeEventListener)(window, PopStateEvent, handlePopState); if (needsHashchangeListener) { (0, _DOMUtils.removeEventListener)(window, HashChangeEvent, handleUnpoppedHashChange); } }; }; var updateLocation = function updateLocation(location, updateState) { var state = location.state; var key = location.key; if (state !== undefined) (0, _DOMStateStorage.saveState)(key, state); updateState({ key: key }, (0, _PathUtils.createPath)(location)); }; var pushLocation = exports.pushLocation = function pushLocation(location) { return updateLocation(location, function (state, path) { return window.history.pushState(state, null, path); }); }; var replaceLocation = exports.replaceLocation = function replaceLocation(location) { return updateLocation(location, function (state, path) { return window.history.replaceState(state, null, path); }); }; var go = exports.go = function go(n) { if (n) window.history.go(n); }; /***/ }, /* 349 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var addEventListener = exports.addEventListener = function addEventListener(node, event, listener) { return node.addEventListener ? node.addEventListener(event, listener, false) : node.attachEvent('on' + event, listener); }; var removeEventListener = exports.removeEventListener = function removeEventListener(node, event, listener) { return node.removeEventListener ? node.removeEventListener(event, listener, false) : node.detachEvent('on' + event, listener); }; /** * Returns true if the HTML5 history API is supported. Taken from Modernizr. * * https://github.com/Modernizr/Modernizr/blob/master/LICENSE * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586 */ var supportsHistory = exports.supportsHistory = function supportsHistory() { var ua = window.navigator.userAgent; if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false; return window.history && 'pushState' in window.history; }; /** * Returns false if using go(n) with hash history causes a full page reload. */ var supportsGoWithoutReloadUsingHash = exports.supportsGoWithoutReloadUsingHash = function supportsGoWithoutReloadUsingHash() { return window.navigator.userAgent.indexOf('Firefox') === -1; }; /** * Returns true if browser fires popstate on hash change. * IE10 and IE11 do not. */ var supportsPopstateOnHashchange = exports.supportsPopstateOnHashchange = function supportsPopstateOnHashchange() { return window.navigator.userAgent.indexOf('Trident') === -1; }; /***/ }, /* 350 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.readState = exports.saveState = undefined; var _warning = __webpack_require__(310); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var QuotaExceededErrors = { QuotaExceededError: true, QUOTA_EXCEEDED_ERR: true }; var SecurityErrors = { SecurityError: true }; var KeyPrefix = '@@History/'; var createKey = function createKey(key) { return KeyPrefix + key; }; var saveState = exports.saveState = function saveState(key, state) { if (!window.sessionStorage) { // Session storage is not available or hidden. // sessionStorage is undefined in Internet Explorer when served via file protocol. true ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available') : void 0; return; } try { if (state == null) { window.sessionStorage.removeItem(createKey(key)); } else { window.sessionStorage.setItem(createKey(key), JSON.stringify(state)); } } catch (error) { if (SecurityErrors[error.name]) { // Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any // attempt to access window.sessionStorage. true ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available due to security settings') : void 0; return; } if (QuotaExceededErrors[error.name] && window.sessionStorage.length === 0) { // Safari "private mode" throws QuotaExceededError. true ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available in Safari private mode') : void 0; return; } throw error; } }; var readState = exports.readState = function readState(key) { var json = void 0; try { json = window.sessionStorage.getItem(createKey(key)); } catch (error) { if (SecurityErrors[error.name]) { // Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any // attempt to access window.sessionStorage. true ? (0, _warning2.default)(false, '[history] Unable to read state; sessionStorage is not available due to security settings') : void 0; return undefined; } } if (json) { try { return JSON.parse(json); } catch (error) { // Ignore invalid JSON. } } return undefined; }; /***/ }, /* 351 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.replaceLocation = exports.pushLocation = exports.getCurrentLocation = exports.go = exports.getUserConfirmation = undefined; var _BrowserProtocol = __webpack_require__(348); Object.defineProperty(exports, 'getUserConfirmation', { enumerable: true, get: function get() { return _BrowserProtocol.getUserConfirmation; } }); Object.defineProperty(exports, 'go', { enumerable: true, get: function get() { return _BrowserProtocol.go; } }); var _LocationUtils = __webpack_require__(337); var _PathUtils = __webpack_require__(338); var getCurrentLocation = exports.getCurrentLocation = function getCurrentLocation() { return (0, _LocationUtils.createLocation)(window.location); }; var pushLocation = exports.pushLocation = function pushLocation(location) { window.location.href = (0, _PathUtils.createPath)(location); return false; // Don't update location }; var replaceLocation = exports.replaceLocation = function replaceLocation(location) { window.location.replace((0, _PathUtils.createPath)(location)); return false; // Don't update location }; /***/ }, /* 352 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = function (createHistory) { var history = void 0; if (canUseDOM) history = (0, _useRouterHistory2.default)(createHistory)(); return history; }; var _useRouterHistory = __webpack_require__(343); var _useRouterHistory2 = _interopRequireDefault(_useRouterHistory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); module.exports = exports['default']; /***/ }, /* 353 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createHashHistory = __webpack_require__(354); var _createHashHistory2 = _interopRequireDefault(_createHashHistory); var _createRouterHistory = __webpack_require__(352); var _createRouterHistory2 = _interopRequireDefault(_createRouterHistory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _createRouterHistory2.default)(_createHashHistory2.default); module.exports = exports['default']; /***/ }, /* 354 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _warning = __webpack_require__(310); var _warning2 = _interopRequireDefault(_warning); var _invariant = __webpack_require__(271); var _invariant2 = _interopRequireDefault(_invariant); var _ExecutionEnvironment = __webpack_require__(347); var _DOMUtils = __webpack_require__(349); var _HashProtocol = __webpack_require__(355); var HashProtocol = _interopRequireWildcard(_HashProtocol); var _createHistory = __webpack_require__(341); var _createHistory2 = _interopRequireDefault(_createHistory); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DefaultQueryKey = '_k'; var addLeadingSlash = function addLeadingSlash(path) { return path.charAt(0) === '/' ? path : '/' + path; }; var HashPathCoders = { hashbang: { encodePath: function encodePath(path) { return path.charAt(0) === '!' ? path : '!' + path; }, decodePath: function decodePath(path) { return path.charAt(0) === '!' ? path.substring(1) : path; } }, noslash: { encodePath: function encodePath(path) { return path.charAt(0) === '/' ? path.substring(1) : path; }, decodePath: addLeadingSlash }, slash: { encodePath: addLeadingSlash, decodePath: addLeadingSlash } }; var createHashHistory = function createHashHistory() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; !_ExecutionEnvironment.canUseDOM ? true ? (0, _invariant2.default)(false, 'Hash history needs a DOM') : (0, _invariant2.default)(false) : void 0; var queryKey = options.queryKey; var hashType = options.hashType; true ? (0, _warning2.default)(queryKey !== false, 'Using { queryKey: false } no longer works. Instead, just don\'t ' + 'use location state if you don\'t want a key in your URL query string') : void 0; if (typeof queryKey !== 'string') queryKey = DefaultQueryKey; if (hashType == null) hashType = 'slash'; if (!(hashType in HashPathCoders)) { true ? (0, _warning2.default)(false, 'Invalid hash type: %s', hashType) : void 0; hashType = 'slash'; } var pathCoder = HashPathCoders[hashType]; var getUserConfirmation = HashProtocol.getUserConfirmation; var getCurrentLocation = function getCurrentLocation() { return HashProtocol.getCurrentLocation(pathCoder, queryKey); }; var pushLocation = function pushLocation(location) { return HashProtocol.pushLocation(location, pathCoder, queryKey); }; var replaceLocation = function replaceLocation(location) { return HashProtocol.replaceLocation(location, pathCoder, queryKey); }; var history = (0, _createHistory2.default)(_extends({ getUserConfirmation: getUserConfirmation }, options, { getCurrentLocation: getCurrentLocation, pushLocation: pushLocation, replaceLocation: replaceLocation, go: HashProtocol.go })); var listenerCount = 0, stopListener = void 0; var startListener = function startListener(listener, before) { if (++listenerCount === 1) stopListener = HashProtocol.startListener(history.transitionTo, pathCoder, queryKey); var unlisten = before ? history.listenBefore(listener) : history.listen(listener); return function () { unlisten(); if (--listenerCount === 0) stopListener(); }; }; var listenBefore = function listenBefore(listener) { return startListener(listener, true); }; var listen = function listen(listener) { return startListener(listener, false); }; var goIsSupportedWithoutReload = (0, _DOMUtils.supportsGoWithoutReloadUsingHash)(); var go = function go(n) { true ? (0, _warning2.default)(goIsSupportedWithoutReload, 'Hash history go(n) causes a full page reload in this browser') : void 0; history.go(n); }; var createHref = function createHref(path) { return '#' + pathCoder.encodePath(history.createHref(path)); }; return _extends({}, history, { listenBefore: listenBefore, listen: listen, go: go, createHref: createHref }); }; exports.default = createHashHistory; /***/ }, /* 355 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.replaceLocation = exports.pushLocation = exports.startListener = exports.getCurrentLocation = exports.go = exports.getUserConfirmation = undefined; var _BrowserProtocol = __webpack_require__(348); Object.defineProperty(exports, 'getUserConfirmation', { enumerable: true, get: function get() { return _BrowserProtocol.getUserConfirmation; } }); Object.defineProperty(exports, 'go', { enumerable: true, get: function get() { return _BrowserProtocol.go; } }); var _warning = __webpack_require__(310); var _warning2 = _interopRequireDefault(_warning); var _LocationUtils = __webpack_require__(337); var _DOMUtils = __webpack_require__(349); var _DOMStateStorage = __webpack_require__(350); var _PathUtils = __webpack_require__(338); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var HashChangeEvent = 'hashchange'; var getHashPath = function getHashPath() { // We can't use window.location.hash here because it's not // consistent across browsers - Firefox will pre-decode it! var href = window.location.href; var hashIndex = href.indexOf('#'); return hashIndex === -1 ? '' : href.substring(hashIndex + 1); }; var pushHashPath = function pushHashPath(path) { return window.location.hash = path; }; var replaceHashPath = function replaceHashPath(path) { var hashIndex = window.location.href.indexOf('#'); window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + '#' + path); }; var getCurrentLocation = exports.getCurrentLocation = function getCurrentLocation(pathCoder, queryKey) { var path = pathCoder.decodePath(getHashPath()); var key = (0, _PathUtils.getQueryStringValueFromPath)(path, queryKey); var state = void 0; if (key) { path = (0, _PathUtils.stripQueryStringValueFromPath)(path, queryKey); state = (0, _DOMStateStorage.readState)(key); } var init = (0, _PathUtils.parsePath)(path); init.state = state; return (0, _LocationUtils.createLocation)(init, undefined, key); }; var prevLocation = void 0; var startListener = exports.startListener = function startListener(listener, pathCoder, queryKey) { var handleHashChange = function handleHashChange() { var path = getHashPath(); var encodedPath = pathCoder.encodePath(path); if (path !== encodedPath) { // Always be sure we have a properly-encoded hash. replaceHashPath(encodedPath); } else { var currentLocation = getCurrentLocation(pathCoder, queryKey); if (prevLocation && currentLocation.key && prevLocation.key === currentLocation.key) return; // Ignore extraneous hashchange events prevLocation = currentLocation; listener(currentLocation); } }; // Ensure the hash is encoded properly. var path = getHashPath(); var encodedPath = pathCoder.encodePath(path); if (path !== encodedPath) replaceHashPath(encodedPath); (0, _DOMUtils.addEventListener)(window, HashChangeEvent, handleHashChange); return function () { return (0, _DOMUtils.removeEventListener)(window, HashChangeEvent, handleHashChange); }; }; var updateLocation = function updateLocation(location, pathCoder, queryKey, updateHash) { var state = location.state; var key = location.key; var path = pathCoder.encodePath((0, _PathUtils.createPath)(location)); if (state !== undefined) { path = (0, _PathUtils.addQueryStringValueToPath)(path, queryKey, key); (0, _DOMStateStorage.saveState)(key, state); } prevLocation = location; updateHash(path); }; var pushLocation = exports.pushLocation = function pushLocation(location, pathCoder, queryKey) { return updateLocation(location, pathCoder, queryKey, function (path) { if (getHashPath() !== path) { pushHashPath(path); } else { true ? (0, _warning2.default)(false, 'You cannot PUSH the same path using hash history') : void 0; } }); }; var replaceLocation = exports.replaceLocation = function replaceLocation(location, pathCoder, queryKey) { return updateLocation(location, pathCoder, queryKey, function (path) { if (getHashPath() !== path) replaceHashPath(path); }); }; /***/ } /******/ ]); //# sourceMappingURL=vendor.4fdab2f3d5915072bfb1.js.map
var utils = require('jsr-util') , HashMap = require('../type/hash') , Constants = require('jsr-constants') , OK = Constants.OK , slice = Array.prototype.slice; // TODO: hincrby // TODO: hincrbyfloat // TODO: hscan (much later!) /** * Set the string value of a hash field. */ function hset(key, field, value, req) { var val = this.getKey(key, req) , exists = this.hexists(key, field, req); if(!val) { val = new HashMap(); // add to the database // must call set to ensure size is correct this.setKey(key, val, undefined, undefined, undefined, req); } // set on the hashmap val.setKey(field, value); return exists ? 0 : 1; } /** * Sets field in the hash stored at key to value, only * if field does not yet exist. */ function hsetnx(key, field, value, req) { var val = this.getKey(key, req) , exists = this.hexists(key, field, req); if(!val) { val = new HashMap(); this.setKey(key, val, undefined, undefined, undefined, req); } if(!exists) { // set on the hashmap val.setKey(field, value); } return exists ? 0 : 1; } /** * Get the value of a hash field. */ function hget(key, field, req) { // get at db level var val = this.getKey(key, req); if(!val) return null; // get at hash level val = val.getKey(field) if(!val) return null; return val; } /** * Determine if a hash field exists. */ function hexists(key, field, req) { var val = this.getKey(key, req); if(!val) return 0; return val.keyExists(field); } /** * Get all the fields and values in a hash. */ function hgetall(key, req) { var val = this.getKey(key, req) , list = []; if(!val) return list; val.getKeys().forEach(function(k) { list.push(k, '' + val.getKey(k)); }); return list; } /** * Get all the fields in a hash. */ function hkeys(key, req) { var val = this.getKey(key, req); if(!val) return []; return val.getKeys(); } /** * Get the number of fields in a hash. */ function hlen(key, req) { var val = this.getKey(key, req); if(!val) return 0; return val.hlen(); } /** * Get all the values in a hash. */ function hvals(key, req) { var val = this.getKey(key, req) , list = []; if(!val) return list; val.getKeys().forEach(function(k) { list.push('' + val.getKey(k)); }); return list; } /** * Delete one or more hash fields. */ function hdel(key /* field-1, field-N, req */) { var args = slice.call(arguments, 1) , req = typeof args[args.length - 1] === 'object' ? args.pop() : null , val = this.getKey(key, req) , deleted = 0 , i; // nothing at key if(!val) return 0; for(i = 0;i < args.length;i++) { deleted += val.delKey(args[i]); } if(val.hlen() === 0) { this.delKey(key, req); } return deleted; } /** * Returns the values associated with the specified fields in * the hash stored at key. */ function hmget(key /* field-1, field-N, req */) { var args = slice.call(arguments, 1) , req = typeof args[args.length - 1] === 'object' ? args.pop() : null , val = this.getKey(key, req) , value , list = [] , i; for(i = 0;i < args.length;i++) { if(!val) { list.push(null); continue; } value = val.getKey(args[i]) list.push(value !== undefined ? value : null); } return list; } /** * Sets the specified fields to their respective values in * the hash stored at key. */ function hmset(key /* field-1, value-1, field-N, value-N, req */) { var args = slice.call(arguments, 1) , req = typeof args[args.length - 1] === 'object' ? args.pop() : null , val = this.getKey(key, req) , i; if(!val) { val = new HashMap(); this.setKey(key, val, undefined, undefined, undefined, req); } for(i = 0;i < args.length;i+=2) { val.setKey(args[i], args[i + 1]); } return OK; } /** * Increment the specified field of hash stored at key, and * representing a floating point number, by the specified increment. */ function hincrbyfloat(key, field, amount, req) { var map = this.getKey(key, req) , val; if(!map) { map = new HashMap(); this.setKey(key, map, undefined, undefined, undefined, req); } val = utils.strtofloat(map.getKey(field)); amount = utils.strtofloat(amount); val += amount; map.setKey(field, val); // store as number and return a number, // the command implementation should coerce the result // to a string for a bulk string reply return val; } /** * Increments the number stored at field in the * hash stored at key by increment. */ function hincrby(key, field, amount, req) { var map = this.getKey(key, req) , val; if(!map) { map = new HashMap(); this.setKey(key, map, undefined, undefined, undefined, req); } val = utils.strtoint(map.getKey(field)); amount = utils.strtoint(amount); val += amount; map.setKey(field, val); return val; } module.exports = { hset: hset, hsetnx: hsetnx, hget: hget, hexists: hexists, hgetall: hgetall, hkeys: hkeys, hvals: hvals, hlen: hlen, hdel: hdel, hmget: hmget, hmset: hmset, hincrby: hincrby, hincrbyfloat: hincrbyfloat, }
/* * @author paper */ function YHAlert(arg){ var obj = arg ||{}, msg = obj.msg || '你没有写提示内容!', bd = document.getElementsByTagName('body')[0], time = obj.time || 2000, way = obj.way == 'leftToRight' ? 'left' : 'top', $ = function(id){ return typeof id == 'string' ? document.getElementById(id) : id; }, html = '<div id="YHAlert" style="visibility:hidden;"><div id="YHAlert_in">' + '<p id="YHAlert_p">' + msg + '</p>' + '</div></div>', asynInnerHTML = function(HTML, doingCallback, endCallback){ var temp = document.createElement('div'), frag = document.createDocumentFragment(); temp.innerHTML = HTML; (function(){ if (temp.firstChild) { frag.appendChild(temp.firstChild); doingCallback(frag); setTimeout(arguments.callee, 0); } else { if (endCallback) endCallback(frag); } })(); }, ie = (function(){ var undef, v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i'); while ( div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', all[0] ); return v > 4 ? v : undef; }()), remove = function(elem){ if (elem.parentNode) elem.parentNode.removeChild(elem); }, getArea = function(){ return { height: document.documentElement.clientHeight, width: document.documentElement.clientWidth } }, getMax = function(){ var dd = document.documentElement; return { height: Math.max(dd.scrollHeight, dd.clientHeight), width: Math.max(dd.scrollWidth, dd.clientWidth) } }, getScroll = function(){ return { top: Math.max(document.documentElement.scrollTop, document.body.scrollTop), left: Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) } }, setStyle = function(elem, styles){ for (var i in styles) { elem.style[i] = styles[i]; } }, setOpacity = function(elem, level){ elem.filters ? elem.style.filter = 'alpha(opacity=' + level + ')' : elem.style.opacity = level / 100; }, fIn = function(elem, callback){ var step = 3; setOpacity(elem, 0); elem.style.visibility = 'visible'; elem.style[way] = parseInt(elem.style[way]) - 100 / step + 'px'; var opacity = 0, t = setInterval(function(){ setOpacity(elem, opacity); if (opacity >= 100) { setOpacity(elem, 100); clearInterval(t); if (callback) callback.call(elem); } opacity += step; elem.style[way] = parseInt(elem.style[way]) + 1 + 'px'; }, 1); }, fOut = function(elem, callback){ elem.style.visibility = 'visible'; var step = 3, opacity = 100, t = setInterval(function(){ setOpacity(elem, opacity); if (opacity <= 0) { setOpacity(elem, 0); elem.style.visibility = 'hidden'; clearInterval(t); if (callback) callback.call(elem); } opacity -= step; elem.style[way] = parseInt(elem.style[way]) + 1 + 'px'; }, 1); }; (function(){ while ($('YHAlert')) { remove($('YHAlert')); }; asynInnerHTML(html, function(f){ bd.appendChild(f); }, function(){ var YHAlert = $('YHAlert'), YHAlert_in = $('YHAlert_in'), YHAlert_p = $('YHAlert_p'), w = getArea().width, h = getArea().height, st = getScroll().top, YHAlert_height = parseInt(YHAlert.offsetHeight), pos=ie==6?'absolute':'fixed', t=ie==6?parseInt(st + h / 2 - YHAlert_height * 6):parseInt(h / 2 - YHAlert_height * 6); setStyle(YHAlert, { 'borderRadius': '5px', 'MozBorderRadius': '5px', 'WebkitBorderRadius': '5px', 'boxShadow': '0 0 3px #ccc', 'MozBoxShadow': '0 0 3px #ccc', 'WebkitBoxShadow': '0 0 3px #ccc', 'left': parseInt(w / 2 - 80) + 'px', 'top': t+'px', 'position': pos, 'width': '160px', 'backgroundColor': '#F3F7FD', 'border': '1px solid #6ed3e3', 'zIndex': '99999' }); setStyle(YHAlert_in, { 'borderRadius': '5px', 'MozBorderRadius': '5px', 'WebkitBorderRadius': '5px', 'backgroundColor':'#fefefe', 'padding':'15px 10px' }); setStyle(YHAlert_p, { 'textAlign': 'left', 'fontSize': '14px', 'margin': '0', 'color': '#000', 'lineHeight': '140%' }); fIn(YHAlert, function(){ setTimeout(function(){ fOut(YHAlert, function(){ remove(YHAlert); }); }, time); }); }); }()); };
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; const u = undefined; function plural(n) { if (n === 1) return 1; return 5; } global.ng.common.locales['mgo'] = [ 'mgo', [['AM', 'PM'], u, u], u, [ ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7'], ['Aneg 1', 'Aneg 2', 'Aneg 3', 'Aneg 4', 'Aneg 5', 'Aneg 6', 'Aneg 7'], u, ['1', '2', '3', '4', '5', '6', '7'] ], u, [ ['M1', 'A2', 'M3', 'N4', 'F5', 'I6', 'A7', 'I8', 'K9', '10', '11', '12'], [ 'mbegtug', 'imeg àbùbì', 'imeg mbəŋchubi', 'iməg ngwə̀t', 'iməg fog', 'iməg ichiibɔd', 'iməg àdùmbə̀ŋ', 'iməg ichika', 'iməg kud', 'iməg tèsiʼe', 'iməg zò', 'iməg krizmed' ], [ 'iməg mbegtug', 'imeg àbùbì', 'imeg mbəŋchubi', 'iməg ngwə̀t', 'iməg fog', 'iməg ichiibɔd', 'iməg àdùmbə̀ŋ', 'iməg ichika', 'iməg kud', 'iməg tèsiʼe', 'iməg zò', 'iməg krizmed' ] ], u, [['BCE', 'CE'], u, u], 1, [6, 0], ['y-MM-dd', 'y MMM d', 'y MMMM d', 'EEEE, y MMMM dd'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'], 'FCFA', 'shirè', {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural, [] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
var DBSCAN = require('../lib/index.js').DBSCAN; var dataset = [ [1, 1], [0, 1], [1, 0], [10, 10], [13, 13], [10, 13], [54, 54], [55, 55], [89, 89], [57, 55] ]; var dbscan = new DBSCAN(); var clusters = dbscan.run(dataset, 5, 2); console.log(clusters);
version https://git-lfs.github.com/spec/v1 oid sha256:9d9d8e01a2a7570aca18bc11a453ed5b5fb412ba1fc025a6e2438040d5254ce3 size 22959
import React from 'react' import {connect} from 'react-redux' import CommentList from './comment-list' import Vote from './vote' export default class Question extends React.Component { render() { const q = this.props.question.question; const comments = this.props.question.comments; return <div className="question"> <div className="question-container"> <Vote upvote={this.props.upvote} downvote={this.props.downvote} score={q.score} upvotes={q.upvotes} downvotes={q.downvotes} /> <div className="question-content">{q.content}</div> </div> <div className="question-comments"> <CommentList comments={comments} question_id={q.id} /> </div> </div> } }
/** * Created by vladi on 27-Jan-17. */ import { removeEventListenerById, suspendEventListenerById, restoreEventListenerById, isListenerSuspended, listenerExists, addTypeFilter, addTypeFilters, resetTypeFilter, removeTypeFilter, removeTypeFilters } from './EventsControl'; export default class EventListener { constructor(listenerUid, onRemoveCallback) { this.listenerUid = listenerUid; this._onRemoveCallback = onRemoveCallback; } filter(mixed) { if (mixed) { Array.isArray(mixed) ? addTypeFilters(this.listenerUid, mixed) : addTypeFilter(this.listenerUid, mixed) } return this; } unFilter(mixed) { if (mixed) { Array.isArray(mixed) ? removeTypeFilters(this.listenerUid, mixed) : removeTypeFilter(this.listenerUid, mixed) } else { resetTypeFilter(this.listenerUid); } return this; } remove() { if (this.isRemoved()) { return; } removeEventListenerById(this.listenerUid); this._onRemoveCallback && this._onRemoveCallback(); return this; } suspend() { suspendEventListenerById(this.listenerUid); return this; } restore() { restoreEventListenerById(this.listenerUid); return this; } isSuspended() { return isListenerSuspended(this.listenerUid); } isRemoved() { return !listenerExists(this.listenerUid); } }
/** * User: Jomaras * Date: 26.09.12. * Time: 17:24 */ FBL.ns(function() { with (FBL) { /*************************************************************************************/ Firecrow.DependencyGraph.DependencyHighlighter = function(htmlContainer, dependencyGraph) { (function establishConnection() { var nodes = dependencyGraph.nodes; for(var i = 0, length = nodes.length; i < length; i++) { var node = nodes[i]; var htmlNode = htmlContainer.querySelector("#node" + FBL.Firecrow.CodeMarkupGenerator.formatId(node.model.nodeId)); if(htmlNode != null) { htmlNode.model = node.model; } } }()); function removeClass(className) { var elements = htmlContainer.querySelectorAll("." + className); for(var i = 0; i < elements.length; i++) { elements[i].classList.remove(className); } } var codeElements = htmlContainer.querySelectorAll(".node"); for(var i = 0, length = codeElements.length; i < length; i++) { codeElements[i].onclick = function(eventArgs) { if(this.id.indexOf("node") == 0) { eventArgs.stopPropagation(); removeClass("selected"); removeClass("dependent"); this.classList.add("selected"); var modelNode = this.model; if(modelNode == null) { return; } var dependencies = modelNode.graphNode.dataDependencies; for(var j = 0, jLength = dependencies.length; j < jLength; j++) { var dependent = dependencies[j]; var htmlDependent = htmlContainer.querySelector("#node" + FBL.Firecrow.CodeMarkupGenerator.formatId(dependent.destinationNode.model.nodeId)); if(htmlDependent != null) { htmlDependent.classList.add("dependent"); } } } } } }; }});
app.controller('MainCtrl', function($scope, cachedGames) { $scope.games = cachedGames.query(); $scope.interval = 5000; });
export default Ember.Route.extend({ model: function() { return ['orange', 'black', 'purple']; } });
// flow-typed signature: 944ad0ad35ca446a54ecf5f7ad58eff9 // flow-typed version: <<STUB>>/node-sass_v^3.10.0/flow_v0.35.0 /** * This is an autogenerated libdef stub for: * * 'node-sass' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'node-sass' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'node-sass/lib/binding' { declare module.exports: any; } declare module 'node-sass/lib/errors' { declare module.exports: any; } declare module 'node-sass/lib/extensions' { declare module.exports: any; } declare module 'node-sass/lib/index' { declare module.exports: any; } declare module 'node-sass/lib/render' { declare module.exports: any; } declare module 'node-sass/scripts/build' { declare module.exports: any; } declare module 'node-sass/scripts/coverage' { declare module.exports: any; } declare module 'node-sass/scripts/install' { declare module.exports: any; } declare module 'node-sass/scripts/prepublish' { declare module.exports: any; } declare module 'node-sass/scripts/util/downloadoptions' { declare module.exports: any; } declare module 'node-sass/scripts/util/proxy' { declare module.exports: any; } declare module 'node-sass/scripts/util/useragent' { declare module.exports: any; } declare module 'node-sass/test/api' { declare module.exports: any; } declare module 'node-sass/test/binding' { declare module.exports: any; } declare module 'node-sass/test/cli' { declare module.exports: any; } declare module 'node-sass/test/downloadoptions' { declare module.exports: any; } declare module 'node-sass/test/errors' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_arrays_of_importers' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_functions_setter' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_functions_string_conversion' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_data_cb' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_data' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_error' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_file_and_data_cb' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_file_and_data' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_file_cb' { declare module.exports: any; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_file' { declare module.exports: any; } declare module 'node-sass/test/lowlevel' { declare module.exports: any; } declare module 'node-sass/test/runtime' { declare module.exports: any; } declare module 'node-sass/test/scripts/util/proxy' { declare module.exports: any; } declare module 'node-sass/test/spec' { declare module.exports: any; } declare module 'node-sass/test/useragent' { declare module.exports: any; } // Filename aliases declare module 'node-sass/lib/binding.js' { declare module.exports: $Exports<'node-sass/lib/binding'>; } declare module 'node-sass/lib/errors.js' { declare module.exports: $Exports<'node-sass/lib/errors'>; } declare module 'node-sass/lib/extensions.js' { declare module.exports: $Exports<'node-sass/lib/extensions'>; } declare module 'node-sass/lib/index.js' { declare module.exports: $Exports<'node-sass/lib/index'>; } declare module 'node-sass/lib/render.js' { declare module.exports: $Exports<'node-sass/lib/render'>; } declare module 'node-sass/scripts/build.js' { declare module.exports: $Exports<'node-sass/scripts/build'>; } declare module 'node-sass/scripts/coverage.js' { declare module.exports: $Exports<'node-sass/scripts/coverage'>; } declare module 'node-sass/scripts/install.js' { declare module.exports: $Exports<'node-sass/scripts/install'>; } declare module 'node-sass/scripts/prepublish.js' { declare module.exports: $Exports<'node-sass/scripts/prepublish'>; } declare module 'node-sass/scripts/util/downloadoptions.js' { declare module.exports: $Exports<'node-sass/scripts/util/downloadoptions'>; } declare module 'node-sass/scripts/util/proxy.js' { declare module.exports: $Exports<'node-sass/scripts/util/proxy'>; } declare module 'node-sass/scripts/util/useragent.js' { declare module.exports: $Exports<'node-sass/scripts/util/useragent'>; } declare module 'node-sass/test/api.js' { declare module.exports: $Exports<'node-sass/test/api'>; } declare module 'node-sass/test/binding.js' { declare module.exports: $Exports<'node-sass/test/binding'>; } declare module 'node-sass/test/cli.js' { declare module.exports: $Exports<'node-sass/test/cli'>; } declare module 'node-sass/test/downloadoptions.js' { declare module.exports: $Exports<'node-sass/test/downloadoptions'>; } declare module 'node-sass/test/errors.js' { declare module.exports: $Exports<'node-sass/test/errors'>; } declare module 'node-sass/test/fixtures/extras/my_custom_arrays_of_importers.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_arrays_of_importers'>; } declare module 'node-sass/test/fixtures/extras/my_custom_functions_setter.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_functions_setter'>; } declare module 'node-sass/test/fixtures/extras/my_custom_functions_string_conversion.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_functions_string_conversion'>; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_data_cb.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_importer_data_cb'>; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_data.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_importer_data'>; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_error.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_importer_error'>; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_file_and_data_cb.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_importer_file_and_data_cb'>; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_file_and_data.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_importer_file_and_data'>; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_file_cb.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_importer_file_cb'>; } declare module 'node-sass/test/fixtures/extras/my_custom_importer_file.js' { declare module.exports: $Exports<'node-sass/test/fixtures/extras/my_custom_importer_file'>; } declare module 'node-sass/test/lowlevel.js' { declare module.exports: $Exports<'node-sass/test/lowlevel'>; } declare module 'node-sass/test/runtime.js' { declare module.exports: $Exports<'node-sass/test/runtime'>; } declare module 'node-sass/test/scripts/util/proxy.js' { declare module.exports: $Exports<'node-sass/test/scripts/util/proxy'>; } declare module 'node-sass/test/spec.js' { declare module.exports: $Exports<'node-sass/test/spec'>; } declare module 'node-sass/test/useragent.js' { declare module.exports: $Exports<'node-sass/test/useragent'>; }
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users'); var prefroshes = require('../../app/controllers/prefroshes'); // Prefroshes Routes app.route('/prefroshes') .get(prefroshes.list) .post(users.requiresLogin, prefroshes.create); app.route('/prefroshes/:prefroshId') .get(prefroshes.read) .put(users.requiresLogin, prefroshes.hasAuthorization, prefroshes.update) .delete(users.requiresLogin, prefroshes.hasAuthorization, prefroshes.delete); // Finish by binding the Prefrosh middleware app.param('prefroshId', prefroshes.prefroshByID); };
/** ******************************************************************************************************************** * * drawer with left navigation * @exports {function} initializeDrawer * **********************************************************************************************************************/ import axios from "axios"; import {DEBUG} from "../../config"; const SELECTOR_DRAWER = "appDrawer"; const SELECTOR_DRAWER_BUTTON = "appDrawerBtn"; const CLASSNAME_OPEN = "aw-drawer--open"; const CLASSNAME_BTN_OPEN = "aw-header__menu-btn--open"; const CLASSNAME_OPENING = "aw-drawer--opening"; const CLASSNAME_CLOSING = "aw-drawer--closing"; // needs to by synched to css value of @keyframes "openDrawer" and "closeDrawer" in theme/components/app/_drawer.scss const ANIMATION_DURATION = 150; /* * simple non-trusted way to find out if the user is logged in. * this is purely to avoid error messages from the server */ const isLoggedIn = () => document.querySelector("body").getAttribute("data-user") === "1"; /* * simple way to find out if the drawer covers the content (<768px width) or pushes it to the side (>= 768opx) * remembering that the drawer is open is totes awesome for clients with enough viewport width * it is not helping if the drawer covers the content anyway - navigation would be very awkward, * since you would have to close the drawer again */ const isSmallViewPort = () => window.innerWidth < 768; /* * @function open the drawer * @param {DOMNode} drawer * @param {DOMNode} button */ const openDrawer = (drawer, button) => { drawer.classList.add(CLASSNAME_OPENING); button.classList.add(CLASSNAME_BTN_OPEN); DEBUG && console.log("opening drawer"); setTimeout(() => { drawer.classList.remove(CLASSNAME_OPENING); drawer.classList.add(CLASSNAME_OPEN); drawer.setAttribute("aria-hidden", "false"); isLoggedIn() && !isSmallViewPort() && axios .post("/api/user/opendrawer") .then(response => { if (response.data.status === "success") { DEBUG && console.log("saved drawer setting in db."); } else { DEBUG && console.error(`error while saving to database: ${response}`); } }) .catch(error => { DEBUG && console.error(error); }); }, ANIMATION_DURATION); }; /* * @function close the drawer * @param {DOMNode} drawer * @param {DOMNode} button */ const closeDrawer = (drawer, button) => { drawer.classList.add(CLASSNAME_CLOSING); button.classList.remove(CLASSNAME_BTN_OPEN); DEBUG && console.log("closing drawer"); setTimeout(() => { drawer.classList.remove(CLASSNAME_OPEN, CLASSNAME_CLOSING); drawer.setAttribute("aria-hidden", "true"); isLoggedIn() && !isSmallViewPort() && axios .post("/api/user/closedrawer") .then(response => { if (response.data.status === "success") { DEBUG && console.log("saved drawer setting in db."); } else { DEBUG && console.error(`error while saving to database: ${response}`); } }) .catch(error => { DEBUG && console.error(error); }); }, ANIMATION_DURATION); }; /* * initialize drawer by binding event listeners */ const initDrawer = () => { const drawer = document.getElementById(SELECTOR_DRAWER); const button = document.getElementById(SELECTOR_DRAWER_BUTTON); // return if no drawer or no trigger if (!drawer || !button) return; // for smaller screens, remove open class since it covers part of the content anyway if (isSmallViewPort()) drawer.classList.remove(CLASSNAME_OPEN); // click event button.addEventListener("click", function() { if (drawer.classList.contains(CLASSNAME_OPEN)) { closeDrawer(drawer, button); } else { openDrawer(drawer, button); } }); }; /* * public export */ export {initDrawer};
// This view renders a single issue, which contains sub-views for the reporter, labels, truncated summary, etc. var IssueView = Backbone.View.extend({ className: 'issuelist-item-view', render: function() { // Append labels to this view. var labels = this.model.get('labels'); var labelView = new LabelView(labels); this.$el.append(labelView.render().$el); // Append the issue title and number to this view. var issueMetaInfoView = new IssueMetaInfoView({ title: this.model.get('title'), number: this.model.get('number'), state: this.model.get('state') }); this.$el.append(issueMetaInfoView.render().$el); // Append a reporter to this view. var reporter = this.model.get('user'); var reporterView = new ReporterView(reporter); this.$el.append(reporterView.render().$el); // Append summary text to this view. var summaryText = this.model.get('body'); if (summaryText !== null && summaryText.length > 0) { var shortSummaryModel = new ShortSummaryModel({ text: summaryText }); var shortSummaryView = new ShortSummaryView({ model: shortSummaryModel }); this.$el.append(shortSummaryView.render().$el); } return this; } });
define(['jquery', 'moment', 'bootstrap', 'datatables.net', 'datatables.net-bs'], function ($, moment) { function PlansList(container) { var that = this; container = $(container); var table; function _init() { table = container.DataTable({ columns: [ {data: 'name'}, {data: 'remark'}, {data: 'deadline', render: tableDeadlineRender}, {data: 'status', render: tableAppraiseViewButtonRender}, {data: 'unfinished', render: tableUnfinishedLabelRender} ] }); container.on('click', 'td .button-appraise', function () { var tr = $(this).closest('tr'); var row = table.row(tr); var data = row.data(); // detail.modify(modify_plan_cb, data); window.location = 'appr_plan#' + data.id; }); container.on('click', 'td .button-view', function () { var tr = $(this).closest('tr'); var row = table.row(tr); var data = row.data(); // detail.modify(modify_plan_cb, data); window.location = 'appr_result#' + data.id; }); load_data(); } function tableDeadlineRender(data, type, row, meta) { return moment.unix(data).format('YYYY-MM-DD HH:mm'); } function tableAppraiseViewButtonRender(data, type, row, meta) { if (data == 1) { return '<button type="button" class="btn btn-success button-appraise">考评</button>'; } else { return '<button type="button" class="btn btn-info button-view">查看</button>' } } function tableUnfinishedLabelRender(data, type, row, meta) { if (data) { return '<span class="label label-danger">未完成</span>' } else { return ''; } } function load_data() { var options = { url: 'api/batch', data: {'apprPlans': 1, 'apprUnfinished': 1}, dataType: 'json', type: 'post', success: load_succ_cb }; $.ajax(options); } function load_succ_cb(data) { var plans = data.apprPlans; var unfinished = data.apprUnfinished; $.each(plans, function(_, plan) { plan.unfinished = (unfinished.indexOf(plan.id) !== -1); }); table.rows.add(plans); table.draw(); } _init(); } return PlansList; });
// Require dependencies const events = require('events'); const { writeFile } = require('fs'); const { promisify } = require('util'); const { join } = require('path'); // Create async writeFile const asyncWrite = promisify(writeFile); /** * Interface for Expr.constructor * @interface IExprConstructor */ const IExprConstructor = { addblock: true }; /** * Expr block code (represent a normal expression). * @class Expr * @extends events * * @property {Boolean} closed * @property {Boolean} addBlock * @property {Boolean} headerDone * @property {Array} childrensExpr * @property {Array} elements * */ class Expr extends events { /** * @constructor * @param {IExprConstructor} options */ constructor(options = {}) { super(); Object.assign(this,IExprConstructor,options); this.closed = false; this.rootExpr = undefined; this.headerDone = false; this.childrensExpr = []; this.elements = []; } /** * set the Expr root * @function Expr.setRoot * @param {Expr} root * @return Self */ setRoot(root) { if(root instanceof Expr === false) { throw new TypeError('Invalid root variable. Instanceof have to be equal to Expr.'); } this.rootExpr = root; return this; } /** * add a new Perl package * @function Expr.setPackage * @param {String} packageName * @return Self */ setPackage(packageName) { if(this.isModule === false) { throw new Error('Cannot set package on non-module file!'); } packageName = packageName.split('.').join('::'); this.elements.push(`package ${packageName};\n`); return this; } /** * Add a breakline into the perl code * @function Expr.breakline * @return Self */ breakline() { this.elements.push('\n'); return this; } /** * Add a new element into the Expr stack * @function Expr.add * @param {Any} element * @return Self */ add(element) { if(this.closed === true) { throw new Error('Expr closed... Impossible to add new element!'); } // When we try to add an undefined value! if('undefined' === typeof(element)) return; // When we try to add this to this... if(element === this) return; /* * When we add multiple element in row! */ if(element instanceof Array) { for(let i = 0,len = element.length;i<len;i++) { this.add(element[i]); } return; } /* * When the element is a perl lib. */ const rootDefined = 'undefined' === typeof(element.rootExpr); if(element instanceof Dependency) { if(this instanceof File === false) { throw new TypeError('Cannot add dependency on non-file expr class!'); } if(rootDefined) { if(this.headerDone === true) { this.elements.unshift(element.toString()); } else { this.elements.push(element.toString()); } return; } else { throw new Error('Cannot add new depencies on non-root Expr'); } } /* * When the element is a return statment (for a routine). */ if(element instanceof ReturnStatment) { if(this instanceof Routine) { this.elements.push(element.toString()); this.closed = true; this.returnStatment = true; this.returnMultiple = element.returnMultiple; this.returnType = element.returnedType; return; } } /* * When the element is a another Expr with no root defined. */ if(element instanceof While) { if(element._inner instanceof Expr && rootDefined === true) { element._inner.setRoot(this); } } else if(element instanceof Expr && rootDefined === true) { element.setRoot(this); } /* * Set SIG routine root! */ if(element instanceof SIG) { element.routine.setRoot(this); } /* * Register variables and routines for seeker mechanism. */ if(element instanceof Primitive) { this.elements.push( Primitive.constructorOf(element) ); return; } if(element instanceof Print || element instanceof RoutineShifting || element instanceof PrimeMethod) { element = element.toString(); } // Final push! this.elements.push( element ); return this; } /** * toString() Expr stack * @function Expr.toString * @return String */ toString() { if(this.elements.length === 0) return ''; let finalStr = ''; let i = 0,len = this.elements.length; for(;i<len;i++) { const element = this.elements[i]; if('string' === typeof(element)) { finalStr+=element; } else { finalStr+=element.toString(); } } return this.addblock === true ? `{\n${finalStr}};\n` : finalStr; } } /** * Default SEALang Perl package dependencies * @const FileDefaultDepencies * @type {Set<String>} */ const FileDefaultDepencies = new Set([ 'strict', 'warnings', 'stdlib.util', 'stdlib.array', 'stdlib.hashmap', 'stdlib.integer', 'stdlib.string', 'stdlib.boolean' ]); /** * Interface for File.constructor * @interface IFileConstructor */ const IFileConstructor = { isModule: false }; /** * @class File * @extend Expr * * @property {String} name * @property {Boolean} isModule */ class File extends Expr { /** * @constructor * @param {IFileConstructor} options */ constructor(options = {}) { super({ addblock: false }); if(typeof (options.name) !== 'string') { throw new TypeError('Invalid name type!'); } Object.assign(this,IFileConstructor,options); FileDefaultDepencies.forEach( DepName => { try { this.add(new Dependency(DepName)); } catch(E) { console.error(`Failed to add default depency ${DepName}`); console.error(E); } }); this.headerDone = true; } /** * Format perl code correctly (with the right indentation) * @function File.indentCode * @param {String} strCode * @return String */ indentCode(strCode) { if('string' !== typeof(strCode)) { throw new TypeError('Invalid type for strCode argument. Should be typeof string'); } let tabSpace = ' '; let incre = 0; return strCode.split('\n').map( line => { const cIncre = incre; let matchClose = false; if(line.match(/{/g)) { incre++; } else if(line.match(/}/g)) { incre--; matchClose = true; } if(incre === 0) return line; return tabSpace.repeat(matchClose ? incre : cIncre)+line; }).join('\n'); } /** * Write file to string location * @function File.write * @param {String} strLocation * @return String */ async write(strLocation,debug = false) { if('undefined' === typeof(strLocation)) { throw new TypeError('strLocation cant be undefined!'); } let filecode = super.toString(); if(this.isModule === true) { filecode += '1;'; } filecode = this.indentCode(filecode); if(debug === true) { console.log(filecode); } const finalStrPath = join( strLocation, `${this.name}.pl` ); console.log(`Write final final with name => ${finalStrPath}`); await asyncWrite(finalStrPath,filecode); return filecode; } } /** * @class Dependency * * @property {String} value */ class Dependency { /** * @constructor * @param {String} pkgName * @param {Array} requiredVars */ constructor(pkgName,requiredVars) { if(typeof(pkgName) !== 'string') { throw new TypeError('Invalid package type'); } pkgName = pkgName.split('.').join('::'); const ret = 'undefined' === typeof(requiredVars); if(ret === false) { if(requiredVars instanceof Array === false) { requiredVars = Array.from(requiredVars); } } this.value = ret === true ? `use ${pkgName};\n` : `use ${pkgName} qw(${requiredVars.join(' ')});\n`; } /** * @function Dependency.toString * @return String */ toString() { return this.value; } } /** * Constructor interface of Routine * @interface IRoutineConstructor */ const IRoutineConstructor = { args: [], shifting: false }; /** * Routine elements (Shiting,ReturnStatment and Routine) * @class Routine * @extends Expr * * @property {String} name * @property {String} routineName * @property {Boolean} anonymous * @property {Boolean} returnStatment * @property {Boolean} returnMultiple * @property {Any} returnType */ class Routine extends Expr { /** * @constructor * @param {IRoutineConstructor} options */ constructor(options = {}) { super({}); options = Object.assign(IRoutineConstructor,options); this.anonymous = 'undefined' === typeof(options.name); this.name = this.anonymous === true ? '' : name; this.routineName = this.anonymous === true ? 'anonymous' : this.name; const charCode = this.name.slice(-1).charCodeAt(0); if(Number.isNaN(charCode) === false && charCode !== ' '.charCodeAt(0)) { this.name+=' '; } this.returnStatment = false; this.returnType = void 0; this.returnMultiple = false; try { this.add(new RoutineShifting(options.arg,options.shifting)); } catch(E) { console.error(`Failed to add routine shifting for routine => ${this.routineName}`); console.error(E); } } /** * toString() Routine Expr * @function Routine.toString * @return String */ toString() { return `sub ${this.name}`+super.toString(); } } /** * Routine Shifting * @class RoutineShifting * * @property {String} value */ class RoutineShifting { /** * @constructor * @param {Array} variables * @param {Boolean} shifting */ constructor(variables,shifting = false) { this.value = ''; if('undefined' === typeof(variables)) { throw new TypeError('Cannot shift undefined variables'); } if(variables instanceof Array) { if(variables.length > 0) { if(shifting === true) { let finalStr = ''; variables.forEach( (element) => { const elName = element instanceof Primitive ? `$${element.name}` : '$'+element; finalStr+='my '+elName+' = shift;\n'; }); this.value = finalStr; } else { const finalStr = variables.map( (element) => element instanceof Primitive ? `$${element.name}` : '$'+element ).join(','); this.value = `my (${finalStr}) = @_;\n`; } } } else { const elName = variables instanceof Primitive ? `$${variables.name}` : '$'+variables; this.value = 'my '+elName+' = shift;\n'; } } /** * @function RoutineShifting.toString * @return String */ toString() { return this.value; } } /** * Return routine statment! * @class ReturnStatment * * @property {String} value */ class ReturnStatment { /** * @constructor * @param {Any} expr */ constructor(expr) { if('undefined' === typeof(expr)) { throw new TypeError('Cannot create a ReturnStatment block with an undefined expr'); } if(expr instanceof Array) { this.returnMultiple = true; this.returnedType = []; const elems = []; expr.forEach( (subExpr,index) => { if(subExpr instanceof Primitive) { this.returnedType[index] = expr.libtype.std; elems.push(`$${subExpr.name}`); } else { this.returnedType[index] = 'any'; elems.push(`${subExpr}`); } }); this.value = `return (${elems.join(',')});\n`; } else { this.returnMultiple = false; if(expr instanceof Primitive) { this.returnedType = expr.libtype.std; this.value = expr.name === 'anonymous' ? `return ${Primitive.constructorOf(expr)}` : `return $${expr.name};\n`; } else { this.returnedType = 'any'; this.value = `return ${expr};\n`; } } } /** * @function ReturnStatment.toString * @return String */ toString() { return this.value; } } /** * Implementation of Print method * @class Print * * @property {String} value; */ class Print { /** * @constructor * @param {String} message * @param {Boolean} newLine */ constructor(message,newLine = true) { if('undefined' === typeof(message)) { message = ''; } else if(message instanceof Primitive) { message = `$${message.name}->valueOf()`; } if('string' !== typeof(message)) { message = ''; } this.value = `print(${message}."${newLine === true ? '\\n' : ''}");\n`; } /** * toString() print method * @function Print.toString * @return String */ toString() { return this.value; } } /** * Process var */ const Process = { exit: (code = 0) => `exit(${code});\n`, argv: () => { return 'stdlib::array->new(@ARGV)'; } }; /** * Condition Enumeration * @enum EConditionBlock * * @member EConditionBlock.if * @member EConditionBlock.else * @member EConditionBlock.elif */ const EConditionBlock = new Set(['if','else','elif']); /** * @class Condition * @extends Expr * * @property {String} cond * @property {String} expr */ class Condition extends Expr { /** * @constructor * @param {String} cond * @param {String} expr */ constructor(cond,expr) { super(); if(EConditionBlock.has(cond) === false) { throw new Error(`Unknown condition type ${cond}!`); } if('undefined' === typeof(expr)) { throw new TypeError('Undefined expr'); } this.cond = cond; this.expr = expr instanceof Primitive ? `$${expr.name}->valueOf() == 1` : expr; this.expr = this.expr.replace(';','').replace('\n',''); } /** * @function Condition.toString * @return String */ toString() { return `${this.cond} (${this.expr}) `+super.toString(); } } /** * Classical While (only for SEA.Array and maybe array late) * @class While * @extends Expr * * @property {Expr} _inner * @property {SEA.Int} incre */ class While extends Expr { /** * @constructor * @param {SEA.Array} SEAArray */ constructor(SEAArray) { super(); if(SEAArray instanceof Arr === false) { throw new TypeError('Unsupported element type for a while block. Must be a SEA.Array'); } this._inner = new Expr(); this.setRoot(this._inner); this.incre = new Int('i',0); this._inner.add(this.incre); this._inner.add(new Int('len',SEAArray.size())); const PrimeRef = IPrimeLibrairies.get(SEAArray.template).schema; this.add(new PrimeRef('element',SEAArray.get(this.incre))); } /** * @function While.toString * @return String */ toString() { this.add(this.incre.add(1)); this._inner.add(`while($i < $len) ${super.toString()}`); return this._inner.toString(); } } /** * Foreach block Expr (for HashMap or Hash) * @class Foreach * @extends Expr * * @property {HashMap} hash * @property {Routine} routine */ class Foreach extends Expr { /** * @constructor * @param {HashMap} SEAHash */ constructor(SEAHash) { super(); if(SEAHash instanceof HashMap === false) { throw new TypeError('Unsupported type for Foreach block!'); } this.hash = SEAHash; this.routine = new Routine({ arg: ['key','value'] }); } /** * @function Foreach.toString * @return String */ toString() { this.routine.add(this.elements); return this.hash.forEach(this.routine).toString(); } } /** * Evaluation (try/catch emulation) * @class Evaluation * @extends Expr * * @property {Condition} catchExpr */ class Evaluation extends Expr { /** * @constructor */ constructor() { super(); try { this.catchExpr = new Condition('if','$@'); this.catchExpr.add(new Print('$@',true)); } catch(E) { console.error('Failed to create catch Expr Condition for Evaluation'); console.error(E); } } /** * @getter Evaluation.catch * @return Self.catchExpr */ get catch() { return this.catchExpr; } /** * @function Evaluation.toString * @return String */ toString() { return 'eval '+super.toString()+this.catchExpr.toString(); } } /** * Enum SIG Event handler * @enum EAvailableSIG */ const EAvailableSIG = new Set([ 'CHLD', 'DIE', 'INT', 'ALRM', 'HUP' ]); /** * @class SIG * * @property {String} code * @property {Routine} routine */ class SIG { /** * constructor * @param {String} code * @param {Routine} routineHandler */ constructor(code,routineHandler) { if(EAvailableSIG.has(code) === false) { throw new RangeError(`Invalid SIG ${code}!`); } if(routineHandler instanceof Routine === false) { throw new TypeError('routine should be instanceof Routine'); } this.code = code; this.routine = routineHandler; } /** * @function SIG.toString * @return String */ toString() { return `$SIG{${this.code}} = `+this.routine.toString(); } } /* ------------------------ PRIMITIVE TYPES ------------------------ */ const IPrimeLibrairies = new Map(); const IPrimeScalarCast = new Set(['stdlib::integer','stdlib::string','stdlib::boolean']); /** * Primitive abstraction handler * @class Primitive * * @property {String} libType * @property {String} name * @property {Boolean} castScalar * @property {String} constructValue * @property {String} value * @property {String} template */ class Primitive { /** * @constructor */ constructor({type,name,template,value = 'undef'}) { if('undefined' === typeof(name)) { name = 'anonymous'; } if(IPrimeLibrairies.has(type) === false) { throw new Error(`Primitive type ${type} doesn't exist!`); } this.libtype = IPrimeLibrairies.get(type); if(value instanceof Routine) { if(value.returnStatment === false) { throw new Error(`Cannot assign undefined value from ${value.routineName} to variable ${type}.${name}`); } if(type !== 'array' && value.returnMultiple === true) { throw new Error(`Cannot assign multiple values from ${value.routineName} to variable ${type}.${name}`); } if(type === 'array') { // Implement array type check! } else { this.castScalar = false; if(IPrimeScalarCast.has(value.returnType) === true && this.libtype.std === 'scalar') { this.castScalar = true; } else if(value.returnType !== this.libtype.std) { throw new Error(`Invalid returned type from ${value.routineName}!`); } } } if(type === 'array' || type === 'map') { this.template = 'undefined' === typeof(template) ? 'scalar' : template; } this.name = name; this.constructValue = value; this.value = value; } /** * @function Primitive.method * @param {String} name * @param {...<any>} args * @return PrimeMethod */ method(name,...args) { return new PrimeMethod({ name, args, element: this }); } /** * Get libtype type * @getter Primitive.type * @return String */ get type() { return this.libtype.std; } /** * @static Primitive.valueOf * @param {instanceof Primitive} SEAElement * @param {Boolean} assign * @param {Boolean} inline * @return String */ static valueOf(parentElement,childrenElement,assign = false,inline = false) { const rC = inline === true ? '' : ';\n'; const assignV = assign === true ? `my $${parentElement.name} = ` : ''; if(childrenElement instanceof Arr === true || childrenElement instanceof HashMap === true) { return `${assignV}$${childrenElement.name}->clone()${rC}`; } else { return `${assignV}$${childrenElement.name}->valueOf()${rC}`; } } /** * @static Primitive.constructorOf * @param {Any} SEAElement * @param {Boolean} inline * @return String */ static constructorOf(SEAElement,inline = false) { if(SEAElement instanceof Primitive === false) { throw new TypeError('SEAElement Instanceof primitive is false!'); } const rC = inline === true ? '' : ';\n'; let value = SEAElement.constructValue; const typeOf = typeof(value); if(value instanceof Primitive === true) { return Primitive.valueOf(SEAElement,value,true,inline); } else if(value instanceof Routine === true) { const castCall = SEAElement.castScalar === true ? '->valueOf()' : ''; return value.routineName === 'anonymous' ? `my $${SEAElement.name} = ${value.toString()}${castCall}` : `my $${SEAElement.name} = ${value.routineName}()${castCall}${rC}`; } else if(value instanceof PrimeMethod === true) { return `my $${SEAElement.name} = ${value.toString()}`; } else { let assignHead = ''; if(SEAElement.name !== 'anonymous') { assignHead = `my $${SEAElement.name} = `; } if(SEAElement instanceof Str === true) { return `${assignHead}${SEAElement.type}->new("${value}")${rC}`; } else if(SEAElement instanceof Scalar === true) { if(typeOf === 'string' || typeOf === 'number') { return typeOf === 'string' ? `${assignHead}"${value}"${rC}` : `${assignHead}${value}${rC}`; } throw new Error('Invalid type for scalar type!'); } else if(SEAElement instanceof Hash) { if(typeOf === 'object') { return `${assignHead}${Hash.ObjectToHash(value)}${rC}`; } throw new Error('Invalid hash type argument!'); } else if(SEAElement instanceof HashMap === true) { if(SEAElement.template !== 'scalar') { const primeRef = IPrimeLibrairies.get(SEAElement.template).schema; for(let [k,v] of Object.entries(value)) { value[k] = Primitive.constructorOf(new primeRef(void 0,v),true); } } return `${assignHead}${SEAElement.type}->new(${Hash.ObjectToHash(value)})${rC}`; } else if(SEAElement instanceof Arr === true && SEAElement.template !== 'scalar') { const primeRef = IPrimeLibrairies.get(SEAElement.template).schema; value = value.map( val => { return Primitive.constructorOf(new primeRef(void 0,val),true); }); return `${assignHead}${SEAElement.type}->new(${value})${rC}`; } return `${assignHead}${SEAElement.type}->new(${value})${rC}`; } } } /** * Primitive Method * @class PrimeMehthod */ class PrimeMethod { /** * @constructor */ constructor({name,element,args = []}) { if('string' !== typeof(name)) { throw new TypeError('name argument should be typeof string'); } this.name = name; this.element = element; this.args = args.map( val => { return val instanceof Primitive ? Primitive.valueOf(element,val,false,true) : val; }); } /** * @function PrimeMethod.toString * @return String */ toString() { return `$${this.element.name}->${this.name}(${this.args.join(',')});\n`; } } /** * SEA String * @class Str * @extends Primitive */ class Str extends Primitive { /* * @constructor * @param {String} varName * @param {String} valueOf */ constructor(varName,valueOf) { super({ type: 'string', name: varName, value: valueOf, }); } updateValue(newValue) { return this.method('updateValue',newValue); } valueOf() { return this.method('valueOf'); } freeze() { return this.method('freeze'); } length() { return this.method('length'); } isEqual(element) { if('undefined' === typeof(element)) { throw new Error('Undefined element'); } return this.method('isEqual',element); } substr(start,end) { return this.method('substr',start,end); } clone() { return this.method('clone'); } slice(start,end) { return this.method('slice',start,end); } last() { return this.method('last'); } charAt(index) { return this.method('charAt',index); } charCodeAt(index) { return this.method('charCodeAt',index); } repeat(count) { if('undefined' === typeof(count)) { count = 1; } return this.method('repeat',count); } constains(substring) { return this.method('contains',substring); } containsRight(substring) { return this.method('containsRight',substring); } split(carac) { return this.method('split',carac); } trim() { return this.method('trim'); } trimLeft() { return this.method('trimLeft'); } trimRight() { return this.method('trimRight'); } toLowerCase() { return this.method('toLowerCase'); } toUpperCase() { return this.method('toUpperCase'); } } /** * SEA Integer * @class Int * @extends Primitive */ class Int extends Primitive { /** * @constructor * @param {String} varName * @param {String} valueOf */ constructor(varName,valueOf) { super({ type: 'integer', name: varName, value: valueOf, }); } updateValue(newValue) { return this.method('updateValue',newValue); } valueOf() { return this.method('valueOf'); } freeze() { return this.method('freeze'); } length() { return this.method('length'); } add(value) { if('undefined' === typeof(value)) { throw new Error('Undefined value'); } return this.method('add',value); } sub(value) { if('undefined' === typeof(value)) { throw new Error('Undefined value'); } return this.method('sub',value); } mul(value) { if('undefined' === typeof(value)) { throw new Error('Undefined value'); } return this.method('mul',value); } div(value) { if('undefined' === typeof(value)) { throw new Error('Undefined value'); } return this.method('div',value); } } /** * SEA Boolean * @class Bool * @extends Primitive */ class Bool extends Primitive { /* * @constructor * @param {String} varName * @param {String} valueOf */ constructor(varName,valueOf) { super({ type: 'boolean', name: varName, value: valueOf ? 1 : 0, }); } updateValue(newValue) { return this.method('updateValue',newValue); } // @PrimeMethod Bool.valueOf valueOf() { return this.method('valueOf'); } } /** * SEA Array * @class Arr * @extends Primitive */ class Arr extends Primitive { /** * @constructor * @param {String} name * @param {String} template * @param {Array} value */ constructor(name,template,value = []) { super({ type: 'array', name, template, value }); } freeze() { return this.method('freeze'); } forEach(routine) { if(routine instanceof Routine === false) { throw new TypeError('Invalid routine type!'); } return this.method('forEach',routine); } map(routine) { if(routine instanceof Routine === false) { throw new TypeError('Invalid routine type!'); } return this.method('map',routine); } every(routine) { if(routine instanceof Routine === false) { throw new TypeError('Invalid routine type!'); } return this.method('every',routine); } get(index) { if('undefined' === typeof(index)) { throw new Error('Undefined index argument'); } return this.method('get',index); } size() { return this.method('size'); } } /** * SEA HashMap * @class HashMap * @extends Primitive */ class HashMap extends Primitive { /** * @constructor * @param {String} name * @param {String} template * @param {Array} value */ constructor(name,template,value = {}) { super({ type: 'map', name, template, value }); } freeze() { return this.method('freeze'); } clear() { return this.method('clear'); } keys() { return this.method('keys'); } values() { return this.method('values'); } forEach(routine) { if(routine instanceof Routine === false) { throw new TypeError('Invalid routine type!'); } return this.method('forEach',routine); } size() { return this.method('size'); } get(value) { return this.method('get',value); } set(key,value) { return this.method('set',key,value); } delete(key) { if('undefined' === typeof(key)) { throw new TypeError('Undefined key!'); } return this.method('delete',key); } } /** * SEA Fallback implementation of Perl Hash * @class Hash * @extends Primitive */ class Hash extends Primitive { /** * @constructor * @param {String} varName * @param {String} valueOf */ constructor(varName,valueOf) { super({ type: 'hash', name: varName, value: valueOf, }); } /** * Transform a JS Object into a Perl Hash * * @static Hash.ObjectToHash * @param {Object} object * @return String */ static ObjectToHash(object) { if(typeof(object) !== 'object') { throw new TypeError('Invalid object type!'); } const parseArray = function(arr) { arr = arr.map( arrV => { const typeOf = typeof(arrV); if(arrV instanceof Array) { return parseArray(arrV); } else if(typeOf === 'object') { return parse(arrV); } else if(typeOf === 'string') { return `"${arrV}"`; } else if(typeOf === 'boolean') { return `${arrV === true ? 1 : 0}`; } else { return arrV.toString(); } }); return `(${arr.join(',')})`; }; const parse = function(_O) { let ret = '{'; for(let k in _O) { const v = _O[k]; const typeOf = typeof(v); if(v instanceof Array) { ret+=`${k} => ${parseArray(v)},`; } else if(typeOf === 'object') { ret+=`${k} => ${parse(v)},`; } else if(typeOf === 'string') { ret+=`${k} => ${v},`; } else if(typeOf === 'boolean') { ret+=`${k} => ${v === true ? 1 : 0},`; } else { ret+=`${k} => ${v.toString()},`; } } return ret.slice(0,-1)+'}'; }; return parse(object); } } /** * SEA Fallback implementation of Perl Scalar * @class Scalar * @extends Primitive */ class Scalar extends Primitive { /** * @constructor * @param {String} varName * @param {String} valueOf */ constructor(varName,valueOf) { super({ type: 'scalar', name: varName, value: valueOf, }); } } // Define prime scheme IPrimeLibrairies.set('string',{ std: 'stdlib::string', schema: Str }); IPrimeLibrairies.set('integer',{ std: 'stdlib::integer', schema: Int }); IPrimeLibrairies.set('boolean',{ std: 'stdlib::boolean', schema: Bool }); IPrimeLibrairies.set('array',{ std: 'stdlib::array', schema: Arr }); IPrimeLibrairies.set('map',{ std: 'stdlib::hashmap', schema: HashMap }); IPrimeLibrairies.set('hash',{ std: 'hash', schema: Hash }); IPrimeLibrairies.set('scalar',{ std: 'scalar', schema: Scalar }); // Export every schema class! module.exports = { File, Process, Dependency, Expr, Routine, ReturnStatment, Condition, SIG, While, Foreach, Print, Primitive, Hash, HashMap, Str, Int, Bool, Arr, Scalar, PrimeMethod, Evaluation };
import { connect } from 'react-redux'; import { toggleShoppingItem } from '../actions/shoppingItems'; import ShoppingItemList from '../components/ShoppingItemList'; const mapStateToProps = (state) => { return { shoppingItems: state.shoppingItems }; }; const mapDispatchToProps = (dispatch) => { return { onShoppingItemClick: (id) => { dispatch(toggleShoppingItem(id)); } }; }; const VisibleShoppingItemList = connect( mapStateToProps, mapDispatchToProps )(ShoppingItemList); export default VisibleShoppingItemList;
import * as types from '../../constants'; import update from 'react/lib/update'; export default function currentPost(state = { lastFetched: null, isLoading: false, error: null, data: {}, }, action) { switch (action.type) { case types.LOAD_POST_REQUEST: return update(state, { isLoading: { $set: true }, error: { $set: null } }); case types.LOAD_POST_SUCCESS: return update(state, { data: { $set: action.body }, lastFetched: { $set: action.lastFetched }, isLoading: { $set: false }, }); case types.LOAD_POST_FAILURE: return update(state, { error: { $set: action.error }, }); default: return state; } }
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import SetForm from 'app/shared_features/set_card/expanded/SetForm'; import * as Actions from './OneRMEditSetFormActions'; import * as DateUtils from 'app/utility/DateUtils'; const mapStateToProps = (state, ownProps) => { const rpeDisabled = !DateUtils.checkDateWithinRange(7, ownProps.initialStartTime) return { rpeDisabled: rpeDisabled, }; } const mapDispatchToProps = (dispatch) => { return bindActionCreators({ saveSet: Actions.saveSet, tapExercise: Actions.presentExercise, tapTags: Actions.presentTags, tapRPE: Actions.editRPE, tapWeight: Actions.editWeight, dismissRPE: Actions.dismissRPE, dismissWeight: Actions.dismissWeight, toggleMetric: Actions.toggleMetric, updateWeight: Actions.updateWeight, updateRPE: Actions.updateRPE, }, dispatch); }; const OneRMEditSetFormScreen = connect( mapStateToProps, mapDispatchToProps )(SetForm); export default OneRMEditSetFormScreen;
const Promise = require('../../src'); const assert = require('chai').assert; const sinon = require('sinon'); describe('flow control - #for', () => { context('instance', () => { it('when called 0 to 10, i variable must be from 0 to 10', done => { let val = 0; Promise.resolve() .for(0, 10, (i) => assert.equal(i, val++)) .then(() => done()); }); it('when called from a resolved value, the val must be equal', done => { let val = 3; Promise.resolve(val) .for(0, 10, (i, v) => assert.equal(v, val)) .then(() => done()); }); }); context('static', () => { it('when called 0 to 10, i variable must be from 0 to 10', done => { let val = 0; Promise.for(0, 10, (i) => assert.equal(i, val++)) .then(() => done()); }); }); });
var RaceData = { human: { name: 'Human', physical: 6, personal: 6, mental: 4, magical: 0, genders: 'male|female', }, dwarf: { name: 'Dwarf', physical: 8, personal: 0, mental: 4, magical: 4, genders: 'male', defenses: { moist:5 }, }, elf: { name: 'Elf', physical: 0, personal: 6, mental: 2, magical: 8, genders: 'female', abilities: ['royalRainbow'], defenses: { sad:5 }, }, troll: { name: 'Troll', physical: 12, personal: 2, mental: 0, magical: 2, genders: 'male', abilities: ['biteAttack'], defenses: { slash:1, crush:1 }, } };
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84l3.96-5.58c.25-.35.25-.81 0-1.16l-3.96-5.58z" /> , 'LabelRounded');
import React, { Component } from 'react' import { connect } from 'react-redux' import { forceCheck } from 'react-lazyload' import { getFiles, thumbnailGenerated, makeFilesLoadedSelector } from 'ducks/files' import { openFileModal } from 'ducks/fileModal' import SingleSelect from 'containers/SingleSelect' import MultiSelect from 'containers/MultiSelect' import IndexMode from 'containers/IndexMode' import ModalSingleSelect from 'containers/ModalSelect/ModalSingleSelect' import FileModal from 'containers/FileModal' import Atoms from 'containers/Atoms' import FilesAppWrap from './styled/FilesAppWrap' class FilesApp extends Component { componentWillMount () { if (this.shouldAutoLoadFiles()) { this.loadFiles(this.props.app.fileType, this.props.app.filesUrl) } this.listenOnActionCable() window.addEventListener('checkLazyload', forceCheck) } loadFiles = (fileType, filesUrl) => { if (!this.props.filesLoaded) { this.props.dispatch(getFiles(fileType, filesUrl)) } } listenOnActionCable () { if (!window.FolioCable) return this.cableSubscription = window.FolioCable.cable.subscriptions.create('FolioThumbnailsChannel', { received: (data) => { if (!data) return if (!data.temporary_url || !data.url) return this.props.dispatch(thumbnailGenerated('images', data.temporary_url, data.url)) } }) } shouldAutoLoadFiles () { return this.props.app.mode !== 'modal-single-select' && this.props.app.mode !== 'atoms' } openFileModal = (fileType, filesUrl, file) => { this.props.dispatch(openFileModal(fileType, filesUrl, file)) } renderMode () { const { mode, fileType, filesUrl, readOnly, reactType } = this.props.app if (mode === 'multi-select') { return <MultiSelect fileType={fileType} filesUrl={filesUrl} /> } if (mode === 'single-select') { return <SingleSelect fileType={fileType} filesUrl={filesUrl} /> } if (mode === 'index') { return <IndexMode fileType={fileType} filesUrl={filesUrl} readOnly={readOnly} /> } if (mode === 'modal-single-select') { return ( <ModalSingleSelect fileType={fileType} filesUrl={filesUrl} reactType={reactType} loadFiles={this.loadFiles} openFileModal={this.openFileModal} /> ) } if (mode === 'atoms') { return ( <Atoms /> ) } return ( <div className='alert alert-danger'> Unknown mode: {mode} </div> ) } render () { return ( <FilesAppWrap className='folio-react-app'> {this.renderMode()} <FileModal readOnly={this.props.app.readOnly} /> </FilesAppWrap> ) } } const mapStateToProps = (state, props) => ({ app: state.app, filesLoaded: makeFilesLoadedSelector(props.fileType)(state) }) function mapDispatchToProps (dispatch) { return { dispatch } } export default connect(mapStateToProps, mapDispatchToProps)(FilesApp)
'use strict'; const keyBy = require('lodash/keyBy'); const CapturesCreateValidator = require('../../../validators/captures/create'); const CapturesDeleteValidator = require('../../../validators/captures/delete'); const Controller = require('./controller'); const Pokemon = require('../../../models/pokemon'); exports.register = (server, options, next) => { let pokemonById; server.route([{ method: 'GET', path: '/users/{username}/dexes/{slug}/captures', config: { handler: (request, reply) => reply(Controller.list(request.params, pokemonById)) } }, { method: 'POST', path: '/captures', config: { auth: 'token', handler: (request, reply) => reply(Controller.create(request.payload, request.auth.credentials)), validate: { payload: CapturesCreateValidator } } }, { method: 'DELETE', path: '/captures', config: { auth: 'token', handler: (request, reply) => reply(Controller.delete(request.payload, request.auth.credentials)), validate: { payload: CapturesDeleteValidator } } }]); return new Pokemon().query((qb) => qb.orderBy('id')).fetchAll({ withRelated: Pokemon.CAPTURE_SUMMARY_RELATED }) .get('models') .then((p) => { pokemonById = keyBy(p, 'id'); next(); }); }; exports.register.attributes = { name: 'captures' };
!function(window,stik){stik.boundary({as:"tplWrapper",from:"all",to:function($template){if(window.hasOwnProperty("MooTools"))return window.document.id($template);if(window.hasOwnProperty("Zepto"))return window.Zepto($template);if(window.hasOwnProperty("jQuery"))return window.jQuery($template);throw"no DOM library found"}})}(window,window.stik),function(stik){stik.boundary({as:"tpl",from:"all",resolvable:!0,to:function($template,tplWrapper){return tplWrapper($template)}})}(window.stik);
function renderTOC(toc) { $('#toc').html( parseList(toc, 0) ); } function renderDoc(path) { window.md = window.md || window.markdownit() .use(window.markdownitContainer) .use(window.markdownitFootnote) .use(window.markdownitIns) .use(window.markdownitMark) .use(window.markdownitSup); $.get(path + '.md', function (doc) { $('#doc').html( window.md.render(doc) ) }) } function parseList(conf, tier) { var html = ''; html += "<ul class='tier tier-" + tier + "'>"; $.each(conf, function (i, item) { if (item.path) { html += "<li class='link' data-path='" + item.path + "'><a href='javascript:void(0);'>"; } else if (item.link) { html += "<li class='link'><a href='" + item.link + "'>"; } else { html += "<li><a>"; } html += item.name + "</a></li>"; if (item.next) { html += parseList(item.next, tier + 1) } }); html += "</ul>"; return html; }
const mail = require('../config').mail const nodemailer = require('nodemailer') const transporter = nodemailer.createTransport({ service: 'gmail', auth: mail }); // transporter.sendMail(mailOptions, (error, info) => { // if (error) { // return console.log(new Date() + ' ' + error); // } // }) module.exports = transporter
/** * Controller used to render the notification icon in the mobile app decoration * * @@source_header * * -- * * This file is part of the focus-app-demonstrator package. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ 'use strict'; (function() { angular.module('focusApp.notifications', [ 'focusApp.dataService', 'focusApp.inboxService' ]) .controller('NotificationsController', [ 'InboxService', function(InboxService) { var _self = this; /** * Reference to the current data sample being rendered */ _self.inboxSvc = InboxService; /** * Ref to data service */ // _self.dataSvc = DataService; } ]); }());
(function() { var checkVersion = Dagaz.Model.checkVersion; Dagaz.Model.checkVersion = function(design, name, value) { if (name != "koom-valley-goal") { checkVersion(design, name, value); } } var checkGoals = Dagaz.Model.checkGoals; Dagaz.Model.checkGoals = function(design, board, player) { var winner = null; var stone = null; _.each(design.allPositions(), function(pos) { if (stone === null) { var piece = board.getPiece(pos); if ((piece !== null) && (piece.type == 0)) { stone = pos; } } }); if (stone !== null) { if (design.inZone(0, 1, stone)) { winner = 1; } else { var cnt = 0; _.each(design.allDirections(), function(dir) { var p = design.navigate(board.player, stone, dir); if (p === null) return; var piece = board.getPiece(p); if (piece === null) return; if (piece.player == 2) cnt++; }); if (cnt >= 3) winner = 2; } } if (winner !== null) { if (winner == player) { return 1; } else { return -1; } } return checkGoals(design, board, player); } })();
enyo.kind({ name : "menuPanel", kind: "FittableRows", classes: "panel", components: [ {kind: "onyx.Toolbar", name : "title", content: "Menü"}, {kind: "menuList", fit:true}, {kind: "onyx.Toolbar", components: [ {kind: "onyx.Grabber"}, // {kind: "onyx.Button", content: "Einstellungen", ontap: "openSettings"}, // {kind: "onyx.Button", content: "Info", ontap: "openInfo" }, {classes: "menu-button", ontap: "openSettings", kind: "onyx.IconButton", src: "assets/settings.png" }, {classes: "menu-button", ontap: "openInfo", kind: "onyx.IconButton", src: "assets/info.png" }, {classes: "menu-button", ontap: "openPanels", kind: "onyx.IconButton", src: "assets/filter.png" } ]}, {kind: enyo.Signals, onFilterChange: "load", onDisplayPricesChange: "load", onSettingsChange: "settingsChange"} ], openPanels: function(){ enyo.Signals.send("onChangePanels"); }, openSettings: function(){ enyo.Signals.send("onRequestSettings"); }, openInfo: function(){ enyo.Signals.send("onRequestInfo"); }, settingsChange: function(inSender, payload){ if(payload.changed){ this.load(); } }, create : function(){ this.inherited(arguments); this.load(); }, load : function(){ this.$.menuList.setLoading(true); // console.time("get"); storage.getSortedSegmented(function(json){ // console.timeEnd("get"); this.$.menuList.setLoading(false); this.$.menuList.menu = json; // console.time("list"); this.$.menuList.load(); // console.timeEnd("list"); // console.time("reflow"); this.reflow(); // console.timeEnd("reflow"); }.bind(this)); } });
/** * Module dependencies. */ const express = require('express'); const compression = require('compression'); const session = require('express-session'); const bodyParser = require('body-parser'); const logger = require('morgan'); const chalk = require('chalk'); const errorHandler = require('errorhandler'); const lusca = require('lusca'); const dotenv = require('dotenv'); const MongoStore = require('connect-mongo')(session); const flash = require('express-flash'); const path = require('path'); const mongoose = require('mongoose'); const passport = require('passport'); const expressValidator = require('express-validator'); const expressStatusMonitor = require('express-status-monitor'); const sass = require('node-sass-middleware'); const multer = require('multer'); const upload = multer({ dest: path.join(__dirname, 'uploads') }); /** * Load environment variables from .env file, where API keys and passwords are configured. */ dotenv.load({ path: '.env' }); /** * Controllers (route handlers). */ const homeController = require('./controllers/home'); const userController = require('./controllers/user'); const apiController = require('./controllers/api'); const contactController = require('./controllers/contact'); const barsController = require('./controllers/bars'); const adminController = require('./controllers/admin'); /** * API keys and Passport configuration. */ const passportConfig = require('./config/passport'); /** * Create Express server. */ const app = express(); /** * Connect to MongoDB. */ mongoose.Promise = global.Promise; mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI); mongoose.connection.on('error', (err) => { console.error(err); console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗')); process.exit(); }); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(expressStatusMonitor()); app.use(compression()); app.use(sass({ src: path.join(__dirname, 'public'), dest: path.join(__dirname, 'public') })); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(expressValidator()); app.use(session({ resave: true, saveUninitialized: true, secret: process.env.SESSION_SECRET, store: new MongoStore({ url: process.env.MONGODB_URI || process.env.MONGOLAB_URI, autoReconnect: true, clear_interval: 3600 }) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.use((req, res, next) => { if (req.path === '/api/upload') { next(); } else { lusca.csrf()(req, res, next); } }); app.use(lusca.xframe('SAMEORIGIN')); app.use(lusca.xssProtection(true)); app.use((req, res, next) => { res.locals.user = req.user; next(); }); app.use((req, res, next) => { // After successful login, redirect back to the intended page if (!req.user && req.path !== '/login' && req.path !== '/signup' && !req.path.match(/^\/auth/) && !req.path.match(/\./)) { req.session.returnTo = req.path; } else if (req.user && req.path == '/account') { req.session.returnTo = req.path; } next(); }); app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); /** * Bars Routes by dev */ //view bars app.get('/', barsController.getAllBars); app.get('/my-bars', passportConfig.isAuthenticated, barsController.getMyBars); app.get('/this-rappa/:id', barsController.getBarsForThisRappa); // set bars app.get('/spit-bars',barsController.spitBars); app.post('/spit-bars', barsController.postBars); // edit bars app.get('/edit-bars', passportConfig.isAuthenticated, barsController.editBars); app.post('/edit-bars', passportConfig.isAuthenticated, barsController.submitEdittedBars); // delete bars app.post('/delete-bars', passportConfig.isAuthenticated, barsController.deleteBars); // post submitting judgement (votes) app.post('/judgement', passportConfig.isAuthenticated, barsController.submitJudgement); // ADMIN ROUTES app.get('/admin', passportConfig.isAuthenticated, passportConfig.isAdmin, adminController.getAdminOverview); /** * Primary app routes. */ app.get('/login', userController.getLogin); app.post('/login', userController.postLogin); app.get('/logout', userController.logout); app.get('/forgot', userController.getForgot); app.post('/forgot', userController.postForgot); app.get('/reset/:token', userController.getReset); app.post('/reset/:token', userController.postReset); app.get('/signup', userController.getSignup); app.post('/signup', userController.postSignup); app.get('/contact', contactController.getContact); app.post('/contact', contactController.postContact); app.get('/account', passportConfig.isAuthenticated, userController.getAccount); app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile); app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword); app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount); // app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink); /** * API examples routes. */ // app.get('/api', apiController.getApi); // app.get('/api/lastfm', apiController.getLastfm); // app.get('/api/nyt', apiController.getNewYorkTimes); // app.get('/api/aviary', apiController.getAviary); // app.get('/api/steam', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getSteam); // app.get('/api/stripe', apiController.getStripe); // app.post('/api/stripe', apiController.postStripe); // app.get('/api/scraping', apiController.getScraping); // app.get('/api/twilio', apiController.getTwilio); // app.post('/api/twilio', apiController.postTwilio); // app.get('/api/clockwork', apiController.getClockwork); // app.post('/api/clockwork', apiController.postClockwork); // app.get('/api/foursquare', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFoursquare); // app.get('/api/tumblr', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getTumblr); // app.get('/api/facebook', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFacebook); // app.get('/api/github', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getGithub); // app.get('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getTwitter); // app.post('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postTwitter); // app.get('/api/linkedin', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getLinkedin); // app.get('/api/instagram', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getInstagram); // app.get('/api/paypal', apiController.getPayPal); // app.get('/api/paypal/success', apiController.getPayPalSuccess); // app.get('/api/paypal/cancel', apiController.getPayPalCancel); // app.get('/api/lob', apiController.getLob); // app.get('/api/upload', apiController.getFileUpload); // app.post('/api/upload', upload.single('myFile'), apiController.postFileUpload); // app.get('/api/pinterest', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getPinterest); // app.post('/api/pinterest', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postPinterest); // app.get('/api/google-maps', apiController.getGoogleMaps); /** * OAuth authentication routes. (Sign in) */ // app.get('/auth/instagram', passport.authenticate('instagram')); // app.get('/auth/instagram/callback', passport.authenticate('instagram', { failureRedirect: '/login' }), (req, res) => { // res.redirect(req.session.returnTo || '/'); // }); // app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'public_profile'] })); // app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), (req, res) => { // res.redirect(req.session.returnTo || '/'); // }); // app.get('/auth/github', passport.authenticate('github')); // app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), (req, res) => { // res.redirect(req.session.returnTo || '/'); // }); // app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' })); // app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) => { // res.redirect(req.session.returnTo || '/'); // }); // app.get('/auth/twitter', passport.authenticate('twitter')); // app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), (req, res) => { // res.redirect(req.session.returnTo || '/'); // }); // app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' })); // app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), (req, res) => { // res.redirect(req.session.returnTo || '/'); // }); // // /** // * OAuth authorization routes. (API examples) // */ // app.get('/auth/foursquare', passport.authorize('foursquare')); // app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), (req, res) => { // res.redirect('/api/foursquare'); // }); // app.get('/auth/tumblr', passport.authorize('tumblr')); // app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), (req, res) => { // res.redirect('/api/tumblr'); // }); // app.get('/auth/steam', passport.authorize('openid', { state: 'SOME STATE' })); // app.get('/auth/steam/callback', passport.authorize('openid', { failureRedirect: '/login' }), (req, res) => { // res.redirect(req.session.returnTo || '/'); // }); // app.get('/auth/pinterest', passport.authorize('pinterest', { scope: 'read_public write_public' })); // app.get('/auth/pinterest/callback', passport.authorize('pinterest', { failureRedirect: '/login' }), (req, res) => { // res.redirect('/api/pinterest'); // }); //404 handler app.use(function(req, res, next){ res.status(404); // respond with html page if (req.accepts('html')) { res.render('404', { url: req.url }); return; } // respond with json if (req.accepts('json')) { res.send({ error: 'Not found' }); return; } // default to plain-text. send() res.type('txt').send('Not found'); }); /** * Error Handler. */ app.use(errorHandler()); /** * Start Express server. */ app.listen(app.get('port'), () => { console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
 console.log(' Press CTRL-C to stop\n'); }); module.exports = app;
import { BaseCustomElement, reflectPropertiesToAttributes, mdlUpgrade } from '../utils'; class CardActions extends BaseCustomElement { createdCallback() { this.classList.add('mdl-card__actions'); } attributeChangedCallback(attrName, oldVal, newVal) { this.classList.toggle('mdl-card--border', this.border); } } export default reflectPropertiesToAttributes( mdlUpgrade(CardActions), [ { propName: 'border', propType: Boolean }, ] )
import { assign } from '@ember/polyfills'; import { A } from '@ember/array'; import { Promise } from 'rsvp'; import { run } from '@ember/runloop'; import Evented from '@ember/object/evented'; import Service from '@ember/service'; import { debug } from '../utils'; import { namespace, tabId, tabIdKey, shouldInvalidateMasterTabKey } from '../consts'; /** * Checks whether the current tab is the master tab. */ function isMasterTab() { return localStorage[tabIdKey] === tabId; } /** The service factory. */ export default Service.extend(Evented, { /** Contains current lock names that will be deleted during the 'beforeunload' window event. */ lockNames: A(), resolve: null, contestTimeout: null, /** * Sets up listeners on the 'storage' and 'beforeunload' window events. * Returns a promise that resolves immediately if this or another tab is the master tab and that * tab is currently present. In case the master tab crashed and a new tab is opened, this promise * will resolve after a short delay while it invalidates the master tab. */ setup() { const storageHandler = e => { switch (e.key) { case tabIdKey: { const newTabId = e.newValue; if (newTabId === null) { debug('Master tab currently being contested.'); localStorage[shouldInvalidateMasterTabKey] = false; this.registerAsMasterTab(); } else { if (this.get('isMasterTab') && e.oldValue !== null && tabId !== newTabId) { debug('Lost master tab status. Probably race condition related.'); run(() => { this.set('isMasterTab', false); this.trigger('isMasterTab', false); }); } } break; } case shouldInvalidateMasterTabKey: { const shouldInvalidateMasterTab = eval(e.newValue); const _isMasterTab = isMasterTab(); if (shouldInvalidateMasterTab && _isMasterTab) { localStorage[shouldInvalidateMasterTabKey] = false; debug('Invalidation of master tab avoided.'); } else if (!shouldInvalidateMasterTab && !_isMasterTab) { if (this.contestTimeout !== null) { clearTimeout(this.contestTimeout); this.contestTimeout = null; if (this.resolve !== null) { this.resolve(); this.resolve = null; } debug('Invalidation of master tab aborted.'); } } break; } } }; window.addEventListener('storage', storageHandler); window.addEventListener('beforeunload', () => { window.removeEventListener('storage', storageHandler); this.lockNames.forEach(l => { delete localStorage[l]; debug(`Deleted lock [${l}].`); }); if (isMasterTab()) { delete localStorage[tabIdKey]; debug('Unregistered as master tab. '); } }); return this.contestMasterTab(); }, isMasterTab: false, /** Tries to register as the master tab if there is no current master tab registered. */ registerAsMasterTab() { let success = false; if (isMasterTab()) { success = true; } else { if (typeof localStorage[tabIdKey] === 'undefined') { localStorage[tabIdKey] = tabId; localStorage[shouldInvalidateMasterTabKey] = false; success = true; } debug(`Trying to register as master tab... ${success ? 'SUCCESS' : 'FAILED'}.`); } run(() => { this.set('isMasterTab', success); this.trigger('isMasterTab', success); }); return success; }, /** * Returns a promise which attempts to contest the master tab. */ contestMasterTab() { return new Promise(resolve => { if (!this.registerAsMasterTab()) { debug('Trying to invalidate master tab.'); this.resolve = resolve; this.contestTimeout = setTimeout(() => { const shouldInvalidateMasterTab = eval(localStorage[shouldInvalidateMasterTabKey]); if (shouldInvalidateMasterTab) { localStorage[shouldInvalidateMasterTabKey] = false; delete localStorage[tabIdKey]; this.registerAsMasterTab(); } resolve(); }, 500); localStorage[shouldInvalidateMasterTabKey] = true; } else { resolve(); } }); }, /** * Runs the provided function if this is the master tab. If this is not the current tab, run * the function provided to 'else()'. */ run(func, options = {}) { if (typeof options !== 'object') { throw 'Options must be an object.'; } const finalOptions = assign({ force: false }, options); const _isMasterTab = isMasterTab(); if (_isMasterTab || finalOptions.force) { func(); } return { else(func) { if (!_isMasterTab && !finalOptions.force) { func(); } } }; }, /** * Runs the provided function (which should return a Promise) if this is the master tab. * It creates a lock which is freed once the Promise is resolved or rejected. * If this is not the master tab, run the function provided to 'wait()'. If there is no * lock present currently, the function runs immediately. If there is, it will run once * the promise on the master tab resolves or rejects. */ lock(lockName, func, options = {}) { if (typeof options !== 'object') { throw 'Options must be an object.'; } const finalOptions = assign({ force: false, waitNext: true, waitNextDelay: 1000 }, options); const lockNameKey = `${namespace}lock:${lockName}`; const lockResultKey = `${lockNameKey}:result`; const lockResultTypeKey = `${lockNameKey}:result-type`; const isLocked = typeof localStorage[lockNameKey] !== 'undefined'; const _isMasterTab = isMasterTab(); if ((_isMasterTab || finalOptions.force) && !isLocked) { localStorage[lockNameKey] = true; delete localStorage[lockResultKey]; delete localStorage[lockResultTypeKey]; if (this.lockNames.indexOf(lockNameKey) === -1) { this.lockNames.push(lockNameKey); } const p = func(); if (!p || !p.then) { throw 'The function argument must return a thennable object.'; } const callback = (type, result) => { localStorage[lockResultTypeKey] = type; localStorage[lockResultKey] = result; delete localStorage[lockNameKey]; const index = this.lockNames.indexOf(lockNameKey); if (index > -1) { this.lockNames.splice(index, 1); } }; p.then(result => callback('success', result), result => callback('failure', result)); } return { wait(success, failure = null) { if ((!_isMasterTab && !finalOptions.force) || isLocked) { const callCallback = waited => { const resultType = localStorage[lockResultTypeKey]; const func = resultType === 'success' ? success : failure; const result = localStorage[lockResultKey]; if (func !== null) { func(result, waited); } }; if (isLocked || finalOptions.waitNext) { const handler = e => { if (e.key === lockNameKey && e.newValue === null) { window.removeEventListener('storage', handler); callCallback(true); } }; window.addEventListener('storage', handler); if (finalOptions.waitNext) { setTimeout(() => { window.removeEventListener('storage', handler); callCallback(true); }, finalOptions.waitNextDelay); } } else { callCallback(false); } } } }; } });
/** * Findout current context. * @function ctx */ 'use strict' const ctx = require('apeman-ctx') module.exports = ctx;
import React from 'react'; import IconBase from '@suitejs/icon-base'; function DvBootstrap(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M6 37.358V10.642A4.642 4.642 0 0 1 10.642 6h26.716A4.642 4.642 0 0 1 42 10.642v26.716A4.642 4.642 0 0 1 37.358 42H10.642A4.642 4.642 0 0 1 6 37.358zm10.136-24.256v21.796h10.562c.977 0 1.929-.122 2.855-.366a7.633 7.633 0 0 0 2.472-1.13 5.563 5.563 0 0 0 1.725-1.968c.427-.804.641-1.756.641-2.855 0-1.363-.33-2.529-.992-3.495-.661-.967-1.664-1.644-3.007-2.03.977-.468 1.715-1.069 2.213-1.802.499-.732.748-1.648.748-2.747 0-1.018-.168-1.872-.503-2.564a4.188 4.188 0 0 0-1.42-1.664c-.61-.417-1.343-.718-2.198-.9a13.575 13.575 0 0 0-2.84-.275H16.137zm4.792 8.822v-5.098h4.488c.427 0 .84.036 1.236.107.397.071.748.198 1.054.381.305.184.55.438.732.764.183.325.275.742.275 1.251 0 .916-.275 1.578-.824 1.985-.55.407-1.252.61-2.107.61h-4.854zm0 9.25v-5.983h5.22c1.039 0 1.873.239 2.504.717.63.478.946 1.277.946 2.396 0 .57-.096 1.038-.29 1.405a2.304 2.304 0 0 1-.778.87 3.296 3.296 0 0 1-1.13.458 6.396 6.396 0 0 1-1.343.137h-5.129z" /> </IconBase> ); } export default DvBootstrap;
/* * ============================================================= * elaostrap * * (c) 2015 Jeremy FAGIS <jeremy@fagis.fr> * ============================================================= */ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/Volumes/Elao/workspace/JeremyFagis/ElaoStrap/assets/js/vendors/jquery.simple-selector.js":[function(require,module,exports){ /* * SimpleSelector 1.0 * Skinning select type * Copyright (c) 2014 Jeremy FAGIS (http://fagis.fr) */ ;(function ( $, window, document, undefined ) { var pluginName = "simpleSelector", defaults = { wrapperClass: "selector-wrapper", caretClass: 'elaostrap-font-arrow' }, isIE = '\v'=='v'; function Plugin ( element, options ) { this.element = element; this.settings = $.extend( {}, defaults, options ); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function () { if (!isIE) { var element = $(this.element); var defaultText = element.data('default-text') || '---'; var value = element.find('option:selected').text() || defaultText; element.removeClass('selector'); element.wrap('<div class="' + this.settings.wrapperClass + ' ' + element.attr('class') +'" />'); element.removeAttr('class'); $('<span/>').text(value).prependTo(element.parent()); $('<i class="' + this.settings.caretClass + '"></i>').appendTo(element.parent()); element.on('change', function() { var value = $(this).find('option:selected').text(); value = (value)? value : defaultText ; $(this).prev('span').text(value); }); } } }; $.fn[ pluginName ] = function ( options ) { this.each(function() { if ( !$.data( this, "plugin_" + pluginName ) ) { $.data( this, "plugin_" + pluginName, new Plugin( this, options ) ); } }); return this; }; })( jQuery, window, document ); },{}]},{},["/Volumes/Elao/workspace/JeremyFagis/ElaoStrap/assets/js/vendors/jquery.simple-selector.js"])
'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-dzbot:app', function () { before(function () { return helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({someAnswer: true}) .toPromise(); }); it('creates files', function () { assert.file([ 'dummyfile.txt' ]); }); });
export const ic_power_input_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M2 9v2h19V9H2zm0 6h5v-2H2v2zm7 0h5v-2H9v2zm7 0h5v-2h-5v2z"},"children":[]}]};
describe('avoidSelect()', function() { 'use strict'; var window, document, utils, PlainOverlay, traceLog, pageDone, IS_TRIDENT, overlayElm, overlayDoc, pBefore, pTarget, pAfter, face1, face2; function setSelection(startElement, startIndex, endElement, endIndex) { var selection = ('getSelection' in window ? window : document).getSelection(), range; function parseNode(node, nodes, index) { if (!nodes) { nodes = []; index = 0; } var children = node.childNodes; for (var i = 0; i < children.length; i++) { if (children[i].nodeType === Node.ELEMENT_NODE) { parseNode(children[i], nodes, index); } else if (children[i].nodeType === Node.TEXT_NODE) { var len = children[i].textContent.length; nodes.push({node: children[i], start: index, end: index + len - 1}); index += len; } } return nodes; } function getPos(index, nodes) { var iList = 0; while (true) { if (index <= nodes[iList].end) { return {node: nodes[iList].node, offset: index - nodes[iList].start}; } if (iList >= nodes.length - 1) { throw new Error('setSelection'); } iList++; } } if (selection.extend) { // Non-IE var posStart = getPos(startIndex, parseNode(startElement)), posEnd = getPos(endIndex, parseNode(endElement)); posEnd.offset++; range = document.createRange(); range.setStart(posStart.node, posStart.offset); range.setEnd(posEnd.node, posEnd.offset); selection.removeAllRanges(); selection.addRange(range); } else { // IE range = document.body.createTextRange(); range.moveToElementText(startElement); range.moveStart('character', startIndex); var range2 = document.body.createTextRange(); // moveEnd() can't move to another node range2.moveToElementText(endElement); range2.moveStart('character', endIndex + 1); range.setEndPoint('EndToStart', range2); try { selection.removeAllRanges(); // Trident bug?, `Error:800a025e` comes sometime } catch (error) { /* ignore */ } range.select(); selection = ('getSelection' in window ? window : document).getSelection(); // Get again } return selection; } function fireKeyup() { var evt; try { evt = new KeyboardEvent('keyup', {shiftKey: true}); // shiftKey is dummy } catch (error) { evt = document.createEvent('KeyboardEvent'); evt.initKeyboardEvent('keyup', true, false, window, 'Shift', 0x01, 'Shift', false, null); } window.dispatchEvent(evt); } beforeAll(function(beforeDone) { loadPage('spec/select.html', function(pageWindow, pageDocument, pageBody, done) { window = pageWindow; document = pageDocument; utils = window.utils; PlainOverlay = window.PlainOverlay; traceLog = PlainOverlay.traceLog; IS_TRIDENT = PlainOverlay.IS_TRIDENT; pBefore = document.getElementById('p-before'); pTarget = document.getElementById('p-target'); pAfter = document.getElementById('p-after'); face1 = document.getElementById('face1'); face2 = document.getElementById('face2'); overlayElm = new PlainOverlay(document.getElementById('target1'), {face: face1, duration: 10}); overlayDoc = new PlainOverlay({face: face2, duration: 10}); // for script in the page window.overlayElm = overlayElm; window.overlayDoc = overlayDoc; pageDone = done; beforeDone(); }, 'avoidSelect()'); }); afterAll(function() { pageDone(); }); it('Check Edition (to be LIMIT: ' + !!self.top.LIMIT + ')', function() { expect(!!window.PlainOverlay.limit).toBe(!!self.top.LIMIT); }); describe('Target: element', function() { beforeAll(function(beforeDone) { var timer1; utils.makeState([overlayElm, overlayDoc], [PlainOverlay.STATE_SHOWN, PlainOverlay.STATE_HIDDEN], function() { overlayElm.hide(true); overlayDoc.hide(true); timer1 = setTimeout(function() { overlayElm.show(true); }, 10); return true; }, function() { clearTimeout(timer1); beforeDone(); } ); }); it('Selection: before 1', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pBefore, 0, pBefore, 1); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('AB'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('AB'); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-before(0),end:P#p-before(2),isCollapsed:false', 'NoSelection', '_id:' + overlayElm._id, '</avoidSelect>', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); it('Selection: before 2', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pBefore, 1, pBefore, 2); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('BC'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('BC'); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-before(1),end:P#p-before(3),isCollapsed:false', 'NoSelection', '_id:' + overlayElm._id, '</avoidSelect>', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); it('Selection: before - target', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pBefore, 2, pTarget, 0); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('CD'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-before(2),end:P#p-target(1),isCollapsed:false', 'DONE', '_id:' + overlayElm._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayElm._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); it('Selection: target 1', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pTarget, 0, pTarget, 1); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('DE'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-target(0),end:P#p-target(2),isCollapsed:false', 'DONE', '_id:' + overlayElm._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayElm._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', 'target:P#p-target', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'target:P#p-target', '<avoidFocus>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'element:P#p-target', 'DONE', '_id:' + overlayElm._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayElm._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', 'target:BODY', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: target 2', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pTarget, 1, pTarget, 2); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('EF'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-target(1),end:P#p-target(3),isCollapsed:false', 'DONE', '_id:' + overlayElm._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayElm._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', 'target:P#p-target', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'target:P#p-target', '<avoidFocus>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'element:P#p-target', 'DONE', '_id:' + overlayElm._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayElm._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', 'target:BODY', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: target - after', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pTarget, 2, pAfter, 0); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('FG'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-target(2),end:P#p-after(1),isCollapsed:false', 'DONE', '_id:' + overlayElm._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayElm._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', 'target:P#p-target', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'target:P#p-target', '<avoidFocus>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'element:P#p-target', 'DONE', '_id:' + overlayElm._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayElm._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', 'target:BODY', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: after 1', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pAfter, 0, pAfter, 1); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('GH'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('GH'); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-after(0),end:P#p-after(2),isCollapsed:false', 'NoSelection', '_id:' + overlayElm._id, '</avoidSelect>', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); it('Selection: after 2', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pAfter, 1, pAfter, 2); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('HI'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('HI'); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-after(1),end:P#p-after(3),isCollapsed:false', 'NoSelection', '_id:' + overlayElm._id, '</avoidSelect>', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); it('Selection: after - face', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pAfter, 2, face1, 0); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); if (IS_TRIDENT) { // Contains hidden text (face1 was moved after `MNO`) expect(selection.toString().replace(/\s/g, '')).toBe('IMNOJ'); } else { expect(selection.toString().replace(/\s/g, '')).toBe('IJ'); } }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); if (IS_TRIDENT) { // Contains hidden text (face1 was moved after `MNO`) expect(selection.toString().replace(/\s/g, '')).toBe('IMNOJ'); } else { expect(selection.toString().replace(/\s/g, '')).toBe('IJ'); } expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#p-after(2),end:P#face1(1),isCollapsed:false', 'NoSelection', '_id:' + overlayElm._id, '</avoidSelect>', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); it('Selection: face 1', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(face1, 0, face1, 1); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('JK'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('JK'); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#face1(0),end:P#face1(2),isCollapsed:false', 'NoSelection', '_id:' + overlayElm._id, '</avoidSelect>', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); it('Selection: face 2', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(face1, 1, face1, 2); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('KL'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('KL'); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayElm._id, 'state:STATE_SHOWN', 'start:P#face1(1),end:P#face1(3),isCollapsed:false', 'NoSelection', '_id:' + overlayElm._id, '</avoidSelect>', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_HIDDEN', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); }); describe('Target: document', function() { beforeAll(function(beforeDone) { var timer1; utils.makeState([overlayElm, overlayDoc], [PlainOverlay.STATE_HIDDEN, PlainOverlay.STATE_SHOWN], function() { overlayElm.hide(true); overlayDoc.hide(true); timer1 = setTimeout(function() { overlayDoc.show(true); }, 10); return true; }, function() { clearTimeout(timer1); beforeDone(); } ); }); it('Selection: before 1', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pBefore, 0, pBefore, 1); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('AB'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-before(0),end:P#p-before(2),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-before', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-before', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: before 2', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pBefore, 1, pBefore, 2); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('BC'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-before(1),end:P#p-before(3),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-before', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-before', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: before - target', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pBefore, 2, pTarget, 0); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('CD'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-before(2),end:P#p-target(1),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-before', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-before', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: target 1', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pTarget, 0, pTarget, 1); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('DE'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-target(0),end:P#p-target(2),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-target', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-target', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: target 2', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pTarget, 1, pTarget, 2); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('EF'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-target(1),end:P#p-target(3),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-target', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-target', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: target - after', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pTarget, 2, pAfter, 0); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('FG'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-target(2),end:P#p-after(1),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-target', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-target', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: after 1', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pAfter, 0, pAfter, 1); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('GH'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-after(0),end:P#p-after(2),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-after', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-after', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: after 2', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pAfter, 1, pAfter, 2); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('HI'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-after(1),end:P#p-after(3),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-after', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-after', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: after - face', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(pAfter, 2, face2, 0); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); if (IS_TRIDENT) { // Contains hidden text expect(selection.toString().replace(/\s/g, '')).toBe('IJKLM'); } else { expect(selection.toString().replace(/\s/g, '')).toBe('IM'); } }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(0); expect(selection.toString()).toBe(''); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#p-after(2),end:P#face2(1),isCollapsed:false', 'DONE', '_id:' + overlayDoc._id, '</avoidSelect>', 'AVOIDED', '_id:' + overlayDoc._id, '</text-select-event>' ].concat(IS_TRIDENT ? [ // `focus` event is fired by `fireKeyup`? '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:P#p-after', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:P#p-after', 'DONE', '_id:' + overlayDoc._id, '</avoidFocus>', // BLURRED 'AVOIDED', '_id:' + overlayDoc._id, '</focusListener>', '<focusListener>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'target:BODY', '<avoidFocus>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'element:BODY', 'NotInTarget', '_id:' + overlayDoc._id, '</avoidFocus>', '_id:' + overlayDoc._id, '</focusListener>' ] : [])); }, // ==================================== 0, done ]); }); it('Selection: face 1', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(face2, 0, face2, 1); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('MN'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('MN'); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#face2(0),end:P#face2(2),isCollapsed:false', 'NoSelection', '_id:' + overlayDoc._id, '</avoidSelect>', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); it('Selection: face 2', function(done) { var selection; utils.intervalExec([ // ==================================== function() { setSelection(face2, 1, face2, 2); selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('NO'); }, // ==================================== function() { // To check after some events in Trident with setSelection traceLog.length = 0; fireKeyup(); }, // ==================================== function() { selection = ('getSelection' in window ? window : document).getSelection(); expect(selection.rangeCount).toBe(1); expect(selection.toString().replace(/\s/g, '')).toBe('NO'); expect(traceLog).toEqual([ '<text-select-event>', '_id:' + overlayElm._id, 'state:STATE_HIDDEN', '_id:' + overlayElm._id, '</text-select-event>', '<text-select-event>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', '<avoidSelect>', '_id:' + overlayDoc._id, 'state:STATE_SHOWN', 'start:P#face2(1),end:P#face2(3),isCollapsed:false', 'NoSelection', '_id:' + overlayDoc._id, '</avoidSelect>', '_id:' + overlayDoc._id, '</text-select-event>' ]); }, // ==================================== 0, done ]); }); }); });
import './adapter'; import './commit'; import './configLoader'; import './init'; import './staging'; import './util';
'use strict;' angular.module('kaptureApp') .filter('percentage', ['$filter', function ($filter) { return function (input, decimals) { return $filter('number')(input * 100, decimals) + '%'; }; }]);
import "../../../data/icon-16.png"; browser.devtools.panels.create( browser.i18n.getMessage("name"), "assets/images/icon-16.png", "devtools/panel/index.html" );
// Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 2015-11-25 using // generator-karma 1.0.0 module.exports = function(config) { 'use strict'; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: '../', // testing framework to use (jasmine/mocha/qunit/...) // as well as any additional frameworks (requirejs/chai/sinon/...) frameworks: [ "jasmine" ], // list of files / patterns to load in the browser files: [ // bower:js 'bower_components/jquery/dist/jquery.js', 'bower_components/angular/angular.js', 'bower_components/bootstrap/dist/js/bootstrap.js', 'bower_components/angular-animate/angular-animate.js', 'bower_components/angular-cookies/angular-cookies.js', 'bower_components/angular-resource/angular-resource.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-sanitize/angular-sanitize.js', 'bower_components/angular-touch/angular-touch.js', 'bower_components/angular-mocks/angular-mocks.js', // endbower "app/scripts/**/*.js", "test/mock/**/*.js", "test/spec/**/*.js" ], // list of files / patterns to exclude exclude: [ ], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ "PhantomJS" ], // Which plugins to enable plugins: [ "karma-phantomjs-launcher", "karma-jasmine" ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
var Component = require('elements-core').Component; class Text extends Component { render(state, content) { let tags = Text.expose().tags; if (!state.content) { state.content = 'Text goes here'; } if (!state.tag) { state.tag = 'p'; } else { state.tag = tags[state.tag]; } return `<${state.tag}>${state.content}${content}</${state.tag}>`; } static expose() { return { tags: ['p', 'label', 'span', 'div'] }; } } module.exports = Text;
"use strict"; /*globals ajaxify, config, utils, app, socket*/ $(document).ready(function () { setupProgressBar(); animateCategoryCards(); setupSideBar(); setupWavesEffect(); setupFloatingLabels(); setupMenus(); setupChatSearch(); setupCheckBox(); function setupProgressBar() { $(window).on('action:ajaxify.start', function () { $('.material-load-bar').css('height', '3px'); }); $(window).on('action:ajaxify.end', function (ev, data) { setTimeout(function () { $('.material-load-bar').css('height', '0px'); }, 1000); }); } function animateCategoryCards() { $(window).on('action:ajaxify.end', function () { var speed = 2000; var container = $('.display-animation'); container.each(function () { var elements = $(this).children(); elements.each(function () { var elementOffset = $(this).offset(); var offset = elementOffset.left * 0.8 + elementOffset.top; var delay = parseFloat(offset / speed).toFixed(2); $(this) .css("-webkit-animation-delay", delay + 's') .css("-o-animation-delay", delay + 's') .css("animation-delay", delay + 's') .addClass('animated'); }); }); }); } function setupSideBar() { $('body').on('click', '#menu-trigger', function (e) { e.preventDefault(); var x = $(this).data('trigger'); $(x).toggleClass('toggled'); $(this).toggleClass('open'); if (x == '#sidebar') { $elem = '#sidebar'; $elem2 = '#menu-trigger'; if (!$('#chat').hasClass('toggled')) { $('#header').toggleClass('sidebar-toggled'); } } //When clicking outside if ($('#header').hasClass('sidebar-toggled')) { $(document).on('click', function (e) { if (($(e.target).closest($elem).length === 0) && ($(e.target).closest($elem2).length === 0)) { setTimeout(function () { $($elem).removeClass('toggled'); $('#header').removeClass('sidebar-toggled'); $($elem2).removeClass('open'); }); } }); } }); //Get saved layout type from LocalStorage var layoutStatus = localStorage.getItem('ma-layout-status'); if (layoutStatus == 1 && !config.menuInHeader) { $('body').addClass('sw-toggled'); $('#tw-switch').prop('checked', true); } $('body').on('change', '#toggle-width input:checkbox', function () { if ($(this).is(':checked')) { $('body').addClass('toggled sw-toggled'); localStorage.setItem('ma-layout-status', 1); } else { $('body').removeClass('toggled sw-toggled'); localStorage.setItem('ma-layout-status', 0); } }); $(window).on('action:ajaxify.start', function () { if ($('#menu-trigger').hasClass('open')) { $('#menu-trigger').click(); } }); } function setupWavesEffect() { $(window).on('action:ajaxify.end', function () { var wavesList = ['.btn']; for (var x = 0; x < wavesList.length; x++) { if ($(wavesList[x])[0]) { if ($(wavesList[x]).is('a')) { $(wavesList[x]).not('.btn-icon, input').addClass('waves-effect waves-button'); } else { $(wavesList[x]).not('.btn-icon, input').addClass('waves-effect'); } } } setTimeout(function () { if ($('.waves-effect')[0]) { Waves.displayEffect(); } }); }); } function setupFloatingLabels() { $(window).on('action:ajaxify.end', function () { //Add blue animated border and remove with condition when focus and blur if ($('.fg-line')[0]) { $('body').on('focus', '.form-control', function () { $(this).closest('.fg-line').addClass('fg-toggled'); }) $('body').on('blur', '.form-control', function () { var p = $(this).closest('.form-group, .input-group'); var i = p.find('.form-control').val(); if (p.hasClass('fg-float')) { if (i.length == 0) { $(this).closest('.fg-line').removeClass('fg-toggled'); } } else { $(this).closest('.fg-line').removeClass('fg-toggled'); } }); } //Add blue border for pre-valued fg-flot text feilds if ($('.fg-float')[0]) { $('.fg-float .form-control').each(function () { var i = $(this).val(); if (!i.length == 0) { $(this).closest('.fg-line').addClass('fg-toggled'); } }); } }); } function setupMenus() { $(window).on('action:ajaxify.start', function () { if ($('.chats.dropdown').hasClass('open')) { $('.chats.dropdown').click(); } if ($('.notifications.dropdown').hasClass('open')) { $('.notifications.dropdown').click(); } }); $('body').on('click', '#chat-list>li', function (e) { if ($('.chats.dropdown').hasClass('open')) { $('.chats.dropdown').click(); } }); $('body').on('click', '#user-control-list>li', function (e) { if ($('#user_label').hasClass('open')) { $('#user_label').click(); } }); $('body').on('click', '#ms-menu-trigger', function (e) { e.preventDefault(); $(this).toggleClass('open'); $('.ms-menu').toggleClass('toggled'); }); $('body').on('click', '.ms-menu .chats-list>li', function (e) { if ($('#ms-menu-trigger').hasClass('open')) { $('#ms-menu-trigger').toggleClass('open'); $('.ms-menu').toggleClass('toggled'); } }); } function setupChatSearch() { $(window).on('action:ajaxify.end', function () { $('body').on('click', '.new-chat', function (e) { e.preventDefault(); $('.chat-search-menu').addClass('toggled'); $('[component="chat/search"]').focus(); }); $(document).keyup(function (e) { if (e.keyCode === 27 && $('.chat-search-menu').hasClass('toggled')) { $('.chat-search-menu').removeClass('toggled'); $('[component="chat/search"]').val(''); } }); $('body').on('click', '#chat-search-menu-trigger', function (e) { $('.chat-search-menu').removeClass('toggled'); $('[component="chat/search"]').val(''); $('[component="chat/search/list"]').empty(); }); }); } function setupCheckBox() { $(window).on('action:ajaxify.end', function () { if (ajaxify.data.template.name == 'registerComplete') { $('#agree-terms').after('<i class="input-helper"></i>'); $('#gdpr_agree_email').after('<i class="input-helper"></i>'); $('#gdpr_agree_data').after('<i class="input-helper"></i>'); } }); } });
var AspxShipmentsManagement = { "Shipping Method ID":"送货方式标识", "Shipping Method Name":"运输方式名称", "Order ID":"订单ID", "Ship to Name":"船名", "Shipping Cost":"运费", "Actions":"操作", "View":"视图", "No Records Found!":"没有找到记录!", "Package Details":"软件包的详细资料", "Shipment Date:":"发货日期:", "Shipments Items:":"出货量的项目:", "Item Name":"项目名称", "SKU":"SKU", "Shipping Address": "送货地址", "Shipping Rate":"邮寄费率", "Price":"价格", "Quantity":"数量", "Line Total":"线路总", "Back":"后面", "View More":"查看更多", "There are no services available!":"没有可用的服务!", "Shipping Method ID":"送货方式标识", "shipping_rate":"shipping_rate", "Shipping Method ID":"Shipping Method ID", "Product Name": "产品名称", "Customer Name:": "客户名称:", "Address:":"地址:", "Address2:": "地址2:", "Country:": "国家:", "City:": "城市:", "State:": "态:", "ZipCode:": "邮编:", "Email Address:": "电子邮件地址:", "Phone No:": "电话号码:", "WareHouse Name:": "仓库名称:", "Street Address1:": "街道地址1:", "Street Address2:": "街道地址2:", "Weight": "重量", "Quantity": "数量", "User Selected Method:": "用户选择的方法:", "Shipping Method Name:": "送货方式名称:", "OrderID:": "订单编号:", "Ship To Name:": "运送到名称:", "Search": "搜索", "Sub Total:": "小计:", "Shipping Cost:": "运费:", "Discount Amount:": "折扣金额:", "Coupon Amount:": "票面​​金额:", "Discount(RewardPoints):": "折扣(RewardPoints):", "GiftCard": "礼金券", "Grand Total:": "总计:" };
/* * angular-cache * http://github.com/jmdobry/angular-cache * * Copyright (c) 2013 Jason Dobry <http://jmdobry.github.io/angular-cache> * Licensed under the MIT license. <https://github.com/jmdobry/angular-cache/blob/master/LICENSE> */ module.exports = function (grunt) { 'use strict'; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), clean: ['dist/', 'docs/'], jshint: { all: ['Gruntfile.js', 'src/**/*.js', 'test/*.js'], jshintrc: '.jshintrc' }, copy: { options: { processContent: function (contents) { contents = contents.replace(/<%= pkg.version %>/g, grunt.file.readJSON('package.json').version); return contents; } }, dist: { src: ['src/angular-cache.js'], dest: 'dist/angular-cache-<%= pkg.version %>.js' } }, uglify: { main: { files: { 'dist/angular-cache-<%= pkg.version %>.min.js': ['dist/angular-cache-<%= pkg.version %>.js'] } } }, karma: { options: { configFile: './karma.conf.js', singleRun: true, autoWatch: false }, dev: { browsers: ['Chrome'] }, drone: { browsers: ['Firefox', 'Chrome', 'PhantomJS'] }, travis: { browsers: ['Firefox', 'PhantomJS'] } }, jsdoc : { dist : { src: ['dist/angular-cache-<%= pkg.version %>.js'], options: { destination: 'docs', lenient: true, verbose: true, private: true } } } }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-karma'); grunt.loadNpmTasks('grunt-jsdoc'); grunt.registerTask('build', ['clean', 'jshint', 'copy', 'uglify', 'karma:dev']); grunt.registerTask('default', ['build']); grunt.registerTask('build:all', ['build', 'jsdoc']); grunt.registerTask('test', ['karma:dev']); // Used by the CLI build servers grunt.registerTask('drone', ['clean', 'jshint', 'copy', 'uglify', 'karma:drone']); grunt.registerTask('travis', ['clean', 'jshint', 'copy', 'uglify', 'karma:travis']); };
/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */ /** * Global object for andeling id. */ dbm.registerClass("dbm.core.globalobjects.idmanager.IdManager", "dbm.core.globalobjects.GlobalObjectBaseObject", function(objectFunctions, staticFunctions, ClassReference) { //console.log("dbm.core.globalobjects.idmanager.IdManager"); var IdManager = dbm.importClass("dbm.core.globalobjects.idmanager.IdManager"); var NormalIdGroup = dbm.importClass("dbm.core.globalobjects.idmanager.objects.NormalIdGroup"); /** * Constructor */ objectFunctions._init = function() { //console.log("dbm.core.globalobjects.idmanager.IdManager"); this._idGroupsObject = new Object(); return this; }; /** * Sets the id group. * * @param aGroupName The name of the group. * @param aGroupObject The group object. */ objectFunctions.setIdGroup = function(aGroupName, aGroupObject) { //console.log("setIdGroup"); if(this._idGroupsObject[aGroupName] !== undefined) { //METODO: warning message } this._idGroupsObject[aGroupName] = aGroupObject; }; /** * Returns a unique id for a group. * * @param aGroupName The name of the group. */ objectFunctions.getNewId = function(aGroupName) { //console.log("getId"); if(this._idGroupsObject[aGroupName] === undefined) { //METODO: warning message var newGroup = (new NormalIdGroup()).init(); newGroup.prefix = aGroupName + "_"; this._idGroupsObject[aGroupName] = newGroup; } var currentGroup = this._idGroupsObject[aGroupName]; return currentGroup.getNewId(); }; });
define([ "jquery", "utils", "lib/pusher.min"], function($, utils) { BaseController = function(){ control = this; this.fieldsToLoad = []; this.permissions = []; }; function BaseController_genericOnLoad(debug){ this.loadData(debug); } function BaseController_loadData(debug){ var copy = this; var notificationFields = {}; var dataBlock = $("#data"); dataBlock.children().each(function() { var elInfo = $(this).data(), data = elInfo.json; //jQuery auto-converts into a Javascript object if (data === undefined || data === "") { console.warn("Missing json for data element", this); return; //continue to next } if (data !== null && data.toString() === data) { //strings aren't auto-converted from JSON strings to actual strings (in other words, they still have the quotes) data = JSON.parse(data); } //console.log(data); if (elInfo.model) { var Class = Utils_safeClass(elInfo.model); if (!Class) { console.warn("Warning: Class " + elInfo.model + " not found. Probably not loaded."); return; //continue to next } copy[Class.prototype.getPluralName().decapitalize()] = (new Class()).fromDjangoJSONObjectAll(data); } else { var field = elInfo.field; if (!field) { console.warn("Missing field on element", this); return; //continue to next } copy[field] = data; } }); dataBlock.remove(); //no longer needed, so we remove it from the DOM } function BaseController_setGenericHandlers(parent) { var copy = this; if (arguments.length === 0) parent = $("html"); this.setMenuHandler(); this.setReferenceHandler(); //button text shouldn't be selectable //$(".button").disableSelection(); //backwards compatibility for the "placeholder" tag $(function() { var i = document.createElement('input'); if (!('placeholder' in i)) { $("input[placeholder]").each(function() { $(this).unbind("focusin").unbind("focusout").focusin(function() { if ($(this).data("showing-placeholder")=="T") { $(this).val("").data("showing-placeholder","F").removeClass("greyText"); } }).focusout(function() { if ($(this).val() === "") { $(this).addClass("greyText").val($(this).attr("placeholder")).data("showing-placeholder","T"); } }).addClass("greyText").val($(this).attr("placeholder")).data("showing-placeholder","T"); }); //make sure jQuery val isn't returning the placeholder text as the value if (!("prePlaceholderVal" in $.fn)) { $.fn.prePlaceholderVal = $.fn.val; $.fn.val = function(a) { if (arguments.length === 0) { if ($(this).data("showing-placeholder")=="T") { return ""; } else { return $(this).prePlaceholderVal(); } } return $(this).prePlaceholderVal(a); }; } } delete i; }); } function BaseController_genericSubscribePusher(channel) { var copy = this; this.pusher = new Pusher('d00c939a712a8d7290e6'); this.pusher.connection.bind('connected', function() { copy.socketId = copy.pusher.connection.socket_id; }); this.channel = this.pusher.subscribe(channel); //this.channel.bind('my_event', function(data) { // alert(data.message); //}); } function BaseController_setMenuHandler() { //Open the menu // Change to classes $(".menu").click(function() { $('#mainArea').css('min-height', $(window).height()); $('nav').css('opacity', 1); $('nav').css('z-index', 1); //set the width of primary content container -> content should not scale while animating var contentWidth = $('#mainArea').width(); //set the content with the width that it has originally $('#content').css('width', contentWidth); //display a layer to disable clicking and scrolling on the content while menu is shown $('#mainOverlay').css('display', 'block'); //disable all scrolling on mobile devices while menu is shown $('#page').bind('touchmove', function (e) { e.preventDefault() }); //set margin for the whole page with a $ UI animation $("#page").animate({"marginRight": "30%"}, { duration: 200 }); }); //close the menu $("#mainOverlay").click(function() { //enable all scrolling on mobile devices when menu is closed $('#page').unbind('touchmove'); //set margin for the whole page back to original state with a $ UI animation $("#page").animate({"marginRight": "-1" }, { duration: 200, complete: function () { $('#mainArea').css('width', 'auto'); $('#mainOverlay').css('display', 'none'); $('nav').css('opacity', 0); $('nav').css('z-index', -1); $('#mainArea').css('min-height', 'auto'); } }); }); $("nav li").click(function() { // Activate chosen panel var panel = $(this).data("panel"); $(".panel").removeClass("active"); $("."+panel).addClass("active"); $("#mainOverlay").click(); }); } function BaseController_setReferenceHandler() { //Open the menu var copy = this; $(".ruleTopic").click(function() { var parent = $(this).parent(); if ($(".ruleDetail", parent).hasClass("expand")) { $(".ruleDetail").removeClass("expand"); } else { $(".ruleDetail").removeClass("expand"); $(".ruleDetail", parent).addClass("expand"); } }); } BaseController.prototype.constructor = BaseController; BaseController.prototype.loadData = BaseController_loadData; BaseController.prototype.genericOnLoad = BaseController_genericOnLoad; BaseController.prototype.setGenericHandlers = BaseController_setGenericHandlers; BaseController.prototype.setMenuHandler = BaseController_setMenuHandler; BaseController.prototype.setReferenceHandler = BaseController_setReferenceHandler; BaseController.prototype.genericSubscribePusher = BaseController_genericSubscribePusher; return BaseController; });
/* jshint camelcase: false */ module.exports = function (cfg, db) { var _ = require('lodash'), services = require('./services')(cfg, db), userMod = require('./users')(cfg, db), fileMod = require('./file')(cfg, db); function GDrive(userId) { return userMod.Repo.getById(userId) .then(function (user) { var drive = new services.google.Drive(user.oauths.google); // Make API call for listing all files return drive.getAllFiles(); }) .then(function (res) { var files = res.items; // Collect tasks for adding multiple files to DB var fileTasks = _.collect(files, function (f) { var file = new fileMod.File(); file.source = 'gdrive'; file.userId = userId; file.fileMeta = { 'id' : f.id, 'selfLink' : f.selfLink, 'alternateLink' : f.alternateLink, 'iconLink' : f.iconLink, 'title' : f.title, 'createdDate' : f.createdDate, 'modifiedDate' : f.modifiedDate, 'lastViewedByMeDate' : f.lastViewedByMeDate , 'markedViewedByMeDate' : f.markedViewedByMeDate, 'parents' : f.parents, }; return fileMod.Repo.add(file); }); return Promise.all(fileTasks); }) .catch(function (e) { throw new Error(e); }); } function Dropbox(userId) { return userMod.Repo.getById(userId) .then(function (user) { var dropbox = new services.dropbox.Client(user.oauths.dropbox.access_token); // Make API call for listing all files return dropbox.getAllFiles(); }) .then(function (files) { // Collect tasks for adding multiple files to DB var fileTasks = _.collect(files, function (f) { var file = new fileMod.File(); file.source = 'dropbox'; file.userId = userId; file.fileMeta = { 'path' : f.path, 'modified' : f.modified, 'size' : f.size, 'is_dir' : f.is_dir, 'mime_type' : f.mime_type, }; return fileMod.Repo.add(file); }); return Promise.all(fileTasks); }) .catch(function (e) { throw new Error(e); }); } return { 'GDrive' : GDrive, 'Dropbox' : Dropbox }; };
var browserify = require( 'gulp-browserify' ), gulp = require( 'gulp' ), buffer = require( 'vinyl-buffer' ), uglify = require( 'gulp-uglify' ), rename = require( 'gulp-rename' ), insert = require( 'gulp-insert' ); gulp.task( 'client', function(){ var out = gulp.src( './scripts/gibber/interface.lib.js') .pipe( browserify({ standalone:'Gibber', bare:true }) ) .pipe( rename('gibber.interface.lib.js') ) .pipe( gulp.dest('./build/') ) .pipe( buffer() ) .pipe( uglify() ) .pipe( rename('gibber.interface.lib.min.js') ) .pipe( gulp.dest('./build/') ) return out }); gulp.task( 'default', ['client'] )
import React from 'react'; import { mount } from 'enzyme'; import localStorageMock from '../__mocks__/localStorageMock'; import * as data from '../__mocks__/mockData'; import { MessageAreaContainer } from '../../dev/js/containers/MessageAreaContainer.jsx'; window.localStorage = localStorageMock; jest.mock('react-router-dom'); jest.mock('../../dev/js/containers/GroupFormContainer.jsx'); jest.mock('../../dev/js/containers/UploadsContainer.jsx'); jest.mock('../../dev/js/containers/Archive.jsx'); jest.mock('../../dev/js/containers/NavContainer.jsx'); jest.mock('../../dev/js/containers/MessageFormContainer.jsx'); jest.mock('../../dev/js/containers/AddUsers.jsx'); const setup = () => { const props = { match: { params: { id: 4 } }, groupData: data.groupData, allUsersData: data.userData, currentUser: data.currentUser, archiveData: data.archiveData, groupMessages: data.messageData, getGroupMessages: () => Promise.resolve(), getGroupUsers: jest.fn(() => Promise.resolve()), selectedGroupDetails: jest.fn(), getArchivedMessages: jest.fn(), getUserGroups: () => Promise.resolve(), getAllUsers: jest.fn(() => Promise.resolve()), handleActiveGroupClicked: jest.fn() }; const wrapper = mount(<MessageAreaContainer {...props} />); return { props, wrapper }; }; describe('Messaging Container', () => { const { props, wrapper } = setup(); it('renders the message area container', () => { wrapper.setState({ redirect: false }); expect(wrapper.find('MessageArea').exists()).toEqual(true); }); it('should call componentDidMount', () => { const enzymeWrapper = mount(<MessageAreaContainer {...{ ...props, ...{ groupMessages: { groupMessages: { Messages: [] }, getMessagesSuccess: true } } }} />); expect(enzymeWrapper.find('MessageBoardIcons').exists()).toBe(true); }); it('should call handleActiveGroupClicked', () => { wrapper.instance().handleActiveGroupClicked(data.event); expect(props.selectedGroupDetails.mock.calls.length).toEqual(1); }); });
{ var config = oneEventLoopTestConfig(three); config.startShouldSetResponder.captured.grandParent = { order: 0, returnVal: false }; config.startShouldSetResponder.captured.parent = { order: 1, returnVal: false }; config.startShouldSetResponder.captured.child = { order: 2, returnVal: false }; config.startShouldSetResponder.bubbled.child = { order: 3, returnVal: true }; config.responderGrant.child = { order: 4 }; config.responderStart.child = { order: 5 }; run(config, three, startConfig(three.child, [three.child], [0])); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child) ); config = oneEventLoopTestConfig(three); config.scrollShouldSetResponder.captured.grandParent = { order: 0, returnVal: false }; config.scrollShouldSetResponder.captured.parent = { order: 1, returnVal: false }; config.scrollShouldSetResponder.bubbled.parent = { order: 2, returnVal: true }; config.responderGrant.parent = { order: 3 }; config.responderTerminationRequest.child = { order: 4, returnVal: false }; config.responderReject.parent = { order: 5 }; run(config, three, { topLevelType: "topScroll", targetInst: getInstanceFromNode(three.parent), nativeEvent: {} }); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.child) ); config = oneEventLoopTestConfig(three); config.scrollShouldSetResponder.captured.grandParent = { order: 0, returnVal: false }; config.scrollShouldSetResponder.captured.parent = { order: 1, returnVal: false }; config.scrollShouldSetResponder.bubbled.parent = { order: 2, returnVal: true }; config.responderGrant.parent = { order: 3 }; config.responderTerminationRequest.child = { order: 4, returnVal: true }; config.responderTerminate.child = { order: 5 }; run(config, three, { topLevelType: "topScroll", targetInst: getInstanceFromNode(three.parent), nativeEvent: {} }); expect(ResponderEventPlugin._getResponder()).toBe( getInstanceFromNode(three.parent) ); }
/** * 二元操作表达式 * @abstract */ define( function ( require, exports, modules ) { var kity = require( "kity" ); return kity.createClass( 'BinaryExpression', { base: require( "expression/compound" ), constructor: function ( firstOperand, lastOperand ) { this.callBase(); this.setFirstOperand( firstOperand ); this.setLastOperand( lastOperand ); }, setFirstOperand: function ( operand ) { return this.setOperand( operand, 0 ); }, getFirstOperand: function () { return this.getOperand( 0 ); }, setLastOperand: function ( operand ) { return this.setOperand( operand, 1 ); }, getLastOperand: function () { return this.getOperand( 1 ); } } ); } );
"use strict"; let logs = require("../logs"); let assert = require("assert"); describe("logs DB collection", function () { let userID = 1; let log = { title: "Food Journal" }; let logID = ""; it("should create a log", function () { return logs.createLog(global.db,userID,log).then(function (savedLog) { assert.equal(savedLog.title, "Food Journal"); assert.equal(savedLog.userID, userID); assert(savedLog._id); logID = savedLog._id.toString(); }); }); it("should update a log", function () { let log = { title: "Updated Food Journal" }; return logs.updateLog(global.db, userID, logID, log); }); it("should read a log", function () { return logs.readLog(global.db, userID, logID).then(function (log) { assert.equal(log._id, logID); assert.equal(log.title, "Updated Food Journal"); }); }); it("should read many logs", function () { return logs.readLogList(global.db, userID).then(function (list) { assert(list.length); assert(list[0]._id); }); }); it("should delete a log", function () { return logs.deleteLog(global.db, userID, logID).then(function () { return logs.readLogList(global.db, userID).then(function (list) { list = list.filter(function (log) { return log._id == logID; }); assert.equal(list.length, 0); }); }); }); it("should delete many logs", function () { return logs.createLog(global.db, userID, log).then(function (savedLog) { return logs.deleteLogList(global.db, userID).then(function () { return logs.readLogList(global.db, userID).then(function (list) { assert.equal(list.length, 0); }); }); }); }); });
'use strict' const express = require('express'); const router = express.Router(); const auth = require('../controllers/authController'); /* GET users listing. */ router.post('/login', auth.login); router.post('/register', auth.register); module.exports = router;
import React from "react" import {Heading, CodePane, Text, Appear} from "spectacle" const colorSchemes = { a: { textColor: 'primary', bgColor: 'black' }, b: { textColor: 'secondary', bgColor: 'secondary' } } export default ({name, es6, es5, scheme, codeSize = 18}) => { const colorScheme = colorSchemes[scheme] return ( <div> <Heading size={1} cap fit textColor={colorScheme.textColor}> {name} </Heading> <Appear fid='1'> <div> <Heading size={5} textColor={colorScheme.textColor}> ES5 </Heading> <CodePane textSize={codeSize} margin={8} transition={["fade"]} bgColor={colorScheme.bgColor} lang="js" source={es5}/> </div> </Appear> <Appear fid='2'> <div> <Heading size={5} textColor={colorScheme.textColor}> ES6 </Heading> <CodePane textSize={codeSize} margin={8} transition={["fade"]} bgColor={colorScheme.bgColor} lang="js" source={es6}/> </div> </Appear> </div> ) }
// Separate Numbers with Commas in JavaScript **Pairing Challenge** // I worked on this challenge with: Tiffany Larson. // Pseudocode // Create a new container. // Remove back number from original container and add it to the front of the new container. // Do this three times or until original container is empty. // Check to see if the original container has any numbers left in it. // If there are numbers left in the original container, add a comma to the front of the new container. // Repeat until original container is empty. // Initial Solution // var separateComma = function(number){ // var stringNumber = number.toString(); // //console.log(stringNumber); // var oldArray = stringNumber.split(""); // //console.log(oldArray); // var newArray = []; // var counter = 0; // while (oldArray.length > 0) { // while (counter < 3) { // newArray.unshift(oldArray.pop()); // //console.log(newArray); // counter++; // } // if (oldArray.length == 0) { // finalNumber = newArray.join(""); // console.log(finalNumber); // } else { // newArray.unshift(","); // //console.log(newArray); // counter = 0; // } // } // return finalNumber; // } // separateComma(12345678); // Refactored Solution var separateComma = function(number){ var oldArray = number.toString().split(""); var newArray = []; var counter = 0; while (oldArray.length > 0) { while (counter < 3) { newArray.unshift(oldArray.pop()); counter++; } if (oldArray.length == 0) { finalNumber = newArray.join(""); console.log(finalNumber); } else { newArray.unshift(","); counter = 0; } } return finalNumber; } separateComma(12345678); // Your Own Tests (OPTIONAL) // Reflection // 1) What was it like to approach the problem from the perspective of JavaScript? Did you approach the problem differently? // I admit that I've focused so much on Ruby that I tend to think about code in Ruby. So thinking in JavaScript is more difficult for me. While writing psuedocode I tried not to approach the problem the same, but definitely while writing code I had to think differently. // 2) What did you learn about iterating over arrays in JavaScript? // I learned that the basic concept of iterating over arrays is very similar to iterating in Ruby, but the syntax is different. // 3) What was different about solving this problem in JavaScript? // The concept is the same, but the syntax is different. // 4) What built-in methods did you find to incorporate in your refactored solution? // .toString, .split, .unshift, and .join. These are all methods that I was already familiar with from Ruby but hadn't used them much in JavaScript.
import * as types from '../mutation-types'; import * as api from '@/api'; let state = { content: '', }; let actions = { getBlogContent ({ commit }, payload) { api.getBlogContent(payload.blogName) .then((data) => { commit({ type: types.OPEN_SOME_BLOG, content: data.content, }) }) } }; let mutations = { [types.OPEN_SOME_BLOG] (state, payload) { state.content = payload.content; } }; export default { namespaced: true, state, actions, mutations, }
module.exports = { main: { files: [{ expand: true, cwd: '<%= app %>/fonts', src: ['**'], dest: '<%= build %>/fonts' }, { expand: true, cwd: 'content/projects/videos', src: ['**'], dest: '<%= build %>/videos/projects' }] } };
var User = require('./fixtures/User'); var should = require('should'); describe('User', function(){ describe('#save()', function(){ it('should save without error', function(done){ var user = new User('Luna'); // user.save takes a callback - // remember mocha's done will accept a potential error // Write a test that saves the User }); }); });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.5-4-96 description: > Object.create - 'enumerable' property of one property in 'Properties' is the global object (8.10.5 step 3.b) includes: - runTestCase.js - fnGlobalObject.js ---*/ function testcase() { var accessed = false; var newObj = Object.create({}, { prop: { enumerable: fnGlobalObject() } }); for (var property in newObj) { if (property === "prop") { accessed = true; } } return accessed; } runTestCase(testcase);
/*====================================================== ************ Picker ************ ======================================================*/ /* global $:true */ + function($) { "use strict"; //Popup 和 picker 之类的不要共用一个弹出方法,因为这样会导致 在 popup 中再弹出 picker 的时候会有问题。 $.openPopup = function(popup, className) { $.closePopup(); popup = $(popup); popup.addClass("weui-popup-container-visible"); var modal = popup.find(".weui-popup-modal"); modal.width(); modal.addClass("weui-popup-modal-visible"); } $.closePopup = function(container, remove) { $(".weui-popup-modal-visible").removeClass("weui-popup-modal-visible").transitionEnd(function() { $(this).parent().removeClass("weui-popup-container-visible"); remove && $(this).parent().remove(); }).trigger("close"); }; $(document).on("click", ".close-popup", function() { $.closePopup(); }); $(document).on("click", ".open-popup", function() { $($(this).data("target")).popup(); }); $.fn.popup = function() { return this.each(function() { $.openPopup(this); }); }; }($);
var margin = { top: 50, right: 62, bottom: 100, left: 50 }, dim = Math.min(parseInt(d3.select("#chart").style("width")), parseInt(d3.select("#chart").style("height"))), width = dim - margin.left - margin.right, height = dim - margin.top - margin.bottom; //width = 700 - margin.left - margin.right, //height = 700 - margin.top - margin.bottom; var parseDate = d3.time.format("%Y").parse; // escalas var x = d3.time.scale().range([0, width]); //var y = d3.scale.log().range([height, 0]); Logaritmica, se necessário var y = d3.scale.linear().range([height, 40]); // eixos var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(7) .innerTickSize(-height) .outerTickSize(0) .tickPadding(10); var yAxis = d3.svg.axis().scale(y) .orient("left") .ticks(6, "%") .tickSize(3, 0) .innerTickSize(-width) .outerTickSize(0) .tickPadding(15); // linhas do gráfico var valueline = d3.svg.line() .x(function (d) { return x(d.date); }) // se usar escala log, cria o valor referência .y(function (d) { return y(d.value + 1); }); var nota = d3.select(".nota") .attr("class", "nota") .style("opacity", "0"); // acrescenta a canvas de svg var svg = d3.select("#chart") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .on("click", function (d) { // button.transition() // .delay(0) // .duration(200) // .style("opacity", "0") // .style("pointer-events", "none"); }); var corpo = d3.selectAll("text") .on("click", function (d) { button.transition() .delay(0) .duration(200) .style("opacity", "0") .style("pointer-events", "none"); }); // puxa os dados da tabela d3.tsv("dados/reject.tsv", function (error, data) { data.forEach(function (d) { d.date = parseDate(d.date); d.value = +d.value; }); // o range dos dados x.domain(d3.extent(data, function (d) { return d.date; })); y.domain([1, d3.max(data, function (d) { return d.value; })]); // colocar os paises em nest var dataNest = d3.nest() .key(function (d) { return d.key; }) .entries(data); var piaui = ["#7bad65", "#777", "#5ea4ab", "#eabf54", "#d94f30"] var color = d3.scale.ordinal() .range(piaui) legendSpace = width / dataNest.length; // espaçamento da legenda // utiliza as categorias dataNest.forEach(function (d, i) { svg.append("path") .attr("class", "line") .style("stroke", function () { return d.color = color(d.key); }) //acrescenta linha dashed pra média .style('stroke-dasharray', function () { return d.key === 'Média' ? '4 4' : ''; }) .style('opacity', function () { if (d.key === 'Rússia') return '.1'; if (d.key === 'China') return '.1' if (d.key === 'Índia') return '.1' if (d.key === 'Média') return '.1' }) .attr("id", 'tag' + d.key.replace(/\s+/g, '')) // aplicar classe das linhas .attr("d", valueline(d.values)) .append("title"); // legenda retangular //svg.append("rect") //.attr("x", (legendSpace / 8) + i * legendSpace) // space legend //.attr("class", "legend") //.style("text-anchor", "end") //.attr("y", -38) //.attr("width", 8) //.attr("height", 8) //.style("fill", function() { return d.color = color(d.key); }); //linhas para anos //svg.selectAll("line").data(data).enter().append("line") //.attr('x1',function(d) { return x(d.date); }) //.attr('y1',function(d) { return y(0); }) //.attr('x2',function(d) { return x(d.date); }) //.attr('y2',function(d) { return y(d.value); }) //.style("stroke-width", 2) //.style("stroke", "gray") //.style("stroke-dasharray", ("2, 2")) //.style("opacity",0); // Define a div para tooltip var button = d3.select("#chart").append("button") .data(data) .attr("class", "tooltip") .style("opacity", 0); // Formata data para tooltip var FormatDate = d3.time.format("%Y"); //rect botões //svg.append("rect") //.attr("x", (legendSpace / 5) + i * legendSpace) // space legend //.attr("y", -38) //.attr("rx", 4) //.attr("class", "botoes") //.style("fill", function () { //return d.color = color(d.key); //}) // .on("mouseover", function () { //nota.transition() //.style("display", "block") // .style("opacity", "1"); // }) // .on("mouseout", function (d) { // nota.transition() // .style("opacity", .5); //}) // .on("click", function () { // Determine if current line is visible // var active = d.active ? false : true, //newOpacity = active ? 1 : 0.2; // Hide or show the elements based on the ID // d3.select("#tag" + d.key.replace(/\s+/g, '')) //.transition().duration(300) //.ease("linear") // .style("opacity", newOpacity); // d.active = active; //}) // .text(d.key); // texto legenda svg.append("text") .attr("x", (legendSpace / 2) + i * legendSpace) // space legend //.attr("y", height + (margin.bottom/1.5)+ 5) .attr("y", -30) .attr("class", "legend") .style("stroke", "none") .style("fill", function () { return d.color = color(d.key); }) //.style("fill", "#fff") .on("mouseover", function () { dot.transition() .style("display", "block") .style("opacity", "1"); }) .on("mouseout", function (d) { dot.transition() .style("opacity", .2); }) .on("click", function () { // Determine if current line is visible var active = d.active ? false : true, newOpacity = active ? 1 : 0.2; // Hide or show the elements based on the ID d3.select("#tag" + d.key.replace(/\s+/g, '')) .transition().duration(300) .ease("linear") .style("opacity", newOpacity); d.active = active; }) .text(d.key); // Acrescenta os pontos pra tooltip svg.selectAll("dot") .data(data) .enter().append("circle") .attr("class", "circulo") .attr("r", 5) .attr("cx", function (d) { return x(d.date); }) .attr("cy", function (d) { return y(d.value + 1); }) .style("fill", function (d) { return d.color = color(d.key); }) .style("opacity", ".1") .classed("hidden", true) .style("display", "block") .style("cursor", "pointer") .attr("id", 'key' + d.key.replace(/\s+/g, '')) .on("mouseover", function (d) { button.transition() .duration(200) .style("cursor", "pointer") .style("opacity", 1); button.html("<h4>Ano: " + d.key + "</h4> <br/>" + "<h4>Ano: </h4>" + FormatDate(d.date) + "<br/>" + "<h4>Taxa de rejeição: </h4> " + d.value + "%<br/>" + "<hr/>" + "<h4>Total de vistos concedidos: </h4>" + d.vistos + "<br/>" + "<h4>Turismo/Negócios: </h4>" + d.v_pct + "<br/>" + "<h4>Trabalho/Estudos: </h4>" + d.t_pct + "<br/>" + "<h4>Outros tipos: </h4>" + d.o_pct) .style("left", d3.select(this).attr("cx") + "px") .style("top", d3.select(this).attr("cy") + "px"); }) .on("touchstart", function (d) { button.transition() .duration(200) .style("cursor", "pointer") .style("opacity", 1); button.html("<h4>Ano: " + d.key + "</h4> <br/>" + "<h4>Ano: </h4>" + FormatDate(d.date) + "<br/>" + "<h4>Taxa de rejeição: </h4> " + d.value + "%<br/>" + "<hr/>" + "<h4>Total de vistos concedidos: </h4>" + d.vistos + "<br/>" + "<h4>Turismo/Negócios: </h4>" + d.v_pct + "<br/>" + "<h4>Trabalho/Estudos: </h4>" + d.t_pct + "<br/>" + "<h4>Outros tipos: </h4>" + d.o_pct) .style("left", d3.select(this).attr("cx") + "px") .style("top", d3.select(this).attr("cy") + "px"); }) .on("mouseout", function (d) { button.interrupt().transition() .delay(0) .duration(200) .style("opacity", "0") .style("pointer-events", "none"); }) //.on("click", function (d) { // button.transition() // .delay(0) // .duration(200) // .style("opacity", "0") // .style("pointer-events", "none"); // }); }); // eixo x svg.append("g") .attr("class", "x_axis") .attr("transform", "translate(0," + height + ")") .style("stroke", "none") .call(xAxis); // eixo y svg.append("g") .attr("class", "y_axis") .style("stroke", "none") .call(yAxis); // Fonte svg.append("text") //.attr("y", 0 - margin.left) //.attr("x",0 - (height / 2)) .attr("transform", "rotate(0)") .attr("class", "fonte") .attr("y", height + 70) .attr("x", margin.right) .attr("dy", "1em") .style("text-anchor", "middle") .style("fill", "#bbb") .style("font-size", ".8em") .text("Fonte: Depto. de Estado dos EUA"); svg.append("rect") //.attr("x",0 - (height / 2)) //.attr("y", 0 - margin.left) .attr("y", height + 60) .attr("x", -38) .attr("width", width - 50) .attr("height", "2px") .style("fill", "#bbbbbb"); svg.append("svg:image") .attr("xlink:href", "piauicinza.png") .attr("y", height + 20) .attr("x", width - 60) .attr("width", 60) .attr("height", 80); }); function resize() { var dim = Math.min(parseInt(d3.select("#chart").style("width")), parseInt(d3.select("#chart").style("height"))), width = dim - margin.left - margin.right, height = dim - margin.top - margin.bottom; console.log(dim); // Update the range of the scale with new width/height x.range([0, width]); y.range([height, 0]); } d3.select(window).on('resize', resize); resize();
// 定一个 reducer function reducer(state, action) { /* 初始化 state 和 switch case */ if (!state) { return { title: { text: 'React.js 小书', color: 'red' }, content: { text: 'React.js 小书内容', color: 'blue' } } } switch (action.type) { case 'UPDATE_TITLE_TEXT': return { ...state, title: { ...state.title, text: action.text } }; case 'UPDATE_TITLE_COLOR': return { ...state, title: { ...state.title, color: action.color } }; default: return state; } } // 生成 store function createStore(reducer) { let state = null; const listeners = []; const subscribe = (listener) => listeners.push(listener); const getState = () => state; const dispatch = (action) => { state = reducer(state, action); listeners.forEach((listener) => { listener(); }); }; dispatch({}); // 初始化 state return { getState, dispatch, subscribe } } // 生成 store const store = createStore(reducer); let oldState = store.getState(); // 缓存旧的state // 监听数据变化重新渲染页面 store.subscribe(() => { const newState = store.getState(); renderApp(newState, oldState); oldState = newState; }); function renderTitle(newTitle, oldTitle) { if (newTitle === oldTitle) { return; } console.log('render title...') const titleDOM = document.getElementById('title'); titleDOM.innerHTML = newTitle.text; titleDOM.style.color = newTitle.color; } function renderContent(newContent, oldContent) { if (newContent === oldContent) { return; } console.log('render content...') const contentDOM = document.getElementById('content'); contentDOM.innerHTML = newContent.text; contentDOM.style.color = newContent.color; } function renderApp(newAppState, oldAppState = {}) { if (newAppState === oldAppState) { return; } console.log('render app...') renderTitle(newAppState.title, oldAppState.title); renderContent(newAppState.content, oldAppState.content); } // 首次渲染页面 renderApp(store.getState()); // 后面可以随意 dispatch 了,页面自动更新 store.dispatch({type: 'UPDATE_TITLE_TEXT', text: '《React.js 小书》'}); // 修改标题文本 store.dispatch({type: 'UPDATE_TITLE_COLOR', color: 'blue'}); // 修改标题颜色
var fs = require('fs'); var path = require('path'); var recursive = require('recursive-readdir-sync'); var git = require('simple-git'); var posts_data = __dirname + '/../data/posts_dates.json'; createFile(posts_data); var listOfPosts = recursive(__dirname + '/../posts/'); var cleanedListOfPosts = listOfPosts.filter(function (f) { return path.extname(path.basename(f)) === '.md' }); cleanedListOfPosts.forEach(function (file) { git().log( ['--diff-filter=A', '--follow', '--format=%aI', '--', file ], function(err, data) { writeToJsonFile(path.basename(file), data.latest.hash, posts_data); }); }); function createFile(filename) { fs.open(filename,'r',function(err, fd){ if (err) { fs.writeFileSync(filename, '{}'); console.log("The file was saved!"); } else { console.log("The file exists!"); } }); } function writeToJsonFile(key, value, fileName) { var file = require(fileName); file[key] = value; fs.writeFile(fileName, JSON.stringify(file, null, 2), function (err) { if (err) return console.log(err); console.log('writing ' + key + ' : ' + value + ' to ' + fileName); }); }
import React from "react"; import { shallow } from "enzyme"; import App from "../../renderer/Components/App"; import EmojiPad from "../../renderer/Components/EmojiPad"; test("<App /> should have div with <EmojiPad />", () => { const app = shallow(<App />); expect( app.contains( <div id="app-container" className="container is-fluid"> <EmojiPad /> </div> ) ).toBe(true); });
require([ "esri/Map", "esri/views/SceneView", "dojo/domReady!" ], function(Map, SceneView) { var map = new Map({ basemap: "streets", ground: "world-elevation" }); var view = new SceneView({ container: "viewDiv", // Reference to the DOM node that will contain the view map: map // References the map object created in step 3 }); });
'use strict'; const { readFileSync, readdirSync, writeFileSync } = require('fs'); // Get all markdown stubs const header = readFileSync('bundler/header.md', 'utf-8'); const badges = readFileSync('bundler/badges.md', 'utf-8'); const installation = readFileSync('bundler/installation.md', 'utf-8'); const api = readFileSync('bundler/api.md', 'utf-8'); const strictnessAndComparisons = readFileSync('bundler/strictness_and_comparisons.md', 'utf-8'); const notImplemented = readFileSync('bundler/not_implemented.md', 'utf-8'); const contribute = readFileSync('bundler/contribute.md', 'utf-8'); const license = readFileSync('bundler/license.md', 'utf-8'); // Get all API docs const methods = readdirSync('docs/api', 'utf-8'); // Build table of contents const tableOfContents = methods.map((file) => { const methodName = file.replace('.md', ''); return `- [${methodName}](#${methodName.toLowerCase()})`; }).join('\n'); // Build methods "readme" const methodDocumentation = methods.map((file) => { let content = readFileSync(`docs/api/${file}`, 'utf-8'); const lines = content.split('\n'); lines[0] = `###${lines[0]}`; lines.pop(); lines.pop(); content = lines.join('\n'); content = content.replace(/(\r\n|\r|\n){2,}/g, '$1\n'); return content; }).join('\n\n'); writeFileSync( 'README.md', [ header, badges, installation, api, tableOfContents, strictnessAndComparisons, notImplemented, methodDocumentation, contribute, license, ].join('\n\n'), );
// JavaScript Document //Override the default setting $(document).bind("mobileinit", function(){ $.mobile.defaultPageTransition = 'slide'; });
'use strict'; /** Module for browsing transfer endpoints. */ angular.module('stork.transfer.browse', [ 'ngCookies' ]) .service('history', function (stork) { var history = []; var listeners = []; this.history = history; this.fetch = function (uri) { stork.history(uri).then(function (h) { history = h; for (var i = 0; i < listeners.length; i++) listeners[i](history); }); }; this.fetch(); /** Add a callback for when history changes. */ this.listen = function (f) { if (!angular.isFunction(f)) return; listeners.push(f); f(history); }; }) /** A place to store browse URIs to persist across pages. */ .service('endpoints', function ($cookieStore) { var ends = {}; /** Get an endpoint by name. */ this.get = function (name) { return ends[name] || (ends[name] = {}); }; }) .controller('History', function (history) { var me = this; this.list = []; history.listen(function (history) { me.list = history; }); }) .controller('Browse', function ( $scope, $q, $modal, $window, $attrs, stork, user, history, endpoints, $location) { // Restore a saved endpoint. side should already be in scope. $scope.end = endpoints.get($attrs.side); // Reset (or initialize) the browse pane. $scope.reset = function () { $scope.uri = {}; $scope.state = {disconnected: true}; delete $scope.error; delete $scope.root; }; $scope.reset(); // Set the endpoint URI. $scope.go = function (uri) { if (!uri) return $scope.reset(); if (typeof uri === 'string') uri = new URI(uri).normalize(); else uri = uri.clone().normalize(); var readable = uri.readable(); // Make sure the input box matches the URI we're dealing with. if (readable != $scope.uri.text) { $scope.uri.text = readable; uri = new URI(readable).normalize(); } $scope.uri.parsed = uri; $scope.uri.text = readable; if ($scope.uri.state) $scope.uri.state.changed = false; else $scope.uri.state = {}; $scope.end.uri = readable; // Clean up after previous calls. if ($scope.history) $scope.history.show = false; delete $scope.root; delete $scope.state.disconnected; $scope.state.loading = true; history.fetch(readable); $scope.fetch(uri).then(function (list) { delete $scope.state.loading; $scope.root = list; $scope.root.name = readable; $scope.open = true; $scope.unselectAll(); }, function (error) { delete $scope.state.loading; $scope.error = error; }); }; /* Reload the existing listing. */ $scope.refresh = function () { $scope.go($scope.uri.parsed); }; /* Fetch and cache the listing for the given URI. */ $scope.fetch = function (uri) { var scope = this; scope.loading = true; delete scope.error; var ep = angular.copy($scope.end); ep.uri = uri.href(); return stork.ls(ep, 1).then( function (d) { if (scope.root) d.name = scope.root.name || d.name; return scope.root = d; }, function (e) { return $q.reject(scope.error = e); } ).finally(function () { scope.loading = false; }); }; // Get the path URI of this item. $scope.path = function () { if ($scope.root === this.root) return $scope.uri.parsed.clone(); return this.parent().path().segmentCoded(this.root.name); }; // Open the mkdir dialog. $scope.mkdir = function () { $modal({ title: 'Create Directory', contentTemplate: 'new-folder.html', scope: $scope }); result.then(function (pn) { var u = new URI(pn[0]).segment(pn[1]); return stork.mkdir(u.href()).then( function (m) { $scope.refresh(); }, function (e) { alert('Could not create folder: '+e.error); } ); }); }; /* Open cred modal. */ $scope.credModal = function () { $modal({ title: 'Select Credential', contentTemplate: 'select-credential.html', scope: $scope }); }; // Delete the selected files. $scope.rm = function (uris) { _.each(uris, function (u) { if (confirm("Delete "+u+"?")) { return stork.delete(u).then( function () { $scope.refresh(); }, function (e) { alert('Could not delete file: '+e.error); } ); } }); }; // Download the selected file. $scope.download = function (uris) { if (uris == undefined || uris.length == 0) return alert('You must select a file.'); else if (uris.length > 1) return alert('You can only download one file at a time.'); var end = { uri: uris[0], credential: $scope.end.credential }; stork.get(end); }; // Share the selected file. $scope.share = function (uris) { if (uris == undefined || uris.length == 0) return alert('You must select a file.'); else if (uris.length > 1) return alert('You must select exactly one file.'); stork.share({ uri: uris[0], credential: $scope.end.credential }).then(function (r) { var link = "https://storkcloud.org/api/stork/get?uuid="+r.uuid; var scope = $scope.$new(); scope.link = link; $modal({ title: 'Share link', contentTemplate: 'show-share-link.html', scope: angular.extend(scope) }); }, function (e) { alert('Could not create share: '+e.error); }); }; // Return the scope corresponding to the parent directory. $scope.parent = function () { if (this !== $scope) { if (this.$parent.root !== this.root) return this.$parent; return this.$parent.parent(); } }; $scope.up_dir = function () { var u = $scope.uri.parsed; if (!u) return; u = u.clone().filename('../').normalize(); $scope.go(u); }; $scope.toggle = function () { var scope = this; var root = scope.root; if (root && root.dir && (scope.open = !scope.open) && !root.files) { scope.fetch(scope.path()); } }; $scope.select = function (e) { var scope = this; var u = this.path(); if (e.ctrlKey) { this.root.selected = !this.root.selected; if (this.root.selected) $scope.end.$selected[u] = this.root; else delete $scope.end.$selected[u]; } else if ($scope.selectedUris().length != 1) { // Either nothing is selected, or multiple things are selected. $scope.unselectAll(); this.root.selected = true; $scope.end.$selected[u] = this.root; } else { // Only one thing is selected. var selected = this.root.selected; $scope.unselectAll(); if (!selected) { this.root.selected = true; $scope.end.$selected[u] = this.root; } } // Unselect text. if (document.selection && document.selection.empty) document.selection.empty(); else if (window.getSelection) window.getSelection().removeAllRanges(); }; $scope.unselectAll = function () { var s = $scope.end.$selected; if (s) _.each(s, function (f) { delete f.selected; }); $scope.end.$selected = {}; }; $scope.selectedUris = function () { if (!$scope.end.$selected) return []; return _.keys($scope.end.$selected); }; /* Default examples to show in the dropdown box. */ $scope.dropdownList = [ ["fa-dropbox", "Dropbox", "dropbox:///"], ["fa-globe", "Mozilla FTP", "ftp://ftp.mozilla.org/"], ["fa-globe", "SDSC Gordon (GridFTP)", "gsiftp://oasis-dm.sdsc.xsede.org/"] ]; $scope.openOAuth = function (url) { $window.oAuthCallback = function (uuid) { $scope.end.credential = {uuid: uuid}; $scope.refresh(); $scope.$apply(); }; var child = $window.open(url, 'oAuthWindow'); return false; }; if ($scope.end.uri) $scope.go($scope.end.uri); });
const NODE_ENV = process.env.NODE_ENV || 'development' module.exports = { /** The environment to use when building the project */ env: NODE_ENV, /** The full path to the project's root directory */ basePath: __dirname, /** The name of the directory containing the application source code */ srcDir: 'src', /** The file name of the application's entry point */ main: 'main', /** The name of the directory in which to emit compiled assets */ outDir: 'dist', /** The base path for all projects assets (relative to the website root) */ publicPath: '/admin/', /** The root path for web */ urlRoot: 'admin', /** Whether to generate sourcemaps */ sourcemaps: true, /** A hash map of keys that the compiler should treat as external to the project */ externals: {}, /** A hash map of variables and their values to expose globally */ globals: {}, /** Whether to enable verbose logging */ verbose: false, /** The list of modules to bundle separately from the core application code */ vendors: [ 'react', 'react-dom', 'redux', 'react-redux', 'redux-thunk', 'react-router', ], apiProxy: { url: 'http://47.94.172.79' } }
var config = require('../config').logger; var bunyan = require('bunyan'); var logstash = require('bunyan-logstash-tcp'); module.exports = function createLogger(){ var log = bunyan.createLogger({ name: 'rabbitmq-connector', streams: [ { type: 'raw', stream: logstash.createStream({ host: config.logStash.host, port: config.logStash.port, tags: ['bunyan', 's3-connector'] }) .on('error', function func(err) { /* eslint-disable */ console.error('[s3-connector] Error in bunyan-logstash-tcp stream'); console.error(err); /* eslint-enable */ }) }, { stream: process.stdout } ] }); return log; };
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ /** * @class ZaResourceController controls display of a single resource * @author Charles Cao * resource controller */ ZaResourceController = function(appCtxt, container) { ZaXFormViewController.call(this, appCtxt, container,"ZaResourceController"); this._UICreated = false; this._helpURL = location.pathname + ZaUtil.HELP_URL + "managing_accounts/managing_resource.htm?locid="+AjxEnv.DEFAULT_LOCALE; this._helpButtonText = ZaMsg.helpManageResourceAccount; this.deleteMsg = ZaMsg.Q_DELETE_RES; this.objType = ZaEvent.S_ACCOUNT; this.tabConstructor = ZaResourceXFormView; } ZaResourceController.prototype = new ZaXFormViewController(); ZaResourceController.prototype.constructor = ZaResourceController; ZaController.initToolbarMethods["ZaResourceController"] = new Array(); ZaController.initPopupMenuMethods["ZaResourceController"] = new Array(); ZaController.setViewMethods["ZaResourceController"] = []; ZaController.changeActionsStateMethods["ZaResourceController"] = new Array(); ZaResourceController.prototype.toString = function () { return "ZaResourceController"; }; ZaResourceController.prototype.setDirty = function (isDirty) { ZaZimbraAdmin.getInstance().getCurrentAppBar().enableButton(ZaOperation.SAVE, isDirty); } ZaResourceController.prototype.handleXFormChange = function (ev) { if(ev && ev.form.hasErrors()) { ZaZimbraAdmin.getInstance().getCurrentAppBar().enableButton(ZaOperation.SAVE, false); } } ZaResourceController.prototype.show = function(entry, openInNewTab, skipRefresh) { this._setView(entry, openInNewTab, skipRefresh); } ZaResourceController.changeActionsStateMethod = function () { var isToEnable = (this._view && this._view.isDirty()); if(this._popupOperations[ZaOperation.SAVE]) { this._popupOperations[ZaOperation.SAVE].enabled = isToEnable; } } ZaController.changeActionsStateMethods["ZaResourceController"].push(ZaResourceController.changeActionsStateMethod); ZaResourceController.setViewMethod = function (entry) { this._createUI(entry); try { //ZaApp.getInstance().pushView(ZaZimbraAdmin._RESOURCE_VIEW); ZaApp.getInstance().pushView(this.getContentViewId()); if(entry.id) { //get the calendar resource by id entry.load("id", entry.id, null); } this._view.setDirty(false); entry[ZaModel.currentTab] = "1" ; this._view.setObject(entry); //disable the save button at the beginning of showing the form ZaZimbraAdmin.getInstance().getCurrentAppBar().enableButton(ZaOperation.SAVE, false); this._currentObject = entry; } catch (ex) { this._handleException(ex, "ZaResourceController.prototype.show", null, false); } }; ZaController.setViewMethods["ZaResourceController"].push(ZaResourceController.setViewMethod); ZaResourceController.initPopupMenuMethod = function () { var showNewCalRes = false; if(ZaSettings.HAVE_MORE_DOMAINS || ZaZimbraAdmin.currentAdminAccount.attrs[ZaAccount.A_zimbraIsAdminAccount] == 'TRUE') { showNewCalRes = true; } else { var domainList = ZaApp.getInstance().getDomainList().getArray(); var cnt = domainList.length; for(var i = 0; i < cnt; i++) { if(ZaItem.hasRight(ZaDomain.RIGHT_CREATE_CALRES,domainList[i])) { showNewCalRes = true; break; } } } this._popupOperations[ZaOperation.SAVE]=new ZaOperation(ZaOperation.SAVE,ZaMsg.TBB_Save, ZaMsg.ALTBB_Save_tt, "Save", "SaveDis", new AjxListener(this, this.saveButtonListener)); this._popupOperations[ZaOperation.CLOSE]=new ZaOperation(ZaOperation.CLOSE,ZaMsg.TBB_Close, ZaMsg.ALTBB_Close_tt, "Close", "CloseDis", new AjxListener(this, this.closeButtonListener)); if(showNewCalRes) { this._popupOperations[ZaOperation.NEW]=new ZaOperation(ZaOperation.NEW,ZaMsg.TBB_New, ZaMsg.RESTBB_New_tt, "Resource", "ResourceDis", new AjxListener(this, this.newButtonListener)); } this._popupOperations[ZaOperation.DELETE]=new ZaOperation(ZaOperation.DELETE,ZaMsg.TBB_Delete, ZaMsg.RESTBB_Delete_tt,"Delete", "DeleteDis", new AjxListener(this, this.deleteButtonListener)); this._popupOrder.push(ZaOperation.NEW); this._popupOrder.push(ZaOperation.SAVE); this._popupOrder.push(ZaOperation.CLOSE); this._popupOrder.push(ZaOperation.DELETE); } ZaController.initPopupMenuMethods["ZaResourceController"].push(ZaResourceController.initPopupMenuMethod); /* ZaResourceController.prototype.getAppBarAction = function () { if (AjxUtil.isEmpty(this._appbarOperation)) { this._appbarOperation[ZaOperation.SAVE]= new ZaOperation(ZaOperation.SAVE, ZaMsg.TBB_Save, ZaMsg.ALTBB_Save_tt, "", "", new AjxListener(this, this.saveButtonListener)); this._appbarOperation[ZaOperation.CLOSE] = new ZaOperation(ZaOperation.CLOSE, ZaMsg.TBB_Close, ZaMsg.ALTBB_Close_tt, "", "", new AjxListener(this, this.closeButtonListener)); } return this._appbarOperation; } ZaResourceController.prototype.getAppBarOrder = function () { if (AjxUtil.isEmpty(this._appbarOrder)) { this._appbarOrder.push(ZaOperation.SAVE); this._appbarOrder.push(ZaOperation.CLOSE); } return this._appbarOrder; }*/ ZaResourceController.prototype.getPopUpOperation = function() { return this._popupOperations; } ZaResourceController.prototype.newResource = function () { try { var newResource = new ZaResource(); //newResource.getAttrs = {all:true}; //newResource._defaultValues = {attrs:{}}; newResource.loadNewObjectDefaults("name", ZaSettings.myDomainName); if(!ZaApp.getInstance().dialogs["newResourceWizard"]) ZaApp.getInstance().dialogs["newResourceWizard"]= new ZaNewResourceXWizard(this._container); ZaApp.getInstance().dialogs["newResourceWizard"].setObject(newResource); ZaApp.getInstance().dialogs["newResourceWizard"].popup(); } catch (ex) { this._handleException(ex, "ZaResourceController.prototype.newResource", null, false); } } // new button was pressed ZaResourceController.prototype.newButtonListener = function(ev) { if(this._view.isDirty()) { //parameters for the confirmation dialog's callback var args = new Object(); args["params"] = null; args["obj"] = this; args["func"] = ZaResourceController.prototype.newResource; //ask if the user wants to save changes //ZaApp.getInstance().dialogs["confirmMessageDialog"] = ZaApp.getInstance().dialogs["confirmMessageDialog"] = new ZaMsgDialog(this._view.shell, null, [DwtDialog.YES_BUTTON, DwtDialog.NO_BUTTON, DwtDialog.CANCEL_BUTTON]); ZaApp.getInstance().dialogs["confirmMessageDialog"].setMessage(ZaMsg.Q_SAVE_CHANGES, DwtMessageDialog.INFO_STYLE); ZaApp.getInstance().dialogs["confirmMessageDialog"].registerCallback(DwtDialog.YES_BUTTON, this.saveAndGoAway, this, args); ZaApp.getInstance().dialogs["confirmMessageDialog"].registerCallback(DwtDialog.NO_BUTTON, this.discardAndGoAway, this, args); ZaApp.getInstance().dialogs["confirmMessageDialog"].popup(); } else { this.newResource(); } } //private and protected methods ZaResourceController.prototype._createUI = function (entry) { //create accounts list view // create the menu operations/listeners first this._contentView = this._view = new this.tabConstructor(this._container, entry); this._initPopupMenu(); //always add Help button at the end of the toolbar var elements = new Object(); elements[ZaAppViewMgr.C_APP_CONTENT] = this._view; ZaApp.getInstance().getAppViewMgr().createView(this.getContentViewId(), elements); this._removeConfirmMessageDialog = new ZaMsgDialog(ZaApp.getInstance().getAppCtxt().getShell(), null, [DwtDialog.YES_BUTTON, DwtDialog.NO_BUTTON], null, ZaId.VIEW_RES + "_removeConfirm"); this._UICreated = true; ZaApp.getInstance()._controllers[this.getContentViewId ()] = this ; } /** * saves the changes in the fields, calls modify or create on the current ZaResource * @return Boolean - indicates if the changes were succesfully saved **/ ZaResourceController.prototype._saveChanges = function () { //check if the XForm has any errors if(this._view.getMyForm().hasErrors()) { var errItems = this._view.getMyForm().getItemsInErrorState(); var dlgMsg = ZaMsg.CORRECT_ERRORS; dlgMsg += "<br><ul>"; var i = 0; for(var key in errItems) { if(i > 19) { dlgMsg += "<li>...</li>"; break; } if(key == "size") continue; var label = errItems[key].getInheritedProperty("msgName"); if(!label && errItems[key].getParentItem()) { //this might be a part of a composite label = errItems[key].getParentItem().getInheritedProperty("msgName"); } if(label) { if(label.substring(label.length-1,1)==":") { label = label.substring(0, label.length-1); } } if(label) { dlgMsg += "<li>"; dlgMsg +=label; dlgMsg += "</li>"; } i++; } dlgMsg += "</ul>"; this.popupMsgDialog(dlgMsg, true); return false; } //check if the data is copmlete var tmpObj = this._view.getObject(); var newName=null; //Check the data if(tmpObj.attrs == null ) { //show error msg this._errorDialog.setMessage(ZaMsg.ERROR_UNKNOWN, null, DwtMessageDialog.CRITICAL_STYLE, null); this._errorDialog.popup(); return false; } ZaResource.prototype.setLdapAttrsFromSchedulePolicy.call(tmpObj); //check if need to rename if(this._currentObject && tmpObj.name != this._currentObject.name) { //var emailRegEx = /^([a-zA-Z0-9_\-])+((\.)?([a-zA-Z0-9_\-])+)*@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; /*if(!AjxUtil.EMAIL_SHORT_RE.test(tmpObj.name) ) {*/ if(!AjxUtil.isValidEmailNonReg(tmpObj.name)) { //show error msg this._errorDialog.setMessage(ZaMsg.ERROR_ACCOUNT_NAME_INVALID, null, DwtMessageDialog.CRITICAL_STYLE, null); this._errorDialog.popup(); return false; } newName = tmpObj.name; } var mods = new Object(); if(!ZaResource.checkValues(tmpObj)) return false; if(ZaItem.hasAnyRight([ZaResource.SET_CALRES_PASSWORD_RIGHT, ZaResource.CHANGE_CALRES_PASSWORD_RIGHT],tmpObj)) { //change password if new password is provided if(tmpObj.attrs[ZaResource.A_password]!=null && tmpObj[ZaResource.A2_confirmPassword]!=null && tmpObj.attrs[ZaResource.A_password].length > 0) { try { this._currentObject.changePassword(tmpObj.attrs[ZaResource.A_password]); } catch (ex) { this.popupErrorDialog(ZaMsg.FAILED_SAVE_ACCOUNT, ex); return false; } } } var changeDetails = new Object(); //set the cosId to "" if the autoCos is enabled. if (tmpObj[ZaResource.A2_autoCos] == "TRUE") { tmpObj.attrs[ZaResource.A_COSId] = "" ; } //check if need to rename if(newName) { changeDetails["newName"] = newName; try { this._currentObject.rename(newName); } catch (ex) { if(ex.code == ZmCsfeException.ACCT_EXISTS) { this.popupErrorDialog(ZaMsg.FAILED_RENAME_ACCOUNT_1, ex); } else { this._handleException(ex, "ZaResourceController.prototype._saveChanges", null, false); } return false; } } //transfer the fields from the tmpObj to the _currentObject for (var a in tmpObj.attrs) { if(a == ZaResource.A_password || a == ZaItem.A_objectClass || a==ZaResource.A_mail || a == ZaItem.A_zimbraId || a == ZaItem.A_zimbraACE) { continue; } if(!ZaItem.hasWritePermission(a,tmpObj)) { continue; } //check if the value has been modified if ((this._currentObject.attrs[a] != tmpObj.attrs[a]) && !(this._currentObject.attrs[a] == undefined && tmpObj.attrs[a] === "")) { if(a==ZaResource.A_uid) { continue; //skip uid, it is changed throw a separate request } if(a == ZaResource.A_COSId && !AjxUtil.isEmpty(tmpObj.attrs[ZaResource.A_COSId]) && !ZaItem.ID_PATTERN.test(tmpObj.attrs[ZaResource.A_COSId])) { this.popupErrorDialog(AjxMessageFormat.format(ZaMsg.ERROR_NO_SUCH_COS,[tmpObj.attrs[ZaResource.A_COSId]]), null); return false; } if(tmpObj.attrs[a] instanceof Array && this._currentObject.attrs[a] instanceof Array) { if(tmpObj.attrs[a].join(",").valueOf() != this._currentObject.attrs[a].join(",").valueOf()) { mods[a] = tmpObj.attrs[a]; } } else { mods[a] = tmpObj.attrs[a]; } } } if (this._currentObject[ZaModel.currentTab]!= tmpObj[ZaModel.currentTab]) this._currentObject[ZaModel.currentTab] = tmpObj[ZaModel.currentTab]; //save changed fields try { this._currentObject.modify(mods); } catch (ex) { if(ex.code == ZmCsfeException.ACCT_EXISTS) { this.popupErrorDialog(ZaMsg.FAILED_CREATE_ACCOUNT_1, ex); } else if(ex.code == ZmCsfeException.NO_SUCH_COS) { this.popupErrorDialog(AjxMessageFormat.format(ZaMsg.ERROR_NO_SUCH_COS,[tmpObj.attrs[ZaResource.A_COSId]]), ex); } else { this._handleException(ex, "ZaResourceController.prototype._saveChanges", null, false); } return false; } ZaApp.getInstance().getAppCtxt().getAppController().setActionStatusMsg(AjxMessageFormat.format(ZaMsg.ResourceModified,[this._currentObject.name])); return true; };
Sammy('#main', function() { this.get('/', function() { var zis = this; this.something = true; this.title = 'Hello!'; this.name = this.params.name; // render the template and pass it through handlebars this.partial('templates/home.hb'); setTimeout(function() { if (localStorage.getItem("kantoorwolven.player")) { zis.redirect('#/pick_game'); } else { zis.redirect('#/create_player'); } }, 1000); }); });
alert(2)
'use strict'; var assert = require('assert'); describe('basic', function () { it('should compile a Smash module', function () { var core = require('../!./fixtures/core.js'); assert.equal('string', typeof(core.hello)); assert.equal('world', core.hello); }); });
Package.describe({ name: 'rocketchat:livechat', version: '0.0.1', summary: 'Livechat plugin for Rocket.Chat' }); Package.registerBuildPlugin({ name: 'Livechat', use: [], sources: [ 'plugin/build-livechat.js' ], npmDependencies: { 'shelljs': '0.5.1' } }); Npm.depends({ 'ua-parser-js': '0.7.10' }); Package.onUse(function(api) { api.use(['webapp', 'autoupdate'], 'server'); api.use('ecmascript'); api.use('underscorestring:underscore.string'); api.use('rocketchat:lib'); api.use('rocketchat:authorization'); api.use('rocketchat:logger'); api.use('rocketchat:api'); api.use('konecty:user-presence'); api.use('rocketchat:ui'); api.use('kadira:flow-router', 'client'); api.use('templating', 'client'); api.use('http'); api.use('check'); api.use('mongo'); api.use('ddp-rate-limiter'); api.use('rocketchat:sms'); api.use('tracker'); api.use('less'); api.addFiles('livechat.js', 'server'); api.addFiles('server/startup.js', 'server'); api.addFiles('permissions.js', 'server'); api.addFiles('messageTypes.js'); api.addFiles('roomType.js'); api.addFiles('config.js', 'server'); api.addFiles('client/ui.js', 'client'); api.addFiles('client/route.js', 'client'); // add stylesheets to theme compiler api.addAssets('client/stylesheets/livechat.less', 'server'); api.addFiles('client/stylesheets/load.js', 'server'); // collections api.addFiles('client/collections/AgentUsers.js', 'client'); api.addFiles('client/collections/LivechatCustomField.js', 'client'); api.addFiles('client/collections/LivechatDepartment.js', 'client'); api.addFiles('client/collections/LivechatDepartmentAgents.js', 'client'); api.addFiles('client/collections/LivechatIntegration.js', 'client'); api.addFiles('client/collections/LivechatPageVisited.js', 'client'); api.addFiles('client/collections/LivechatQueueUser.js', 'client'); api.addFiles('client/collections/LivechatTrigger.js', 'client'); api.addFiles('client/collections/LivechatInquiry.js', 'client'); api.addFiles('client/collections/livechatOfficeHour.js', 'client'); api.addFiles('client/methods/changeLivechatStatus.js', 'client'); // client views api.addFiles('client/views/app/livechatAppearance.html', 'client'); api.addFiles('client/views/app/livechatAppearance.js', 'client'); api.addFiles('client/views/app/livechatCurrentChats.html', 'client'); api.addFiles('client/views/app/livechatCurrentChats.js', 'client'); api.addFiles('client/views/app/livechatCustomFields.html', 'client'); api.addFiles('client/views/app/livechatCustomFields.js', 'client'); api.addFiles('client/views/app/livechatCustomFieldForm.html', 'client'); api.addFiles('client/views/app/livechatCustomFieldForm.js', 'client'); api.addFiles('client/views/app/livechatDashboard.html', 'client'); api.addFiles('client/views/app/livechatDepartmentForm.html', 'client'); api.addFiles('client/views/app/livechatDepartmentForm.js', 'client'); api.addFiles('client/views/app/livechatDepartments.html', 'client'); api.addFiles('client/views/app/livechatDepartments.js', 'client'); api.addFiles('client/views/app/livechatInstallation.html', 'client'); api.addFiles('client/views/app/livechatInstallation.js', 'client'); api.addFiles('client/views/app/livechatIntegrations.html', 'client'); api.addFiles('client/views/app/livechatIntegrations.js', 'client'); api.addFiles('client/views/app/livechatNotSubscribed.html', 'client'); api.addFiles('client/views/app/livechatQueue.html', 'client'); api.addFiles('client/views/app/livechatQueue.js', 'client'); api.addFiles('client/views/app/livechatTriggers.html', 'client'); api.addFiles('client/views/app/livechatTriggers.js', 'client'); api.addFiles('client/views/app/livechatTriggersForm.html', 'client'); api.addFiles('client/views/app/livechatTriggersForm.js', 'client'); api.addFiles('client/views/app/livechatUsers.html', 'client'); api.addFiles('client/views/app/livechatUsers.js', 'client'); api.addFiles('client/views/app/livechatOfficeHours.html', 'client'); api.addFiles('client/views/app/livechatOfficeHours.js', 'client'); api.addFiles('client/views/app/tabbar/externalSearch.html', 'client'); api.addFiles('client/views/app/tabbar/externalSearch.js', 'client'); api.addFiles('client/views/app/tabbar/visitorHistory.html', 'client'); api.addFiles('client/views/app/tabbar/visitorHistory.js', 'client'); api.addFiles('client/views/app/tabbar/visitorNavigation.html', 'client'); api.addFiles('client/views/app/tabbar/visitorNavigation.js', 'client'); api.addFiles('client/views/app/tabbar/visitorEdit.html', 'client'); api.addFiles('client/views/app/tabbar/visitorEdit.js', 'client'); api.addFiles('client/views/app/tabbar/visitorForward.html', 'client'); api.addFiles('client/views/app/tabbar/visitorForward.js', 'client'); api.addFiles('client/views/app/tabbar/visitorInfo.html', 'client'); api.addFiles('client/views/app/tabbar/visitorInfo.js', 'client'); api.addFiles('client/views/sideNav/livechat.html', 'client'); api.addFiles('client/views/sideNav/livechat.js', 'client'); api.addFiles('client/views/sideNav/livechatFlex.html', 'client'); api.addFiles('client/views/sideNav/livechatFlex.js', 'client'); api.addFiles('client/views/app/triggers/livechatTriggerAction.html', 'client'); api.addFiles('client/views/app/triggers/livechatTriggerAction.js', 'client'); api.addFiles('client/views/app/triggers/livechatTriggerCondition.html', 'client'); api.addFiles('client/views/app/triggers/livechatTriggerCondition.js', 'client'); // hooks api.addFiles('server/hooks/externalMessage.js', 'server'); api.addFiles('server/hooks/markRoomResponded.js', 'server'); api.addFiles('server/hooks/offlineMessage.js', 'server'); api.addFiles('server/hooks/sendToCRM.js', 'server'); // methods api.addFiles('server/methods/addAgent.js', 'server'); api.addFiles('server/methods/addManager.js', 'server'); api.addFiles('server/methods/changeLivechatStatus.js', 'server'); api.addFiles('server/methods/closeByVisitor.js', 'server'); api.addFiles('server/methods/closeRoom.js', 'server'); api.addFiles('server/methods/getCustomFields.js', 'server'); api.addFiles('server/methods/getInitialData.js', 'server'); api.addFiles('server/methods/loginByToken.js', 'server'); api.addFiles('server/methods/pageVisited.js', 'server'); api.addFiles('server/methods/registerGuest.js', 'server'); api.addFiles('server/methods/removeAgent.js', 'server'); api.addFiles('server/methods/removeCustomField.js', 'server'); api.addFiles('server/methods/removeDepartment.js', 'server'); api.addFiles('server/methods/removeManager.js', 'server'); api.addFiles('server/methods/removeTrigger.js', 'server'); api.addFiles('server/methods/saveCustomField.js', 'server'); api.addFiles('server/methods/saveDepartment.js', 'server'); api.addFiles('server/methods/saveInfo.js', 'server'); api.addFiles('server/methods/saveIntegration.js', 'server'); api.addFiles('server/methods/saveSurveyFeedback.js', 'server'); api.addFiles('server/methods/saveTrigger.js', 'server'); api.addFiles('server/methods/searchAgent.js', 'server'); api.addFiles('server/methods/sendMessageLivechat.js', 'server'); api.addFiles('server/methods/sendOfflineMessage.js', 'server'); api.addFiles('server/methods/setCustomField.js', 'server'); api.addFiles('server/methods/startVideoCall.js', 'server'); api.addFiles('server/methods/transfer.js', 'server'); api.addFiles('server/methods/webhookTest.js', 'server'); api.addFiles('server/methods/takeInquiry.js', 'server'); api.addFiles('server/methods/returnAsInquiry.js', 'server'); api.addFiles('server/methods/saveOfficeHours.js', 'server'); api.addFiles('server/methods/sendTranscript.js', 'server'); // models api.addFiles('server/models/Users.js', 'server'); api.addFiles('server/models/Rooms.js', 'server'); api.addFiles('server/models/LivechatExternalMessage.js', ['client', 'server']); api.addFiles('server/models/LivechatCustomField.js', 'server'); api.addFiles('server/models/LivechatDepartment.js', 'server'); api.addFiles('server/models/LivechatDepartmentAgents.js', 'server'); api.addFiles('server/models/LivechatPageVisited.js', 'server'); api.addFiles('server/models/LivechatTrigger.js', 'server'); api.addFiles('server/models/indexes.js', 'server'); api.addFiles('server/models/LivechatInquiry.js', 'server'); api.addFiles('server/models/LivechatOfficeHour.js', 'server'); // server lib api.addFiles('server/lib/Livechat.js', 'server'); api.addFiles('server/lib/QueueMethods.js', 'server'); api.addFiles('server/lib/OfficeClock.js', 'server'); api.addFiles('server/sendMessageBySMS.js', 'server'); api.addFiles('server/unclosedLivechats.js', 'server'); // publications api.addFiles('server/publications/customFields.js', 'server'); api.addFiles('server/publications/departmentAgents.js', 'server'); api.addFiles('server/publications/externalMessages.js', 'server'); api.addFiles('server/publications/livechatAgents.js', 'server'); api.addFiles('server/publications/livechatDepartments.js', 'server'); api.addFiles('server/publications/livechatIntegration.js', 'server'); api.addFiles('server/publications/livechatManagers.js', 'server'); api.addFiles('server/publications/livechatRooms.js', 'server'); api.addFiles('server/publications/livechatQueue.js', 'server'); api.addFiles('server/publications/livechatTriggers.js', 'server'); api.addFiles('server/publications/visitorHistory.js', 'server'); api.addFiles('server/publications/visitorInfo.js', 'server'); api.addFiles('server/publications/visitorPageVisited.js', 'server'); api.addFiles('server/publications/livechatInquiries.js', 'server'); api.addFiles('server/publications/livechatOfficeHours.js', 'server'); // REST endpoints api.addFiles('server/api.js', 'server'); // livechat app api.addAssets('assets/demo.html', 'client'); api.addAssets('assets/rocket-livechat.js', 'client'); api.addAssets('public/head.html', 'server'); });
(function () { "use strict"; var PLUGIN_ID = require("./package.json").name, MENU_ID = "Blendin generator", MENU_LABEL = "$$$/JavaScripts/Generator/Blendin generator/Menu=Blendin generator"; var _generator = null, _currentDocumentId = null, _config = null; var fs = require('fs'), path = require('path'); function mkdir(path, root) { var dirs = path.split('/'), dir = dirs.shift(), root = (root||'')+dir+'/'; try { fs.mkdirSync(root); } catch (e) { //dir wasn't made, something went wrong if(!fs.statSync(root).isDirectory()) throw new Error(e); } return !dirs.length||mkdir(dirs.join('/'), root); } function init(generator, config) { _generator = generator; _config = config; console.log("initializing generator getting started tutorial with config %j", _config); _generator.addMenuItem(MENU_ID, MENU_LABEL, true, false).then( function () { console.log("Menu created", MENU_ID); }, function () { console.error("Menu creation failed", MENU_ID); } ); _generator.onPhotoshopEvent("generatorMenuChanged", function(event) { // Ignore changes to other menus var menu = event.generatorMenuChanged; if (!menu || menu.name !== MENU_ID) { return; } var startingMenuState = _generator.getMenuState(menu.name); console.log("Menu event %s, starting state %s", event, startingMenuState); }); function initLater() { // Flip foreground color var flipColorsExtendScript = "var color = app.foregroundColor; color.rgb.red = 255 - color.rgb.red; color.rgb.green = 255 - color.rgb.green; color.rgb.blue = 255 - color.rgb.blue; app.foregroundColor = color;"; sendJavascript(flipColorsExtendScript); _generator.onPhotoshopEvent("currentDocumentChanged", function(id) { console.log("handleCurrentDocumentChanged: "+id) setCurrentDocumentId(id); }); _generator.onPhotoshopEvent("toolChanged", function(document){ console.log("Tool changed " + document.id + " was changed:"); }); //requestEntireDocument(); _generator.onPhotoshopEvent("imageChanged", function(document) { var _document = document; /* { version: '1.0.0', timeStamp: 1386700608.151, id: 1116, layers: [ { id: 5, index: 2, added: true, type: 'layer', name: 'Layer 3', bounds: [Object] } ], selection: [ 2 ] } */ if(!_document.layers || _document.layers.length === 0){ return console.log('Did nothing','Was metadata',_document.metaDataOnly); } var layerId = _document.layers[0].id; requestEntireDocument(_currentDocumentId,function(error,data){ if(error){ return console.error(error); } if(!data || !data.layers || data.layers.length === 0){ return console.error('Wrong data object given:',data); } // console.log('All Data:', data); // console.log('All Document', _document); // data.layers.forEach(function(layer){ // if(layer.type === 'layerSection'){ // console.log('MASK',layer.mask) // console.log('BlendOptions',layer.blendOptions); // console.log('LAYERS',layer.layers) // } // }); // return; var layer = data.layers.filter(function(layer){ return layer.id === layerId ? true : false; }) || []; if(layer.length === 0){ return console.error('Layer not found!'); } var psdName = data.file.substr(data.file.lastIndexOf('/')+1,data.file.length); psdName = psdName.split('.')[0]; console.log(psdName) layer = layer[0]; _generator.getPixmap(_document.id,layerId,{}).then( function(pixmap){ var layerName = layer.name.split(' '); if(layerName[0] !== 'EXP'){ return console.log('Not working in a export layer'); } var filename = '/Users/kristjanmik/Desktop/ps/' + psdName + '/' + layerName[1] + '.png'; var foldername = filename.substr(0,filename.lastIndexOf('/')); mkdir(foldername) console.log("got Pixmap: "+pixmap.width+" x "+pixmap.height); _generator.savePixmap(pixmap, filename, {format:"png8",ppi:72}); }, function(err){ console.error("err pixmap:",err); } ).done(); }) return; }); } process.nextTick(initLater); } function requestEntireDocument(documentId,callback) { if (!documentId) { console.log("Determining the current document ID"); } _generator.getDocumentInfo(documentId).then( function (document) { callback(null,document); }, function (err) { callback(err); } ).done(); } function getBitmap(options,callback){ console.log('getBitmap:',options); _generator.getPixmap(options.documentId,options.layerId,{}).then( function(pixmap){ console.log("got Pixmap: "+pixmap.width+" x "+pixmap.height); console.log(stringify(pixmap)); savePixmap(pixmap); }, function(err){ console.error("err pixmap:",err); } ).done(); } function updateMenuState(enabled) { console.log("Setting menu state to", enabled); _generator.toggleMenu(MENU_ID, true, enabled); } /*********** HELPERS ***********/ function sendJavascript(str){ _generator.evaluateJSXString(str).then( function(result){ console.log(result); }, function(err){ console.log(err); }); } function setCurrentDocumentId(id) { if (_currentDocumentId === id) { return; } console.log("Current document ID:", id); _currentDocumentId = id; } exports.init = init; // Unit test function exports exports._setConfig = function (config) { _config = config; }; }());
import selectorParser from "postcss-selector-parser" import { isKeyframeRule, isStandardRule, isStandardSelector, isStandardTypeSelector, report, ruleMessages, validateOptions, } from "../../utils" export const ruleName = "selector-type-case" export const messages = ruleMessages(ruleName, { expected: (actual, expected) => `Expected "${actual}" to be "${expected}"`, }) export default function (expectation) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: expectation, possible: [ "lower", "upper", ], }) if (!validOptions) { return } root.walkRules(rule => { if (!isStandardRule(rule)) { return } if (isKeyframeRule(rule)) { return } const { selector } = rule if (!isStandardSelector(selector)) { return } function checkSelector(selectorAST) { selectorAST.walkTags(tag => { if (!isStandardTypeSelector(tag)) { return } const { sourceIndex, value } = tag const expectedValue = expectation === "lower" ? value.toLowerCase() : value.toUpperCase() if (value === expectedValue) { return } report({ message: messages.expected(value, expectedValue), node: rule, index: sourceIndex, ruleName, result, }) }) } selectorParser(checkSelector).process(selector) }) } }
// Chord types const SoundFontType = { STANDARD_LIGHT: 0, STANDARD_HEAVY: 1, // NES_STYLE: 2, SNES_STYLE: 2, // OPL2FM_STYLE: 4, GXSCC_STYLE: 3, // GB_STYLE: 6, getSamplesPrefix: function(type) { switch (type) { case SoundFontType.STANDARD_LIGHT: return "standard_light"; case SoundFontType.STANDARD_HEAVY: return "standard_heavy"; // case SoundFontType.NES_STYLE: // return "nes_style"; // case SoundFontType.OPL2FM_STYLE: // return "opl2fm_style"; case SoundFontType.SNES_STYLE: return "snes_style"; case SoundFontType.GXSCC_STYLE: return "gxscc_style"; // case SoundFontType.GB_STYLE: // return "gb_style"; } return "Unknown soundfont type " + type; }, toString: function(type) { switch (type) { case SoundFontType.STANDARD_LIGHT: return "Standard (light)"; case SoundFontType.STANDARD_HEAVY: return "Standard (heavy)"; // case SoundFontType.NES_STYLE: // return "NES Style"; // case SoundFontType.OPL2FM_STYLE: // return "OPL2 FM Style"; case SoundFontType.SNES_STYLE: return "SNES Style"; case SoundFontType.GXSCC_STYLE: return "GXSCC Style"; // case SoundFontType.GB_STYLE: // return "GB Style"; } return "Unknown soundfont type " + type; }, toShortString: function(type) { switch (type) { case SoundFontType.STANDARD_LIGHT: return "Light"; case SoundFontType.STANDARD_HEAVY: return "Heavy"; // case SoundFontType.NES_STYLE: // return "NES"; // case SoundFontType.OPL2FM_STYLE: // return "OPL2"; case SoundFontType.SNES_STYLE: return "SNES"; case SoundFontType.GXSCC_STYLE: return "GXSCC"; // case SoundFontType.GB_STYLE: // return "GB"; } return "Unknown soundfont type " + type; } }; addPossibleValuesFunction(SoundFontType, SoundFontType.STANDARD_LIGHT, SoundFontType.GXSCC_STYLE);
import { expect } from 'chai'; import FormLogic from '../src'; describe('Field', () => { it('creates fields with presence validation', () => { const field = FormLogic.Field({ presence: true }); expect(field.validations.length).to.equal(1); expect(field.validations[0].validationName).to.equal('presence'); }); it('passes validations associated with the field', () => { const field = FormLogic.Field({ presence: true }); const errors = field.validate('test'); expect(errors.length).to.equal(0); }); it('fails validations associated with the field', () => { const field = FormLogic.Field({ presence: true }); const errors = field.validate(''); expect(errors.length).to.equal(1); expect(errors[0]).to.deep.equal({ key: 'blank', message: "can't be blank" }); }); });
/** * This file is a part of hale_aloha_dashboard. * * Created by Cam Moore on 11/12/15. * * Copyright (C) 2015 Cam Moore. * * The MIT License (MIT) * * 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, deistribute, sublicense, and/or sell * copies of the Software, and to permit person to whom the Software is * furnished to do so, subject to the following condtions: * * 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 * AUTHOERS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETER IN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISIGN FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE */ //Meteor.subscribe("hourly");