repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
oliviertassinari/material-ui | packages/mui-icons-material/lib/AccountTreeOutlined.js | 575 | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3h7zM7 9H4V5h3v4zm10 6h3v4h-3v-4zm0-10h3v4h-3V5z"
}), 'AccountTreeOutlined');
exports.default = _default; | mit |
uktrade/data-hub-fe-beta2 | src/apps/propositions/router.js | 466 | const router = require('express').Router()
const { APP_PERMISSIONS } = require('./constants')
const { renderDetailsPage } = require('./controllers/details')
const { handleRoutePermissions } = require('../middleware')
const { getPropositionDetails } = require('./middleware/details')
router.use(handleRoutePermissions(APP_PERMISSIONS))
router.param('propositionId', getPropositionDetails)
router.get('/:propositionId', renderDetailsPage)
module.exports = router
| mit |
peterkokot/dojoModule | src/Sds/DojoModule/Service/CliFactory.php | 1282 | <?php
/**
* @package Sds
* @license MIT
*/
namespace Sds\DojoModule\Service;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
/**
* Factory to create the CLI app used to generate a dojo build profile
*
* @since 1.0
* @version $Revision$
* @author Tim Roediger <superdweebie@gmail.com>
*/
class CliFactory implements FactoryInterface
{
/**
* Sets the dojo theme to use.
*
* @param \Zend\ServiceManager\ServiceLocatorInterface $serviceLocator
* @return \Symfony\Component\Console\Application
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('Config')['sds']['dojo'];
$configHelper = new \Sds\DojoModule\Tools\Console\Helper\ConfigHelper($config);
$helperSet = new HelperSet;
$helperSet->set($configHelper, 'config');
$cli = new Application;
$cli->setName('DojoModule Command Line Interface');
$cli->setHelperSet($helperSet);
$cli->addCommands(array(
new \Sds\DojoModule\Tools\Console\Command\GenerateProfile(),
));
return $cli;
}
}
| mit |
stoplightio/gitlabhq | app/services/namespaces/statistics_refresher_service.rb | 598 | # frozen_string_literal: true
module Namespaces
class StatisticsRefresherService
RefresherError = Class.new(StandardError)
def execute(root_namespace)
root_storage_statistics = find_or_create_root_storage_statistics(root_namespace.id)
root_storage_statistics.recalculate!
rescue ActiveRecord::ActiveRecordError => e
raise RefresherError.new(e.message)
end
private
def find_or_create_root_storage_statistics(root_namespace_id)
Namespace::RootStorageStatistics
.safe_find_or_create_by!(namespace_id: root_namespace_id)
end
end
end
| mit |
fcpxhacks/fcpxhacks | src/plugins/finalcutpro/timeline/colorboardv2.lua | 7036 | --- === plugins.finalcutpro.timeline.colorboardv2 ===
---
--- Color Board Plugins.
local require = require
--local log = require "hs.logger".new "colorBoard"
local deferred = require "cp.deferred"
local fcp = require "cp.apple.finalcutpro"
local go = require "cp.rx.go"
local i18n = require "cp.i18n"
local prop = require "cp.prop"
local Do = go.Do
local Done = go.Done
local format = string.format
local If = go.If
local mod = {}
local plugin = {
id = "finalcutpro.timeline.colorboardv2",
group = "finalcutpro",
dependencies = {
["core.action.manager"] = "actionmanager",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Only load plugin if Final Cut Pro is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
local options = {}
local updateUI = deferred.new(0.01)
local aspects = { "color", "saturation", "exposure" }
local ranges = { "master", "shadows", "midtones", "highlights" }
local amounts = {1, 2, 3, 4, 5, 10}
local cb = fcp.colorBoard
local iColorBoard = i18n("colorBoard")
local iAngle = i18n("angle")
local iPercentage = i18n("percentage")
local iUp = i18n("up")
local iDown = i18n("down")
for _, currentAspect in ipairs(aspects) do
local iAspect = i18n(currentAspect)
local aspect = cb[currentAspect](cb)
for _, range in ipairs(ranges) do
local iRange = i18n(range)
local puck = aspect[range](aspect)
-- set up the UI update action...
local percentChange, angleChange = 0, 0
local updating = prop.FALSE()
local update = Do(
If(updating):Is(false):Then(
Do(function()
updating(true)
return true
end)
:Then(
If(function() return percentChange ~= 0 end)
:Then(
If(function() return puck:isShowing() end):Is(false):Then(puck:doShow()):Then(Done())
)
:Then(function()
local value = puck:percent()
if value then
puck:percent(value + percentChange)
percentChange = 0
return true
end
return false
end)
:ThenYield()
:Otherwise(false)
):Then(
If(function() return angleChange ~= 0 end)
:Then(
If(function() return puck:isShowing() end):Is(false):Then(puck:doShow()):Then(Done())
)
:Then(function()
local value = puck:angle()
if value then
puck:angle(value + angleChange)
angleChange = 0
return true
end
return false
end)
:ThenYield()
:Otherwise(false)
)
:Finally(function() updating(false) end)
)
)
:Label("plugins.finalcutpro.timeline.colorboardv2:update")
updateUI:action(update)
--------------------------------------------------------------------------------
-- Setup all the different types of actions:
--------------------------------------------------------------------------------
for _, amount in pairs(amounts) do
local id
id = format("colorboard_%s_%s_percentage_up_%s", aspect, range, amount)
options[id] = {
id = id,
label = format("%s - %s - %s - %s - %s %s", iColorBoard, iAspect, iRange, iPercentage, iUp, amount),
fn = function()
percentChange = percentChange + amount
updateUI()
end
}
id = format("colorboard_%s_%s_percentage_down_%s", aspect, range, amount)
options[id] = {
id = id,
label = format("%s - %s - %s - %s - %s %s", iColorBoard, iAspect, iRange, iPercentage, iDown, amount),
fn = function()
percentChange = percentChange - amount
updateUI()
end
}
if puck:hasAngle() then
id = format("colorboard_%s_%s_angle_up_%s", aspect, range, amount)
options[id] = {
id = id,
label = format("%s - %s - %s - %s - %s %s", iColorBoard, iAspect, iRange, iAngle, iUp, amount),
fn = function()
percentChange = percentChange + amount
updateUI()
end
}
id = format("colorboard_%s_%s_angle_down_%s", aspect, range, amount)
options[id] = {
id = id,
label = format("%s - %s - %s - %s - %s %s", iColorBoard, iAspect, iRange, iAngle, iDown, amount),
fn = function()
percentChange = percentChange - amount
updateUI()
end
}
end
end
end
end
--------------------------------------------------------------------------------
-- Setup Action Manager:
--------------------------------------------------------------------------------
local actionmanager = deps.actionmanager
local colorBoardActionSubTitle = i18n("colorBoardActionSubTitle")
mod._handler = actionmanager.addHandler("fcpx_colorboard", "fcpx")
:onChoices(function(choices)
for id, item in pairs(options) do
choices
:add(item.label)
:subText(colorBoardActionSubTitle)
:params({
id = id,
})
:id(id)
end
end)
:onExecute(function(action)
options[action.id].fn()
end)
:onActionId(function(params)
return params.id
end)
return mod
end
return plugin
| mit |
Fadhilamadan/Reminder | vendor/symfony/debug/Tests/phpt/debug_class_loader.phpt | 777 | --TEST--
Test DebugClassLoader with previously loaded parents
--FILE--
<?php
namespace Symfony\Component\Debug\Tests\Fixtures;
use Symfony\Component\Debug\DebugClassLoader;
$vendor = __DIR__;
while (!file_exists($vendor.'/vendor')) {
$vendor = \dirname($vendor);
}
require $vendor.'/vendor/autoload.php';
class_exists(FinalMethod::class);
set_error_handler(function ($type, $msg) { echo $msg, "\n"; });
DebugClassLoader::enable();
class_exists(ExtendedFinalMethod::class);
?>
--EXPECTF--
The "Symfony\Component\Debug\Tests\Fixtures\FinalMethod::finalMethod()" method is considered final since version 3.3. It may change without further notice as of its next major version. You should not extend it from "Symfony\Component\Debug\Tests\Fixtures\ExtendedFinalMethod".
| mit |
jaredpalmer/razzle | examples/with-jest-snapshots/src/client.js | 280 | import React from "react";
import { hydrate } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
hydrate(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
if (module.hot) {
module.hot.accept();
}
| mit |
oliviertassinari/material-ui | packages/mui-icons-material/lib/esm/BubbleChartTwoTone.js | 893 | import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M16.5 12c1.93 0 3.5-1.57 3.5-3.5S18.43 5 16.5 5 13 6.57 13 8.5s1.57 3.5 3.5 3.5z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("circle", {
cx: "15.01",
cy: "18",
r: "1",
opacity: ".3"
}, "1"), /*#__PURE__*/_jsx("circle", {
cx: "7",
cy: "14",
r: "2",
opacity: ".3"
}, "2"), /*#__PURE__*/_jsx("path", {
d: "M7 18c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0-6c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm11.01 6c0-1.65-1.35-3-3-3s-3 1.35-3 3 1.35 3 3 3 3-1.35 3-3zm-4 0c0-.55.45-1 1-1s1 .45 1 1-.45 1-1 1-1-.45-1-1zm2.49-4c3.03 0 5.5-2.47 5.5-5.5S19.53 3 16.5 3 11 5.47 11 8.5s2.47 5.5 5.5 5.5zm0-9C18.43 5 20 6.57 20 8.5S18.43 12 16.5 12 13 10.43 13 8.5 14.57 5 16.5 5z"
}, "3")], 'BubbleChartTwoTone'); | mit |
harini-nyros/Custom-Login-system-in-symfony2 | app/cache/dev/twig/06/6b/bedea584a3d866feb1181f56db63.php | 4885 | <?php
/* AcmeDemoBundle::layout.html.twig */
class __TwigTemplate_066bbedea584a3d866feb1181f56db63 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("TwigBundle::layout.html.twig");
$this->blocks = array(
'head' => array($this, 'block_head'),
'title' => array($this, 'block_title'),
'body' => array($this, 'block_body'),
'content_header' => array($this, 'block_content_header'),
'content_header_more' => array($this, 'block_content_header_more'),
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "TwigBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_head($context, array $blocks = array())
{
// line 4
echo " <link rel=\"icon\" sizes=\"16x16\" href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("favicon.ico"), "html", null, true);
echo "\" />
<link rel=\"stylesheet\" href=\"";
// line 5
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/acmedemo/css/demo.css"), "html", null, true);
echo "\" />
";
}
// line 8
public function block_title($context, array $blocks = array())
{
echo "Demo Bundle";
}
// line 10
public function block_body($context, array $blocks = array())
{
// line 11
echo " ";
$context['_parent'] = (array) $context;
$context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getAttribute($this->getAttribute($this->getContext($context, "app"), "session"), "flashbag"), "get", array(0 => "notice"), "method"));
foreach ($context['_seq'] as $context["_key"] => $context["flashMessage"]) {
// line 12
echo " <div class=\"flash-message\">
<em>Notice</em>: ";
// line 13
echo twig_escape_filter($this->env, $this->getContext($context, "flashMessage"), "html", null, true);
echo "
</div>
";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['flashMessage'], $context['_parent'], $context['loop']);
$context = array_merge($_parent, array_intersect_key($context, $_parent));
// line 16
echo "
";
// line 17
$this->displayBlock('content_header', $context, $blocks);
// line 26
echo "
<div class=\"block\">
";
// line 28
$this->displayBlock('content', $context, $blocks);
// line 29
echo " </div>
";
// line 31
if (array_key_exists("code", $context)) {
// line 32
echo " <h2>Code behind this page</h2>
<div class=\"block\">
<div class=\"symfony-content\">";
// line 34
echo $this->getContext($context, "code");
echo "</div>
</div>
";
}
}
// line 17
public function block_content_header($context, array $blocks = array())
{
// line 18
echo " <ul id=\"menu\">
";
// line 19
$this->displayBlock('content_header_more', $context, $blocks);
// line 22
echo " </ul>
<div style=\"clear: both\"></div>
";
}
// line 19
public function block_content_header_more($context, array $blocks = array())
{
// line 20
echo " <li><a href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_demo"), "html", null, true);
echo "\">Demo Home</a></li>
";
}
// line 28
public function block_content($context, array $blocks = array())
{
}
public function getTemplateName()
{
return "AcmeDemoBundle::layout.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 120 => 20, 117 => 19, 110 => 22, 108 => 19, 105 => 18, 102 => 17, 94 => 34, 90 => 32, 88 => 31, 84 => 29, 82 => 28, 78 => 26, 73 => 16, 64 => 13, 61 => 12, 56 => 11, 53 => 10, 47 => 8, 41 => 5, 33 => 3, 158 => 79, 139 => 63, 135 => 62, 131 => 61, 127 => 28, 123 => 59, 106 => 45, 101 => 43, 97 => 41, 85 => 32, 80 => 30, 76 => 17, 74 => 27, 63 => 19, 58 => 17, 48 => 9, 45 => 8, 42 => 7, 36 => 4, 30 => 3,);
}
}
| mit |
oliwierptak/Everon1 | src/Everon/Event/Interfaces/Context.php | 776 | <?php
/**
* This file is part of the Everon framework.
*
* (c) Oliwier Ptak <oliwierptak@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Everon\Event\Interfaces;
/**
* @author Zeger Hoogeboom <zeger_hoogeboom@hotmail.com>
* @author Oliwier Ptak <oliwierptak@gmail.com>
*/
interface Context
{
/**
* @param \Closure $Callback
*/
function setCallback(\Closure $Callback);
/**
* @return \Closure
*/
function getCallback();
/**
* @param mixed $Callee
*/
function setCaller($Callee);
/**
* @return mixed
*/
function getCaller();
/**
* @return mixed
*/
function execute();
} | mit |
kentaromiura/Reshape | test_transforms/ensureFilesEndInNewLine.js | 184 | module.exports = function(what){
var source = what.source,
length = source.length
if(source.charAt(length-1) != '\n'){
what.source = what.source + '\n'
}
return what
}
| mit |
claupcv/Internship | claupcv/2017/mai/Queries/Queries/Core/Domain/Cover.cs | 151 | namespace Queries.Core.Domain
{
public class Cover
{
public int Id { get; set; }
public Course Course { get; set; }
}
}
| mit |
JarvusInnovations/Emergence-Skeleton | dwoo-plugins/builtin/functions/mailto.php | 3831 | <?php
/**
* Outputs a mailto link with optional spam-proof (okay probably not) encoding
* <pre>
* * address : target email address
* * text : display text to show for the link, defaults to the address if not provided
* * subject : the email subject
* * encode : one of the available encoding (none, js, jscharcode or hex)
* * cc : address(es) to carbon copy, comma separated
* * bcc : address(es) to blind carbon copy, comma separated
* * newsgroups : newsgroup(s) to post to, comma separated
* * followupto : address(es) to follow up, comma separated
* * extra : additional attributes to add to the <a> tag
* </pre>
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @copyright Copyright (c) 2008, Jordi Boggiano
* @license http://dwoo.org/LICENSE Modified BSD License
* @link http://dwoo.org/
* @version 1.1.0
* @date 2009-07-18
* @package Dwoo
*/
function Dwoo_Plugin_mailto(Dwoo_Core $dwoo, $address, $text=null, $subject=null, $encode=null, $cc=null, $bcc=null, $newsgroups=null, $followupto=null, $extra=null)
{
if (empty($address)) {
return '';
}
if (empty($text)) {
$text = $address;
}
// build address string
$address .= '?';
if (!empty($subject)) {
$address .= 'subject='.rawurlencode($subject).'&';
}
if (!empty($cc)) {
$address .= 'cc='.rawurlencode($cc).'&';
}
if (!empty($bcc)) {
$address .= 'bcc='.rawurlencode($bcc).'&';
}
if (!empty($newsgroups)) {
$address .= 'newsgroups='.rawurlencode($newsgroups).'&';
}
if (!empty($followupto)) {
$address .= 'followupto='.rawurlencode($followupto).'&';
}
$address = rtrim($address, '?&');
// output
switch ($encode) {
case 'none':
case null:
return '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';
case 'js':
case 'javascript':
$str = 'document.write(\'<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>\');';
$len = strlen($str);
$out = '';
for ($i=0; $i<$len; $i++) {
$out .= '%'.bin2hex($str[$i]);
}
return '<script type="text/javascript">eval(unescape(\''.$out.'\'));</script>';
break;
case 'javascript_charcode':
case 'js_charcode':
case 'jscharcode':
case 'jschar':
$str = '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>';
$len = strlen($str);
$out = '<script type="text/javascript">'."\n<!--\ndocument.write(String.fromCharCode(";
for ($i=0; $i<$len; $i++) {
$out .= ord($str[$i]).',';
}
return rtrim($out, ',')."));\n-->\n</script>\n";
break;
case 'hex':
if (strpos($address, '?') !== false) {
return $dwoo->triggerError('Mailto: Hex encoding is not possible with extra attributes, use one of : <em>js, jscharcode or none</em>.', E_USER_WARNING);
}
$out = '<a href="mailto:';
$len = strlen($address);
for ($i=0; $i<$len; $i++) {
if (preg_match('#\w#', $address[$i])) {
$out .= '%'.bin2hex($address[$i]);
} else {
$out .= $address[$i];
}
}
$out .= '" '.$extra.'>';
$len = strlen($text);
for ($i=0; $i<$len; $i++) {
$out .= '&#x'.bin2hex($text[$i]);
}
return $out.'</a>';
default:
return $dwoo->triggerError('Mailto: <em>encode</em> argument is invalid, it must be one of : <em>none (= no value), js, js_charcode or hex</em>', E_USER_WARNING);
}
}
| mit |
flanfly/qml-rust | examples/resources/build.rs | 1322 | extern crate fs_utils;
use std::env;
use std::process::Command;
use std::path::*;
use std::str::*;
use fs_utils::*;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
let path = Path::new(&manifest_dir).join("resources");
let path_res = copy::copy_directory(path, &out_dir);
let path = match path_res {
Ok(path) => path,
Err(err) => {
match err {
copy::Error::DestinationDirectoryExists(dir) => dir,
_ => panic!("failed to copy resources dir: {}", err),
}
}
};
let output = Command::new("sh")
.current_dir(&path)
.arg("build_lib.sh")
.output()
.unwrap_or_else(|e| panic!("failed to execute process: {}", e));
if !output.status.success() {
panic!("Cannot build qrc resource:\n{:#?}\n{:#?}",
to_utf(&output.stdout),
to_utf(&output.stderr));
}
println!("cargo:rerun-if-changed={}", path.display());
println!("cargo:rustc-link-search=native={}", path.display());
println!("cargo:rustc-link-lib=static=qrc");
}
fn to_utf(buf: &[u8]) -> &str {
match from_utf8(buf) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
}
}
| mit |
reacrea/KlaunChris | node_modules/angular2/upgrade.js | 366 | 'use strict';/**
* @module
* @description
* Adapter allowing AngularJS v1 and Angular v2 to run side by side in the same application.
*/
var upgrade_adapter_1 = require('./src/upgrade/upgrade_adapter');
exports.UpgradeAdapter = upgrade_adapter_1.UpgradeAdapter;
exports.UpgradeAdapterRef = upgrade_adapter_1.UpgradeAdapterRef;
//# sourceMappingURL=upgrade.js.map | mit |
berryma4/diirt | vtype/vtype/src/main/java/org/diirt/vtype/next/EnumMetaData.java | 1398 | /**
* Copyright (C) 2010-14 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.vtype.next;
import java.util.List;
/**
* Enum metadata information.
*
* @author carcassi
*/
public abstract class EnumMetaData {
/**
* Returns the possible labels for the enum.
*
* @return the labels; not null
*/
public abstract List<String> getLabels();
/**
* Whether the given object is an EnumMetadata with the same labels.
*
* @param obj another alarm
* @return true if equal
*/
@Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof EnumMetaData) {
EnumMetaData other = (EnumMetaData) obj;
return getLabels().equals(other.getLabels());
}
return false;
}
@Override
public final int hashCode() {
return getLabels().hashCode();
}
@Override
public final String toString() {
return getLabels().toString();
}
/**
* New EnumMetaData with the given labels.
*
* @param labels the enum labels
* @return the new alarm
*/
public static EnumMetaData create(final List<String> labels) {
return new IEnumMetaData(labels);
}
}
| mit |
AbraaoAlves/ionic | src/components/virtual-scroll/virtual-scroll.ts | 21798 | import { AfterContentInit, ChangeDetectorRef, ContentChild, ContentChildren, Directive, DoCheck, ElementRef, Input, IterableDiffers, IterableDiffer, NgZone, OnDestroy, Optional, QueryList, Renderer, TrackByFn } from '@angular/core';
import { adjustRendered, calcDimensions, estimateHeight, initReadNodes, processRecords, populateNodeData, updateDimensions, writeToNodes } from './virtual-util';
import { clearNativeTimeout, nativeRaf, nativeTimeout } from '../../util/dom';
import { Config } from '../../config/config';
import { Content } from '../content/content';
import { Img } from '../img/img';
import { isBlank, isFunction, isPresent } from '../../util/util';
import { Platform } from '../../platform/platform';
import { ViewController } from '../../navigation/view-controller';
import { VirtualCell, VirtualData, VirtualNode } from './virtual-util';
import { VirtualFooter, VirtualHeader, VirtualItem } from './virtual-item';
/**
* @name VirtualScroll
* @description
* Virtual Scroll displays a virtual, "infinite" list. An array of records
* is passed to the virtual scroll containing the data to create templates
* for. The template created for each record, referred to as a cell, can
* consist of items, headers, and footers.
*
* For performance reasons, not every record in the list is rendered at once;
* instead a small subset of records (enough to fill the viewport) are rendered
* and reused as the user scrolls.
*
* ### The Basics
*
* The array of records should be passed to the `virtualScroll` property.
* The data given to the `virtualScroll` property must be an array. An item
* template with the `*virtualItem` property is required in the `virtualScroll`.
* The `virtualScroll` and `*virtualItem` properties can be added to any element.
*
* ```html
* <ion-list [virtualScroll]="items">
*
* <ion-item *virtualItem="let item">
* {% raw %}{{ item }}{% endraw %}
* </ion-item>
*
* </ion-list>
* ```
*
*
* ### Section Headers and Footers
*
* Section headers and footers are optional. They can be dynamically created
* from developer-defined functions. For example, a large list of contacts
* usually has a divider for each letter in the alphabet. Developers provide
* their own custom function to be called on each record. The logic in the
* custom function should determine whether to create the section template
* and what data to provide to the template. The custom function should
* return `null` if a template shouldn't be created.
*
* ```html
* <ion-list [virtualScroll]="items" [headerFn]="myHeaderFn">
*
* <ion-item-divider *virtualHeader="let header">
* Header: {% raw %}{{ header }}{% endraw %}
* </ion-item-divider>
*
* <ion-item *virtualItem="let item">
* Item: {% raw %}{{ item }}{% endraw %}
* </ion-item>
*
* </ion-list>
* ```
*
* Below is an example of a custom function called on every record. It
* gets passed the individual record, the record's index number,
* and the entire array of records. In this example, after every 20
* records a header will be inserted. So between the 19th and 20th records,
* between the 39th and 40th, and so on, a `<ion-item-divider>` will
* be created and the template's data will come from the function's
* returned data.
*
* ```ts
* myHeaderFn(record, recordIndex, records) {
* if (recordIndex % 20 === 0) {
* return 'Header ' + recordIndex;
* }
* return null;
* }
* ```
*
*
* ### Approximate Widths and Heights
*
* If the height of items in the virtual scroll are not close to the
* default size of 40px, it is extremely important to provide an value for
* approxItemHeight height. An exact pixel-perfect size is not necessary,
* but without an estimate the virtual scroll will not render correctly.
*
* The approximate width and height of each template is used to help
* determine how many cells should be created, and to help calculate
* the height of the scrollable area. Note that the actual rendered size
* of each cell comes from the app's CSS, whereas this approximation
* is only used to help calculate initial dimensions.
*
* It's also important to know that Ionic's default item sizes have
* slightly different heights between platforms, which is perfectly fine.
*
*
*
* ### Images Within Virtual Scroll
*
* Ionic provides `<ion-img>` to manage HTTP requests and image rendering.
* Additionally, it includes a customizable placeholder element which shows
* before the image has finished loading. While scrolling through items
* quickly, `<ion-img>` knows not to make any image requests, and only loads
* the images that are viewable after scrolling. It's also important for app
* developers to ensure image sizes are locked in, and after images have fully
* loaded they do not change size and affect any other element sizes.
*
* We recommend using our `<ion-img>` element over the native `<img>` element
* because when an `<img>` element is added to the DOM, it immediately
* makes a HTTP request for the image file. HTTP requests, image
* decoding, and image rendering can cause issues while scrolling. For virtual
* scrolling, the natural effects of the `<img>` are not desirable features.
*
* Note: `<ion-img>` should only be used with Virtual Scroll. If you are using
* an image outside of Virtual Scroll you should use the standard `<img>` tag.
*
* ```html
* <ion-list [virtualScroll]="items">
*
* <ion-item *virtualItem="let item">
* <ion-avatar item-left>
* <ion-img [src]="item.avatarUrl"></ion-img>
* </ion-avatar>
* {% raw %} {{ item.firstName }} {{ item.lastName }}{% endraw %}
* </ion-item>
*
* </ion-list>
* ```
*
*
* ### Performance Tips
*
* - Use `<ion-img>` rather than `<img>` so images are lazy loaded
* while scrolling.
* - Image sizes should be locked in, meaning the size of any element
* should not change after the image has loaded.
* - Provide an approximate width and height so the virtual scroll can
* best calculate the cell height.
* - Changing the dataset requires the entire virtual scroll to be
* reset, which is an expensive operation and should be avoided
* if possible.
* - Do not perform any DOM manipulation within section header and
* footer functions. These functions are called for every record in the
* dataset, so please make sure they're performant.
*
*/
@Directive({
selector: '[virtualScroll]'
})
export class VirtualScroll implements DoCheck, AfterContentInit, OnDestroy {
_trackBy: TrackByFn;
_differ: IterableDiffer;
_unreg: Function;
_init: boolean;
_rafId: number;
_tmId: number;
_hdrFn: Function;
_ftrFn: Function;
_records: any[] = [];
_cells: VirtualCell[] = [];
_nodes: VirtualNode[] = [];
_vHeight: number = 0;
_lastCheck: number = 0;
_data: VirtualData = {
scrollTop: 0,
};
_eventAssist: boolean;
_queue: number = null;
@ContentChild(VirtualItem) _itmTmp: VirtualItem;
@ContentChild(VirtualHeader) _hdrTmp: VirtualHeader;
@ContentChild(VirtualFooter) _ftrTmp: VirtualFooter;
@ContentChildren(Img) _imgs: QueryList<Img>;
/**
* @input {array} The data that builds the templates within the virtual scroll.
* This is the same data that you'd pass to `ngFor`. It's important to note
* that when this data has changed, then the entire virtual scroll is reset,
* which is an expensive operation and should be avoided if possible.
*/
@Input()
set virtualScroll(val: any) {
this._records = val;
if (isBlank(this._differ) && isPresent(val)) {
this._differ = this._iterableDiffers.find(val).create(this._cd, this._trackBy);
}
}
/**
* @input {number} The buffer ratio is used to decide how many cells
* should get created when initially rendered. The number is a
* multiplier against the viewable area's height. For example, if it
* takes `20` cells to fill up the height of the viewable area, then
* with a buffer ratio of `2` it will create `40` cells that are
* available for reuse while scrolling. For better performance, it's
* better to have more cells than what are required to fill the
* viewable area. Default is `2`.
*/
@Input() bufferRatio: number = 2;
/**
* @input {string} The approximate width of each item template's cell.
* This dimension is used to help determine how many cells should
* be created when initialized, and to help calculate the height of
* the scrollable area. This value can use either `px` or `%` units.
* Note that the actual rendered size of each cell comes from the
* app's CSS, whereas this approximation is used to help calculate
* initial dimensions. Default is `100%`.
*/
@Input() approxItemWidth: string = '100%';
/**
* @input {string} Default is `40px`. It is important to provide this
* if virtual item height will be significantly larger than the default
* The approximate height of each virtual item template's cell.
* This dimension is used to help determine how many cells should
* be created when initialized, and to help calculate the height of
* the scrollable area. This height value can only use `px` units.
* Note that the actual rendered size of each cell comes from the
* app's CSS, whereas this approximation is used to help calculate
* initial dimensions.
*/
@Input() approxItemHeight: string;
/**
* @input {string} The approximate width of each header template's cell.
* This dimension is used to help determine how many cells should
* be created when initialized, and to help calculate the height of
* the scrollable area. This value can use either `px` or `%` units.
* Note that the actual rendered size of each cell comes from the
* app's CSS, whereas this approximation is used to help calculate
* initial dimensions. Default is `100%`.
*/
@Input() approxHeaderWidth: string = '100%';
/**
* @input {string} The approximate height of each header template's cell.
* This dimension is used to help determine how many cells should
* be created when initialized, and to help calculate the height of
* the scrollable area. This height value can only use `px` units.
* Note that the actual rendered size of each cell comes from the
* app's CSS, whereas this approximation is used to help calculate
* initial dimensions. Default is `40px`.
*/
@Input() approxHeaderHeight: string = '40px';
/**
* @input {string} The approximate width of each footer template's cell.
* This dimension is used to help determine how many cells should
* be created when initialized, and to help calculate the height of
* the scrollable area. This value can use either `px` or `%` units.
* Note that the actual rendered size of each cell comes from the
* app's CSS, whereas this approximation is used to help calculate
* initial dimensions. Default is `100%`.
*/
@Input() approxFooterWidth: string = '100%';
/**
* @input {string} The approximate height of each footer template's cell.
* This dimension is used to help determine how many cells should
* be created when initialized, and to help calculate the height of
* the scrollable area. This height value can only use `px` units.
* Note that the actual rendered size of each cell comes from the
* app's CSS, whereas this approximation is used to help calculate
* initial dimensions. Default is `40px`.
*/
@Input() approxFooterHeight: string = '40px';
/**
* @input {function} Section headers and the data used within its given
* template can be dynamically created by passing a function to `headerFn`.
* For example, a large list of contacts usually has dividers between each
* letter in the alphabet. App's can provide their own custom `headerFn`
* which is called with each record within the dataset. The logic within
* the header function can decide if the header template should be used,
* and what data to give to the header template. The function must return
* `null` if a header cell shouldn't be created.
*/
@Input() set headerFn(val: Function) {
if (isFunction(val)) {
this._hdrFn = val.bind((this._ctrl && this._ctrl._cmp) || this);
}
}
/**
* @input {function} Section footers and the data used within its given
* template can be dynamically created by passing a function to `footerFn`.
* The logic within the footer function can decide if the footer template
* should be used, and what data to give to the footer template. The function
* must return `null` if a footer cell shouldn't be created.
*/
@Input() set footerFn(val: Function) {
if (isFunction(val)) {
this._ftrFn = val.bind((this._ctrl && this._ctrl._cmp) || this);
}
}
/**
* @input {function} Same as `ngForTrackBy` which can be used on `ngFor`.
*/
@Input() set virtualTrackBy(val: TrackByFn) {
this._trackBy = val;
}
constructor(
private _iterableDiffers: IterableDiffers,
private _elementRef: ElementRef,
private _renderer: Renderer,
private _zone: NgZone,
private _cd: ChangeDetectorRef,
private _content: Content,
private _platform: Platform,
@Optional() private _ctrl: ViewController,
config: Config) {
this._eventAssist = config.getBoolean('virtualScrollEventAssist');
}
/**
* @private
*/
ngDoCheck() {
if (this._init) {
this.update(true);
}
}
/**
* @private
*/
ngAfterContentInit() {
if (!this._init) {
if (!this._itmTmp) {
throw 'virtualItem required within virtualScroll';
}
this._init = true;
if (!this.approxItemHeight) {
this.approxItemHeight = '40px';
console.warn('Virtual Scroll: Please provide an "approxItemHeight" input to ensure proper virtual scroll rendering');
}
this.update(true);
this._platform.onResize(() => {
console.debug('VirtualScroll, onResize');
this.update(false);
});
}
}
/**
* @private
* DOM READ THEN DOM WRITE
*/
update(checkChanges: boolean) {
var self = this;
if (!self._records || !self._records.length) return;
if (checkChanges) {
if (isPresent(self._differ)) {
let changes = self._differ.diff(self._records);
if (!isPresent(changes)) return;
}
}
console.debug('VirtualScroll, update, records:', self._records.length);
// reset everything
self._cells.length = 0;
self._nodes.length = 0;
self._itmTmp.viewContainer.clear();
self._elementRef.nativeElement.parentElement.scrollTop = 0;
let attempts = 0;
function readDimensions(done: Function/* cuz promises add unnecessary overhead here */) {
if (self._data.valid) {
// good to go, we already have good dimension data
done();
} else {
// ******** DOM READ ****************
calcDimensions(self._data, self._elementRef.nativeElement.parentElement,
self.approxItemWidth, self.approxItemHeight,
self.approxHeaderWidth, self.approxHeaderHeight,
self.approxFooterWidth, self.approxFooterHeight,
self.bufferRatio);
if (self._data.valid) {
// sweet, we got some good dimension data!
done();
} else if (attempts < 30) {
// oh no! the DOM doesn't have good data yet!
// let's try again in XXms, and give up eventually if we never get data
attempts++;
nativeRaf(function() {
readDimensions(done);
});
}
}
}
// ******** DOM READ ****************
readDimensions(function() {
processRecords(self._data.renderHeight,
self._records,
self._cells,
self._hdrFn,
self._ftrFn,
self._data);
// ******** DOM WRITE ****************
self.renderVirtual();
// list for scroll events
self.addScrollListener();
});
}
/**
* @private
* DOM WRITE
*/
renderVirtual() {
// initialize nodes with the correct cell data
this._data.topCell = 0;
this._data.bottomCell = (this._cells.length - 1);
populateNodeData(0, this._data.bottomCell,
this._data.viewWidth, true,
this._cells, this._records, this._nodes,
this._itmTmp.viewContainer,
this._itmTmp.templateRef,
this._hdrTmp && this._hdrTmp.templateRef,
this._ftrTmp && this._ftrTmp.templateRef, true);
// ******** DOM WRITE ****************
this._cd.detectChanges();
// wait a frame before trying to read and calculate the dimensions
nativeRaf(this.postRenderVirtual.bind(this));
}
/**
* @private
* DOM READ THEN DOM WRITE
*/
postRenderVirtual() {
// ******** DOM READ THEN DOM WRITE ****************
initReadNodes(this._nodes, this._cells, this._data);
// ******** DOM READS ABOVE / DOM WRITES BELOW ****************
// ******** DOM WRITE ****************
this._renderer.setElementClass(this._elementRef.nativeElement, 'virtual-scroll', true);
// ******** DOM WRITE ****************
writeToNodes(this._nodes, this._cells, this._records.length);
// ******** DOM WRITE ****************
this.setVirtualHeight(
estimateHeight(this._records.length, this._cells[this._cells.length - 1], this._vHeight, 0.25)
);
}
/**
* @private
*/
scrollUpdate() {
clearNativeTimeout(this._tmId);
this._tmId = nativeTimeout(this.onScrollEnd.bind(this), SCROLL_END_TIMEOUT_MS);
let data = this._data;
if (this._queue === QUEUE_CHANGE_DETECTION) {
// ******** DOM WRITE ****************
this._cd.detectChanges();
// ******** DOM WRITE ****************
writeToNodes(this._nodes, this._cells, this._records.length);
// ******** DOM WRITE ****************
this.setVirtualHeight(
estimateHeight(this._records.length, this._cells[this._cells.length - 1], this._vHeight, 0.25)
);
this._queue = null;
} else {
data.scrollDiff = (data.scrollTop - this._lastCheck);
if (Math.abs(data.scrollDiff) > SCROLL_DIFFERENCE_MINIMUM) {
// don't bother updating if the scrollTop hasn't changed much
this._lastCheck = data.scrollTop;
if (data.scrollDiff > 0) {
// load data we may not have processed yet
let stopAtHeight = (data.scrollTop + data.renderHeight);
processRecords(stopAtHeight, this._records, this._cells,
this._hdrFn, this._ftrFn, data);
}
// ******** DOM READ ****************
updateDimensions(this._nodes, this._cells, data, false);
adjustRendered(this._cells, data);
let madeChanges = populateNodeData(data.topCell, data.bottomCell,
data.viewWidth, data.scrollDiff > 0,
this._cells, this._records, this._nodes,
this._itmTmp.viewContainer,
this._itmTmp.templateRef,
this._hdrTmp && this._hdrTmp.templateRef,
this._ftrTmp && this._ftrTmp.templateRef, false);
if (madeChanges) {
// do not update images while scrolling
this._imgs.forEach(img => {
img.enable(false);
});
// queue making updates in the next frame
this._queue = QUEUE_CHANGE_DETECTION;
} else {
this._queue = null;
}
}
}
}
/**
* @private
* DOM WRITE
*/
onScrollEnd() {
// scrolling is done, allow images to be updated now
this._imgs.forEach(img => {
img.enable(true);
});
// ******** DOM READ ****************
updateDimensions(this._nodes, this._cells, this._data, false);
adjustRendered(this._cells, this._data);
// ******** DOM WRITE ****************
this._cd.detectChanges();
// ******** DOM WRITE ****************
this.setVirtualHeight(
estimateHeight(this._records.length, this._cells[this._cells.length - 1], this._vHeight, 0.05)
);
}
/**
* @private
* DOM WRITE
*/
setVirtualHeight(newVirtualHeight: number) {
if (newVirtualHeight !== this._vHeight) {
// ******** DOM WRITE ****************
this._renderer.setElementStyle(this._elementRef.nativeElement, 'height', newVirtualHeight > 0 ? newVirtualHeight + 'px' : '');
this._vHeight = newVirtualHeight;
console.debug('VirtualScroll, height', newVirtualHeight);
}
}
/**
* @private
* NO DOM
*/
addScrollListener() {
let self = this;
if (!self._unreg) {
self._zone.runOutsideAngular(() => {
function onScroll() {
// ******** DOM READ ****************
self._data.scrollTop = self._content.getScrollTop();
// ******** DOM READ THEN DOM WRITE ****************
self.scrollUpdate();
}
if (self._eventAssist) {
// use JS scrolling for iOS UIWebView
// goal is to completely remove this when iOS
// fully supports scroll events
// listen to JS scroll events
self._unreg = self._content.jsScroll(onScroll);
} else {
// listen to native scroll events
self._unreg = self._content.addScrollListener(onScroll);
}
});
}
}
/**
* @private
* NO DOM
*/
ngOnDestroy() {
this._unreg && this._unreg();
this._unreg = null;
}
}
const SCROLL_END_TIMEOUT_MS = 140;
const SCROLL_DIFFERENCE_MINIMUM = 20;
const QUEUE_CHANGE_DETECTION = 0;
| mit |
timsvoice/great_green_sources | core/lexicon/es/permissions.inc.php | 11203 | <?php
/**
* Permissions Spanish lexicon topic
*
* @language es_MX
* @package modx
* @subpackage lexicon
*/
$_lang['perm.about_desc'] = 'La página de Nosotros.';
$_lang['perm.access_permissions_desc'] = 'Cualquier página o acción relacionada con Permiso de Acceso.';
$_lang['perm.actions_desc'] = 'La página de Acciones.';
$_lang['perm.add_children_desc'] = 'Para añadir cualquier Recurso como hijo del Recurso o Elemento especificado a una Categoría.';
$_lang['perm.change_password_desc'] = 'El usuario puede cambiar su contraseña.';
$_lang['perm.change_profile_desc'] = 'El usuario puede cambiar su perfil.';
$_lang['perm.charsets_desc'] = 'Para ver una lista de conjuntos de caractéres.';
$_lang['perm.class_map_desc'] = 'Para ver una lista de clases en el Mapa de Clases.';
$_lang['perm.components_desc'] = 'Para ver el menú de Componentes.';
$_lang['perm.content_types_desc'] = 'La página de Tipos de Contenido.';
$_lang['perm.copy_desc'] = 'La habilidad de copiar un objeto.';
$_lang['perm.countries_desc'] = 'Para ver una lista de paises.';
$_lang['perm.create_desc'] = 'Acceso básico de "crear" objetos nuevos.';
$_lang['perm.credits_desc'] = 'Ver la página de Créditos.';
$_lang['perm.customize_forms_desc'] = 'Ver y admin la página de Personalización de Formas.';
$_lang['perm.database_desc'] = 'La página de Información del sistema.';
$_lang['perm.database_truncate_desc'] = 'La habilidad de truncar una tabla de la base de datos.';
$_lang['perm.delete_desc'] = 'Acceso básico de "borrar" objectos.';
$_lang['perm.delete_category_desc'] = 'Para borrar o remover cualquier Categoría.';
$_lang['perm.delete_chunk_desc'] = 'Para borrar o remover cualesquiera Chunks.';
$_lang['perm.delete_context_desc'] = 'Para borrar o remover cualesquiera Contextos.';
$_lang['perm.delete_document_desc'] = 'Para borrar o remover cualquier Recurso.';
$_lang['perm.delete_eventlog_desc'] = 'Para vaciar la bitácora de Eventos.';
$_lang['perm.delete_plugin_desc'] = 'Para borrar o remover cualesquiera Plugins.';
$_lang['perm.delete_propertyset_desc'] = 'Para borrar o remover cualesquiera Conjuntos de Propiedades.';
$_lang['perm.delete_role_desc'] = 'Para borrar o remover cualesquiera Roles.';
$_lang['perm.delete_snippet_desc'] = 'Para borrar o remover cualesquiera Snippets.';
$_lang['perm.delete_template_desc'] = 'Para borrar o remover cualesquiera Plantillas.';
$_lang['perm.delete_tv_desc'] = 'Para borrar o remover cualesquiera Variables de Plantilla.';
$_lang['perm.delete_user_desc'] = 'Para borrar o remover cualesquiera Usuarios.';
$_lang['perm.directory_chmod_desc'] = 'Para chmod un directorio.';
$_lang['perm.directory_create_desc'] = 'Para crear un directorio.';
$_lang['perm.directory_list_desc'] = 'Para listar subdirectorios para un directorio.';
$_lang['perm.directory_remove_desc'] = 'Para remover un directorio.';
$_lang['perm.directory_update_desc'] = 'Para renombrar un directorio.';
$_lang['perm.edit_category_desc'] = 'Para editar cualquier Categoría.';
$_lang['perm.edit_chunk_desc'] = 'Para editar cualesquiera Chunks.';
$_lang['perm.edit_context_desc'] = 'Para editar cualesquiera Contextos.';
$_lang['perm.edit_document_desc'] = 'Para editar cualesquiera Recursos.';
$_lang['perm.edit_locked_desc'] = 'Permite a un usuario quitar un cerrojo y editar un Recurso cerrado.';
$_lang['perm.edit_plugin_desc'] = 'Para editar cualesquiera Plugins.';
$_lang['perm.edit_propertyset_desc'] = 'Para editar cualesquiera Conjuntos de Propiedades.';
$_lang['perm.edit_role_desc'] = 'Para editar cualesquiera Roles.';
$_lang['perm.edit_snippet_desc'] = 'Para editar cualesquiera Snippets.';
$_lang['perm.edit_template_desc'] = 'Para editar cualesquiera Plantillas.';
$_lang['perm.edit_tv_desc'] = 'Para editar cualesquiera Variables de Plantillas.';
$_lang['perm.edit_user_desc'] = 'Para editar cualquier Usuario.';
$_lang['perm.element_tree_desc'] = 'La habilidad de ver el árbol de Elementos en la navegación en la izquierda.';
$_lang['perm.empty_cache_desc'] = 'Para vaciar el cache del sitio.';
$_lang['perm.error_log_erase_desc'] = 'Para borrar la bitácora de errores.';
$_lang['perm.error_log_view_desc'] = 'Para ver la bitácora de errores.';
$_lang['perm.export_static_desc'] = 'Para exportar el sitio a HTML estático.';
$_lang['perm.file_list_desc'] = 'Para listar archivos dentro de cierto directorio.';
$_lang['perm.file_manager_desc'] = 'Para usar el administrador de archivos.';
$_lang['perm.file_remove_desc'] = 'Para remover archivos.';
$_lang['perm.file_tree_desc'] = 'Para ver el Árbol de Archivos en la navegación de la izquierda.';
$_lang['perm.file_update_desc'] = 'Para actualizar el contenido de archivos.';
$_lang['perm.file_upload_desc'] = 'Para subir archivos a un directorio.';
$_lang['perm.file_view_desc'] = 'Para ver los contenidos de un archivo.';
$_lang['perm.flush_sessions_desc'] = 'Poder limpiar Sesiones a lo largo del sitio.';
$_lang['perm.frames_desc'] = 'Para usar el el Administrador de MODX.';
$_lang['perm.help_desc'] = 'Para ver la página de Ayuda.';
$_lang['perm.home_desc'] = 'Para ver la página de Bienvenida.';
$_lang['perm.import_static_desc'] = 'Para ver o usar las páginas de Importar.';
$_lang['perm.languages_desc'] = 'Para editar o ver Idiomas del Léxico.';
$_lang['perm.lexicons_desc'] = 'Para editar o ver Léxicos e Internacionalización.';
$_lang['perm.list_desc'] = 'Permiso básico para "listar" cualquier objeto. Listar significa obtener una colección de objetos.';
$_lang['perm.load_desc'] = 'Permiso básico para "cargar" cualquier objeto o ser capaz de regresarlo como una instancia.';
$_lang['perm.logout_desc'] = 'Para ser capáz de salir como un usuario.';
$_lang['perm.logs_desc'] = 'Para ver las bitácoras, como la de errores o la de administración.';
$_lang['perm.menus_desc'] = 'Para editar o guardar cualquier artículo del Menú superior.';
$_lang['perm.messages_desc'] = 'Para enviar o ver cualquier Mensaje personal.';
$_lang['perm.move_desc'] = 'Acceso básico de "mover" cualquier objeto.';
$_lang['perm.namespaces_desc'] = 'Para editar o ver Espacios de Nombre.';
$_lang['perm.new_category_desc'] = 'Para crear una Categoría nueva.';
$_lang['perm.new_chunk_desc'] = 'Para crear un Chunk nuevo.';
$_lang['perm.new_context_desc'] = 'Para crear un Contexto nuevo.';
$_lang['perm.new_document_desc'] = 'Para crear un Recurso nuevo.';
$_lang['perm.new_document_in_root_desc'] = 'Para ser capáz de crear un Recurso a nivel de la raíz.';
$_lang['perm.new_plugin_desc'] = 'Para crear un Plugin nuevo.';
$_lang['perm.new_propertyset_desc'] = 'Para crear un Conjunto de Propiedades nuevo.';
$_lang['perm.new_role_desc'] = 'Para crear un Rol nuevo.';
$_lang['perm.new_snippet_desc'] = 'Para crear un Snippet nuevo.';
$_lang['perm.new_template_desc'] = 'Para crear una Plantilla nueva.';
$_lang['perm.new_tv_desc'] = 'Para crear una Variable de Plantilla nueva.';
$_lang['perm.new_user_desc'] = 'Para crear un Usuario nuevo.';
$_lang['perm.packages_desc'] = 'Para usar cualquier Paquete de Transporte en el sistema de Admin de Paquetes.';
$_lang['perm.property_sets_desc'] = 'Para ver y editar Propiedades y Conjuntos de Propiedades.';
$_lang['perm.providers_desc'] = 'Para ver y editar Proveedores a lo largo del sitio.';
$_lang['perm.publish_desc'] = 'Acceso básico a "publicar" cualquier objeto.';
$_lang['perm.publish_document_desc'] = 'Para publicar o despublicar cualquier Recurso.';
$_lang['perm.purge_deleted_desc'] = 'Para vaciar el Basurero.';
$_lang['perm.remove_desc'] = 'Permiso básico para remover cualquier objeto.';
$_lang['perm.remove_locks_desc'] = 'Para remover todos los bloqueos existentes a lo largo del sitio.';
$_lang['perm.resource_tree_desc'] = 'Para ver el Árbol de Recursos en la navegación izquierda.';
$_lang['perm.save_desc'] = 'Permiso básico para guardar cualquier objeto.';
$_lang['perm.save_category_desc'] = 'Para guardar cualesquiera Categorías.';
$_lang['perm.save_chunk_desc'] = 'Para guardar cualesquiera Chunks.';
$_lang['perm.save_context_desc'] = 'Para guardar cualesquiera Contextos.';
$_lang['perm.save_document_desc'] = 'Para guardar cualesquiera Recursos.';
$_lang['perm.save_plugin_desc'] = 'Para guardar cualesquiera Plugins.';
$_lang['perm.save_propertyset_desc'] = 'Para guardar cualesquiera Conjuntos de Propiedades.';
$_lang['perm.save_role_desc'] = 'Para guardar cualesquiera Roles.';
$_lang['perm.save_snippet_desc'] = 'Para guardar cualesquiera Snippets.';
$_lang['perm.save_template_desc'] = 'Para guardar cualesquiera Plantillas.';
$_lang['perm.save_tv_desc'] = 'Para guardar cualesquiera Variables de Plantilla.';
$_lang['perm.save_user_desc'] = 'Para guardar cualesquiera Usuarios.';
$_lang['perm.search_desc'] = 'Par usar la página de Búsqueda.';
$_lang['perm.settings_desc'] = 'Para ver y editar cualesquiera Configuraciones del Sistema.';
$_lang['perm.steal_lock_desc'] = 'Para "robar", o remover, un bloqueo de un Recurso.';
$_lang['perm.steal_locks_desc'] = 'Para "robar" bloqueos, anulando un bloqueo actual en un Recurso.';
$_lang['perm.tree_show_resource_ids_desc'] = 'Mostrar los IDs en el árbol de Recursos.';
$_lang['perm.tree_show_element_ids_desc'] = 'Mostrar los IDx en el árbol de Elementos.';
$_lang['perm.undelete_desc'] = 'Permiso básico para "des-borrar" cualquier objeto.';
$_lang['perm.undelete_document_desc'] = 'Para des-borrar cualquier Recurso.';
$_lang['perm.unlock_element_properties_desc'] = 'Para ser capáz de editar las propiedades prefijadas para cualquier Elemento.';
$_lang['perm.unpublish_desc'] = 'Para despublicar cualquier Recurso.';
$_lang['perm.unpublish_document_desc'] = 'Para despublicar cualesquiera Recursos.';
$_lang['perm.view_desc'] = 'Permiso básico para "ver" cualquier objeto.';
$_lang['perm.view_category_desc'] = 'Para ver cualesquiera Categorías.';
$_lang['perm.view_chunk_desc'] = 'Para ver cualesquiera Chunks.';
$_lang['perm.view_context_desc'] = 'Para ver cualesquiera Contextos.';
$_lang['perm.view_document_desc'] = 'Para ver cualesquiera Recursos.';
$_lang['perm.view_element_desc'] = 'Para obtener una lista de Elementos o clases de Elementos.';
$_lang['perm.view_eventlog_desc'] = 'Para ver cualesquiera Bitácoras de Eventos.';
$_lang['perm.view_offline_desc'] = 'Para ser capáz de ver el sitio cuando es puesto en estado de fuera de línea.';
$_lang['perm.view_plugin_desc'] = 'Para ver cualesquiera Plugins.';
$_lang['perm.view_propertyset_desc'] = 'Para ver cualesquiera Conjuntos de Propiedades.';
$_lang['perm.view_role_desc'] = 'Para ver cualesquiera Roles.';
$_lang['perm.view_snippet_desc'] = 'Para ver cualesquiera Snippets.';
$_lang['perm.view_sysinfo_desc'] = 'Para ver la página de información del sistema.';
$_lang['perm.view_template_desc'] = 'Para ver cualesquiera Plantillas.';
$_lang['perm.view_tv_desc'] = 'Para ver cualesquiera Variables de Plantilla.';
$_lang['perm.view_unpublished_desc'] = 'Para ver cualesquiera Recursos no publicados.';
$_lang['perm.view_user_desc'] = 'Para ver cualquier Usuario.';
$_lang['perm.workspaces_desc'] = 'Para usar la Administración de Paquetes.'; | mit |
vamshins/apr-actionplan | apr/db/migrate/20151111044457_alter_action_plans.rb | 460 | class AlterActionPlans < ActiveRecord::Migration
def up
remove_column("action_plans", "unit")
rename_column("action_plans", "submitter_name", "submitter_first_name")
add_column("action_plans", "submitter_last_name", :string)
end
def down
remove_column("action_plans", "submitter_last_name")
rename_column("action_plans", "submitter_first_name", "submitter_name")
add_column("action_plans", "unit", :string, :null => false)
end
end
| mit |
ovelasquez/sigcot | app/cache/prod/annotations/Sigcotweb-AplicativoBundle-Entity-Dcfotosactivos$foto.cache.php | 258 | <?php return unserialize('a:1:{i:0;O:27:"Doctrine\\ORM\\Mapping\\Column":9:{s:4:"name";s:4:"foto";s:4:"type";s:4:"blob";s:6:"length";N;s:9:"precision";i:0;s:5:"scale";i:0;s:6:"unique";b:0;s:8:"nullable";b:0;s:7:"options";a:0:{}s:16:"columnDefinition";N;}}'); | mit |
dudakp/rasPi_systemInfo | lib_mpu6050/lib_mpu6050.py | 4879 | #!/usr/bin/python
import time, datetime, math
from ops_i2cbase import I2CBase
# ===========================================================================
# MPU6050 Class
#
# Ported from http://blog.bitify.co.uk/2013/11/reading-data-from-mpu-6050-on-raspberry.html
# ===========================================================================
class MPU6050:
i2c = None
# MPU6050 Address
address = 0x68
# Command / Register Address
MPU6050_PWR_MGMT_1 = 0x6B #R/W
MPU6050_PWR_MGMT_2 = 0x6C #R/W
MPU6050_RA_ACCEL_XOUT_H = 0x3B #R
MPU6050_RA_ACCEL_XOUT_L = 0x3C #R
MPU6050_RA_ACCEL_YOUT_H = 0x3D #R
MPU6050_RA_ACCEL_YOUT_L = 0x3E #R
MPU6050_RA_ACCEL_ZOUT_H = 0x3F #R
MPU6050_RA_ACCEL_ZOUT_L = 0x40 #R
MPU6050_RA_TEMP_OUT_H = 0x41 #R
MPU6050_RA_TEMP_OUT_L = 0x42 #R
MPU6050_RA_GYRO_XOUT_H = 0x43 #R
MPU6050_RA_GYRO_XOUT_L = 0x44 #R
MPU6050_RA_GYRO_YOUT_H = 0x45 #R
MPU6050_RA_GYRO_YOUT_L = 0x46 #R
MPU6050_RA_GYRO_ZOUT_H = 0x47 #R
MPU6050_RA_GYRO_ZOUT_L = 0x48 #R
MPU6050_PWR1_SLEEP_BIT = 6
# Constant
pi = 3.1415926
AcceRatio = 16384.0
GyroRatio = 131.0
# Variable
offset_acc_x = 0
offset_acc_y = 0
offset_acc_z = 0
offset_gyr_x = 0
offset_gyr_y = 0
offset_gyr_z = 0
last_read_time = datetime.datetime.now()
# Constructor
def __init__(self):
self.i2c = I2CBase(self.address)
self.initialize()
def initialize(self):
"Initiate the sensor by set and clear the power sleep bit, and collector an average offset"
# Set the sleep bit
self.setBit(self.MPU6050_PWR_MGMT_1, self.MPU6050_PWR1_SLEEP_BIT)
# Clear the sleep bit
self.clearBit(self.MPU6050_PWR_MGMT_1, self.MPU6050_PWR1_SLEEP_BIT)
# The above Set/Clear process is necessary to prevent the sensor going halt or freeze
# Take simple and calculate the average offset
simple_time = 200
sum_acc_x = 0
sum_acc_y = 0
sum_acc_z = 0
sum_gyro_x = 0
sum_gyro_y = 0
sum_gyro_z = 0
for i in range(simple_time):
x_accel = self.readSint16(self.MPU6050_RA_ACCEL_XOUT_H) / self.AcceRatio
y_accel = self.readSint16(self.MPU6050_RA_ACCEL_YOUT_H) / self.AcceRatio
z_accel = self.readSint16(self.MPU6050_RA_ACCEL_ZOUT_H) / self.AcceRatio
x_gyro = self.readSint16(self.MPU6050_RA_GYRO_XOUT_H) / self.AcceRatio
y_gyro = self.readSint16(self.MPU6050_RA_GYRO_YOUT_H) / self.AcceRatio
z_gyro = self.readSint16(self.MPU6050_RA_GYRO_ZOUT_H) / self.AcceRatio
temperature = self.readSint16(self.MPU6050_RA_TEMP_OUT_H)
temperature = (temperature + 521.0) / 340.0 + 35.0
sum_acc_x += x_accel
sum_acc_y += y_accel
sum_acc_z += z_accel
sum_gyro_x += x_gyro
sum_gyro_y += y_gyro
sum_gyro_z += z_gyro
self.offset_acc_x = sum_acc_x / simple_time
self.offset_acc_y = sum_acc_y / simple_time
self.offset_acc_z = sum_acc_z / simple_time
self.offset_gyr_x = sum_gyro_x / simple_time
self.offset_gyr_y = sum_gyro_y / simple_time
self.offset_gyr_z = sum_gyro_z / simple_time
def setBit(self, register, bit):
"Set a bit in the register"
# Read
original = self.i2c.readU8(register)
# Set
self.i2c.write8( register, original | ( 0x01 << bit ) )
def clearBit(self, register, bit):
"Clear a bit in the register"
# Read
original = self.i2c.readU8(register)
# Clear
self.i2c.write8( register, original ^ ( 0x01 << bit ) )
def readSint16(self, address):
"Read a signed 16 bits register"
high = self.i2c.readU8(address)
low = self.i2c.readU8(address + 1)
value = (high << 8) + low
if (value >= 0x8000):
return -((65535 - value) + 1)
else:
return value
def readMPU6050(self):
"Read and return the Gyro and the Accelerometer value"
current_time = datetime.datetime.now()
dt_timedelta = ( current_time - self.last_read_time )
dt_milliseconds = ( dt_timedelta.seconds * 1000 * 1000 + dt_timedelta.microseconds ) / 1000
self.last_read_time = current_time
x_accel = self.readSint16(self.MPU6050_RA_ACCEL_XOUT_H) / self.AcceRatio
y_accel = self.readSint16(self.MPU6050_RA_ACCEL_YOUT_H) / self.AcceRatio
z_accel = self.readSint16(self.MPU6050_RA_ACCEL_ZOUT_H) / self.AcceRatio
x_gyro = self.readSint16(self.MPU6050_RA_GYRO_XOUT_H) / self.AcceRatio
y_gyro = self.readSint16(self.MPU6050_RA_GYRO_YOUT_H) / self.AcceRatio
z_gyro = self.readSint16(self.MPU6050_RA_GYRO_ZOUT_H) / self.AcceRatio
temperature = self.readSint16(self.MPU6050_RA_TEMP_OUT_H)
temperature = (temperature + 521.0) / 340.0 + 35.0
x_rotation = -math.degrees( math.atan2(x_accel, math.sqrt((y_accel*y_accel)+(z_accel*z_accel))) )
y_rotation = math.degrees( math.atan2(y_accel, math.sqrt((x_accel*x_accel)+(z_accel*z_accel))) )
return x_accel, y_accel, z_accel, x_gyro, y_gyro, z_gyro, temperature, x_rotation, y_rotation
| mit |
ASP-NET-MVC-Boilerplate/Framework | Source/Boxed.Mapping/Factory.cs | 954 | namespace Boxed.Mapping
{
using System;
using System.Linq.Expressions;
/// <summary>
/// Creates instances of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type with a parameterless constructor.</typeparam>
public static class Factory<T>
where T : new()
{
private static readonly Func<T> CreateInstanceFunc =
Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile();
/// <summary>
/// Creates an instance of type <typeparamref name="T"/> by calling it's parameterless constructor.
/// </summary>
/// <returns>An instance of type <typeparamref name="T"/>.</returns>
#pragma warning disable CA1000 // Do not declare static members on generic types
public static T CreateInstance() => CreateInstanceFunc();
#pragma warning restore CA1000 // Do not declare static members on generic types
}
}
| mit |
netTiers/netTiers | Samples/Petshop/Source/PetShop.Data/Bases/CategoryProviderBase.cs | 630 | #region Using directives
using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using PetShop.Business;
using PetShop.Data;
#endregion
namespace PetShop.Data.Bases
{
///<summary>
/// This class is the base class for any <see cref="CategoryProviderBase"/> implementation.
/// It exposes CRUD methods as well as selecting on index, foreign keys and custom stored procedures.
///</summary>
public abstract partial class CategoryProviderBase : CategoryProviderBaseCore
{
} // end class
} // end namespace
| mit |
ltalirz/asetk | scripts/cube-roll.py | 1072 | #!/usr/bin/env python
import numpy as np
import argparse
from asetk.format.cube import Cube
# Define command line parser
parser = argparse.ArgumentParser(
description='Rolls cube file by specified shift along direction.')
parser.add_argument('--version', action='version', version='%(prog)s 12.05.2016')
parser.add_argument(
'cube',
metavar='filename',
help='Cube file to be sliced.')
parser.add_argument(
'--dir',
metavar='direction',
type=str,
help='"x", "y" or "z"')
parser.add_argument(
'--shift',
metavar='INTEGER',
type=int,
default=None,
help='Shift specified in steps of cube file grid.')
parser.add_argument(
'--distance',
metavar='FLOAT',
type=float,
help='Shift specified in Angstroms.')
args = parser.parse_args()
# Make list of jobs
print("Reading cube file {}".format(args.cube))
c = Cube.from_file(args.cube, read_data=True)
c.roll(dir=args.dir, shift=args.shift, distance=args.distance)
fname_out = 's.' + args.cube
print("Writing {}".format(fname_out))
c.write_cube_file(fname_out)
| mit |
turbonetix/bus.io-receiver | examples/receiver.js | 1667 | var Message = require('bus.io-common').Message;
var receiver = require('../.')();
receiver.on('error', function (err){
console.log('Received an error: %s', err);
});
receiver.on('received', function (msg) {
console.log('This receiver is finished and triggered the "received" event with the message %j', msg.data);
console.log('the args', arguments);
});
receiver.use(function (msg, next) {
console.log('All messages go through this handler!', msg.action());
next();
});
receiver.use(/some/, function (msg, next) {
console.log('/some/ messages go through this handler!', msg.action());
next();
});
receiver.use('some *',function (msg, next) {
console.log('"some *" messages go through this handler! %s', msg.action());
next();
});
receiver.use('some event', function (msg, next) {
console.log('"some event" messages go through this handler! %s', msg.action());
console.log('triggering an Error that should be captured in the next error handler');
next(new Error('Some Error'));
});
receiver.use(function (err, msg, next) {
console.log('We received an "Error" from a previous handler! %s', err);
console.log('We will receover! by just calling "next()"');
next();
});
receiver.use('*event', function (msg, next) {
console.log('"*event*" messages go through this handler! %s', msg.action());
console.log('we are going to invoke "deliver()" on the msg to prevent the next handler');
msg.deliver();
console.log('attempting to call next to trigger the next handler');
next();
});
receiver.use('some event', function (msg, next) {
throw new Error('We should not get this!!');
});
receiver.onReceive(Message({action:'some event'}));
| mit |
activewarehouse/activewarehouse-etl | lib/etl/parser/nokogiri_xml_parser.rb | 2128 | optional_require 'nokogiri'
require 'open-uri'
optional_require 'zlib'
module ETL
module Parser
class NokogiriXmlParser < ETL::Parser::Parser
# Initialize the parser
# * <tt>source</tt>: The Source object
# * <tt>options</tt>: Parser options Hash
def initialize(source, options={})
super
configure
end
# Returns each row
def each
Dir.glob(file).each do |source|
doc = nil
gzip = false
magic = "1F8B".to_i(base=16) # Check for gzip archives
if File.exist?(source)
gzip = true if magic == (
File.open(source).read(2).unpack("H2H2").to_s.to_i(base=16))
end
if gzip
doc = Nokogiri::XML(Zlib::GzipReader.open(source))
else
doc = Nokogiri::XML(open(source))
end
doc.xpath(@collection_xpath).each do |nodeset|
row = {}
fields.each do |f|
value = nodeset.xpath(f.xpath).text
row[f.name] = value
end
yield row
end
end
end
# Get an array of defined fields
def fields
@fields ||= []
end
private
def configure
@collection_xpath = source.definition[:collection]
if @collection_xpath.nil?
raise ":collection => 'XPath' argument required"
end
source.definition[:fields].each do |options|
case options
when Symbol
fields << Field.new(options, options.to_s)
when Hash
options[:xpath] ||= options[:name]
fields << Field.new(options[:name], options[:xpath].to_s)
else
raise DefinitionError,
"Each field definition must either be an symbol " +
"or a hash of options for the field"
end
end
end
class Field
attr_reader :name, :xpath
def initialize(name, xpath)
@name = name
@xpath = xpath
end
end
end
end
end
| mit |
yugangw-msft/autorest | src/core/AutoRest.Core/Model/PrimaryType.cs | 3697 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
using System.Collections.Generic;
using System.Linq;
using AutoRest.Core.Utilities;
namespace AutoRest.Core.Model
{
/// <summary>
/// Defines known model type.
/// </summary>
public class PrimaryType : ModelType
{
protected PrimaryType()
{
}
/// <summary>
/// Initializes a new instance of PrimaryType class from a known type.
/// </summary>
protected PrimaryType(KnownPrimaryType knownPrimaryType)
{
KnownPrimaryType = knownPrimaryType;
Name = KnownPrimaryType.ToString();
}
public override IEnumerable<IChild> Children => Enumerable.Empty<IChild>();
public override string Qualifier => "PrimaryType";
public override string RefName => $"AutoRest.Core.Model.PrimaryType, AutoRest.Core";
/// <summary>
/// Gets or sets the model type format.
/// </summary>
public virtual string Format { get; set; }
/// <summary>
/// Returns the KnownFormat of the Format string (provided it matches a KnownFormat)
/// Otherwise, returns KnownFormat.none
/// </summary>
public KnownFormat KnownFormat => KnownFormatExtensions.Parse(Format);
/// <summary>
/// Gets or sets the underlying known type.
/// </summary>
public KnownPrimaryType KnownPrimaryType { get; set; }
/// <Summary>
/// Backing field for <code>SerializedName</code> property.
/// </Summary>
/// <remarks>This field should be marked as 'readonly' as write access to it's value is controlled thru Fixable[T].</remarks>
private readonly Fixable<string> _serializedName = new Fixable<string>();
/// <Summary>
/// The name on the wire for the model type.
/// </Summary>
/// <remarks>
/// The Get and Set operations for this accessor may be overridden by using the
/// <code>SerializedName.OnGet</code> and <code>SerializedName.OnSet</code> events in this class' constructor.
/// (ie <code> SerializedName.OnGet += serializedName => serializedName.ToUpper();</code> )
/// </remarks>
public Fixable<string> SerializedName
{
get { return _serializedName; }
set { _serializedName.CopyFrom(value); }
}
public override void Disambiguate()
{
// not needed, right?
}
/// <summary>
/// Returns a string representation of the PrimaryType object.
/// </summary>
/// <returns>
/// A string representation of the PrimaryType object.
/// </returns>
public override string ToString()
{
return Name;
}
/// <summary>
/// Determines whether the specified model type is structurally equal to this object.
/// </summary>
/// <param name="other">The object to compare with this object.</param>
/// <returns>true if the specified object is functionally equal to this object; otherwise, false.</returns>
public override bool StructurallyEquals(IModelType other)
{
if (ReferenceEquals(other as PrimaryType, null))
{
return false;
}
return base.StructurallyEquals(other) &&
KnownPrimaryType == (other as PrimaryType).KnownPrimaryType &&
Format == (other as PrimaryType).Format;
}
}
} | mit |
CalleyChatham/up-next | public/bundle.js | 766980 | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/*!********************!*\
!*** ./app/app.js ***!
\********************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Include the Main React Dependencies
var React = __webpack_require__(/*! react */ 1);
var ReactDOM = __webpack_require__(/*! react-dom */ 158);
// Include the main Main Component
var Main = __webpack_require__(/*! ./components/Main */ 159);
// This code here allows us to render our main component (in this case Main)
ReactDOM.render(React.createElement(Main, null), document.getElementById("app"));
/***/ }),
/* 1 */
/*!**************************!*\
!*** ./~/react/react.js ***!
\**************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(/*! ./lib/React */ 2);
/***/ }),
/* 2 */
/*!******************************!*\
!*** ./~/react/lib/React.js ***!
\******************************/
/***/ (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.
*
* @providesModule React
*/
'use strict';
var ReactDOM = __webpack_require__(/*! ./ReactDOM */ 3);
var ReactDOMServer = __webpack_require__(/*! ./ReactDOMServer */ 148);
var ReactIsomorphic = __webpack_require__(/*! ./ReactIsomorphic */ 152);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var deprecated = __webpack_require__(/*! ./deprecated */ 157);
// `version` will be added here by ReactIsomorphic.
var React = {};
assign(React, ReactIsomorphic);
assign(React, {
// ReactDOM
findDOMNode: deprecated('findDOMNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.findDOMNode),
render: deprecated('render', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.render),
unmountComponentAtNode: deprecated('unmountComponentAtNode', 'ReactDOM', 'react-dom', ReactDOM, ReactDOM.unmountComponentAtNode),
// ReactDOMServer
renderToString: deprecated('renderToString', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToString),
renderToStaticMarkup: deprecated('renderToStaticMarkup', 'ReactDOMServer', 'react-dom/server', ReactDOMServer, ReactDOMServer.renderToStaticMarkup)
});
React.__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOM;
React.__SECRET_DOM_SERVER_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactDOMServer;
module.exports = React;
/***/ }),
/* 3 */
/*!*********************************!*\
!*** ./~/react/lib/ReactDOM.js ***!
\*********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOM
*/
/* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/
'use strict';
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var ReactDOMTextComponent = __webpack_require__(/*! ./ReactDOMTextComponent */ 6);
var ReactDefaultInjection = __webpack_require__(/*! ./ReactDefaultInjection */ 71);
var ReactInstanceHandles = __webpack_require__(/*! ./ReactInstanceHandles */ 45);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var ReactReconciler = __webpack_require__(/*! ./ReactReconciler */ 50);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var ReactVersion = __webpack_require__(/*! ./ReactVersion */ 146);
var findDOMNode = __webpack_require__(/*! ./findDOMNode */ 91);
var renderSubtreeIntoContainer = __webpack_require__(/*! ./renderSubtreeIntoContainer */ 147);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
ReactDefaultInjection.inject();
var render = ReactPerf.measure('React', 'render', ReactMount.render);
var React = {
findDOMNode: findDOMNode,
render: render,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
version: ReactVersion,
/* eslint-disable camelcase */
unstable_batchedUpdates: ReactUpdates.batchedUpdates,
unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
/* eslint-enable camelcase */
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
CurrentOwner: ReactCurrentOwner,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
Reconciler: ReactReconciler,
TextComponent: ReactDOMTextComponent
});
}
if (process.env.NODE_ENV !== 'production') {
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// First check if devtools is not installed
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
// If we're in Chrome or Firefox, provide a download link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) {
console.debug('Download the React DevTools for a better development experience: ' + 'https://fb.me/react-devtools');
}
}
// If we're in IE8, check to see if we are in compatibility mode and provide
// information on preventing compatibility mode
var ieCompatibilityMode = document.documentMode && document.documentMode < 8;
process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, 'Internet Explorer is running in compatibility mode; please add the ' + 'following tag to your HTML to prevent this from happening: ' + '<meta http-equiv="X-UA-Compatible" content="IE=edge" />') : undefined;
var expectedFeatures = [
// shims
Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim,
// shams
Object.create, Object.freeze];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
console.error('One or more ES5 shim/shams expected by React are not available: ' + 'https://fb.me/react-warning-polyfills');
break;
}
}
}
}
module.exports = React;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 4 */
/*!******************************!*\
!*** ./~/process/browser.js ***!
\******************************/
/***/ (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.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
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; };
/***/ }),
/* 5 */
/*!******************************************!*\
!*** ./~/react/lib/ReactCurrentOwner.js ***!
\******************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ReactCurrentOwner
*/
'use strict';
/**
* Keeps track of the current owner.
*
* The current owner is the component who should own any components that are
* currently being constructed.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
/***/ }),
/* 6 */
/*!**********************************************!*\
!*** ./~/react/lib/ReactDOMTextComponent.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOMTextComponent
* @typechecks static-only
*/
'use strict';
var DOMChildrenOperations = __webpack_require__(/*! ./DOMChildrenOperations */ 7);
var DOMPropertyOperations = __webpack_require__(/*! ./DOMPropertyOperations */ 22);
var ReactComponentBrowserEnvironment = __webpack_require__(/*! ./ReactComponentBrowserEnvironment */ 26);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var escapeTextContentForBrowser = __webpack_require__(/*! ./escapeTextContentForBrowser */ 21);
var setTextContent = __webpack_require__(/*! ./setTextContent */ 20);
var validateDOMNesting = __webpack_require__(/*! ./validateDOMNesting */ 70);
/**
* Text nodes violate a couple assumptions that React makes about components:
*
* - When mounting text into the DOM, adjacent text nodes are merged.
* - Text nodes cannot be assigned a React root ID.
*
* This component is used to wrap strings in elements so that they can undergo
* the same reconciliation that is applied to elements.
*
* TODO: Investigate representing React components in the DOM with text nodes.
*
* @class ReactDOMTextComponent
* @extends ReactComponent
* @internal
*/
var ReactDOMTextComponent = function (props) {
// This constructor and its argument is currently used by mocks.
};
assign(ReactDOMTextComponent.prototype, {
/**
* @param {ReactText} text
* @internal
*/
construct: function (text) {
// TODO: This is really a ReactText (ReactNode), not a ReactElement
this._currentElement = text;
this._stringText = '' + text;
// Properties
this._rootNodeID = null;
this._mountIndex = 0;
},
/**
* Creates the markup for this text node. This node is not intended to have
* any features besides containing text content.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function (rootID, transaction, context) {
if (process.env.NODE_ENV !== 'production') {
if (context[validateDOMNesting.ancestorInfoContextKey]) {
validateDOMNesting('span', null, context[validateDOMNesting.ancestorInfoContextKey]);
}
}
this._rootNodeID = rootID;
if (transaction.useCreateElement) {
var ownerDocument = context[ReactMount.ownerDocumentContextKey];
var el = ownerDocument.createElement('span');
DOMPropertyOperations.setAttributeForID(el, rootID);
// Populate node cache
ReactMount.getID(el);
setTextContent(el, this._stringText);
return el;
} else {
var escapedText = escapeTextContentForBrowser(this._stringText);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this in a `span` for the reasons stated above, but
// since this is a situation where React won't take over (static pages),
// we can simply return the text as it is.
return escapedText;
}
return '<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' + escapedText + '</span>';
}
},
/**
* Updates this component by updating the text content.
*
* @param {ReactText} nextText The next text content
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function (nextText, transaction) {
if (nextText !== this._currentElement) {
this._currentElement = nextText;
var nextStringText = '' + nextText;
if (nextStringText !== this._stringText) {
// TODO: Save this as pending props and use performUpdateIfNecessary
// and/or updateComponent to do the actual update for consistency with
// other component types?
this._stringText = nextStringText;
var node = ReactMount.getNode(this._rootNodeID);
DOMChildrenOperations.updateTextContent(node, nextStringText);
}
}
},
unmountComponent: function () {
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
}
});
module.exports = ReactDOMTextComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 7 */
/*!**********************************************!*\
!*** ./~/react/lib/DOMChildrenOperations.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule DOMChildrenOperations
* @typechecks static-only
*/
'use strict';
var Danger = __webpack_require__(/*! ./Danger */ 8);
var ReactMultiChildUpdateTypes = __webpack_require__(/*! ./ReactMultiChildUpdateTypes */ 16);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var setInnerHTML = __webpack_require__(/*! ./setInnerHTML */ 19);
var setTextContent = __webpack_require__(/*! ./setTextContent */ 20);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* Inserts `childNode` as a child of `parentNode` at the `index`.
*
* @param {DOMElement} parentNode Parent node in which to insert.
* @param {DOMElement} childNode Child node to insert.
* @param {number} index Index at which to insert the child.
* @internal
*/
function insertChildAt(parentNode, childNode, index) {
// By exploiting arrays returning `undefined` for an undefined index, we can
// rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. However, using `undefined` is not allowed by all
// browsers so we must replace it with `null`.
// fix render order error in safari
// IE8 will throw error when index out of list size.
var beforeChild = index >= parentNode.childNodes.length ? null : parentNode.childNodes.item(index);
parentNode.insertBefore(childNode, beforeChild);
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: setTextContent,
/**
* Updates a component's children by processing a series of updates. The
* update configurations are each expected to have a `parentNode` property.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markupList List of markup strings.
* @internal
*/
processUpdates: function (updates, markupList) {
var update;
// Mapping from parent IDs to initial child orderings.
var initialChildren = null;
// List of children that will be moved or removed.
var updatedChildren = null;
for (var i = 0; i < updates.length; i++) {
update = updates[i];
if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
var updatedIndex = update.fromIndex;
var updatedChild = update.parentNode.childNodes[updatedIndex];
var parentID = update.parentID;
!updatedChild ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processUpdates(): Unable to find child %s of element. This ' + 'probably means the DOM was unexpectedly mutated (e.g., by the ' + 'browser), usually due to forgetting a <tbody> when using tables, ' + 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + 'in an <svg> parent. Try inspecting the child nodes of the element ' + 'with React ID `%s`.', updatedIndex, parentID) : invariant(false) : undefined;
initialChildren = initialChildren || {};
initialChildren[parentID] = initialChildren[parentID] || [];
initialChildren[parentID][updatedIndex] = updatedChild;
updatedChildren = updatedChildren || [];
updatedChildren.push(updatedChild);
}
}
var renderedMarkup;
// markupList is either a list of markup or just a list of elements
if (markupList.length && typeof markupList[0] === 'string') {
renderedMarkup = Danger.dangerouslyRenderMarkup(markupList);
} else {
renderedMarkup = markupList;
}
// Remove updated children first so that `toIndex` is consistent.
if (updatedChildren) {
for (var j = 0; j < updatedChildren.length; j++) {
updatedChildren[j].parentNode.removeChild(updatedChildren[j]);
}
}
for (var k = 0; k < updates.length; k++) {
update = updates[k];
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertChildAt(update.parentNode, renderedMarkup[update.markupIndex], update.toIndex);
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
insertChildAt(update.parentNode, initialChildren[update.parentID][update.fromIndex], update.toIndex);
break;
case ReactMultiChildUpdateTypes.SET_MARKUP:
setInnerHTML(update.parentNode, update.content);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
setTextContent(update.parentNode, update.content);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', {
updateTextContent: 'updateTextContent'
});
module.exports = DOMChildrenOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 8 */
/*!*******************************!*\
!*** ./~/react/lib/Danger.js ***!
\*******************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule Danger
* @typechecks static-only
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var createNodesFromMarkup = __webpack_require__(/*! fbjs/lib/createNodesFromMarkup */ 10);
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ 15);
var getMarkupWrap = __webpack_require__(/*! fbjs/lib/getMarkupWrap */ 14);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/;
var RESULT_INDEX_ATTR = 'data-danger-index';
/**
* Extracts the `nodeName` from a string of markup.
*
* NOTE: Extracting the `nodeName` does not require a regular expression match
* because we make assumptions about React-generated markup (i.e. there are no
* spaces surrounding the opening tag and there is at least one attribute).
*
* @param {string} markup String of markup.
* @return {string} Node name of the supplied markup.
* @see http://jsperf.com/extract-nodename
*/
function getNodeName(markup) {
return markup.substring(1, markup.indexOf(' '));
}
var Danger = {
/**
* Renders markup into an array of nodes. The markup is expected to render
* into a list of root nodes. Also, the length of `resultList` and
* `markupList` should be the same.
*
* @param {array<string>} markupList List of markup strings to render.
* @return {array<DOMElement>} List of rendered nodes.
* @internal
*/
dangerouslyRenderMarkup: function (markupList) {
!ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' + 'thread. Make sure `window` and `document` are available globally ' + 'before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString for server rendering.') : invariant(false) : undefined;
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
!markupList[i] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : undefined;
nodeName = getNodeName(markupList[i]);
nodeName = getMarkupWrap(nodeName) ? nodeName : '*';
markupByNodeName[nodeName] = markupByNodeName[nodeName] || [];
markupByNodeName[nodeName][i] = markupList[i];
}
var resultList = [];
var resultListAssignmentCount = 0;
for (nodeName in markupByNodeName) {
if (!markupByNodeName.hasOwnProperty(nodeName)) {
continue;
}
var markupListByNodeName = markupByNodeName[nodeName];
// This for-in loop skips the holes of the sparse array. The order of
// iteration should follow the order of assignment, which happens to match
// numerical index order, but we don't rely on that.
var resultIndex;
for (resultIndex in markupListByNodeName) {
if (markupListByNodeName.hasOwnProperty(resultIndex)) {
var markup = markupListByNodeName[resultIndex];
// Push the requested markup with an additional RESULT_INDEX_ATTR
// attribute. If the markup does not start with a < character, it
// will be discarded below (with an appropriate console.error).
markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP,
// This index will be parsed back out below.
'$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" ');
}
}
// Render each group of markup with similar wrapping `nodeName`.
var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags.
);
for (var j = 0; j < renderNodes.length; ++j) {
var renderNode = renderNodes[j];
if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
!!resultList.hasOwnProperty(resultIndex) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : undefined;
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if (process.env.NODE_ENV !== 'production') {
console.error('Danger: Discarding unexpected node:', renderNode);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
!(resultListAssignmentCount === resultList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : undefined;
!(resultList.length === markupList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : undefined;
return resultList;
},
/**
* Replaces a node with a string of markup at its current position within its
* parent. The markup must render into a single root node.
*
* @param {DOMElement} oldChild Child node to replace.
* @param {string} markup Markup to render in place of the child node.
* @internal
*/
dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) {
!ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' + 'worker thread. Make sure `window` and `document` are available ' + 'globally before requiring React when unit testing or use ' + 'ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
!markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : undefined;
!(oldChild.tagName.toLowerCase() !== 'html') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the ' + '<html> node. This is because browser quirks make this unreliable ' + 'and/or slow. If you want to render to the root you must use ' + 'server rendering. See ReactDOMServer.renderToString().') : invariant(false) : undefined;
var newChild;
if (typeof markup === 'string') {
newChild = createNodesFromMarkup(markup, emptyFunction)[0];
} else {
newChild = markup;
}
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 9 */
/*!********************************************!*\
!*** ./~/fbjs/lib/ExecutionEnvironment.js ***!
\********************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ExecutionEnvironment
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ }),
/* 10 */
/*!*********************************************!*\
!*** ./~/fbjs/lib/createNodesFromMarkup.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule createNodesFromMarkup
* @typechecks
*/
/*eslint-disable fb-www/unsafe-html*/
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! ./ExecutionEnvironment */ 9);
var createArrayFromMixed = __webpack_require__(/*! ./createArrayFromMixed */ 11);
var getMarkupWrap = __webpack_require__(/*! ./getMarkupWrap */ 14);
var invariant = __webpack_require__(/*! ./invariant */ 13);
/**
* Dummy container used to render all markup.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Pattern used by `getNodeName`.
*/
var nodeNamePattern = /^\s*<(\w+)/;
/**
* Extracts the `nodeName` of the first element in a string of markup.
*
* @param {string} markup String of markup.
* @return {?string} Node name of the supplied markup.
*/
function getNodeName(markup) {
var nodeNameMatch = markup.match(nodeNamePattern);
return nodeNameMatch && nodeNameMatch[1].toLowerCase();
}
/**
* Creates an array containing the nodes rendered from the supplied markup. The
* optionally supplied `handleScript` function will be invoked once for each
* <script> element that is rendered. If no `handleScript` function is supplied,
* an exception is thrown if any <script> elements are rendered.
*
* @param {string} markup A string of valid HTML markup.
* @param {?function} handleScript Invoked once for each rendered <script>.
* @return {array<DOMElement|DOMTextNode>} An array of rendered nodes.
*/
function createNodesFromMarkup(markup, handleScript) {
var node = dummyNode;
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : undefined;
var nodeName = getNodeName(markup);
var wrap = nodeName && getMarkupWrap(nodeName);
if (wrap) {
node.innerHTML = wrap[1] + markup + wrap[2];
var wrapDepth = wrap[0];
while (wrapDepth--) {
node = node.lastChild;
}
} else {
node.innerHTML = markup;
}
var scripts = node.getElementsByTagName('script');
if (scripts.length) {
!handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : undefined;
createArrayFromMixed(scripts).forEach(handleScript);
}
var nodes = createArrayFromMixed(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 11 */
/*!********************************************!*\
!*** ./~/fbjs/lib/createArrayFromMixed.js ***!
\********************************************/
/***/ (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.
*
* @providesModule createArrayFromMixed
* @typechecks
*/
'use strict';
var toArray = __webpack_require__(/*! ./toArray */ 12);
/**
* Perform a heuristic test to determine if an object is "array-like".
*
* A monk asked Joshu, a Zen master, "Has a dog Buddha nature?"
* Joshu replied: "Mu."
*
* This function determines if its argument has "array nature": it returns
* true if the argument is an actual array, an `arguments' object, or an
* HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()).
*
* It will return false for other array-like objects like Filelist.
*
* @param {*} obj
* @return {boolean}
*/
function hasArrayNature(obj) {
return(
// not null/false
!!obj && (
// arrays are objects, NodeLists are functions in Safari
typeof obj == 'object' || typeof obj == 'function') &&
// quacks like an array
'length' in obj &&
// not window
!('setInterval' in obj) &&
// no DOM node should be considered an array-like
// a 'select' element has 'length' and 'item' properties on IE8
typeof obj.nodeType != 'number' && (
// a real array
Array.isArray(obj) ||
// arguments
'callee' in obj ||
// HTMLCollection/NodeList
'item' in obj)
);
}
/**
* Ensure that the argument is an array by wrapping it in an array if it is not.
* Creates a copy of the argument if it is already an array.
*
* This is mostly useful idiomatically:
*
* var createArrayFromMixed = require('createArrayFromMixed');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFromMixed(things);
* ...
* }
*
* This allows you to treat `things' as an array, but accept scalars in the API.
*
* If you need to convert an array-like object, like `arguments`, into an array
* use toArray instead.
*
* @param {*} obj
* @return {array}
*/
function createArrayFromMixed(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFromMixed;
/***/ }),
/* 12 */
/*!*******************************!*\
!*** ./~/fbjs/lib/toArray.js ***!
\*******************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule toArray
* @typechecks
*/
'use strict';
var invariant = __webpack_require__(/*! ./invariant */ 13);
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFromMixed.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browse builtin objects can report typeof 'function' (e.g. NodeList in
// old versions of Safari).
!(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : undefined;
!(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : undefined;
!(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : undefined;
// Old IE doesn't give collections access to hasOwnProperty. Assume inputs
// without method will throw during the slice call and skip straight to the
// fallback.
if (obj.hasOwnProperty) {
try {
return Array.prototype.slice.call(obj);
} catch (e) {
// IE < 9 does not support Array#slice on collections objects
}
}
// Fall back to copying key by key. This assumes all keys have a value,
// so will not preserve sparsely populated inputs.
var ret = Array(length);
for (var ii = 0; ii < length; ii++) {
ret[ii] = obj[ii];
}
return ret;
}
module.exports = toArray;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 13 */
/*!*********************************!*\
!*** ./~/fbjs/lib/invariant.js ***!
\*********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 14 */
/*!*************************************!*\
!*** ./~/fbjs/lib/getMarkupWrap.js ***!
\*************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule getMarkupWrap
*/
/*eslint-disable fb-www/unsafe-html */
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! ./ExecutionEnvironment */ 9);
var invariant = __webpack_require__(/*! ./invariant */ 13);
/**
* Dummy container used to detect which wraps are necessary.
*/
var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null;
/**
* Some browsers cannot use `innerHTML` to render certain elements standalone,
* so we wrap them, render the wrapped nodes, then extract the desired node.
*
* In IE8, certain elements cannot render alone, so wrap all elements ('*').
*/
var shouldWrap = {};
var selectWrap = [1, '<select multiple="true">', '</select>'];
var tableWrap = [1, '<table>', '</table>'];
var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>'];
var markupWrap = {
'*': [1, '?<div>', '</div>'],
'area': [1, '<map>', '</map>'],
'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
'legend': [1, '<fieldset>', '</fieldset>'],
'param': [1, '<object>', '</object>'],
'tr': [2, '<table><tbody>', '</tbody></table>'],
'optgroup': selectWrap,
'option': selectWrap,
'caption': tableWrap,
'colgroup': tableWrap,
'tbody': tableWrap,
'tfoot': tableWrap,
'thead': tableWrap,
'td': trWrap,
'th': trWrap
};
// Initialize the SVG elements since we know they'll always need to be wrapped
// consistently. If they are created inside a <div> they will be initialized in
// the wrong namespace (and will not display).
var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan'];
svgElements.forEach(function (nodeName) {
markupWrap[nodeName] = svgWrap;
shouldWrap[nodeName] = true;
});
/**
* Gets the markup wrap configuration for the supplied `nodeName`.
*
* NOTE: This lazily detects which wraps are necessary for the current browser.
*
* @param {string} nodeName Lowercase `nodeName`.
* @return {?array} Markup wrap configuration, if applicable.
*/
function getMarkupWrap(nodeName) {
!!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : undefined;
if (!markupWrap.hasOwnProperty(nodeName)) {
nodeName = '*';
}
if (!shouldWrap.hasOwnProperty(nodeName)) {
if (nodeName === '*') {
dummyNode.innerHTML = '<link />';
} else {
dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>';
}
shouldWrap[nodeName] = !dummyNode.firstChild;
}
return shouldWrap[nodeName] ? markupWrap[nodeName] : null;
}
module.exports = getMarkupWrap;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 15 */
/*!*************************************!*\
!*** ./~/fbjs/lib/emptyFunction.js ***!
\*************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule emptyFunction
*/
"use strict";
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.
*/
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;
/***/ }),
/* 16 */
/*!***************************************************!*\
!*** ./~/react/lib/ReactMultiChildUpdateTypes.js ***!
\***************************************************/
/***/ (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.
*
* @providesModule ReactMultiChildUpdateTypes
*/
'use strict';
var keyMirror = __webpack_require__(/*! fbjs/lib/keyMirror */ 17);
/**
* When a component's children are updated, a series of update configuration
* objects are created in order to batch and serialize the required changes.
*
* Enumerates all the possible types of update configurations.
*
* @internal
*/
var ReactMultiChildUpdateTypes = keyMirror({
INSERT_MARKUP: null,
MOVE_EXISTING: null,
REMOVE_NODE: null,
SET_MARKUP: null,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
/***/ }),
/* 17 */
/*!*********************************!*\
!*** ./~/fbjs/lib/keyMirror.js ***!
\*********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule keyMirror
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(/*! ./invariant */ 13);
/**
* Constructs an enumeration with keys equal to their value.
*
* For example:
*
* var COLORS = keyMirror({blue: null, red: null});
* var myColor = COLORS.blue;
* var isColorValid = !!COLORS[myColor];
*
* The last line could not be performed if the values of the generated enum were
* not equal to their keys.
*
* Input: {key1: val1, key2: val2}
* Output: {key1: key1, key2: key2}
*
* @param {object} obj
* @return {object}
*/
var keyMirror = function (obj) {
var ret = {};
var key;
!(obj instanceof Object && !Array.isArray(obj)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : undefined;
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 18 */
/*!**********************************!*\
!*** ./~/react/lib/ReactPerf.js ***!
\**********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactPerf
* @typechecks static-only
*/
'use strict';
/**
* ReactPerf is a general AOP system designed to measure performance. This
* module only has the hooks: see ReactDefaultPerf for the analysis tool.
*/
var ReactPerf = {
/**
* Boolean to enable/disable measurement. Set to false by default to prevent
* accidental logging and perf loss.
*/
enableMeasure: false,
/**
* Holds onto the measure function in use. By default, don't measure
* anything, but we'll override this if we inject a measure function.
*/
storedMeasure: _noMeasure,
/**
* @param {object} object
* @param {string} objectName
* @param {object<string>} methodNames
*/
measureMethods: function (object, objectName, methodNames) {
if (process.env.NODE_ENV !== 'production') {
for (var key in methodNames) {
if (!methodNames.hasOwnProperty(key)) {
continue;
}
object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]);
}
}
},
/**
* Use this to wrap methods you want to measure. Zero overhead in production.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
measure: function (objName, fnName, func) {
if (process.env.NODE_ENV !== 'production') {
var measuredFunc = null;
var wrapper = function () {
if (ReactPerf.enableMeasure) {
if (!measuredFunc) {
measuredFunc = ReactPerf.storedMeasure(objName, fnName, func);
}
return measuredFunc.apply(this, arguments);
}
return func.apply(this, arguments);
};
wrapper.displayName = objName + '_' + fnName;
return wrapper;
}
return func;
},
injection: {
/**
* @param {function} measure
*/
injectMeasure: function (measure) {
ReactPerf.storedMeasure = measure;
}
}
};
/**
* Simply passes through the measured function, without measuring it.
*
* @param {string} objName
* @param {string} fnName
* @param {function} func
* @return {function}
*/
function _noMeasure(objName, fnName, func) {
return func;
}
module.exports = ReactPerf;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 19 */
/*!*************************************!*\
!*** ./~/react/lib/setInnerHTML.js ***!
\*************************************/
/***/ (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.
*
* @providesModule setInnerHTML
*/
/* globals MSApp */
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = function (node, html) {
node.innerHTML = html;
};
// Win8 apps: Allow all html to be inserted
if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) {
setInnerHTML = function (node, html) {
MSApp.execUnsafeLocalFunction(function () {
node.innerHTML = html;
});
};
}
if (ExecutionEnvironment.canUseDOM) {
// IE8: When updating a just created node with innerHTML only leading
// whitespace is removed. When updating an existing node with innerHTML
// whitespace in root TextNodes is also collapsed.
// @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html
// Feature detection; only IE8 is known to behave improperly like this.
var testElement = document.createElement('div');
testElement.innerHTML = ' ';
if (testElement.innerHTML === '') {
setInnerHTML = function (node, html) {
// Magic theory: IE8 supposedly differentiates between added and updated
// nodes when processing innerHTML, innerHTML on updated nodes suffers
// from worse whitespace behavior. Re-adding a node like this triggers
// the initial and more favorable whitespace behavior.
// TODO: What to do on a detached node?
if (node.parentNode) {
node.parentNode.replaceChild(node, node);
}
// We also implement a workaround for non-visible tags disappearing into
// thin air on IE8, this only happens if there is no visible text
// in-front of the non-visible tags. Piggyback on the whitespace fix
// and simply check if any non-visible tags appear in the source.
if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) {
// Recover leading whitespace by temporarily prepending any character.
// \uFEFF has the potential advantage of being zero-width/invisible.
// UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode
// in hopes that this is preserved even if "\uFEFF" is transformed to
// the actual Unicode character (by Babel, for example).
// https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216
node.innerHTML = String.fromCharCode(0xFEFF) + html;
// deleteData leaves an empty `TextNode` which offsets the index of all
// children. Definitely want to avoid this.
var textNode = node.firstChild;
if (textNode.data.length === 1) {
node.removeChild(textNode);
} else {
textNode.deleteData(0, 1);
}
} else {
node.innerHTML = html;
}
};
}
}
module.exports = setInnerHTML;
/***/ }),
/* 20 */
/*!***************************************!*\
!*** ./~/react/lib/setTextContent.js ***!
\***************************************/
/***/ (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.
*
* @providesModule setTextContent
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var escapeTextContentForBrowser = __webpack_require__(/*! ./escapeTextContentForBrowser */ 21);
var setInnerHTML = __webpack_require__(/*! ./setInnerHTML */ 19);
/**
* Set the textContent property of a node, ensuring that whitespace is preserved
* even in IE8. innerText is a poor substitute for textContent and, among many
* issues, inserts <br> instead of the literal newline chars. innerHTML behaves
* as it should.
*
* @param {DOMElement} node
* @param {string} text
* @internal
*/
var setTextContent = function (node, text) {
node.textContent = text;
};
if (ExecutionEnvironment.canUseDOM) {
if (!('textContent' in document.documentElement)) {
setTextContent = function (node, text) {
setInnerHTML(node, escapeTextContentForBrowser(text));
};
}
}
module.exports = setTextContent;
/***/ }),
/* 21 */
/*!****************************************************!*\
!*** ./~/react/lib/escapeTextContentForBrowser.js ***!
\****************************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule escapeTextContentForBrowser
*/
'use strict';
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'\'': '''
};
var ESCAPE_REGEX = /[&><"']/g;
function escaper(match) {
return ESCAPE_LOOKUP[match];
}
/**
* Escapes text to prevent scripting attacks.
*
* @param {*} text Text value to escape.
* @return {string} An escaped string.
*/
function escapeTextContentForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextContentForBrowser;
/***/ }),
/* 22 */
/*!**********************************************!*\
!*** ./~/react/lib/DOMPropertyOperations.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule DOMPropertyOperations
* @typechecks static-only
*/
'use strict';
var DOMProperty = __webpack_require__(/*! ./DOMProperty */ 23);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var quoteAttributeValueForBrowser = __webpack_require__(/*! ./quoteAttributeValueForBrowser */ 24);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
// Simplified subset
var VALID_ATTRIBUTE_NAME_REGEX = /^[a-zA-Z_][\w\.\-]*$/;
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (validatedAttributeNameCache.hasOwnProperty(attributeName)) {
return true;
}
if (illegalAttributeNameCache.hasOwnProperty(attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : undefined;
return false;
}
function shouldIgnoreValue(propertyInfo, value) {
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
}
if (process.env.NODE_ENV !== 'production') {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function (name) {
if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) {
return;
}
warnedProperties[name] = true;
var lowerCasedName = name.toLowerCase();
// data-* attributes should be lowercase; suggest the lowercase version
var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null;
// For now, only warn when we have a suggested correction. This prevents
// logging too much when using transferPropsTo.
process.env.NODE_ENV !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : undefined;
};
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function (id) {
return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id);
},
setAttributeForID: function (node, id) {
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function (name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) {
return '';
}
var attributeName = propertyInfo.attributeName;
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
return attributeName + '=""';
}
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
} else if (process.env.NODE_ENV !== 'production') {
warnUnknownProperty(name);
}
return null;
},
/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/
createMarkupForCustomAttribute: function (name, value) {
if (!isAttributeNameSafe(name) || value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function (node, name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(propertyInfo, value)) {
this.deleteValueForProperty(node, name);
} else if (propertyInfo.mustUseAttribute) {
var attributeName = propertyInfo.attributeName;
var namespace = propertyInfo.attributeNamespace;
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (namespace) {
node.setAttributeNS(namespace, attributeName, '' + value);
} else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
node.setAttribute(attributeName, '');
} else {
node.setAttribute(attributeName, '' + value);
}
} else {
var propName = propertyInfo.propertyName;
// Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
// property type before comparing; only `value` does and is string.
if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
DOMPropertyOperations.setValueForAttribute(node, name, value);
} else if (process.env.NODE_ENV !== 'production') {
warnUnknownProperty(name);
}
},
setValueForAttribute: function (node, name, value) {
if (!isAttributeNameSafe(name)) {
return;
}
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function (node, name) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (propertyInfo.mustUseAttribute) {
node.removeAttribute(propertyInfo.attributeName);
} else {
var propName = propertyInfo.propertyName;
var defaultValue = DOMProperty.getDefaultValueForProperty(node.nodeName, propName);
if (!propertyInfo.hasSideEffects || '' + node[propName] !== defaultValue) {
node[propName] = defaultValue;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
} else if (process.env.NODE_ENV !== 'production') {
warnUnknownProperty(name);
}
}
};
ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', {
setValueForProperty: 'setValueForProperty',
setValueForAttribute: 'setValueForAttribute',
deleteValueForProperty: 'deleteValueForProperty'
});
module.exports = DOMPropertyOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 23 */
/*!************************************!*\
!*** ./~/react/lib/DOMProperty.js ***!
\************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule DOMProperty
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
function checkMask(value, bitmask) {
return (value & bitmask) === bitmask;
}
var DOMPropertyInjection = {
/**
* Mapping from normalized, camelcased property names to a configuration that
* specifies how the associated DOM property should be accessed or rendered.
*/
MUST_USE_ATTRIBUTE: 0x1,
MUST_USE_PROPERTY: 0x2,
HAS_SIDE_EFFECTS: 0x4,
HAS_BOOLEAN_VALUE: 0x8,
HAS_NUMERIC_VALUE: 0x10,
HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x40,
/**
* Inject some specialized knowledge about the DOM. This takes a config object
* with the following properties:
*
* isCustomAttribute: function that given an attribute name will return true
* if it can be inserted into the DOM verbatim. Useful for data-* or aria-*
* attributes where it's impossible to enumerate all of the possible
* attribute names,
*
* Properties: object mapping DOM property name to one of the
* DOMPropertyInjection constants or null. If your attribute isn't in here,
* it won't get written to the DOM.
*
* DOMAttributeNames: object mapping React attribute name to the DOM
* attribute name. Attribute names not specified use the **lowercase**
* normalized name.
*
* DOMAttributeNamespaces: object mapping React attribute name to the DOM
* attribute namespace URL. (Attribute names not specified use no namespace.)
*
* DOMPropertyNames: similar to DOMAttributeNames but for DOM properties.
* Property names not specified use the normalized name.
*
* DOMMutationMethods: Properties that require special mutation methods. If
* `value` is undefined, the mutation method should unset the property.
*
* @param {object} domPropertyConfig the config as described above.
*/
injectDOMPropertyConfig: function (domPropertyConfig) {
var Injection = DOMPropertyInjection;
var Properties = domPropertyConfig.Properties || {};
var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {};
var DOMAttributeNames = domPropertyConfig.DOMAttributeNames || {};
var DOMPropertyNames = domPropertyConfig.DOMPropertyNames || {};
var DOMMutationMethods = domPropertyConfig.DOMMutationMethods || {};
if (domPropertyConfig.isCustomAttribute) {
DOMProperty._isCustomAttributeFunctions.push(domPropertyConfig.isCustomAttribute);
}
for (var propName in Properties) {
!!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : undefined;
var lowerCased = propName.toLowerCase();
var propConfig = Properties[propName];
var propertyInfo = {
attributeName: lowerCased,
attributeNamespace: null,
propertyName: propName,
mutationMethod: null,
mustUseAttribute: checkMask(propConfig, Injection.MUST_USE_ATTRIBUTE),
mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY),
hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS),
hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE),
hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE),
hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE),
hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE)
};
!(!propertyInfo.mustUseAttribute || !propertyInfo.mustUseProperty) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Cannot require using both attribute and property: %s', propName) : invariant(false) : undefined;
!(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : undefined;
!(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
DOMProperty.getPossibleStandardName[lowerCased] = propName;
}
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
propertyInfo.attributeName = attributeName;
if (process.env.NODE_ENV !== 'production') {
DOMProperty.getPossibleStandardName[attributeName] = propName;
}
}
if (DOMAttributeNamespaces.hasOwnProperty(propName)) {
propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName];
}
if (DOMPropertyNames.hasOwnProperty(propName)) {
propertyInfo.propertyName = DOMPropertyNames[propName];
}
if (DOMMutationMethods.hasOwnProperty(propName)) {
propertyInfo.mutationMethod = DOMMutationMethods[propName];
}
DOMProperty.properties[propName] = propertyInfo;
}
}
};
var defaultValueCache = {};
/**
* DOMProperty exports lookup objects that can be used like functions:
*
* > DOMProperty.isValid['id']
* true
* > DOMProperty.isValid['foobar']
* undefined
*
* Although this may be confusing, it performs better in general.
*
* @see http://jsperf.com/key-exists
* @see http://jsperf.com/key-missing
*/
var DOMProperty = {
ID_ATTRIBUTE_NAME: 'data-reactid',
/**
* Map from property "standard name" to an object with info about how to set
* the property in the DOM. Each object contains:
*
* attributeName:
* Used when rendering markup or with `*Attribute()`.
* attributeNamespace
* propertyName:
* Used on DOM node instances. (This includes properties that mutate due to
* external factors.)
* mutationMethod:
* If non-null, used instead of the property or `setAttribute()` after
* initial render.
* mustUseAttribute:
* Whether the property must be accessed and mutated using `*Attribute()`.
* (This includes anything that fails `<propName> in <element>`.)
* mustUseProperty:
* Whether the property must be accessed and mutated as an object property.
* hasSideEffects:
* Whether or not setting a value causes side effects such as triggering
* resources to be loaded or text selection changes. If true, we read from
* the DOM before updating to ensure that the value is only set if it has
* changed.
* hasBooleanValue:
* Whether the property should be removed when set to a falsey value.
* hasNumericValue:
* Whether the property must be numeric or parse as a numeric and should be
* removed when set to a falsey value.
* hasPositiveNumericValue:
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* hasOverloadedBooleanValue:
* Whether the property can be used as a flag as well as with a value.
* Removed when strictly equal to false; present without a value when
* strictly equal to true; present with a value otherwise.
*/
properties: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties. Available only in __DEV__.
* @type {Object}
*/
getPossibleStandardName: process.env.NODE_ENV !== 'production' ? {} : null,
/**
* All of the isCustomAttribute() functions that have been injected.
*/
_isCustomAttributeFunctions: [],
/**
* Checks whether a property name is a custom attribute.
* @method
*/
isCustomAttribute: function (attributeName) {
for (var i = 0; i < DOMProperty._isCustomAttributeFunctions.length; i++) {
var isCustomAttributeFn = DOMProperty._isCustomAttributeFunctions[i];
if (isCustomAttributeFn(attributeName)) {
return true;
}
}
return false;
},
/**
* Returns the default property value for a DOM property (i.e., not an
* attribute). Most default values are '' or false, but not all. Worse yet,
* some (in particular, `type`) vary depending on the type of element.
*
* TODO: Is it better to grab all the possible properties when creating an
* element to avoid having to create the same element twice?
*/
getDefaultValueForProperty: function (nodeName, prop) {
var nodeDefaults = defaultValueCache[nodeName];
var testElement;
if (!nodeDefaults) {
defaultValueCache[nodeName] = nodeDefaults = {};
}
if (!(prop in nodeDefaults)) {
testElement = document.createElement(nodeName);
nodeDefaults[prop] = testElement[prop];
}
return nodeDefaults[prop];
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 24 */
/*!******************************************************!*\
!*** ./~/react/lib/quoteAttributeValueForBrowser.js ***!
\******************************************************/
/***/ (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.
*
* @providesModule quoteAttributeValueForBrowser
*/
'use strict';
var escapeTextContentForBrowser = __webpack_require__(/*! ./escapeTextContentForBrowser */ 21);
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Value to escape.
* @return {string} An escaped string.
*/
function quoteAttributeValueForBrowser(value) {
return '"' + escapeTextContentForBrowser(value) + '"';
}
module.exports = quoteAttributeValueForBrowser;
/***/ }),
/* 25 */
/*!*******************************!*\
!*** ./~/fbjs/lib/warning.js ***!
\*******************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule warning
*/
'use strict';
var emptyFunction = __webpack_require__(/*! ./emptyFunction */ 15);
/**
* 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 (process.env.NODE_ENV !== 'production') {
warning = function (condition, format) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _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.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
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) {}
}
};
}
module.exports = warning;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 26 */
/*!*********************************************************!*\
!*** ./~/react/lib/ReactComponentBrowserEnvironment.js ***!
\*********************************************************/
/***/ (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.
*
* @providesModule ReactComponentBrowserEnvironment
*/
'use strict';
var ReactDOMIDOperations = __webpack_require__(/*! ./ReactDOMIDOperations */ 27);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
/**
* Abstracts away all functionality of the reconciler that requires knowledge of
* the browser context. TODO: These callers should be refactored to avoid the
* need for this injection.
*/
var ReactComponentBrowserEnvironment = {
processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates,
replaceNodeWithMarkupByID: ReactDOMIDOperations.dangerouslyReplaceNodeWithMarkupByID,
/**
* If a particular environment requires that some resources be cleaned up,
* specify this in the injected Mixin. In the DOM, we would likely want to
* purge any cached node ID lookups.
*
* @private
*/
unmountIDFromEnvironment: function (rootNodeID) {
ReactMount.purgeID(rootNodeID);
}
};
module.exports = ReactComponentBrowserEnvironment;
/***/ }),
/* 27 */
/*!*********************************************!*\
!*** ./~/react/lib/ReactDOMIDOperations.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOMIDOperations
* @typechecks static-only
*/
'use strict';
var DOMChildrenOperations = __webpack_require__(/*! ./DOMChildrenOperations */ 7);
var DOMPropertyOperations = __webpack_require__(/*! ./DOMPropertyOperations */ 22);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* Errors for properties that should not be updated with `updatePropertyByID()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML: '`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* Operations used to process updates to DOM nodes.
*/
var ReactDOMIDOperations = {
/**
* Updates a DOM node with new property values. This should only be used to
* update DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A valid property name, see `DOMProperty`.
* @param {*} value New value of the property.
* @internal
*/
updatePropertyByID: function (id, name, value) {
var node = ReactMount.getNode(id);
!!INVALID_PROPERTY_ERRORS.hasOwnProperty(name) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updatePropertyByID(...): %s', INVALID_PROPERTY_ERRORS[name]) : invariant(false) : undefined;
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (value != null) {
DOMPropertyOperations.setValueForProperty(node, name, value);
} else {
DOMPropertyOperations.deleteValueForProperty(node, name);
}
},
/**
* Replaces a DOM node that exists in the document with markup.
*
* @param {string} id ID of child to be replaced.
* @param {string} markup Dangerous markup to inject in place of child.
* @internal
* @see {Danger.dangerouslyReplaceNodeWithMarkup}
*/
dangerouslyReplaceNodeWithMarkupByID: function (id, markup) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
},
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markup List of markup strings.
* @internal
*/
dangerouslyProcessChildrenUpdates: function (updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
};
ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', {
dangerouslyReplaceNodeWithMarkupByID: 'dangerouslyReplaceNodeWithMarkupByID',
dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates'
});
module.exports = ReactDOMIDOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 28 */
/*!***********************************!*\
!*** ./~/react/lib/ReactMount.js ***!
\***********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactMount
*/
'use strict';
var DOMProperty = __webpack_require__(/*! ./DOMProperty */ 23);
var ReactBrowserEventEmitter = __webpack_require__(/*! ./ReactBrowserEventEmitter */ 29);
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var ReactDOMFeatureFlags = __webpack_require__(/*! ./ReactDOMFeatureFlags */ 41);
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactEmptyComponentRegistry = __webpack_require__(/*! ./ReactEmptyComponentRegistry */ 44);
var ReactInstanceHandles = __webpack_require__(/*! ./ReactInstanceHandles */ 45);
var ReactInstanceMap = __webpack_require__(/*! ./ReactInstanceMap */ 47);
var ReactMarkupChecksum = __webpack_require__(/*! ./ReactMarkupChecksum */ 48);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var ReactReconciler = __webpack_require__(/*! ./ReactReconciler */ 50);
var ReactUpdateQueue = __webpack_require__(/*! ./ReactUpdateQueue */ 53);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ 58);
var containsNode = __webpack_require__(/*! fbjs/lib/containsNode */ 59);
var instantiateReactComponent = __webpack_require__(/*! ./instantiateReactComponent */ 62);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var setInnerHTML = __webpack_require__(/*! ./setInnerHTML */ 19);
var shouldUpdateReactComponent = __webpack_require__(/*! ./shouldUpdateReactComponent */ 67);
var validateDOMNesting = __webpack_require__(/*! ./validateDOMNesting */ 70);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var nodeCache = {};
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
var ownerDocumentContextKey = '__ReactMount_ownerDocument$' + Math.random().toString(36).slice(2);
/** Mapping from reactRootID to React component instance. */
var instancesByReactRootID = {};
/** Mapping from reactRootID to `container` nodes. */
var containersByReactRootID = {};
if (process.env.NODE_ENV !== 'production') {
/** __DEV__-only mapping from reactRootID to root elements. */
var rootElementsByReactRootID = {};
}
// Used to store breadth-first search state in findComponentRoot.
var findComponentRootReusableArray = [];
/**
* Finds the index of the first character
* that's not common between the two given strings.
*
* @return {number} the index of the character where the strings diverge
*/
function firstDifferenceIndex(string1, string2) {
var minLen = Math.min(string1.length, string2.length);
for (var i = 0; i < minLen; i++) {
if (string1.charAt(i) !== string2.charAt(i)) {
return i;
}
}
return string1.length === string2.length ? -1 : minLen;
}
/**
* @param {DOMElement|DOMDocument} container DOM element that may contain
* a React component
* @return {?*} DOM element that may have the reactRoot ID, or null.
*/
function getReactRootElementInContainer(container) {
if (!container) {
return null;
}
if (container.nodeType === DOC_NODE_TYPE) {
return container.documentElement;
} else {
return container.firstChild;
}
}
/**
* @param {DOMElement} container DOM element that may contain a React component.
* @return {?string} A "reactRoot" ID, if a React component is rendered.
*/
function getReactRootID(container) {
var rootElement = getReactRootElementInContainer(container);
return rootElement && ReactMount.getID(rootElement);
}
/**
* Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
* element can return its control whose name or ID equals ATTR_NAME. All
* DOM nodes support `getAttributeNode` but this can also get called on
* other objects so just return '' if we're given something other than a
* DOM node (such as window).
*
* @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
* @return {string} ID of the supplied `domNode`.
*/
function getID(node) {
var id = internalGetID(node);
if (id) {
if (nodeCache.hasOwnProperty(id)) {
var cached = nodeCache[id];
if (cached !== node) {
!!isValid(cached, id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Two valid but unequal nodes with the same `%s`: %s', ATTR_NAME, id) : invariant(false) : undefined;
nodeCache[id] = node;
}
} else {
nodeCache[id] = node;
}
}
return id;
}
function internalGetID(node) {
// If node is something like a window, document, or text node, none of
// which support attributes or a .getAttribute method, gracefully return
// the empty string, as if the attribute were missing.
return node && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Sets the React-specific ID of the given node.
*
* @param {DOMElement} node The DOM node whose ID will be set.
* @param {string} id The value of the ID attribute.
*/
function setID(node, id) {
var oldID = internalGetID(node);
if (oldID !== id) {
delete nodeCache[oldID];
}
node.setAttribute(ATTR_NAME, id);
nodeCache[id] = node;
}
/**
* Finds the node with the supplied React-generated DOM ID.
*
* @param {string} id A React-generated DOM ID.
* @return {DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNode(id) {
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* Finds the node with the supplied public React instance.
*
* @param {*} instance A public React instance.
* @return {?DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNodeFromInstance(instance) {
var id = ReactInstanceMap.get(instance)._rootNodeID;
if (ReactEmptyComponentRegistry.isNullComponentID(id)) {
return null;
}
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* A node is "valid" if it is contained by a currently mounted container.
*
* This means that the node does not have to be contained by a document in
* order to be considered valid.
*
* @param {?DOMElement} node The candidate DOM node.
* @param {string} id The expected ID of the node.
* @return {boolean} Whether the node is contained by a mounted container.
*/
function isValid(node, id) {
if (node) {
!(internalGetID(node) === id) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactMount: Unexpected modification of `%s`', ATTR_NAME) : invariant(false) : undefined;
var container = ReactMount.findReactContainerForID(id);
if (container && containsNode(container, node)) {
return true;
}
}
return false;
}
/**
* Causes the cache to forget about one React-specific ID.
*
* @param {string} id The ID to forget.
*/
function purgeID(id) {
delete nodeCache[id];
}
var deepestNodeSoFar = null;
function findDeepestCachedAncestorImpl(ancestorID) {
var ancestor = nodeCache[ancestorID];
if (ancestor && isValid(ancestor, ancestorID)) {
deepestNodeSoFar = ancestor;
} else {
// This node isn't populated in the cache, so presumably none of its
// descendants are. Break out of the loop.
return false;
}
}
/**
* Return the deepest cached node whose ID is a prefix of `targetID`.
*/
function findDeepestCachedAncestor(targetID) {
deepestNodeSoFar = null;
ReactInstanceHandles.traverseAncestors(targetID, findDeepestCachedAncestorImpl);
var foundNode = deepestNodeSoFar;
deepestNodeSoFar = null;
return foundNode;
}
/**
* Mounts this component and inserts it into the DOM.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function mountComponentIntoNode(componentInstance, rootID, container, transaction, shouldReuseMarkup, context) {
if (ReactDOMFeatureFlags.useCreateElement) {
context = assign({}, context);
if (container.nodeType === DOC_NODE_TYPE) {
context[ownerDocumentContextKey] = container;
} else {
context[ownerDocumentContextKey] = container.ownerDocument;
}
}
if (process.env.NODE_ENV !== 'production') {
if (context === emptyObject) {
context = {};
}
var tag = container.nodeName.toLowerCase();
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(null, tag, null);
}
var markup = ReactReconciler.mountComponent(componentInstance, rootID, transaction, context);
componentInstance._renderedComponent._topLevelWrapper = componentInstance;
ReactMount._mountImageIntoNode(markup, container, shouldReuseMarkup, transaction);
}
/**
* Batched mount.
*
* @param {ReactComponent} componentInstance The instance to mount.
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
*/
function batchedMountComponentIntoNode(componentInstance, rootID, container, shouldReuseMarkup, context) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
/* forceHTML */shouldReuseMarkup);
transaction.perform(mountComponentIntoNode, null, componentInstance, rootID, container, transaction, shouldReuseMarkup, context);
ReactUpdates.ReactReconcileTransaction.release(transaction);
}
/**
* Unmounts a component and removes it from the DOM.
*
* @param {ReactComponent} instance React component instance.
* @param {DOMElement} container DOM element to unmount from.
* @final
* @internal
* @see {ReactMount.unmountComponentAtNode}
*/
function unmountComponentFromNode(instance, container) {
ReactReconciler.unmountComponent(instance);
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
}
/**
* True if the supplied DOM node has a direct React-rendered child that is
* not a React root element. Useful for warning in `render`,
* `unmountComponentAtNode`, etc.
*
* @param {?DOMElement} node The candidate DOM node.
* @return {boolean} True if the DOM element contains a direct child that was
* rendered by React but is not a root element.
* @internal
*/
function hasNonRootReactChild(node) {
var reactRootID = getReactRootID(node);
return reactRootID ? reactRootID !== ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID) : false;
}
/**
* Returns the first (deepest) ancestor of a node which is rendered by this copy
* of React.
*/
function findFirstReactDOMImpl(node) {
// This node might be from another React instance, so we make sure not to
// examine the node cache here
for (; node && node.parentNode !== node; node = node.parentNode) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
continue;
}
var nodeID = internalGetID(node);
if (!nodeID) {
continue;
}
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
// If containersByReactRootID contains the container we find by crawling up
// the tree, we know that this instance of React rendered the node.
// nb. isValid's strategy (with containsNode) does not work because render
// trees may be nested and we don't want a false positive in that case.
var current = node;
var lastID;
do {
lastID = internalGetID(current);
current = current.parentNode;
if (current == null) {
// The passed-in node has been detached from the container it was
// originally rendered into.
return null;
}
} while (lastID !== reactRootID);
if (current === containersByReactRootID[reactRootID]) {
return node;
}
}
return null;
}
/**
* Temporary (?) hack so that we can store all top-level pending updates on
* composites instead of having to worry about different types of components
* here.
*/
var TopLevelWrapper = function () {};
TopLevelWrapper.prototype.isReactComponent = {};
if (process.env.NODE_ENV !== 'production') {
TopLevelWrapper.displayName = 'TopLevelWrapper';
}
TopLevelWrapper.prototype.render = function () {
// this.props is actually a ReactElement
return this.props;
};
/**
* Mounting is the process of initializing a React component by creating its
* representative DOM elements and inserting them into a supplied `container`.
* Any prior content inside `container` is destroyed in the process.
*
* ReactMount.render(
* component,
* document.getElementById('container')
* );
*
* <div id="container"> <-- Supplied `container`.
* <div data-reactid=".3"> <-- Rendered reactRoot of React
* // ... component.
* </div>
* </div>
*
* Inside of `container`, the first element rendered is the "reactRoot".
*/
var ReactMount = {
TopLevelWrapper: TopLevelWrapper,
/** Exposed for debugging purposes **/
_instancesByReactRootID: instancesByReactRootID,
/**
* This is a hook provided to support rendering React components while
* ensuring that the apparent scroll position of its `container` does not
* change.
*
* @param {DOMElement} container The `container` being rendered into.
* @param {function} renderCallback This must be called once to do the render.
*/
scrollMonitor: function (container, renderCallback) {
renderCallback();
},
/**
* Take a component that's already mounted into the DOM and replace its props
* @param {ReactComponent} prevComponent component instance already in the DOM
* @param {ReactElement} nextElement component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function (prevComponent, nextElement, container, callback) {
ReactMount.scrollMonitor(container, function () {
ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback);
}
});
if (process.env.NODE_ENV !== 'production') {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[getReactRootID(container)] = getReactRootElementInContainer(container);
}
return prevComponent;
},
/**
* Register a component into the instance map and starts scroll value
* monitoring
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @return {string} reactRoot ID prefix
*/
_registerComponent: function (nextComponent, container) {
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : undefined;
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var reactRootID = ReactMount.registerContainer(container);
instancesByReactRootID[reactRootID] = nextComponent;
return reactRootID;
},
/**
* Render a new component into the DOM.
* @param {ReactElement} nextElement element to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
var componentInstance = instantiateReactComponent(nextElement, null);
var reactRootID = ReactMount._registerComponent(componentInstance, container);
// The initial render is synchronous but any updates that happen during
// rendering, in componentWillMount or componentDidMount, will be batched
// according to the current batching strategy.
ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, reactRootID, container, shouldReuseMarkup, context);
if (process.env.NODE_ENV !== 'production') {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[reactRootID] = getReactRootElementInContainer(container);
}
return componentInstance;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactComponent} parentComponent The conceptual parent of this render tree.
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!(parentComponent != null && parentComponent._reactInternalInstance != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : undefined;
return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback);
},
_renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) {
!ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing an element string, make sure to instantiate ' + 'it by passing it to React.createElement.' : typeof nextElement === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' :
// Check if it quacks like an element
nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : undefined;
process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', 'render(): Rendering components directly into document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try rendering into a container element created ' + 'for your app.') : undefined;
var nextWrappedElement = new ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement);
var prevComponent = instancesByReactRootID[getReactRootID(container)];
if (prevComponent) {
var prevWrappedElement = prevComponent._currentElement;
var prevElement = prevWrappedElement.props;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
var publicInst = prevComponent._renderedComponent.getPublicInstance();
var updatedCallback = callback && function () {
callback.call(publicInst);
};
ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback);
return publicInst;
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement);
var containerHasNonRootReactChild = hasNonRootReactChild(container);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'render(...): Replacing React-rendered children with a new root ' + 'component. If you intended to update the children of this node, ' + 'you should instead have the existing children update their state ' + 'and render the new components instead of calling ReactDOM.render.') : undefined;
if (!containerHasReactMarkup || reactRootElement.nextSibling) {
var rootElementSibling = reactRootElement;
while (rootElementSibling) {
if (internalGetID(rootElementSibling)) {
process.env.NODE_ENV !== 'production' ? warning(false, 'render(): Target node has markup rendered by React, but there ' + 'are unrelated nodes as well. This is most commonly caused by ' + 'white-space inserted around server-rendered markup.') : undefined;
break;
}
rootElementSibling = rootElementSibling.nextSibling;
}
}
}
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild;
var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance();
if (callback) {
callback.call(component);
}
return component;
},
/**
* Renders a React component into the DOM in the supplied `container`.
*
* If the React component was previously rendered into `container`, this will
* perform an update on it and only mutate the DOM as necessary to reflect the
* latest React component.
*
* @param {ReactElement} nextElement Component element to render.
* @param {DOMElement} container DOM element to render into.
* @param {?function} callback function triggered on completion
* @return {ReactComponent} Component instance rendered in `container`.
*/
render: function (nextElement, container, callback) {
return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback);
},
/**
* Registers a container node into which React components will be rendered.
* This also creates the "reactRoot" ID that will be assigned to the element
* rendered within.
*
* @param {DOMElement} container DOM element to register as a container.
* @return {string} The "reactRoot" ID of elements rendered within.
*/
registerContainer: function (container) {
var reactRootID = getReactRootID(container);
if (reactRootID) {
// If one exists, make sure it is a valid "reactRoot" ID.
reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(reactRootID);
}
if (!reactRootID) {
// No valid "reactRoot" ID found, create one.
reactRootID = ReactInstanceHandles.createReactRootID();
}
containersByReactRootID[reactRootID] = container;
return reactRootID;
},
/**
* Unmounts and destroys the React component rendered in the `container`.
*
* @param {DOMElement} container DOM element containing a React component.
* @return {boolean} True if a component was found in and unmounted from
* `container`
*/
unmountComponentAtNode: function (container) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (Strictly speaking, unmounting won't cause a
// render but we still don't expect to be in a render call here.)
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : undefined;
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : undefined;
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
// Check if the node being unmounted was rendered by React, but isn't a
// root node.
var containerHasNonRootReactChild = hasNonRootReactChild(container);
// Check if the container itself is a React root node.
var containerID = internalGetID(container);
var isContainerReactRoot = containerID && containerID === ReactInstanceHandles.getReactRootIDFromNodeID(containerID);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? 'You may have accidentally passed in a React root node instead ' + 'of its container.' : 'Instead, have the parent component update its state and ' + 'rerender in order to remove this component.') : undefined;
}
return false;
}
ReactUpdates.batchedUpdates(unmountComponentFromNode, component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if (process.env.NODE_ENV !== 'production') {
delete rootElementsByReactRootID[reactRootID];
}
return true;
},
/**
* Finds the container DOM element that contains React component to which the
* supplied DOM `id` belongs.
*
* @param {string} id The ID of an element rendered by a React component.
* @return {?DOMElement} DOM element that contains the `id`.
*/
findReactContainerForID: function (id) {
var reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
var container = containersByReactRootID[reactRootID];
if (process.env.NODE_ENV !== 'production') {
var rootElement = rootElementsByReactRootID[reactRootID];
if (rootElement && rootElement.parentNode !== container) {
process.env.NODE_ENV !== 'production' ? warning(
// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID, 'ReactMount: Root element ID differed from reactRootID.') : undefined;
var containerChild = container.firstChild;
if (containerChild && reactRootID === internalGetID(containerChild)) {
// If the container has a new child with the same ID as the old
// root element, then rootElementsByReactRootID[reactRootID] is
// just stale and needs to be updated. The case that deserves a
// warning is when the container is empty.
rootElementsByReactRootID[reactRootID] = containerChild;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactMount: Root element has been removed from its original ' + 'container. New container: %s', rootElement.parentNode) : undefined;
}
}
}
return container;
},
/**
* Finds an element rendered by React with the supplied ID.
*
* @param {string} id ID of a DOM node in the React component.
* @return {DOMElement} Root DOM node of the React component.
*/
findReactNodeByID: function (id) {
var reactRoot = ReactMount.findReactContainerForID(id);
return ReactMount.findComponentRoot(reactRoot, id);
},
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component rendered by this copy of React.
*
* @param {*} node
* @return {?DOMEventTarget}
* @internal
*/
getFirstReactDOM: function (node) {
return findFirstReactDOMImpl(node);
},
/**
* Finds a node with the supplied `targetID` inside of the supplied
* `ancestorNode`. Exploits the ID naming scheme to perform the search
* quickly.
*
* @param {DOMEventTarget} ancestorNode Search from this root.
* @pararm {string} targetID ID of the DOM representation of the component.
* @return {DOMEventTarget} DOM node with the supplied `targetID`.
* @internal
*/
findComponentRoot: function (ancestorNode, targetID) {
var firstChildren = findComponentRootReusableArray;
var childIndex = 0;
var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;
if (process.env.NODE_ENV !== 'production') {
// This will throw on the next line; give an early warning
process.env.NODE_ENV !== 'production' ? warning(deepestAncestor != null, 'React can\'t find the root component node for data-reactid value ' + '`%s`. If you\'re seeing this message, it probably means that ' + 'you\'ve loaded two copies of React on the page. At this time, only ' + 'a single copy of React can be loaded at a time.', targetID) : undefined;
}
firstChildren[0] = deepestAncestor.firstChild;
firstChildren.length = 1;
while (childIndex < firstChildren.length) {
var child = firstChildren[childIndex++];
var targetChild;
while (child) {
var childID = ReactMount.getID(child);
if (childID) {
// Even if we find the node we're looking for, we finish looping
// through its siblings to ensure they're cached so that we don't have
// to revisit this node again. Otherwise, we make n^2 calls to getID
// when visiting the many children of a single node in order.
if (targetID === childID) {
targetChild = child;
} else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
// If we find a child whose ID is an ancestor of the given ID,
// then we can be sure that we only want to search the subtree
// rooted at this child, so we can throw out the rest of the
// search state.
firstChildren.length = childIndex = 0;
firstChildren.push(child.firstChild);
}
} else {
// If this child had no ID, then there's a chance that it was
// injected automatically by the browser, as when a `<table>`
// element sprouts an extra `<tbody>` child as a side effect of
// `.innerHTML` parsing. Optimistically continue down this
// branch, but not before examining the other siblings.
firstChildren.push(child.firstChild);
}
child = child.nextSibling;
}
if (targetChild) {
// Emptying firstChildren/findComponentRootReusableArray is
// not necessary for correctness, but it helps the GC reclaim
// any nodes that were left at the end of the search.
firstChildren.length = 0;
return targetChild;
}
}
firstChildren.length = 0;
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findComponentRoot(..., %s): Unable to find element. This probably ' + 'means the DOM was unexpectedly mutated (e.g., by the browser), ' + 'usually due to forgetting a <tbody> when using tables, nesting tags ' + 'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' + 'parent. ' + 'Try inspecting the child nodes of the element with React ID `%s`.', targetID, ReactMount.getID(ancestorNode)) : invariant(false) : undefined;
},
_mountImageIntoNode: function (markup, container, shouldReuseMarkup, transaction) {
!(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : undefined;
if (shouldReuseMarkup) {
var rootElement = getReactRootElementInContainer(container);
if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) {
return;
} else {
var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
var rootMarkup = rootElement.outerHTML;
rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum);
var normalizedMarkup = markup;
if (process.env.NODE_ENV !== 'production') {
// because rootMarkup is retrieved from the DOM, various normalizations
// will have occurred which will not be present in `markup`. Here,
// insert markup into a <div> or <iframe> depending on the container
// type to perform the same normalizations before comparing.
var normalizer;
if (container.nodeType === ELEMENT_NODE_TYPE) {
normalizer = document.createElement('div');
normalizer.innerHTML = markup;
normalizedMarkup = normalizer.innerHTML;
} else {
normalizer = document.createElement('iframe');
document.body.appendChild(normalizer);
normalizer.contentDocument.write(markup);
normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML;
document.body.removeChild(normalizer);
}
}
var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup);
var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20);
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document using ' + 'server rendering but the checksum was invalid. This usually ' + 'means you rendered a different component type or props on ' + 'the client from the one on the server, or your render() ' + 'methods are impure. React cannot handle this case due to ' + 'cross-browser quirks by rendering at the document root. You ' + 'should look for environment dependent code in your components ' + 'and ensure the props are the same client and server side:\n%s', difference) : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'React attempted to reuse markup in a container but the ' + 'checksum was invalid. This generally means that you are ' + 'using server rendering and the markup generated on the ' + 'server was not what the client was expecting. React injected ' + 'new markup to compensate which works but you have lost many ' + 'of the benefits of server rendering. Instead, figure out ' + 'why the markup being generated is different on the client ' + 'or server:\n%s', difference) : undefined;
}
}
}
!(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'You\'re trying to render a component to the document but ' + 'you didn\'t use server rendering. We can\'t do this ' + 'without using server rendering due to cross-browser quirks. ' + 'See ReactDOMServer.renderToString() for server rendering.') : invariant(false) : undefined;
if (transaction.useCreateElement) {
while (container.lastChild) {
container.removeChild(container.lastChild);
}
container.appendChild(markup);
} else {
setInnerHTML(container, markup);
}
},
ownerDocumentContextKey: ownerDocumentContextKey,
/**
* React ID utilities.
*/
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
getNodeFromInstance: getNodeFromInstance,
isValid: isValid,
purgeID: purgeID
};
ReactPerf.measureMethods(ReactMount, 'ReactMount', {
_renderNewRootComponent: '_renderNewRootComponent',
_mountImageIntoNode: '_mountImageIntoNode'
});
module.exports = ReactMount;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 29 */
/*!*************************************************!*\
!*** ./~/react/lib/ReactBrowserEventEmitter.js ***!
\*************************************************/
/***/ (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.
*
* @providesModule ReactBrowserEventEmitter
* @typechecks static-only
*/
'use strict';
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var EventPluginHub = __webpack_require__(/*! ./EventPluginHub */ 31);
var EventPluginRegistry = __webpack_require__(/*! ./EventPluginRegistry */ 32);
var ReactEventEmitterMixin = __webpack_require__(/*! ./ReactEventEmitterMixin */ 37);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var ViewportMetrics = __webpack_require__(/*! ./ViewportMetrics */ 38);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var isEventSupported = __webpack_require__(/*! ./isEventSupported */ 40);
/**
* Summary of `ReactBrowserEventEmitter` event handling:
*
* - Top-level delegation is used to trap most native browser events. This
* may only occur in the main thread and is the responsibility of
* ReactEventListener, which is injected and can therefore support pluggable
* event sources. This is the only work that occurs in the main thread.
*
* - We normalize and de-duplicate events to account for browser quirks. This
* may be done in the worker thread.
*
* - Forward these native events (with the associated top-level type used to
* trap it) to `EventPluginHub`, which in turn will ask plugins if they want
* to extract any synthetic events.
*
* - The `EventPluginHub` will then process each event by annotating them with
* "dispatches", a sequence of listeners and IDs that care about that event.
*
* - The `EventPluginHub` then dispatches the events.
*
* Overview of React and the event system:
*
* +------------+ .
* | DOM | .
* +------------+ .
* | .
* v .
* +------------+ .
* | ReactEvent | .
* | Listener | .
* +------------+ . +-----------+
* | . +--------+|SimpleEvent|
* | . | |Plugin |
* +-----|------+ . v +-----------+
* | | | . +--------------+ +------------+
* | +-----------.--->|EventPluginHub| | Event |
* | | . | | +-----------+ | Propagators|
* | ReactEvent | . | | |TapEvent | |------------|
* | Emitter | . | |<---+|Plugin | |other plugin|
* | | . | | +-----------+ | utilities |
* | +-----------.--->| | +------------+
* | | | . +--------------+
* +-----|------+ . ^ +-----------+
* | . | |Enter/Leave|
* + . +-------+|Plugin |
* +-------------+ . +-----------+
* | application | .
* |-------------| .
* | | .
* | | .
* +-------------+ .
* .
* React Core . General Purpose Event Plugin System
*/
var alreadyListeningTo = {};
var isMonitoringScrollValue = false;
var reactTopListenersCounter = 0;
// For events like 'submit' which don't consistently bubble (which we trap at a
// lower node than `document`), binding at `document` would cause duplicate
// events so we don't include them here
var topEventMapping = {
topAbort: 'abort',
topBlur: 'blur',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topScroll: 'scroll',
topSeeked: 'seeked',
topSeeking: 'seeking',
topSelectionChange: 'selectionchange',
topStalled: 'stalled',
topSuspend: 'suspend',
topTextInput: 'textInput',
topTimeUpdate: 'timeupdate',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topVolumeChange: 'volumechange',
topWaiting: 'waiting',
topWheel: 'wheel'
};
/**
* To ensure no conflicts with other potential React instances on the page
*/
var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2);
function getListeningForDocument(mountAt) {
// In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty`
// directly.
if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) {
mountAt[topListenersIDKey] = reactTopListenersCounter++;
alreadyListeningTo[mountAt[topListenersIDKey]] = {};
}
return alreadyListeningTo[mountAt[topListenersIDKey]];
}
/**
* `ReactBrowserEventEmitter` is used to attach top-level event listeners. For
* example:
*
* ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction);
*
* This would allocate a "registration" of `('onClick', myFunction)` on 'myID'.
*
* @internal
*/
var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, {
/**
* Injectable event backend
*/
ReactEventListener: null,
injection: {
/**
* @param {object} ReactEventListener
*/
injectReactEventListener: function (ReactEventListener) {
ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel);
ReactBrowserEventEmitter.ReactEventListener = ReactEventListener;
}
},
/**
* Sets whether or not any created callbacks should be enabled.
*
* @param {boolean} enabled True if callbacks should be enabled.
*/
setEnabled: function (enabled) {
if (ReactBrowserEventEmitter.ReactEventListener) {
ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled);
}
},
/**
* @return {boolean} True if callbacks are enabled.
*/
isEnabled: function () {
return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled());
},
/**
* We listen for bubbled touch events on the document object.
*
* Firefox v8.01 (and possibly others) exhibited strange behavior when
* mounting `onmousemove` events at some node that was not the document
* element. The symptoms were that if your mouse is not moving over something
* contained within that mount point (for example on the background) the
* top-level listeners for `onmousemove` won't be called. However, if you
* register the `mousemove` on the document object, then it will of course
* catch all `mousemove`s. This along with iOS quirks, justifies restricting
* top-level listeners to the document object only, at least for these
* movement types of events and possibly all events.
*
* @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html
*
* Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but
* they bubble to document.
*
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {object} contentDocumentHandle Document which owns the container
*/
listenTo: function (registrationName, contentDocumentHandle) {
var mountAt = contentDocumentHandle;
var isListening = getListeningForDocument(mountAt);
var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName];
var topLevelTypes = EventConstants.topLevelTypes;
for (var i = 0; i < dependencies.length; i++) {
var dependency = dependencies[i];
if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) {
if (dependency === topLevelTypes.topWheel) {
if (isEventSupported('wheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt);
} else if (isEventSupported('mousewheel')) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt);
} else {
// Firefox needs to capture a different mouse scroll event.
// @see http://www.quirksmode.org/dom/events/tests/scroll.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt);
}
} else if (dependency === topLevelTypes.topScroll) {
if (isEventSupported('scroll', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt);
} else {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE);
}
} else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) {
if (isEventSupported('focus', true)) {
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt);
} else if (isEventSupported('focusin')) {
// IE has `focusin` and `focusout` events which bubble.
// @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt);
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt);
}
// to make sure blur and focus event listeners are only attached once
isListening[topLevelTypes.topBlur] = true;
isListening[topLevelTypes.topFocus] = true;
} else if (topEventMapping.hasOwnProperty(dependency)) {
ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt);
}
isListening[dependency] = true;
}
}
},
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle);
},
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle);
},
/**
* Listens to window scroll and resize events. We cache scroll values so that
* application code can access them without triggering reflows.
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function () {
if (!isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
},
eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs,
registrationNameModules: EventPluginHub.registrationNameModules,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteListener: EventPluginHub.deleteListener,
deleteAllListeners: EventPluginHub.deleteAllListeners
});
ReactPerf.measureMethods(ReactBrowserEventEmitter, 'ReactBrowserEventEmitter', {
putListener: 'putListener',
deleteListener: 'deleteListener'
});
module.exports = ReactBrowserEventEmitter;
/***/ }),
/* 30 */
/*!***************************************!*\
!*** ./~/react/lib/EventConstants.js ***!
\***************************************/
/***/ (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.
*
* @providesModule EventConstants
*/
'use strict';
var keyMirror = __webpack_require__(/*! fbjs/lib/keyMirror */ 17);
var PropagationPhases = keyMirror({ bubbled: null, captured: null });
/**
* Types of raw signals from the browser caught at the top level.
*/
var topLevelTypes = keyMirror({
topAbort: null,
topBlur: null,
topCanPlay: null,
topCanPlayThrough: null,
topChange: null,
topClick: null,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topDurationChange: null,
topEmptied: null,
topEncrypted: null,
topEnded: null,
topError: null,
topFocus: null,
topInput: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topLoadedData: null,
topLoadedMetadata: null,
topLoadStart: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topPause: null,
topPlay: null,
topPlaying: null,
topProgress: null,
topRateChange: null,
topReset: null,
topScroll: null,
topSeeked: null,
topSeeking: null,
topSelectionChange: null,
topStalled: null,
topSubmit: null,
topSuspend: null,
topTextInput: null,
topTimeUpdate: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topVolumeChange: null,
topWaiting: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
/***/ }),
/* 31 */
/*!***************************************!*\
!*** ./~/react/lib/EventPluginHub.js ***!
\***************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule EventPluginHub
*/
'use strict';
var EventPluginRegistry = __webpack_require__(/*! ./EventPluginRegistry */ 32);
var EventPluginUtils = __webpack_require__(/*! ./EventPluginUtils */ 33);
var ReactErrorUtils = __webpack_require__(/*! ./ReactErrorUtils */ 34);
var accumulateInto = __webpack_require__(/*! ./accumulateInto */ 35);
var forEachAccumulated = __webpack_require__(/*! ./forEachAccumulated */ 36);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
/**
* Internal store for event listeners
*/
var listenerBank = {};
/**
* Internal queue of events that have accumulated their dispatches and are
* waiting to have their dispatches executed.
*/
var eventQueue = null;
/**
* Dispatches an event and releases it back into the pool, unless persistent.
*
* @param {?object} event Synthetic event to be dispatched.
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @private
*/
var executeDispatchesAndRelease = function (event, simulated) {
if (event) {
EventPluginUtils.executeDispatchesInOrder(event, simulated);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
var executeDispatchesAndReleaseSimulated = function (e) {
return executeDispatchesAndRelease(e, true);
};
var executeDispatchesAndReleaseTopLevel = function (e) {
return executeDispatchesAndRelease(e, false);
};
/**
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
* hierarchy given ids of the logical DOM elements involved.
*/
var InstanceHandle = null;
function validateInstanceHandle() {
var valid = InstanceHandle && InstanceHandle.traverseTwoPhase && InstanceHandle.traverseEnterLeave;
process.env.NODE_ENV !== 'production' ? warning(valid, 'InstanceHandle not injected before use!') : undefined;
}
/**
* This is a unified interface for event plugins to be installed and configured.
*
* Event plugins can implement the following properties:
*
* `extractEvents` {function(string, DOMEventTarget, string, object): *}
* Required. When a top-level event is fired, this method is expected to
* extract synthetic events that will in turn be queued and dispatched.
*
* `eventTypes` {object}
* Optional, plugins that fire events must publish a mapping of registration
* names that are used to register listeners. Values of this mapping must
* be objects that contain `registrationName` or `phasedRegistrationNames`.
*
* `executeDispatch` {function(object, function, string)}
* Optional, allows plugins to override how an event gets dispatched. By
* default, the listener is simply invoked.
*
* Each plugin that is injected into `EventsPluginHub` is immediately operable.
*
* @public
*/
var EventPluginHub = {
/**
* Methods for injecting dependencies.
*/
injection: {
/**
* @param {object} InjectedMount
* @public
*/
injectMount: EventPluginUtils.injection.injectMount,
/**
* @param {object} InjectedInstanceHandle
* @public
*/
injectInstanceHandle: function (InjectedInstanceHandle) {
InstanceHandle = InjectedInstanceHandle;
if (process.env.NODE_ENV !== 'production') {
validateInstanceHandle();
}
},
getInstanceHandle: function () {
if (process.env.NODE_ENV !== 'production') {
validateInstanceHandle();
}
return InstanceHandle;
},
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs,
registrationNameModules: EventPluginRegistry.registrationNameModules,
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {?function} listener The callback to store.
*/
putListener: function (id, registrationName, listener) {
!(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : undefined;
var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = listener;
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.didPutListener) {
PluginModule.didPutListener(id, registrationName, listener);
}
},
/**
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function (id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[id];
},
/**
* Deletes a listener from the registration bank.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function (id, registrationName) {
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(id, registrationName);
}
var bankForRegistrationName = listenerBank[registrationName];
// TODO: This should never be null -- when is it?
if (bankForRegistrationName) {
delete bankForRegistrationName[id];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {string} id ID of the DOM element.
*/
deleteAllListeners: function (id) {
for (var registrationName in listenerBank) {
if (!listenerBank[registrationName][id]) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[registrationName];
if (PluginModule && PluginModule.willDeleteListener) {
PluginModule.willDeleteListener(id, registrationName);
}
delete listenerBank[registrationName][id];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0; i < plugins.length; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget);
if (extractedEvents) {
events = accumulateInto(events, extractedEvents);
}
}
}
return events;
},
/**
* Enqueues a synthetic event that should be dispatched when
* `processEventQueue` is invoked.
*
* @param {*} events An accumulation of synthetic events.
* @internal
*/
enqueueEvents: function (events) {
if (events) {
eventQueue = accumulateInto(eventQueue, events);
}
},
/**
* Dispatches all synthetic events on the event queue.
*
* @internal
*/
processEventQueue: function (simulated) {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
if (simulated) {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated);
} else {
forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel);
}
!!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : undefined;
// This would be a good time to rethrow if any of the event handlers threw.
ReactErrorUtils.rethrowCaughtError();
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function () {
listenerBank = {};
},
__getListenerBank: function () {
return listenerBank;
}
};
module.exports = EventPluginHub;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 32 */
/*!********************************************!*\
!*** ./~/react/lib/EventPluginRegistry.js ***!
\********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule EventPluginRegistry
* @typechecks static-only
*/
'use strict';
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* Injectable ordering of event plugins.
*/
var EventPluginOrder = null;
/**
* Injectable mapping from names to event plugin modules.
*/
var namesToPlugins = {};
/**
* Recomputes the plugin list using the injected plugins and plugin ordering.
*
* @private
*/
function recomputePluginOrdering() {
if (!EventPluginOrder) {
// Wait until an `EventPluginOrder` is injected.
return;
}
for (var pluginName in namesToPlugins) {
var PluginModule = namesToPlugins[pluginName];
var pluginIndex = EventPluginOrder.indexOf(pluginName);
!(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : undefined;
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
!PluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : undefined;
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
!publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : undefined;
}
}
}
/**
* Publishes an event so that it can be dispatched by the supplied plugin.
*
* @param {object} dispatchConfig Dispatch configuration for the event.
* @param {object} PluginModule Plugin publishing the event.
* @return {boolean} True if the event was successfully published.
* @private
*/
function publishEventForPlugin(dispatchConfig, PluginModule, eventName) {
!!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : undefined;
EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig;
var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames;
if (phasedRegistrationNames) {
for (var phaseName in phasedRegistrationNames) {
if (phasedRegistrationNames.hasOwnProperty(phaseName)) {
var phasedRegistrationName = phasedRegistrationNames[phaseName];
publishRegistrationName(phasedRegistrationName, PluginModule, eventName);
}
}
return true;
} else if (dispatchConfig.registrationName) {
publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName);
return true;
}
return false;
}
/**
* Publishes a registration name that is used to identify dispatched events and
* can be used with `EventPluginHub.putListener` to register listeners.
*
* @param {string} registrationName Registration name to add.
* @param {object} PluginModule Plugin publishing the event.
* @private
*/
function publishRegistrationName(registrationName, PluginModule, eventName) {
!!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : undefined;
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies;
}
/**
* Registers plugins so that they can extract and dispatch events.
*
* @see {EventPluginHub}
*/
var EventPluginRegistry = {
/**
* Ordered list of injected plugins.
*/
plugins: [],
/**
* Mapping from event name to dispatch config
*/
eventNameDispatchConfigs: {},
/**
* Mapping from registration name to plugin module
*/
registrationNameModules: {},
/**
* Mapping from registration name to event name
*/
registrationNameDependencies: {},
/**
* Injects an ordering of plugins (by plugin name). This allows the ordering
* to be decoupled from injection of the actual plugins so that ordering is
* always deterministic regardless of packaging, on-the-fly injection, etc.
*
* @param {array} InjectedEventPluginOrder
* @internal
* @see {EventPluginHub.injection.injectEventPluginOrder}
*/
injectEventPluginOrder: function (InjectedEventPluginOrder) {
!!EventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : undefined;
// Clone the ordering so it cannot be dynamically mutated.
EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder);
recomputePluginOrdering();
},
/**
* Injects plugins to be used by `EventPluginHub`. The plugin names must be
* in the ordering injected by `injectEventPluginOrder`.
*
* Plugins can be injected as part of page initialization or on-the-fly.
*
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
* @internal
* @see {EventPluginHub.injection.injectEventPluginsByName}
*/
injectEventPluginsByName: function (injectedNamesToPlugins) {
var isOrderingDirty = false;
for (var pluginName in injectedNamesToPlugins) {
if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) {
continue;
}
var PluginModule = injectedNamesToPlugins[pluginName];
if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) {
!!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : undefined;
namesToPlugins[pluginName] = PluginModule;
isOrderingDirty = true;
}
}
if (isOrderingDirty) {
recomputePluginOrdering();
}
},
/**
* Looks up the plugin for the supplied event.
*
* @param {object} event A synthetic event.
* @return {?object} The plugin that created the supplied event.
* @internal
*/
getPluginModuleForEvent: function (event) {
var dispatchConfig = event.dispatchConfig;
if (dispatchConfig.registrationName) {
return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null;
}
for (var phase in dispatchConfig.phasedRegistrationNames) {
if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) {
continue;
}
var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];
if (PluginModule) {
return PluginModule;
}
}
return null;
},
/**
* Exposed for unit testing.
* @private
*/
_resetEventPlugins: function () {
EventPluginOrder = null;
for (var pluginName in namesToPlugins) {
if (namesToPlugins.hasOwnProperty(pluginName)) {
delete namesToPlugins[pluginName];
}
}
EventPluginRegistry.plugins.length = 0;
var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs;
for (var eventName in eventNameDispatchConfigs) {
if (eventNameDispatchConfigs.hasOwnProperty(eventName)) {
delete eventNameDispatchConfigs[eventName];
}
}
var registrationNameModules = EventPluginRegistry.registrationNameModules;
for (var registrationName in registrationNameModules) {
if (registrationNameModules.hasOwnProperty(registrationName)) {
delete registrationNameModules[registrationName];
}
}
}
};
module.exports = EventPluginRegistry;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 33 */
/*!*****************************************!*\
!*** ./~/react/lib/EventPluginUtils.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule EventPluginUtils
*/
'use strict';
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var ReactErrorUtils = __webpack_require__(/*! ./ReactErrorUtils */ 34);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
/**
* Injected dependencies:
*/
/**
* - `Mount`: [required] Module that can convert between React dom IDs and
* actual node references.
*/
var injection = {
Mount: null,
injectMount: function (InjectedMount) {
injection.Mount = InjectedMount;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(InjectedMount && InjectedMount.getNode && InjectedMount.getID, 'EventPluginUtils.injection.injectMount(...): Injected Mount ' + 'module is missing getNode or getID.') : undefined;
}
}
};
var topLevelTypes = EventConstants.topLevelTypes;
function isEndish(topLevelType) {
return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel;
}
function isMoveish(topLevelType) {
return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove;
}
function isStartish(topLevelType) {
return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart;
}
var validateEventDispatches;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches = function (event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
var listenersIsArr = Array.isArray(dispatchListeners);
var idsIsArr = Array.isArray(dispatchIDs);
var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0;
var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0;
process.env.NODE_ENV !== 'production' ? warning(idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : undefined;
};
}
/**
* Dispatch the event to the listener.
* @param {SyntheticEvent} event SyntheticEvent to handle
* @param {boolean} simulated If the event is simulated (changes exn behavior)
* @param {function} listener Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(event, simulated, listener, domID) {
var type = event.type || 'unknown-event';
event.currentTarget = injection.Mount.getNode(domID);
if (simulated) {
ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event, domID);
} else {
ReactErrorUtils.invokeGuardedCallback(type, listener, event, domID);
}
event.currentTarget = null;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, simulated) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
executeDispatch(event, simulated, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
executeDispatch(event, simulated, dispatchListeners, dispatchIDs);
}
event._dispatchListeners = null;
event._dispatchIDs = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return {?string} id of the first dispatch execution who's listener returns
* true, or null if no listener returned true.
*/
function executeDispatchesInOrderStopAtTrueImpl(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchIDs[i])) {
return dispatchIDs[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchIDs)) {
return dispatchIDs;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchIDs = null;
event._dispatchListeners = null;
return ret;
}
/**
* Execution of a "direct" dispatch - there must be at most one dispatch
* accumulated on the event or it is considered an error. It doesn't really make
* sense for an event with multiple dispatches (bubbled) to keep track of the
* return values at each dispatch execution, but it does tend to make sense when
* dealing with "direct" dispatches.
*
* @return {*} The return value of executing the single dispatch.
*/
function executeDirectDispatch(event) {
if (process.env.NODE_ENV !== 'production') {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchID = event._dispatchIDs;
!!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : undefined;
var res = dispatchListener ? dispatchListener(event, dispatchID) : null;
event._dispatchListeners = null;
event._dispatchIDs = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {boolean} True iff number of dispatches accumulated is greater than 0.
*/
function hasDispatches(event) {
return !!event._dispatchListeners;
}
/**
* General utilities that are useful in creating custom Event Plugins.
*/
var EventPluginUtils = {
isEndish: isEndish,
isMoveish: isMoveish,
isStartish: isStartish,
executeDirectDispatch: executeDirectDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
getNode: function (id) {
return injection.Mount.getNode(id);
},
getID: function (node) {
return injection.Mount.getID(node);
},
injection: injection
};
module.exports = EventPluginUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 34 */
/*!****************************************!*\
!*** ./~/react/lib/ReactErrorUtils.js ***!
\****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactErrorUtils
* @typechecks
*/
'use strict';
var caughtError = null;
/**
* Call a function while guarding against errors that happens within it.
*
* @param {?String} name of the guard to use for logging or debugging
* @param {Function} func The function to invoke
* @param {*} a First argument
* @param {*} b Second argument
*/
function invokeGuardedCallback(name, func, a, b) {
try {
return func(a, b);
} catch (x) {
if (caughtError === null) {
caughtError = x;
}
return undefined;
}
}
var ReactErrorUtils = {
invokeGuardedCallback: invokeGuardedCallback,
/**
* Invoked by ReactTestUtils.Simulate so that any errors thrown by the event
* handler are sure to be rethrown by rethrowCaughtError.
*/
invokeGuardedCallbackWithCatch: invokeGuardedCallback,
/**
* During execution of guarded functions we will capture the first error which
* we will rethrow to be handled by the top level error handler.
*/
rethrowCaughtError: function () {
if (caughtError) {
var error = caughtError;
caughtError = null;
throw error;
}
}
};
if (process.env.NODE_ENV !== 'production') {
/**
* To help development we can get better devtools integration by simulating a
* real browser event.
*/
if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
var fakeNode = document.createElement('react');
ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) {
var boundFunc = func.bind(null, a, b);
var evtType = 'react-' + name;
fakeNode.addEventListener(evtType, boundFunc, false);
var evt = document.createEvent('Event');
evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt);
fakeNode.removeEventListener(evtType, boundFunc, false);
};
}
}
module.exports = ReactErrorUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 35 */
/*!***************************************!*\
!*** ./~/react/lib/accumulateInto.js ***!
\***************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule accumulateInto
*/
'use strict';
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
*
* Accumulates items that must not be null or undefined into the first one. This
* is used to conserve memory by avoiding array allocations, and thus sacrifices
* API cleanness. Since `current` can be null before being passed in and not
* null after this function, make sure to assign it back to `current`:
*
* `a = accumulateInto(a, b);`
*
* This API should be sparingly used. Try `accumulate` for something cleaner.
*
* @return {*|array<*>} An accumulation of items.
*/
function accumulateInto(current, next) {
!(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : undefined;
if (current == null) {
return next;
}
// Both are not empty. Warning: Never call x.concat(y) when you are not
// certain that x is an Array (x could be a string with concat method).
var currentIsArray = Array.isArray(current);
var nextIsArray = Array.isArray(next);
if (currentIsArray && nextIsArray) {
current.push.apply(current, next);
return current;
}
if (currentIsArray) {
current.push(next);
return current;
}
if (nextIsArray) {
// A bit too dangerous to mutate `next`.
return [current].concat(next);
}
return [current, next];
}
module.exports = accumulateInto;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 36 */
/*!*******************************************!*\
!*** ./~/react/lib/forEachAccumulated.js ***!
\*******************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule forEachAccumulated
*/
'use strict';
/**
* @param {array} arr an "accumulation" of items which is either an Array or
* a single item. Useful when paired with the `accumulate` module. This is a
* simple utility that allows us to reason about a collection of items, but
* handling the case when there is exactly one item (and we do not need to
* allocate an array).
*/
var forEachAccumulated = function (arr, cb, scope) {
if (Array.isArray(arr)) {
arr.forEach(cb, scope);
} else if (arr) {
cb.call(scope, arr);
}
};
module.exports = forEachAccumulated;
/***/ }),
/* 37 */
/*!***********************************************!*\
!*** ./~/react/lib/ReactEventEmitterMixin.js ***!
\***********************************************/
/***/ (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.
*
* @providesModule ReactEventEmitterMixin
*/
'use strict';
var EventPluginHub = __webpack_require__(/*! ./EventPluginHub */ 31);
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue(false);
}
var ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native environment event.
*/
handleTopLevel: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var events = EventPluginHub.extractEvents(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
/***/ }),
/* 38 */
/*!****************************************!*\
!*** ./~/react/lib/ViewportMetrics.js ***!
\****************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ViewportMetrics
*/
'use strict';
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function (scrollPosition) {
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
/***/ }),
/* 39 */
/*!**************************************!*\
!*** ./~/react/lib/Object.assign.js ***!
\**************************************/
/***/ (function(module, exports) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
'use strict';
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
}
module.exports = assign;
/***/ }),
/* 40 */
/*!*****************************************!*\
!*** ./~/react/lib/isEventSupported.js ***!
\*****************************************/
/***/ (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.
*
* @providesModule isEventSupported
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var useHasFeature;
if (ExecutionEnvironment.canUseDOM) {
useHasFeature = document.implementation && document.implementation.hasFeature &&
// always returns true in newer browsers as per the standard.
// @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature
document.implementation.hasFeature('', '') !== true;
}
/**
* Checks if an event is supported in the current execution environment.
*
* NOTE: This will not work correctly for non-generic events such as `change`,
* `reset`, `load`, `error`, and `select`.
*
* Borrows from Modernizr.
*
* @param {string} eventNameSuffix Event name, e.g. "click".
* @param {?boolean} capture Check if the capture phase is supported.
* @return {boolean} True if the event is supported.
* @internal
* @license Modernizr 3.0.0pre (Custom Build) | MIT
*/
function isEventSupported(eventNameSuffix, capture) {
if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) {
return false;
}
var eventName = 'on' + eventNameSuffix;
var isSupported = (eventName in document);
if (!isSupported) {
var element = document.createElement('div');
element.setAttribute(eventName, 'return;');
isSupported = typeof element[eventName] === 'function';
}
if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {
// This is the only way to test support for the `wheel` event in IE9+.
isSupported = document.implementation.hasFeature('Events.wheel', '3.0');
}
return isSupported;
}
module.exports = isEventSupported;
/***/ }),
/* 41 */
/*!*********************************************!*\
!*** ./~/react/lib/ReactDOMFeatureFlags.js ***!
\*********************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ReactDOMFeatureFlags
*/
'use strict';
var ReactDOMFeatureFlags = {
useCreateElement: false
};
module.exports = ReactDOMFeatureFlags;
/***/ }),
/* 42 */
/*!*************************************!*\
!*** ./~/react/lib/ReactElement.js ***!
\*************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactElement
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var canDefineProperty = __webpack_require__(/*! ./canDefineProperty */ 43);
// 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;
var RESERVED_PROPS = {
key: true,
ref: true,
__self: true,
__source: true
};
/**
* Base constructor for all React elements. This is only used to make this
* work with a dynamic instanceof check. Nothing should live on this prototype.
*
* @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 (process.env.NODE_ENV !== 'production') {
// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {};
// To make comparing ReactElements easier for testing purposes, we make
// the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
if (canDefineProperty) {
Object.defineProperty(element._store, 'validated', {
configurable: false,
enumerable: false,
writable: true,
value: false
});
// self and source are DEV only properties.
Object.defineProperty(element, '_self', {
configurable: false,
enumerable: false,
writable: false,
value: self
});
// Two elements created in two different places should be considered
// equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: false,
enumerable: false,
writable: false,
value: source
});
} else {
element._store.validated = false;
element._self = self;
element._source = source;
}
Object.freeze(element.props);
Object.freeze(element);
}
return element;
};
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) {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + 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 (config.hasOwnProperty(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];
}
props.children = childArray;
}
// Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
};
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;
};
ReactElement.cloneAndReplaceProps = function (oldElement, newProps) {
var newElement = ReactElement(oldElement.type, oldElement.key, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, newProps);
if (process.env.NODE_ENV !== 'production') {
// If the key on the original is valid, then the clone is valid
newElement._store.validated = oldElement._store.validated;
}
return newElement;
};
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 (config.ref !== undefined) {
// Silently steal the ref from the parent.
ref = config.ref;
owner = ReactCurrentOwner.current;
}
if (config.key !== undefined) {
key = '' + config.key;
}
// Remaining properties override existing props
for (propName in config) {
if (config.hasOwnProperty(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];
}
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
};
/**
* @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;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 43 */
/*!******************************************!*\
!*** ./~/react/lib/canDefineProperty.js ***!
\******************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule canDefineProperty
*/
'use strict';
var canDefineProperty = false;
if (process.env.NODE_ENV !== 'production') {
try {
Object.defineProperty({}, 'x', { get: function () {} });
canDefineProperty = true;
} catch (x) {
// IE will fail on defineProperty
}
}
module.exports = canDefineProperty;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 44 */
/*!****************************************************!*\
!*** ./~/react/lib/ReactEmptyComponentRegistry.js ***!
\****************************************************/
/***/ (function(module, exports) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactEmptyComponentRegistry
*/
'use strict';
// This registry keeps track of the React IDs of the components that rendered to
// `null` (in reality a placeholder such as `noscript`)
var nullComponentIDsRegistry = {};
/**
* @param {string} id Component's `_rootNodeID`.
* @return {boolean} True if the component is rendered to null.
*/
function isNullComponentID(id) {
return !!nullComponentIDsRegistry[id];
}
/**
* Mark the component as having rendered to null.
* @param {string} id Component's `_rootNodeID`.
*/
function registerNullComponentID(id) {
nullComponentIDsRegistry[id] = true;
}
/**
* Unmark the component as having rendered to null: it renders to something now.
* @param {string} id Component's `_rootNodeID`.
*/
function deregisterNullComponentID(id) {
delete nullComponentIDsRegistry[id];
}
var ReactEmptyComponentRegistry = {
isNullComponentID: isNullComponentID,
registerNullComponentID: registerNullComponentID,
deregisterNullComponentID: deregisterNullComponentID
};
module.exports = ReactEmptyComponentRegistry;
/***/ }),
/* 45 */
/*!*********************************************!*\
!*** ./~/react/lib/ReactInstanceHandles.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactInstanceHandles
* @typechecks static-only
*/
'use strict';
var ReactRootIndex = __webpack_require__(/*! ./ReactRootIndex */ 46);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var SEPARATOR = '.';
var SEPARATOR_LENGTH = SEPARATOR.length;
/**
* Maximum depth of traversals before we consider the possibility of a bad ID.
*/
var MAX_TREE_DEPTH = 10000;
/**
* Creates a DOM ID prefix to use when mounting React components.
*
* @param {number} index A unique integer
* @return {string} React root ID.
* @internal
*/
function getReactRootIDString(index) {
return SEPARATOR + index.toString(36);
}
/**
* Checks if a character in the supplied ID is a separator or the end.
*
* @param {string} id A React DOM ID.
* @param {number} index Index of the character to check.
* @return {boolean} True if the character is a separator or end of the ID.
* @private
*/
function isBoundary(id, index) {
return id.charAt(index) === SEPARATOR || index === id.length;
}
/**
* Checks if the supplied string is a valid React DOM ID.
*
* @param {string} id A React DOM ID, maybe.
* @return {boolean} True if the string is a valid React DOM ID.
* @private
*/
function isValidID(id) {
return id === '' || id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR;
}
/**
* Checks if the first ID is an ancestor of or equal to the second ID.
*
* @param {string} ancestorID
* @param {string} descendantID
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
* @internal
*/
function isAncestorIDOf(ancestorID, descendantID) {
return descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length);
}
/**
* Gets the parent ID of the supplied React DOM ID, `id`.
*
* @param {string} id ID of a component.
* @return {string} ID of the parent, or an empty string.
* @private
*/
function getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* Gets the next DOM ID on the tree path from the supplied `ancestorID` to the
* supplied `destinationID`. If they are equal, the ID is returned.
*
* @param {string} ancestorID ID of an ancestor node of `destinationID`.
* @param {string} destinationID ID of the destination node.
* @return {string} Next ID on the path from `ancestorID` to `destinationID`.
* @private
*/
function getNextDescendantID(ancestorID, destinationID) {
!(isValidID(ancestorID) && isValidID(destinationID)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID) : invariant(false) : undefined;
!isAncestorIDOf(ancestorID, destinationID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID) : invariant(false) : undefined;
if (ancestorID === destinationID) {
return ancestorID;
}
// Skip over the ancestor and the immediate separator. Traverse until we hit
// another separator or we reach the end of `destinationID`.
var start = ancestorID.length + SEPARATOR_LENGTH;
var i;
for (i = start; i < destinationID.length; i++) {
if (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
/**
* Gets the nearest common ancestor ID of two IDs.
*
* Using this ID scheme, the nearest common ancestor ID is the longest common
* prefix of the two IDs that immediately preceded a "marker" in both strings.
*
* @param {string} oneID
* @param {string} twoID
* @return {string} Nearest common ancestor ID, or the empty string if none.
* @private
*/
function getFirstCommonAncestorID(oneID, twoID) {
var minLength = Math.min(oneID.length, twoID.length);
if (minLength === 0) {
return '';
}
var lastCommonMarkerIndex = 0;
// Use `<=` to traverse until the "EOL" of the shorter string.
for (var i = 0; i <= minLength; i++) {
if (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
!isValidID(longestCommonID) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID) : invariant(false) : undefined;
return longestCommonID;
}
/**
* Traverses the parent path between two IDs (either up or down). The IDs must
* not be the same, and there must exist a parent path between them. If the
* callback returns `false`, traversal is stopped.
*
* @param {?string} start ID at which to start traversal.
* @param {?string} stop ID at which to end traversal.
* @param {function} cb Callback to invoke each ID with.
* @param {*} arg Argument to invoke the callback with.
* @param {?boolean} skipFirst Whether or not to skip the first node.
* @param {?boolean} skipLast Whether or not to skip the last node.
* @private
*/
function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) {
start = start || '';
stop = stop || '';
!(start !== stop) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start) : invariant(false) : undefined;
var traverseUp = isAncestorIDOf(stop, start);
!(traverseUp || isAncestorIDOf(start, stop)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop) : invariant(false) : undefined;
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start;; /* until break */id = traverse(id, stop)) {
var ret;
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
ret = cb(id, traverseUp, arg);
}
if (ret === false || id === stop) {
// Only break //after// visiting `stop`.
break;
}
!(depth++ < MAX_TREE_DEPTH) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop, id) : invariant(false) : undefined;
}
}
/**
* Manages the IDs assigned to DOM representations of React components. This
* uses a specific scheme in order to traverse the DOM efficiently (e.g. in
* order to simulate events).
*
* @internal
*/
var ReactInstanceHandles = {
/**
* Constructs a React root ID
* @return {string} A React root ID.
*/
createReactRootID: function () {
return getReactRootIDString(ReactRootIndex.createReactRootIndex());
},
/**
* Constructs a React ID by joining a root ID with a name.
*
* @param {string} rootID Root ID of a parent component.
* @param {string} name A component's name (as flattened children).
* @return {string} A React ID.
* @internal
*/
createReactID: function (rootID, name) {
return rootID + name;
},
/**
* Gets the DOM ID of the React component that is the root of the tree that
* contains the React component with the supplied DOM ID.
*
* @param {string} id DOM ID of a React component.
* @return {?string} DOM ID of the React component that is the root.
* @internal
*/
getReactRootIDFromNodeID: function (id) {
if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
var index = id.indexOf(SEPARATOR, 1);
return index > -1 ? id.substr(0, index) : id;
}
return null;
},
/**
* Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that
* should would receive a `mouseEnter` or `mouseLeave` event.
*
* NOTE: Does not invoke the callback on the nearest common ancestor because
* nothing "entered" or "left" that element.
*
* @param {string} leaveID ID being left.
* @param {string} enterID ID being entered.
* @param {function} cb Callback to invoke on each entered/left ID.
* @param {*} upArg Argument to invoke the callback with on left IDs.
* @param {*} downArg Argument to invoke the callback with on entered IDs.
* @internal
*/
traverseEnterLeave: function (leaveID, enterID, cb, upArg, downArg) {
var ancestorID = getFirstCommonAncestorID(leaveID, enterID);
if (ancestorID !== leaveID) {
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
}
if (ancestorID !== enterID) {
traverseParentPath(ancestorID, enterID, cb, downArg, true, false);
}
},
/**
* Simulates the traversal of a two-phase, capture/bubble event dispatch.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseTwoPhase: function (targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, false);
traverseParentPath(targetID, '', cb, arg, false, true);
}
},
/**
* Same as `traverseTwoPhase` but skips the `targetID`.
*/
traverseTwoPhaseSkipTarget: function (targetID, cb, arg) {
if (targetID) {
traverseParentPath('', targetID, cb, arg, true, true);
traverseParentPath(targetID, '', cb, arg, true, true);
}
},
/**
* Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
* example, passing `.0.$row-0.1` would result in `cb` getting called
* with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
*
* NOTE: This traversal happens on IDs without touching the DOM.
*
* @param {string} targetID ID of the target node.
* @param {function} cb Callback to invoke.
* @param {*} arg Argument to invoke the callback with.
* @internal
*/
traverseAncestors: function (targetID, cb, arg) {
traverseParentPath('', targetID, cb, arg, true, false);
},
getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 46 */
/*!***************************************!*\
!*** ./~/react/lib/ReactRootIndex.js ***!
\***************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ReactRootIndex
* @typechecks
*/
'use strict';
var ReactRootIndexInjection = {
/**
* @param {function} _createReactRootIndex
*/
injectCreateReactRootIndex: function (_createReactRootIndex) {
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
}
};
var ReactRootIndex = {
createReactRootIndex: null,
injection: ReactRootIndexInjection
};
module.exports = ReactRootIndex;
/***/ }),
/* 47 */
/*!*****************************************!*\
!*** ./~/react/lib/ReactInstanceMap.js ***!
\*****************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ReactInstanceMap
*/
'use strict';
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*/
// TODO: Replace this with ES6: var ReactInstanceMap = new Map();
var ReactInstanceMap = {
/**
* This API should be called `delete` but we'd have to make sure to always
* transform these to strings for IE support. When this transform is fully
* supported we can rename it.
*/
remove: function (key) {
key._reactInternalInstance = undefined;
},
get: function (key) {
return key._reactInternalInstance;
},
has: function (key) {
return key._reactInternalInstance !== undefined;
},
set: function (key, value) {
key._reactInternalInstance = value;
}
};
module.exports = ReactInstanceMap;
/***/ }),
/* 48 */
/*!********************************************!*\
!*** ./~/react/lib/ReactMarkupChecksum.js ***!
\********************************************/
/***/ (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.
*
* @providesModule ReactMarkupChecksum
*/
'use strict';
var adler32 = __webpack_require__(/*! ./adler32 */ 49);
var TAG_END = /\/?>/;
var ReactMarkupChecksum = {
CHECKSUM_ATTR_NAME: 'data-react-checksum',
/**
* @param {string} markup Markup string
* @return {string} Markup string with checksum attribute attached
*/
addChecksumToMarkup: function (markup) {
var checksum = adler32(markup);
// Add checksum (handle both parent tags and self-closing tags)
return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&');
},
/**
* @param {string} markup to use
* @param {DOMElement} element root React element
* @returns {boolean} whether or not the markup is the same
*/
canReuseMarkup: function (markup, element) {
var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);
existingChecksum = existingChecksum && parseInt(existingChecksum, 10);
var markupChecksum = adler32(markup);
return markupChecksum === existingChecksum;
}
};
module.exports = ReactMarkupChecksum;
/***/ }),
/* 49 */
/*!********************************!*\
!*** ./~/react/lib/adler32.js ***!
\********************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule adler32
*/
'use strict';
var MOD = 65521;
// adler32 is not cryptographically strong, and is only used to sanity check that
// markup generated on the server matches the markup generated on the client.
// This implementation (a modified version of the SheetJS version) has been optimized
// for our use case, at the expense of conforming to the adler32 specification
// for non-ascii inputs.
function adler32(data) {
var a = 1;
var b = 0;
var i = 0;
var l = data.length;
var m = l & ~0x3;
while (i < m) {
for (; i < Math.min(i + 4096, m); i += 4) {
b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3));
}
a %= MOD;
b %= MOD;
}
for (; i < l; i++) {
b += a += data.charCodeAt(i);
}
a %= MOD;
b %= MOD;
return a | b << 16;
}
module.exports = adler32;
/***/ }),
/* 50 */
/*!****************************************!*\
!*** ./~/react/lib/ReactReconciler.js ***!
\****************************************/
/***/ (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.
*
* @providesModule ReactReconciler
*/
'use strict';
var ReactRef = __webpack_require__(/*! ./ReactRef */ 51);
/**
* Helper to call ReactRef.attachRefs with this composite component, split out
* to avoid allocations in the transaction mount-ready queue.
*/
function attachRefs() {
ReactRef.attachRefs(this, this._currentElement);
}
var ReactReconciler = {
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {ReactComponent} internalInstance
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (internalInstance, rootID, transaction, context) {
var markup = internalInstance.mountComponent(rootID, transaction, context);
if (internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
return markup;
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function (internalInstance) {
ReactRef.detachRefs(internalInstance, internalInstance._currentElement);
internalInstance.unmountComponent();
},
/**
* Update a component using a new element.
*
* @param {ReactComponent} internalInstance
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @internal
*/
receiveComponent: function (internalInstance, nextElement, transaction, context) {
var prevElement = internalInstance._currentElement;
if (nextElement === prevElement && context === internalInstance._context) {
// Since elements are immutable after the owner is rendered,
// we can do a cheap identity compare here to determine if this is a
// superfluous reconcile. It's possible for state to be mutable but such
// change should trigger an update of the owner which would recreate
// the element. We explicitly check for the existence of an owner since
// it's possible for an element created outside a composite to be
// deeply mutated and reused.
// TODO: Bailing out early is just a perf optimization right?
// TODO: Removing the return statement should affect correctness?
return;
}
var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement);
if (refsChanged) {
ReactRef.detachRefs(internalInstance, prevElement);
}
internalInstance.receiveComponent(nextElement, transaction, context);
if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) {
transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
}
},
/**
* Flush any dirty changes in a component.
*
* @param {ReactComponent} internalInstance
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (internalInstance, transaction) {
internalInstance.performUpdateIfNecessary(transaction);
}
};
module.exports = ReactReconciler;
/***/ }),
/* 51 */
/*!*********************************!*\
!*** ./~/react/lib/ReactRef.js ***!
\*********************************/
/***/ (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.
*
* @providesModule ReactRef
*/
'use strict';
var ReactOwner = __webpack_require__(/*! ./ReactOwner */ 52);
var ReactRef = {};
function attachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(component.getPublicInstance());
} else {
// Legacy ref
ReactOwner.addComponentAsRefTo(component, ref, owner);
}
}
function detachRef(ref, component, owner) {
if (typeof ref === 'function') {
ref(null);
} else {
// Legacy ref
ReactOwner.removeComponentAsRefFrom(component, ref, owner);
}
}
ReactRef.attachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
attachRef(ref, instance, element._owner);
}
};
ReactRef.shouldUpdateRefs = function (prevElement, nextElement) {
// If either the owner or a `ref` has changed, make sure the newest owner
// has stored a reference to `this`, and the previous owner (if different)
// has forgotten the reference to `this`. We use the element instead
// of the public this.props because the post processing cannot determine
// a ref. The ref conceptually lives on the element.
// TODO: Should this even be possible? The owner cannot change because
// it's forbidden by shouldUpdateReactComponent. The ref can change
// if you swap the keys of but not the refs. Reconsider where this check
// is made. It probably belongs where the key checking and
// instantiateReactComponent is done.
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
return(
// This has a few false positives w/r/t empty components.
prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref
);
};
ReactRef.detachRefs = function (instance, element) {
if (element === null || element === false) {
return;
}
var ref = element.ref;
if (ref != null) {
detachRef(ref, instance, element._owner);
}
};
module.exports = ReactRef;
/***/ }),
/* 52 */
/*!***********************************!*\
!*** ./~/react/lib/ReactOwner.js ***!
\***********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactOwner
*/
'use strict';
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* ReactOwners are capable of storing references to owned components.
*
* All components are capable of //being// referenced by owner components, but
* only ReactOwner components are capable of //referencing// owned components.
* The named reference is known as a "ref".
*
* Refs are available when mounted and updated during reconciliation.
*
* var MyComponent = React.createClass({
* render: function() {
* return (
* <div onClick={this.handleClick}>
* <CustomComponent ref="custom" />
* </div>
* );
* },
* handleClick: function() {
* this.refs.custom.handleClick();
* },
* componentDidMount: function() {
* this.refs.custom.initialize();
* }
* });
*
* Refs should rarely be used. When refs are used, they should only be done to
* control data that is not handled by React's data flow.
*
* @class ReactOwner
*/
var ReactOwner = {
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid owner.
* @final
*/
isValidOwner: function (object) {
return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function');
},
/**
* Adds a component by ref to an owner component.
*
* @param {ReactComponent} component Component to reference.
* @param {string} ref Name by which to refer to the component.
* @param {ReactOwner} owner Component on which to record the ref.
* @final
* @internal
*/
addComponentAsRefTo: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'addComponentAsRefTo(...): Only a ReactOwner can have refs. You might ' + 'be adding a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
owner.attachRef(ref, component);
},
/**
* Removes a component by ref from an owner component.
*
* @param {ReactComponent} component Component to dereference.
* @param {string} ref Name of the ref to remove.
* @param {ReactOwner} owner Component on which the ref is recorded.
* @final
* @internal
*/
removeComponentAsRefFrom: function (component, ref, owner) {
!ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might ' + 'be removing a ref to a component that was not created inside a component\'s ' + '`render` method, or you have multiple copies of React loaded ' + '(details: https://fb.me/react-refs-must-have-owner).') : invariant(false) : undefined;
// Check that `component` is still the current ref because we do not want to
// detach the ref if another component stole it.
if (owner.getPublicInstance().refs[ref] === component.getPublicInstance()) {
owner.detachRef(ref);
}
}
};
module.exports = ReactOwner;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 53 */
/*!*****************************************!*\
!*** ./~/react/lib/ReactUpdateQueue.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactUpdateQueue
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactInstanceMap = __webpack_require__(/*! ./ReactInstanceMap */ 47);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
function enqueueUpdate(internalInstance) {
ReactUpdates.enqueueUpdate(internalInstance);
}
function getInternalInstanceReadyForUpdate(publicInstance, callerName) {
var internalInstance = ReactInstanceMap.get(publicInstance);
if (!internalInstance) {
if (process.env.NODE_ENV !== 'production') {
// Only warn when we have a callerName. Otherwise we should be silent.
// We're probably calling from enqueueCallback. We don't want to warn
// there because we already warned for the corresponding lifecycle method.
process.env.NODE_ENV !== 'production' ? warning(!callerName, '%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, publicInstance.constructor.displayName) : undefined;
}
return null;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition ' + '(such as within `render`). Render methods should be a pure function ' + 'of props and state.', callerName) : undefined;
}
return internalInstance;
}
/**
* ReactUpdateQueue allows for state updates to be scheduled into a later
* reconciliation step.
*/
var ReactUpdateQueue = {
/**
* 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) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing isMounted inside its render() function. ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
var internalInstance = ReactInstanceMap.get(publicInstance);
if (internalInstance) {
// During componentWillMount and render this will still be null but after
// that will always render to something. At least for now. So we can use
// this hack.
return !!internalInstance._renderedComponent;
} else {
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) {
!(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);
// Previously we would throw an error if we didn't have an internal
// instance. Since we want to make it a no-op instead, we mirror the same
// behavior we have in other enqueue* methods.
// We also need to ignore callbacks in componentWillMount. See
// enqueueUpdates.
if (!internalInstance) {
return null;
}
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState. Alternatively, we can disallow
// componentWillMount during server-side rendering.
enqueueUpdate(internalInstance);
},
enqueueCallbackInternal: function (internalInstance, callback) {
!(typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'enqueueCallback(...): You called `setProps`, `replaceProps`, ' + '`setState`, `replaceState`, or `forceUpdate` with a callback that ' + 'isn\'t callable.') : invariant(false) : undefined;
if (internalInstance._pendingCallbacks) {
internalInstance._pendingCallbacks.push(callback);
} else {
internalInstance._pendingCallbacks = [callback];
}
enqueueUpdate(internalInstance);
},
/**
* 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) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate');
if (!internalInstance) {
return;
}
internalInstance._pendingForceUpdate = true;
enqueueUpdate(internalInstance);
},
/**
* 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) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState');
if (!internalInstance) {
return;
}
internalInstance._pendingStateQueue = [completeState];
internalInstance._pendingReplaceState = true;
enqueueUpdate(internalInstance);
},
/**
* 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) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return;
}
var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},
/**
* Sets a subset of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialProps Subset of the next props.
* @internal
*/
enqueueSetProps: function (publicInstance, partialProps) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setProps');
if (!internalInstance) {
return;
}
ReactUpdateQueue.enqueueSetPropsInternal(internalInstance, partialProps);
},
enqueueSetPropsInternal: function (internalInstance, partialProps) {
var topLevelWrapper = internalInstance._topLevelWrapper;
!topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setProps(...): You called `setProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
// Merge with the pending element if it exists, otherwise with existing
// element props.
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
var element = wrapElement.props;
var props = assign({}, element.props, partialProps);
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
enqueueUpdate(topLevelWrapper);
},
/**
* Replaces all of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} props New props.
* @internal
*/
enqueueReplaceProps: function (publicInstance, props) {
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceProps');
if (!internalInstance) {
return;
}
ReactUpdateQueue.enqueueReplacePropsInternal(internalInstance, props);
},
enqueueReplacePropsInternal: function (internalInstance, props) {
var topLevelWrapper = internalInstance._topLevelWrapper;
!topLevelWrapper ? process.env.NODE_ENV !== 'production' ? invariant(false, 'replaceProps(...): You called `replaceProps` on a ' + 'component with a parent. This is an anti-pattern since props will ' + 'get reactively updated when rendered. Instead, change the owner\'s ' + '`render` method to pass the correct value as props to the component ' + 'where it is created.') : invariant(false) : undefined;
// Merge with the pending element if it exists, otherwise with existing
// element props.
var wrapElement = topLevelWrapper._pendingElement || topLevelWrapper._currentElement;
var element = wrapElement.props;
topLevelWrapper._pendingElement = ReactElement.cloneAndReplaceProps(wrapElement, ReactElement.cloneAndReplaceProps(element, props));
enqueueUpdate(topLevelWrapper);
},
enqueueElementInternal: function (internalInstance, newElement) {
internalInstance._pendingElement = newElement;
enqueueUpdate(internalInstance);
}
};
module.exports = ReactUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 54 */
/*!*************************************!*\
!*** ./~/react/lib/ReactUpdates.js ***!
\*************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactUpdates
*/
'use strict';
var CallbackQueue = __webpack_require__(/*! ./CallbackQueue */ 55);
var PooledClass = __webpack_require__(/*! ./PooledClass */ 56);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var ReactReconciler = __webpack_require__(/*! ./ReactReconciler */ 50);
var Transaction = __webpack_require__(/*! ./Transaction */ 57);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var dirtyComponents = [];
var asapCallbackQueue = CallbackQueue.getPooled();
var asapEnqueued = false;
var batchingStrategy = null;
function ensureInjected() {
!(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : undefined;
}
var NESTED_UPDATES = {
initialize: function () {
this.dirtyComponentsLength = dirtyComponents.length;
},
close: function () {
if (this.dirtyComponentsLength !== dirtyComponents.length) {
// Additional updates were enqueued by componentDidUpdate handlers or
// similar; before our own UPDATE_QUEUEING wrapper closes, we want to run
// these new updates so that if A's componentDidUpdate calls setState on
// B, B will update before the callback A's updater provided when calling
// setState.
dirtyComponents.splice(0, this.dirtyComponentsLength);
flushBatchedUpdates();
} else {
dirtyComponents.length = 0;
}
}
};
var UPDATE_QUEUEING = {
initialize: function () {
this.callbackQueue.reset();
},
close: function () {
this.callbackQueue.notifyAll();
}
};
var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING];
function ReactUpdatesFlushTransaction() {
this.reinitializeTransaction();
this.dirtyComponentsLength = null;
this.callbackQueue = CallbackQueue.getPooled();
this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* forceHTML */false);
}
assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
destructor: function () {
this.dirtyComponentsLength = null;
CallbackQueue.release(this.callbackQueue);
this.callbackQueue = null;
ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction);
this.reconcileTransaction = null;
},
perform: function (method, scope, a) {
// Essentially calls `this.reconcileTransaction.perform(method, scope, a)`
// with this transaction's wrappers around it.
return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a);
}
});
PooledClass.addPoolingTo(ReactUpdatesFlushTransaction);
function batchedUpdates(callback, a, b, c, d, e) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b, c, d, e);
}
/**
* Array comparator for ReactComponents by mount ordering.
*
* @param {ReactComponent} c1 first component you're comparing
* @param {ReactComponent} c2 second component you're comparing
* @return {number} Return value usable by Array.prototype.sort().
*/
function mountOrderComparator(c1, c2) {
return c1._mountOrder - c2._mountOrder;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
!(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : undefined;
// Since reconciling a component higher in the owner hierarchy usually (not
// always -- see shouldComponentUpdate()) will reconcile children, reconcile
// them before their children by sorting the array.
dirtyComponents.sort(mountOrderComparator);
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, it will still
// be here, but we assume that it has cleared its _pendingCallbacks and
// that performUpdateIfNecessary is a noop.
var component = dirtyComponents[i];
// If performUpdateIfNecessary happens to enqueue any new updates, we
// shouldn't execute the callbacks until the next render happens, so
// stash the callbacks first
var callbacks = component._pendingCallbacks;
component._pendingCallbacks = null;
ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction);
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance());
}
}
}
}
var flushBatchedUpdates = function () {
// ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents
// array and perform any updates enqueued by mount-ready handlers (i.e.,
// componentDidUpdate) but we need to check here too in order to catch
// updates enqueued by setState callbacks and asap calls.
while (dirtyComponents.length || asapEnqueued) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
ReactUpdatesFlushTransaction.release(transaction);
}
if (asapEnqueued) {
asapEnqueued = false;
var queue = asapCallbackQueue;
asapCallbackQueue = CallbackQueue.getPooled();
queue.notifyAll();
CallbackQueue.release(queue);
}
}
};
flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates);
/**
* Mark a component as needing a rerender, adding an optional callback to a
* list of functions which will be executed once the rerender occurs.
*/
function enqueueUpdate(component) {
ensureInjected();
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case. (This is called by each top-level update
// function, like setProps, setState, forceUpdate, etc.; creation and
// destruction of top-level components is guarded in ReactMount.)
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component);
return;
}
dirtyComponents.push(component);
}
/**
* Enqueue a callback to be run at the end of the current batching cycle. Throws
* if no updates are currently being performed.
*/
function asap(callback, context) {
!batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : undefined;
asapCallbackQueue.enqueue(callback, context);
asapEnqueued = true;
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function (ReconcileTransaction) {
!ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : undefined;
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function (_batchingStrategy) {
!_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : undefined;
!(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : undefined;
!(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : undefined;
batchingStrategy = _batchingStrategy;
}
};
var ReactUpdates = {
/**
* React references `ReactReconcileTransaction` using this property in order
* to allow dependency injection.
*
* @internal
*/
ReactReconcileTransaction: null,
batchedUpdates: batchedUpdates,
enqueueUpdate: enqueueUpdate,
flushBatchedUpdates: flushBatchedUpdates,
injection: ReactUpdatesInjection,
asap: asap
};
module.exports = ReactUpdates;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 55 */
/*!**************************************!*\
!*** ./~/react/lib/CallbackQueue.js ***!
\**************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule CallbackQueue
*/
'use strict';
var PooledClass = __webpack_require__(/*! ./PooledClass */ 56);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function CallbackQueue() {
this._callbacks = null;
this._contexts = null;
}
assign(CallbackQueue.prototype, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
enqueue: function (callback, context) {
this._callbacks = this._callbacks || [];
this._contexts = this._contexts || [];
this._callbacks.push(callback);
this._contexts.push(context);
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function () {
var callbacks = this._callbacks;
var contexts = this._contexts;
if (callbacks) {
!(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : undefined;
this._callbacks = null;
this._contexts = null;
for (var i = 0; i < callbacks.length; i++) {
callbacks[i].call(contexts[i]);
}
callbacks.length = 0;
contexts.length = 0;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function () {
this._callbacks = null;
this._contexts = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function () {
this.reset();
}
});
PooledClass.addPoolingTo(CallbackQueue);
module.exports = CallbackQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 56 */
/*!************************************!*\
!*** ./~/react/lib/PooledClass.js ***!
\************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule PooledClass
*/
'use strict';
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* 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) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : undefined;
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 (optional).
*
* @param {Function} CopyConstructor Constructor that can be used to reset.
* @param {Function} pooler Customizable pooler.
*/
var addPoolingTo = function (CopyConstructor, pooler) {
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;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 57 */
/*!************************************!*\
!*** ./~/react/lib/Transaction.js ***!
\************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule Transaction
*/
'use strict';
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* `Transaction` creates a black box that is able to wrap any method such that
* certain invariants are maintained before and after the method is invoked
* (Even if an exception is thrown while invoking the wrapped method). Whoever
* instantiates a transaction can provide enforcers of the invariants at
* creation time. The `Transaction` class itself will supply one additional
* automatic invariant for you - the invariant that any transaction instance
* should not be run while it is already being run. You would typically create a
* single instance of a `Transaction` for reuse multiple times, that potentially
* is used to wrap several different methods. Wrappers are extremely simple -
* they only require implementing two methods.
*
* <pre>
* wrappers (injected at creation time)
* + +
* | |
* +-----------------|--------|--------------+
* | v | |
* | +---------------+ | |
* | +--| wrapper1 |---|----+ |
* | | +---------------+ v | |
* | | +-------------+ | |
* | | +----| wrapper2 |--------+ |
* | | | +-------------+ | | |
* | | | | | |
* | v v v v | wrapper
* | +---+ +---+ +---------+ +---+ +---+ | invariants
* perform(anyMethod) | | | | | | | | | | | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | | | | | | | | | | | |
* | +---+ +---+ +---------+ +---+ +---+ |
* | initialize close |
* +-----------------------------------------+
* </pre>
*
* Use cases:
* - Preserving the input selection ranges before/after reconciliation.
* Restoring selection even in the event of an unexpected error.
* - Deactivating events while rearranging the DOM, preventing blurs/focuses,
* while guaranteeing that afterwards, the event system is reactivated.
* - Flushing a queue of collected DOM mutations to the main UI thread after a
* reconciliation takes place in a worker thread.
* - Invoking any collected `componentDidUpdate` callbacks after rendering new
* content.
* - (Future use case): Wrapping particular flushes of the `ReactWorker` queue
* to preserve the `scrollTop` (an automatic scroll aware DOM).
* - (Future use case): Layout calculations before and after DOM updates.
*
* Transactional plugin API:
* - A module that has an `initialize` method that returns any precomputation.
* - and a `close` method that accepts the precomputation. `close` is invoked
* when the wrapped process is completed, or has failed.
*
* @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules
* that implement `initialize` and `close`.
* @return {Transaction} Single transaction for reuse in thread.
*
* @class Transaction
*/
var Mixin = {
/**
* Sets up this instance so that it is prepared for collecting metrics. Does
* so such that this setup method may be used on an instance that is already
* initialized, in a way that does not consume additional memory upon reuse.
* That can be useful if you decide to make your subclass of this mixin a
* "PooledClass".
*/
reinitializeTransaction: function () {
this.transactionWrappers = this.getTransactionWrappers();
if (this.wrapperInitData) {
this.wrapperInitData.length = 0;
} else {
this.wrapperInitData = [];
}
this._isInTransaction = false;
},
_isInTransaction: false,
/**
* @abstract
* @return {Array<TransactionWrapper>} Array of transaction wrappers.
*/
getTransactionWrappers: null,
isInTransaction: function () {
return !!this._isInTransaction;
},
/**
* Executes the function within a safety window. Use this for the top level
* methods that result in large amounts of computation/mutations that would
* need to be safety checked. The optional arguments helps prevent the need
* to bind in many cases.
*
* @param {function} method Member of scope to call.
* @param {Object} scope Scope to invoke from.
* @param {Object?=} a Argument to pass to the method.
* @param {Object?=} b Argument to pass to the method.
* @param {Object?=} c Argument to pass to the method.
* @param {Object?=} d Argument to pass to the method.
* @param {Object?=} e Argument to pass to the method.
* @param {Object?=} f Argument to pass to the method.
*
* @return {*} Return value from `method`.
*/
perform: function (method, scope, a, b, c, d, e, f) {
!!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : undefined;
var errorThrown;
var ret;
try {
this._isInTransaction = true;
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// one of these calls threw.
errorThrown = true;
this.initializeAll(0);
ret = method.call(scope, a, b, c, d, e, f);
errorThrown = false;
} finally {
try {
if (errorThrown) {
// If `method` throws, prefer to show that stack trace over any thrown
// by invoking `closeAll`.
try {
this.closeAll(0);
} catch (err) {}
} else {
// Since `method` didn't throw, we don't want to silence the exception
// here.
this.closeAll(0);
}
} finally {
this._isInTransaction = false;
}
}
return ret;
},
initializeAll: function (startIndex) {
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
try {
// Catching errors makes debugging more difficult, so we start with the
// OBSERVED_ERROR state before overwriting it with the real return value
// of initialize -- if it's still set to OBSERVED_ERROR in the finally
// block, it means wrapper.initialize threw.
this.wrapperInitData[i] = Transaction.OBSERVED_ERROR;
this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
} finally {
if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) {
// The initializer for wrapper i threw an error; initialize the
// remaining wrappers but silence any exceptions from them to ensure
// that the first error is the one to bubble up.
try {
this.initializeAll(i + 1);
} catch (err) {}
}
}
}
},
/**
* Invokes each of `this.transactionWrappers.close[i]` functions, passing into
* them the respective return values of `this.transactionWrappers.init[i]`
* (`close`rs that correspond to initializers that failed will not be
* invoked).
*/
closeAll: function (startIndex) {
!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : undefined;
var transactionWrappers = this.transactionWrappers;
for (var i = startIndex; i < transactionWrappers.length; i++) {
var wrapper = transactionWrappers[i];
var initData = this.wrapperInitData[i];
var errorThrown;
try {
// Catching errors makes debugging more difficult, so we start with
// errorThrown set to true before setting it to false after calling
// close -- if it's still set to true in the finally block, it means
// wrapper.close threw.
errorThrown = true;
if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) {
wrapper.close.call(this, initData);
}
errorThrown = false;
} finally {
if (errorThrown) {
// The closer for wrapper i threw an error; close the remaining
// wrappers but silence any exceptions from them to ensure that the
// first error is the one to bubble up.
try {
this.closeAll(i + 1);
} catch (e) {}
}
}
}
this.wrapperInitData.length = 0;
}
};
var Transaction = {
Mixin: Mixin,
/**
* Token to look for to determine if an error occurred.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 58 */
/*!***********************************!*\
!*** ./~/fbjs/lib/emptyObject.js ***!
\***********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule emptyObject
*/
'use strict';
var emptyObject = {};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 59 */
/*!************************************!*\
!*** ./~/fbjs/lib/containsNode.js ***!
\************************************/
/***/ (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.
*
* @providesModule containsNode
* @typechecks
*/
'use strict';
var isTextNode = __webpack_require__(/*! ./isTextNode */ 60);
/*eslint-disable no-bitwise */
/**
* Checks if a given DOM node contains or is another DOM node.
*
* @param {?DOMNode} outerNode Outer DOM node.
* @param {?DOMNode} innerNode Inner DOM node.
* @return {boolean} True if `outerNode` contains or is `innerNode`.
*/
function containsNode(_x, _x2) {
var _again = true;
_function: while (_again) {
var outerNode = _x,
innerNode = _x2;
_again = false;
if (!outerNode || !innerNode) {
return false;
} else if (outerNode === innerNode) {
return true;
} else if (isTextNode(outerNode)) {
return false;
} else if (isTextNode(innerNode)) {
_x = outerNode;
_x2 = innerNode.parentNode;
_again = true;
continue _function;
} else if (outerNode.contains) {
return outerNode.contains(innerNode);
} else if (outerNode.compareDocumentPosition) {
return !!(outerNode.compareDocumentPosition(innerNode) & 16);
} else {
return false;
}
}
}
module.exports = containsNode;
/***/ }),
/* 60 */
/*!**********************************!*\
!*** ./~/fbjs/lib/isTextNode.js ***!
\**********************************/
/***/ (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.
*
* @providesModule isTextNode
* @typechecks
*/
'use strict';
var isNode = __webpack_require__(/*! ./isNode */ 61);
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM text node.
*/
function isTextNode(object) {
return isNode(object) && object.nodeType == 3;
}
module.exports = isTextNode;
/***/ }),
/* 61 */
/*!******************************!*\
!*** ./~/fbjs/lib/isNode.js ***!
\******************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule isNode
* @typechecks
*/
/**
* @param {*} object The object to check.
* @return {boolean} Whether or not the object is a DOM node.
*/
'use strict';
function isNode(object) {
return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string'));
}
module.exports = isNode;
/***/ }),
/* 62 */
/*!**************************************************!*\
!*** ./~/react/lib/instantiateReactComponent.js ***!
\**************************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule instantiateReactComponent
* @typechecks static-only
*/
'use strict';
var ReactCompositeComponent = __webpack_require__(/*! ./ReactCompositeComponent */ 63);
var ReactEmptyComponent = __webpack_require__(/*! ./ReactEmptyComponent */ 68);
var ReactNativeComponent = __webpack_require__(/*! ./ReactNativeComponent */ 69);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
// To avoid a cyclic dependency, we create the final class in this module
var ReactCompositeComponentWrapper = function () {};
assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, {
_instantiateReactComponent: instantiateReactComponent
});
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Check if the type reference is a known internal type. I.e. not a user
* provided composite type.
*
* @param {function} type
* @return {boolean} Returns true if this is a valid internal type.
*/
function isInternalComponentType(type) {
return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function';
}
/**
* Given a ReactNode, create an instance that will actually be mounted.
*
* @param {ReactNode} node
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(node) {
var instance;
if (node === null || node === false) {
instance = new ReactEmptyComponent(instantiateReactComponent);
} else if (typeof node === 'object') {
var element = node;
!(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : undefined;
// Special case string values
if (typeof element.type === 'string') {
instance = ReactNativeComponent.createInternalComponent(element);
} else if (isInternalComponentType(element.type)) {
// This is temporarily available for custom components that are not string
// representations. I.e. ART. Once those are updated to use the string
// representation, we can drop this code path.
instance = new element.type(element);
} else {
instance = new ReactCompositeComponentWrapper();
}
} else if (typeof node === 'string' || typeof node === 'number') {
instance = ReactNativeComponent.createInstanceForText(node);
} else {
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : undefined;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : undefined;
}
// Sets up the instance. This can probably just move into the constructor now.
instance.construct(node);
// These two fields are used by the DOM and ART diffing algorithms
// respectively. Instead of using expandos on components, we should be
// storing the state needed by the diffing algorithms elsewhere.
instance._mountIndex = 0;
instance._mountImage = null;
if (process.env.NODE_ENV !== 'production') {
instance._isOwnerNecessary = false;
instance._warnedAboutRefsInRender = false;
}
// Internal instances should fully constructed at this point, so they should
// not get any new fields added to them at this point.
if (process.env.NODE_ENV !== 'production') {
if (Object.preventExtensions) {
Object.preventExtensions(instance);
}
}
return instance;
}
module.exports = instantiateReactComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 63 */
/*!************************************************!*\
!*** ./~/react/lib/ReactCompositeComponent.js ***!
\************************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactCompositeComponent
*/
'use strict';
var ReactComponentEnvironment = __webpack_require__(/*! ./ReactComponentEnvironment */ 64);
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactInstanceMap = __webpack_require__(/*! ./ReactInstanceMap */ 47);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var ReactPropTypeLocations = __webpack_require__(/*! ./ReactPropTypeLocations */ 65);
var ReactPropTypeLocationNames = __webpack_require__(/*! ./ReactPropTypeLocationNames */ 66);
var ReactReconciler = __webpack_require__(/*! ./ReactReconciler */ 50);
var ReactUpdateQueue = __webpack_require__(/*! ./ReactUpdateQueue */ 53);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ 58);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var shouldUpdateReactComponent = __webpack_require__(/*! ./shouldUpdateReactComponent */ 67);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
function getDeclarationErrorAddendum(component) {
var owner = component._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
function StatelessComponent(Component) {}
StatelessComponent.prototype.render = function () {
var Component = ReactInstanceMap.get(this)._currentElement.type;
return Component(this.props, this.context, this.updater);
};
/**
* ------------------ The Life-Cycle of a Composite Component ------------------
*
* - constructor: Initialization of state. The instance is now retained.
* - componentWillMount
* - render
* - [children's constructors]
* - [children's componentWillMount and render]
* - [children's componentDidMount]
* - componentDidMount
*
* Update Phases:
* - componentWillReceiveProps (only called if parent updated)
* - shouldComponentUpdate
* - componentWillUpdate
* - render
* - [children's constructors or receive props phases]
* - componentDidUpdate
*
* - componentWillUnmount
* - [children's componentWillUnmount]
* - [children destroyed]
* - (destroyed): The instance is now blank, released by React and ready for GC.
*
* -----------------------------------------------------------------------------
*/
/**
* An incrementing ID assigned to each component when it is mounted. This is
* used to enforce the order in which `ReactUpdates` updates dirty components.
*
* @private
*/
var nextMountID = 1;
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function (element) {
this._currentElement = element;
this._rootNodeID = null;
this._instance = null;
// See ReactUpdateQueue
this._pendingElement = null;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._renderedComponent = null;
this._context = null;
this._mountOrder = 0;
this._topLevelWrapper = null;
// See ReactUpdates and ReactUpdateQueue.
this._pendingCallbacks = null;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: function (rootID, transaction, context) {
this._context = context;
this._mountOrder = nextMountID++;
this._rootNodeID = rootID;
var publicProps = this._processProps(this._currentElement.props);
var publicContext = this._processContext(context);
var Component = this._currentElement.type;
// Initialize the public class
var inst;
var renderedElement;
// This is a way to detect if Component is a stateless arrow function
// component, which is not newable. It might not be 100% reliable but is
// something we can do until we start detecting that Component extends
// React.Component. We already assume that typeof Component === 'function'.
var canInstantiate = ('prototype' in Component);
if (canInstantiate) {
if (process.env.NODE_ENV !== 'production') {
ReactCurrentOwner.current = this;
try {
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
} finally {
ReactCurrentOwner.current = null;
}
} else {
inst = new Component(publicProps, publicContext, ReactUpdateQueue);
}
}
if (!canInstantiate || inst === null || inst === false || ReactElement.isValidElement(inst)) {
renderedElement = inst;
inst = new StatelessComponent(Component);
}
if (process.env.NODE_ENV !== 'production') {
// This will throw later in _renderValidatedComponent, but add an early
// warning now to help debugging
if (inst.render == null) {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`, returned ' + 'null/false from a stateless component, or tried to render an ' + 'element whose type is a function that isn\'t a React component.', Component.displayName || Component.name || 'Component') : undefined;
} else {
// We support ES6 inheriting from React.Component, the module pattern,
// and stateless components, but not ES6 classes that don't extend
process.env.NODE_ENV !== 'production' ? warning(Component.prototype && Component.prototype.isReactComponent || !canInstantiate || !(inst instanceof Component), '%s(...): React component classes must extend React.Component.', Component.displayName || Component.name || 'Component') : undefined;
}
}
// These should be set up in the constructor, but as a convenience for
// simpler class abstractions, we set them up after the fact.
inst.props = publicProps;
inst.context = publicContext;
inst.refs = emptyObject;
inst.updater = ReactUpdateQueue;
this._instance = inst;
// Store a reference from the instance back to the internal representation
ReactInstanceMap.set(inst, this);
if (process.env.NODE_ENV !== 'production') {
// Since plain JS classes are defined without any special initialization
// logic, we can not catch common errors early. Therefore, we have to
// catch them here, at initialization time, instead.
process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.getInitialState.isReactClassApproved, 'getInitialState was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Did you mean to define a state property instead?', this.getName() || 'a component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.getDefaultProps.isReactClassApproved, 'getDefaultProps was defined on %s, a plain JavaScript class. ' + 'This is only supported for classes created using React.createClass. ' + 'Use a static property to define defaultProps instead.', this.getName() || 'a component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%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.', this.getName() || 'A component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : undefined;
}
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
!(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
if (inst.componentWillMount) {
inst.componentWillMount();
// When mounting, calls to `setState` by `componentWillMount` will set
// `this._pendingStateQueue` without triggering a re-render.
if (this._pendingStateQueue) {
inst.state = this._processPendingState(inst.props, inst.context);
}
}
// If not a stateless component, we now render
if (renderedElement === undefined) {
renderedElement = this._renderValidatedComponent();
}
this._renderedComponent = this._instantiateReactComponent(renderedElement);
var markup = ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, this._processChildContext(context));
if (inst.componentDidMount) {
transaction.getReactMountReady().enqueue(inst.componentDidMount, inst);
}
return markup;
},
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function () {
var inst = this._instance;
if (inst.componentWillUnmount) {
inst.componentWillUnmount();
}
ReactReconciler.unmountComponent(this._renderedComponent);
this._renderedComponent = null;
this._instance = null;
// Reset pending fields
// Even if this component is scheduled for another update in ReactUpdates,
// it would still be ignored because these fields are reset.
this._pendingStateQueue = null;
this._pendingReplaceState = false;
this._pendingForceUpdate = false;
this._pendingCallbacks = null;
this._pendingElement = null;
// These fields do not really need to be reset since this object is no
// longer accessible.
this._context = null;
this._rootNodeID = null;
this._topLevelWrapper = null;
// Delete the reference from the instance to this internal representation
// which allow the internals to be properly cleaned up even if the user
// leaks a reference to the public instance.
ReactInstanceMap.remove(inst);
// Some existing components rely on inst.props even after they've been
// destroyed (in event handlers).
// TODO: inst.props = null;
// TODO: inst.state = null;
// TODO: inst.context = null;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`
*
* @param {object} context
* @return {?object}
* @private
*/
_maskContext: function (context) {
var maskedContext = null;
var Component = this._currentElement.type;
var contextTypes = Component.contextTypes;
if (!contextTypes) {
return emptyObject;
}
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
},
/**
* Filters the context object to only contain keys specified in
* `contextTypes`, and asserts that they are valid.
*
* @param {object} context
* @return {?object}
* @private
*/
_processContext: function (context) {
var maskedContext = this._maskContext(context);
if (process.env.NODE_ENV !== 'production') {
var Component = this._currentElement.type;
if (Component.contextTypes) {
this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function (currentContext) {
var Component = this._currentElement.type;
var inst = this._instance;
var childContext = inst.getChildContext && inst.getChildContext();
if (childContext) {
!(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext);
}
for (var name in childContext) {
!(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : undefined;
}
return assign({}, currentContext, childContext);
}
return currentContext;
},
/**
* Processes props by setting default values for unspecified props and
* asserting that the props are valid. Does not mutate its argument; returns
* a new props object with defaults merged in.
*
* @param {object} newProps
* @return {object}
* @private
*/
_processProps: function (newProps) {
if (process.env.NODE_ENV !== 'production') {
var Component = this._currentElement.type;
if (Component.propTypes) {
this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop);
}
}
return newProps;
},
/**
* Assert that the props are valid
*
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
_checkPropTypes: function (propTypes, props, location) {
// TODO: Stop validating prop types here and only use the element
// validation.
var componentName = this.getName();
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error;
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
!(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error = ex;
}
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// top-level render calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
if (location === ReactPropTypeLocations.prop) {
// Preface gives us something to blacklist in warning module
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : undefined;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : undefined;
}
}
}
}
},
receiveComponent: function (nextElement, transaction, nextContext) {
var prevElement = this._currentElement;
var prevContext = this._context;
this._pendingElement = null;
this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext);
},
/**
* If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function (transaction) {
if (this._pendingElement != null) {
ReactReconciler.receiveComponent(this, this._pendingElement || this._currentElement, transaction, this._context);
}
if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);
}
},
/**
* Perform an update to a mounted component. The componentWillReceiveProps and
* shouldComponentUpdate methods are called, then (assuming the update isn't
* skipped) the remaining update lifecycle methods are called and the DOM
* representation is updated.
*
* By default, this implements React's rendering and reconciliation algorithm.
* Sophisticated clients may wish to override this.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevParentElement
* @param {ReactElement} nextParentElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext);
var nextProps;
// Distinguish between a props update versus a simple state update
if (prevParentElement === nextParentElement) {
// Skip checking prop types again -- we don't read inst.props to avoid
// warning for DOM component props in this upgrade
nextProps = nextParentElement.props;
} else {
nextProps = this._processProps(nextParentElement.props);
// An update here will schedule an update but immediately set
// _pendingStateQueue which will ensure that any state updates gets
// immediately reconciled instead of waiting for the next batch.
if (inst.componentWillReceiveProps) {
inst.componentWillReceiveProps(nextProps, nextContext);
}
}
var nextState = this._processPendingState(nextProps, nextContext);
var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext);
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(typeof shouldUpdate !== 'undefined', '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : undefined;
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext);
} else {
// If it's determined that a component should not update, we still want
// to set props and state but we shortcut the rest of the update.
this._currentElement = nextParentElement;
this._context = nextUnmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
}
},
_processPendingState: function (props, context) {
var inst = this._instance;
var queue = this._pendingStateQueue;
var replace = this._pendingReplaceState;
this._pendingReplaceState = false;
this._pendingStateQueue = null;
if (!queue) {
return inst.state;
}
if (replace && queue.length === 1) {
return queue[0];
}
var nextState = assign({}, replace ? queue[0] : inst.state);
for (var i = replace ? 1 : 0; i < queue.length; i++) {
var partial = queue[i];
assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial);
}
return nextState;
},
/**
* Merges new props and state, notifies delegate methods of update and
* performs update.
*
* @param {ReactElement} nextElement Next element
* @param {object} nextProps Next public object to set as properties.
* @param {?object} nextState Next object to set as state.
* @param {?object} nextContext Next public object to set as context.
* @param {ReactReconcileTransaction} transaction
* @param {?object} unmaskedContext
* @private
*/
_performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) {
var inst = this._instance;
var hasComponentDidUpdate = Boolean(inst.componentDidUpdate);
var prevProps;
var prevState;
var prevContext;
if (hasComponentDidUpdate) {
prevProps = inst.props;
prevState = inst.state;
prevContext = inst.context;
}
if (inst.componentWillUpdate) {
inst.componentWillUpdate(nextProps, nextState, nextContext);
}
this._currentElement = nextElement;
this._context = unmaskedContext;
inst.props = nextProps;
inst.state = nextState;
inst.context = nextContext;
this._updateRenderedComponent(transaction, unmaskedContext);
if (hasComponentDidUpdate) {
transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst);
}
},
/**
* Call the component's `render` method and update the DOM accordingly.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
_updateRenderedComponent: function (transaction, context) {
var prevComponentInstance = this._renderedComponent;
var prevRenderedElement = prevComponentInstance._currentElement;
var nextRenderedElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) {
ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context));
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
ReactReconciler.unmountComponent(prevComponentInstance);
this._renderedComponent = this._instantiateReactComponent(nextRenderedElement);
var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, thisID, transaction, this._processChildContext(context));
this._replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
}
},
/**
* @protected
*/
_replaceNodeWithMarkupByID: function (prevComponentID, nextMarkup) {
ReactComponentEnvironment.replaceNodeWithMarkupByID(prevComponentID, nextMarkup);
},
/**
* @protected
*/
_renderValidatedComponentWithoutOwnerOrContext: function () {
var inst = this._instance;
var renderedComponent = inst.render();
if (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
renderedComponent = null;
}
}
return renderedComponent;
},
/**
* @private
*/
_renderValidatedComponent: function () {
var renderedComponent;
ReactCurrentOwner.current = this;
try {
renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext();
} finally {
ReactCurrentOwner.current = null;
}
!(
// TODO: An `isValidNode` function would probably be more appropriate
renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid ReactComponent must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : undefined;
return renderedComponent;
},
/**
* Lazily allocates the refs object and stores `component` as `ref`.
*
* @param {string} ref Reference name.
* @param {component} component Component to store as `ref`.
* @final
* @private
*/
attachRef: function (ref, component) {
var inst = this.getPublicInstance();
!(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : undefined;
var publicComponentInstance = component.getPublicInstance();
if (process.env.NODE_ENV !== 'production') {
var componentName = component && component.getName ? component.getName() : 'a component';
process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : undefined;
}
var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs;
refs[ref] = publicComponentInstance;
},
/**
* Detaches a reference name.
*
* @param {string} ref Name to dereference.
* @final
* @private
*/
detachRef: function (ref) {
var refs = this.getPublicInstance().refs;
delete refs[ref];
},
/**
* Get a text description of the component that can be used to identify it
* in error messages.
* @return {string} The name or null.
* @internal
*/
getName: function () {
var type = this._currentElement.type;
var constructor = this._instance && this._instance.constructor;
return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
},
/**
* Get the publicly accessible representation of this component - i.e. what
* is exposed by refs and returned by render. Can be null for stateless
* components.
*
* @return {ReactComponent} the public component instance.
* @internal
*/
getPublicInstance: function () {
var inst = this._instance;
if (inst instanceof StatelessComponent) {
return null;
}
return inst;
},
// Stub
_instantiateReactComponent: null
};
ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', {
mountComponent: 'mountComponent',
updateComponent: 'updateComponent',
_renderValidatedComponent: '_renderValidatedComponent'
});
var ReactCompositeComponent = {
Mixin: ReactCompositeComponentMixin
};
module.exports = ReactCompositeComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 64 */
/*!**************************************************!*\
!*** ./~/react/lib/ReactComponentEnvironment.js ***!
\**************************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactComponentEnvironment
*/
'use strict';
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var injected = false;
var ReactComponentEnvironment = {
/**
* Optionally injectable environment dependent cleanup hook. (server vs.
* browser etc). Example: A browser system caches DOM nodes based on component
* ID and must remove that cache entry when this instance is unmounted.
*/
unmountIDFromEnvironment: null,
/**
* Optionally injectable hook for swapping out mount images in the middle of
* the tree.
*/
replaceNodeWithMarkupByID: null,
/**
* Optionally injectable hook for processing a queue of child updates. Will
* later move into MultiChildComponents.
*/
processChildrenUpdates: null,
injection: {
injectEnvironment: function (environment) {
!!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : undefined;
ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment;
ReactComponentEnvironment.replaceNodeWithMarkupByID = environment.replaceNodeWithMarkupByID;
ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates;
injected = true;
}
}
};
module.exports = ReactComponentEnvironment;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 65 */
/*!***********************************************!*\
!*** ./~/react/lib/ReactPropTypeLocations.js ***!
\***********************************************/
/***/ (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.
*
* @providesModule ReactPropTypeLocations
*/
'use strict';
var keyMirror = __webpack_require__(/*! fbjs/lib/keyMirror */ 17);
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
/***/ }),
/* 66 */
/*!***************************************************!*\
!*** ./~/react/lib/ReactPropTypeLocationNames.js ***!
\***************************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactPropTypeLocationNames
*/
'use strict';
var ReactPropTypeLocationNames = {};
if (process.env.NODE_ENV !== 'production') {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 67 */
/*!***************************************************!*\
!*** ./~/react/lib/shouldUpdateReactComponent.js ***!
\***************************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule shouldUpdateReactComponent
* @typechecks static-only
*/
'use strict';
/**
* Given a `prevElement` and `nextElement`, determines if the existing
* instance should be updated as opposed to being destroyed or replaced by a new
* instance. Both arguments are elements. This ensures that this logic can
* operate on stateless trees without any backing instance.
*
* @param {?object} prevElement
* @param {?object} nextElement
* @return {boolean} True if the existing instance should be updated.
* @protected
*/
function shouldUpdateReactComponent(prevElement, nextElement) {
var prevEmpty = prevElement === null || prevElement === false;
var nextEmpty = nextElement === null || nextElement === false;
if (prevEmpty || nextEmpty) {
return prevEmpty === nextEmpty;
}
var prevType = typeof prevElement;
var nextType = typeof nextElement;
if (prevType === 'string' || prevType === 'number') {
return nextType === 'string' || nextType === 'number';
} else {
return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key;
}
return false;
}
module.exports = shouldUpdateReactComponent;
/***/ }),
/* 68 */
/*!********************************************!*\
!*** ./~/react/lib/ReactEmptyComponent.js ***!
\********************************************/
/***/ (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.
*
* @providesModule ReactEmptyComponent
*/
'use strict';
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactEmptyComponentRegistry = __webpack_require__(/*! ./ReactEmptyComponentRegistry */ 44);
var ReactReconciler = __webpack_require__(/*! ./ReactReconciler */ 50);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var placeholderElement;
var ReactEmptyComponentInjection = {
injectEmptyComponent: function (component) {
placeholderElement = ReactElement.createElement(component);
}
};
function registerNullComponentID() {
ReactEmptyComponentRegistry.registerNullComponentID(this._rootNodeID);
}
var ReactEmptyComponent = function (instantiate) {
this._currentElement = null;
this._rootNodeID = null;
this._renderedComponent = instantiate(placeholderElement);
};
assign(ReactEmptyComponent.prototype, {
construct: function (element) {},
mountComponent: function (rootID, transaction, context) {
transaction.getReactMountReady().enqueue(registerNullComponentID, this);
this._rootNodeID = rootID;
return ReactReconciler.mountComponent(this._renderedComponent, rootID, transaction, context);
},
receiveComponent: function () {},
unmountComponent: function (rootID, transaction, context) {
ReactReconciler.unmountComponent(this._renderedComponent);
ReactEmptyComponentRegistry.deregisterNullComponentID(this._rootNodeID);
this._rootNodeID = null;
this._renderedComponent = null;
}
});
ReactEmptyComponent.injection = ReactEmptyComponentInjection;
module.exports = ReactEmptyComponent;
/***/ }),
/* 69 */
/*!*********************************************!*\
!*** ./~/react/lib/ReactNativeComponent.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactNativeComponent
*/
'use strict';
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var autoGenerateWrapperClass = null;
var genericComponentClass = null;
// This registry keeps track of wrapper classes around native tags.
var tagToComponentClass = {};
var textComponentClass = null;
var ReactNativeComponentInjection = {
// This accepts a class that receives the tag string. This is a catch all
// that can render any kind of tag.
injectGenericComponentClass: function (componentClass) {
genericComponentClass = componentClass;
},
// This accepts a text component class that takes the text string to be
// rendered as props.
injectTextComponentClass: function (componentClass) {
textComponentClass = componentClass;
},
// This accepts a keyed object with classes as values. Each key represents a
// tag. That particular tag will use this class instead of the generic one.
injectComponentClasses: function (componentClasses) {
assign(tagToComponentClass, componentClasses);
}
};
/**
* Get a composite component wrapper class for a specific tag.
*
* @param {ReactElement} element The tag for which to get the class.
* @return {function} The React class constructor function.
*/
function getComponentClassForElement(element) {
if (typeof element.type === 'function') {
return element.type;
}
var tag = element.type;
var componentClass = tagToComponentClass[tag];
if (componentClass == null) {
tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag);
}
return componentClass;
}
/**
* Get a native internal component class for a specific tag.
*
* @param {ReactElement} element The element to create.
* @return {function} The internal class constructor function.
*/
function createInternalComponent(element) {
!genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : undefined;
return new genericComponentClass(element.type, element.props);
}
/**
* @param {ReactText} text
* @return {ReactComponent}
*/
function createInstanceForText(text) {
return new textComponentClass(text);
}
/**
* @param {ReactComponent} component
* @return {boolean}
*/
function isTextComponent(component) {
return component instanceof textComponentClass;
}
var ReactNativeComponent = {
getComponentClassForElement: getComponentClassForElement,
createInternalComponent: createInternalComponent,
createInstanceForText: createInstanceForText,
isTextComponent: isTextComponent,
injection: ReactNativeComponentInjection
};
module.exports = ReactNativeComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 70 */
/*!*******************************************!*\
!*** ./~/react/lib/validateDOMNesting.js ***!
\*******************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule validateDOMNesting
*/
'use strict';
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ 15);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var validateDOMNesting = emptyFunction;
if (process.env.NODE_ENV !== 'production') {
// This validation code was written based on the HTML5 parsing spec:
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
//
// Note: this does not catch all invalid nesting, nor does it try to (as it's
// not clear what practical benefit doing so provides); instead, we warn only
// for cases where the parser will give a parse tree differing from what React
// intended. For example, <b><div></div></b> is invalid but we don't warn
// because it still parses correctly; we do warn for other cases like nested
// <p> tags where the beginning of the second element implicitly closes the
// first, causing a confusing mess.
// https://html.spec.whatwg.org/multipage/syntax.html#special
var specialTags = ['address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope
var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template',
// https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point
// TODO: Distinguish by namespace here -- for <title>, including it here
// errs on the side of fewer warnings
'foreignObject', 'desc', 'title'];
// https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope
var buttonScopeTags = inScopeTags.concat(['button']);
// https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags
var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'];
var emptyAncestorInfo = {
parentTag: null,
formTag: null,
aTagInScope: null,
buttonTagInScope: null,
nobrTagInScope: null,
pTagInButtonScope: null,
listItemTagAutoclosing: null,
dlItemTagAutoclosing: null
};
var updatedAncestorInfo = function (oldInfo, tag, instance) {
var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo);
var info = { tag: tag, instance: instance };
if (inScopeTags.indexOf(tag) !== -1) {
ancestorInfo.aTagInScope = null;
ancestorInfo.buttonTagInScope = null;
ancestorInfo.nobrTagInScope = null;
}
if (buttonScopeTags.indexOf(tag) !== -1) {
ancestorInfo.pTagInButtonScope = null;
}
// See rules for 'li', 'dd', 'dt' start tags in
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') {
ancestorInfo.listItemTagAutoclosing = null;
ancestorInfo.dlItemTagAutoclosing = null;
}
ancestorInfo.parentTag = info;
if (tag === 'form') {
ancestorInfo.formTag = info;
}
if (tag === 'a') {
ancestorInfo.aTagInScope = info;
}
if (tag === 'button') {
ancestorInfo.buttonTagInScope = info;
}
if (tag === 'nobr') {
ancestorInfo.nobrTagInScope = info;
}
if (tag === 'p') {
ancestorInfo.pTagInButtonScope = info;
}
if (tag === 'li') {
ancestorInfo.listItemTagAutoclosing = info;
}
if (tag === 'dd' || tag === 'dt') {
ancestorInfo.dlItemTagAutoclosing = info;
}
return ancestorInfo;
};
/**
* Returns whether
*/
var isTagValidWithParent = function (tag, parentTag) {
// First, let's check if we're in an unusual parsing mode...
switch (parentTag) {
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect
case 'select':
return tag === 'option' || tag === 'optgroup' || tag === '#text';
case 'optgroup':
return tag === 'option' || tag === '#text';
// Strictly speaking, seeing an <option> doesn't mean we're in a <select>
// but
case 'option':
return tag === '#text';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption
// No special behavior since these rules fall back to "in body" mode for
// all except special table nodes which cause bad parsing behavior anyway.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr
case 'tr':
return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody
case 'tbody':
case 'thead':
case 'tfoot':
return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup
case 'colgroup':
return tag === 'col' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable
case 'table':
return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead
case 'head':
return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template';
// https://html.spec.whatwg.org/multipage/semantics.html#the-html-element
case 'html':
return tag === 'head' || tag === 'body';
}
// Probably in the "in body" parsing mode, so we outlaw only tag combos
// where the parsing rules cause implicit opens or closes to be added.
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody
switch (tag) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6';
case 'rp':
case 'rt':
return impliedEndTags.indexOf(parentTag) === -1;
case 'caption':
case 'col':
case 'colgroup':
case 'frame':
case 'head':
case 'tbody':
case 'td':
case 'tfoot':
case 'th':
case 'thead':
case 'tr':
// These tags are only valid with a few parents that have special child
// parsing rules -- if we're down here, then none of those matched and
// so we allow it only if we don't know what the parent is, as all other
// cases are invalid.
return parentTag == null;
}
return true;
};
/**
* Returns whether
*/
var findInvalidAncestorForTag = function (tag, ancestorInfo) {
switch (tag) {
case 'address':
case 'article':
case 'aside':
case 'blockquote':
case 'center':
case 'details':
case 'dialog':
case 'dir':
case 'div':
case 'dl':
case 'fieldset':
case 'figcaption':
case 'figure':
case 'footer':
case 'header':
case 'hgroup':
case 'main':
case 'menu':
case 'nav':
case 'ol':
case 'p':
case 'section':
case 'summary':
case 'ul':
case 'pre':
case 'listing':
case 'table':
case 'hr':
case 'xmp':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return ancestorInfo.pTagInButtonScope;
case 'form':
return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
case 'li':
return ancestorInfo.listItemTagAutoclosing;
case 'dd':
case 'dt':
return ancestorInfo.dlItemTagAutoclosing;
case 'button':
return ancestorInfo.buttonTagInScope;
case 'a':
// Spec says something about storing a list of markers, but it sounds
// equivalent to this check.
return ancestorInfo.aTagInScope;
case 'nobr':
return ancestorInfo.nobrTagInScope;
}
return null;
};
/**
* Given a ReactCompositeComponent instance, return a list of its recursive
* owners, starting at the root and ending with the instance itself.
*/
var findOwnerStack = function (instance) {
if (!instance) {
return [];
}
var stack = [];
/*eslint-disable space-after-keywords */
do {
/*eslint-enable space-after-keywords */
stack.push(instance);
} while (instance = instance._currentElement._owner);
stack.reverse();
return stack;
};
var didWarn = {};
validateDOMNesting = function (childTag, childInstance, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.parentTag;
var parentTag = parentInfo && parentInfo.tag;
var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo;
var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
var problematic = invalidParent || invalidAncestor;
if (problematic) {
var ancestorTag = problematic.tag;
var ancestorInstance = problematic.instance;
var childOwner = childInstance && childInstance._currentElement._owner;
var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner;
var childOwners = findOwnerStack(childOwner);
var ancestorOwners = findOwnerStack(ancestorOwner);
var minStackLen = Math.min(childOwners.length, ancestorOwners.length);
var i;
var deepestCommon = -1;
for (i = 0; i < minStackLen; i++) {
if (childOwners[i] === ancestorOwners[i]) {
deepestCommon = i;
} else {
break;
}
}
var UNKNOWN = '(unknown)';
var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) {
return inst.getName() || UNKNOWN;
});
var ownerInfo = [].concat(
// If the parent and child instances have a common owner ancestor, start
// with that -- otherwise we just start with the parent's owners.
deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag,
// If we're warning about an invalid (non-parent) ancestry, add '...'
invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > ');
var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo;
if (didWarn[warnKey]) {
return;
}
didWarn[warnKey] = true;
if (invalidParent) {
var info = '';
if (ancestorTag === 'table' && childTag === 'tr') {
info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.';
}
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + 'See %s.%s', childTag, ancestorTag, ownerInfo, info) : undefined;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + '<%s>. See %s.', childTag, ancestorTag, ownerInfo) : undefined;
}
}
};
validateDOMNesting.ancestorInfoContextKey = '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2);
validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo;
// For testing
validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) {
ancestorInfo = ancestorInfo || emptyAncestorInfo;
var parentInfo = ancestorInfo.parentTag;
var parentTag = parentInfo && parentInfo.tag;
return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo);
};
}
module.exports = validateDOMNesting;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 71 */
/*!**********************************************!*\
!*** ./~/react/lib/ReactDefaultInjection.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDefaultInjection
*/
'use strict';
var BeforeInputEventPlugin = __webpack_require__(/*! ./BeforeInputEventPlugin */ 72);
var ChangeEventPlugin = __webpack_require__(/*! ./ChangeEventPlugin */ 80);
var ClientReactRootIndex = __webpack_require__(/*! ./ClientReactRootIndex */ 83);
var DefaultEventPluginOrder = __webpack_require__(/*! ./DefaultEventPluginOrder */ 84);
var EnterLeaveEventPlugin = __webpack_require__(/*! ./EnterLeaveEventPlugin */ 85);
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var HTMLDOMPropertyConfig = __webpack_require__(/*! ./HTMLDOMPropertyConfig */ 89);
var ReactBrowserComponentMixin = __webpack_require__(/*! ./ReactBrowserComponentMixin */ 90);
var ReactComponentBrowserEnvironment = __webpack_require__(/*! ./ReactComponentBrowserEnvironment */ 26);
var ReactDefaultBatchingStrategy = __webpack_require__(/*! ./ReactDefaultBatchingStrategy */ 92);
var ReactDOMComponent = __webpack_require__(/*! ./ReactDOMComponent */ 93);
var ReactDOMTextComponent = __webpack_require__(/*! ./ReactDOMTextComponent */ 6);
var ReactEventListener = __webpack_require__(/*! ./ReactEventListener */ 118);
var ReactInjection = __webpack_require__(/*! ./ReactInjection */ 121);
var ReactInstanceHandles = __webpack_require__(/*! ./ReactInstanceHandles */ 45);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var ReactReconcileTransaction = __webpack_require__(/*! ./ReactReconcileTransaction */ 125);
var SelectEventPlugin = __webpack_require__(/*! ./SelectEventPlugin */ 130);
var ServerReactRootIndex = __webpack_require__(/*! ./ServerReactRootIndex */ 131);
var SimpleEventPlugin = __webpack_require__(/*! ./SimpleEventPlugin */ 132);
var SVGDOMPropertyConfig = __webpack_require__(/*! ./SVGDOMPropertyConfig */ 141);
var alreadyInjected = false;
function inject() {
if (alreadyInjected) {
// TODO: This is currently true because these injections are shared between
// the client and the server package. They should be built independently
// and not share any injection state. Then this problem will be solved.
return;
}
alreadyInjected = true;
ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles);
ReactInjection.EventPluginHub.injectMount(ReactMount);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent);
ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent);
ReactInjection.Class.injectMixin(ReactBrowserComponentMixin);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponent('noscript');
ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction);
ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy);
ReactInjection.RootIndex.injectCreateReactRootIndex(ExecutionEnvironment.canUseDOM ? ClientReactRootIndex.createReactRootIndex : ServerReactRootIndex.createReactRootIndex);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if (process.env.NODE_ENV !== 'production') {
var url = ExecutionEnvironment.canUseDOM && window.location.href || '';
if (/[?&]react_perf\b/.test(url)) {
var ReactDefaultPerf = __webpack_require__(/*! ./ReactDefaultPerf */ 142);
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 72 */
/*!***********************************************!*\
!*** ./~/react/lib/BeforeInputEventPlugin.js ***!
\***********************************************/
/***/ (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.
*
* @providesModule BeforeInputEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var EventPropagators = __webpack_require__(/*! ./EventPropagators */ 73);
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var FallbackCompositionState = __webpack_require__(/*! ./FallbackCompositionState */ 74);
var SyntheticCompositionEvent = __webpack_require__(/*! ./SyntheticCompositionEvent */ 76);
var SyntheticInputEvent = __webpack_require__(/*! ./SyntheticInputEvent */ 78);
var keyOf = __webpack_require__(/*! fbjs/lib/keyOf */ 79);
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window;
var documentMode = null;
if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) {
documentMode = document.documentMode;
}
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto();
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11);
/**
* Opera <= 12 includes TextEvent in window, but does not fire
* text input events. Rely on keypress instead.
*/
function isPresto() {
var opera = window.opera;
return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12;
}
var SPACEBAR_CODE = 32;
var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
var topLevelTypes = EventConstants.topLevelTypes;
// Events and their corresponding property names.
var eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: keyOf({ onBeforeInput: null }),
captured: keyOf({ onBeforeInputCapture: null })
},
dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste]
},
compositionEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionEnd: null }),
captured: keyOf({ onCompositionEndCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionStart: null }),
captured: keyOf({ onCompositionStartCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
},
compositionUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onCompositionUpdate: null }),
captured: keyOf({ onCompositionUpdateCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown]
}
};
// Track whether we've ever handled a keypress on the space key.
var hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey);
}
/**
* Translate native top level events into event types.
*
* @param {string} topLevelType
* @return {object}
*/
function getCompositionEventType(topLevelType) {
switch (topLevelType) {
case topLevelTypes.topCompositionStart:
return eventTypes.compositionStart;
case topLevelTypes.topCompositionEnd:
return eventTypes.compositionEnd;
case topLevelTypes.topCompositionUpdate:
return eventTypes.compositionUpdate;
}
}
/**
* Does our fallback best-guess model think this event signifies that
* composition has begun?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionStart(topLevelType, nativeEvent) {
return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE;
}
/**
* Does our fallback mode think that this event is the end of composition?
*
* @param {string} topLevelType
* @param {object} nativeEvent
* @return {boolean}
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topKeyUp:
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case topLevelTypes.topKeyDown:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case topLevelTypes.topKeyPress:
case topLevelTypes.topMouseDown:
case topLevelTypes.topBlur:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
* @param {object} nativeEvent
* @return {?string}
*/
function getDataFromCustomEvent(nativeEvent) {
var detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
// Track the current IME composition fallback object, if any.
var currentComposition = null;
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {?object} A SyntheticCompositionEvent.
*/
function extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var eventType;
var fallbackData;
if (canUseCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackCompositionStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (!eventType) {
return null;
}
if (useFallbackCompositionData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = FallbackCompositionState.getPooled(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
fallbackData = currentComposition.getData();
}
}
}
var event = SyntheticCompositionEvent.getPooled(eventType, topLevelTargetID, nativeEvent, nativeEventTarget);
if (fallbackData) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = fallbackData;
} else {
var customData = getDataFromCustomEvent(nativeEvent);
if (customData !== null) {
event.data = customData;
}
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The string corresponding to this `beforeInput` event.
*/
function getNativeBeforeInputChars(topLevelType, nativeEvent) {
switch (topLevelType) {
case topLevelTypes.topCompositionEnd:
return getDataFromCustomEvent(nativeEvent);
case topLevelTypes.topKeyPress:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
var which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
var chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to blacklist it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} nativeEvent Native browser event.
* @return {?string} The fallback string for this `beforeInput` event.
*/
function getFallbackBeforeInputChars(topLevelType, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
if (currentComposition) {
if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) {
var chars = currentComposition.getData();
FallbackCompositionState.release(currentComposition);
currentComposition = null;
return chars;
}
return null;
}
switch (topLevelType) {
case topLevelTypes.topPaste:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case topLevelTypes.topKeyPress:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (nativeEvent.which && !isKeypressCommand(nativeEvent)) {
return String.fromCharCode(nativeEvent.which);
}
return null;
case topLevelTypes.topCompositionEnd:
return useFallbackCompositionData ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {?object} A SyntheticInputEvent.
*/
function extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, topLevelTargetID, nativeEvent, nativeEventTarget);
event.data = chars;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
return [extractCompositionEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget)];
}
};
module.exports = BeforeInputEventPlugin;
/***/ }),
/* 73 */
/*!*****************************************!*\
!*** ./~/react/lib/EventPropagators.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule EventPropagators
*/
'use strict';
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var EventPluginHub = __webpack_require__(/*! ./EventPluginHub */ 31);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var accumulateInto = __webpack_require__(/*! ./accumulateInto */ 35);
var forEachAccumulated = __webpack_require__(/*! ./forEachAccumulated */ 36);
var PropagationPhases = EventConstants.PropagationPhases;
var getListener = EventPluginHub.getListener;
/**
* Some event types have a notion of different registration names for different
* "phases" of propagation. This finds listeners by a given phase.
*/
function listenerAtPhase(id, event, propagationPhase) {
var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(id, registrationName);
}
/**
* Tags a `SyntheticEvent` with dispatched listeners. Creating this function
* here, allows us to not have to bind or create functions for each event.
* Mutating the event's members allows us to not have to create a wrapping
* "dispatch" object that pairs the event with the listener.
*/
function accumulateDirectionalDispatches(domID, upwards, event) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(domID, 'Dispatching id must not be null') : undefined;
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, domID);
}
}
/**
* Collect dispatches (must be entirely collected before dispatching - see unit
* tests). Lazily allocate the array to conserve memory. We must loop through
* each event and perform the traversal for each one. We cannot perform a
* single traversal for the entire collection of events because each event may
* have a different target.
*/
function accumulateTwoPhaseDispatchesSingle(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker, accumulateDirectionalDispatches, event);
}
}
/**
* Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID.
*/
function accumulateTwoPhaseDispatchesSingleSkipTarget(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(event.dispatchMarker, accumulateDirectionalDispatches, event);
}
}
/**
* Accumulates without regard to direction, does not look for phased
* registration names. Same as `accumulateDirectDispatchesSingle` but without
* requiring that the `dispatchMarker` be the same as the dispatched ID.
*/
function accumulateDispatches(id, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(id, registrationName);
if (listener) {
event._dispatchListeners = accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event.dispatchMarker, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateTwoPhaseDispatchesSkipTarget(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(fromID, toID, accumulateDispatches, leave, enter);
}
function accumulateDirectDispatches(events) {
forEachAccumulated(events, accumulateDirectDispatchesSingle);
}
/**
* A small set of propagation patterns, each of which will accept a small amount
* of information, and generate a set of "dispatch ready event objects" - which
* are sets of events that have already been annotated with a set of dispatched
* listener functions/ids. The API is designed this way to discourage these
* propagation strategies from actually executing the dispatches, since we
* always want to collect the entire set of dispatches before executing event a
* single one.
*
* @constructor EventPropagators
*/
var EventPropagators = {
accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches,
accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 74 */
/*!*************************************************!*\
!*** ./~/react/lib/FallbackCompositionState.js ***!
\*************************************************/
/***/ (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.
*
* @providesModule FallbackCompositionState
* @typechecks static-only
*/
'use strict';
var PooledClass = __webpack_require__(/*! ./PooledClass */ 56);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var getTextContentAccessor = __webpack_require__(/*! ./getTextContentAccessor */ 75);
/**
* This helper class stores information about text content of a target node,
* allowing comparison of content before and after a given event.
*
* Identify the node where selection currently begins, then observe
* both its text content and its current position in the DOM. Since the
* browser may natively replace the target node during composition, we can
* use its position to find its replacement.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this._root = root;
this._startText = this.getText();
this._fallbackText = null;
}
assign(FallbackCompositionState.prototype, {
destructor: function () {
this._root = null;
this._startText = null;
this._fallbackText = null;
},
/**
* Get current text of input.
*
* @return {string}
*/
getText: function () {
if ('value' in this._root) {
return this._root.value;
}
return this._root[getTextContentAccessor()];
},
/**
* Determine the differing substring between the initially stored
* text content and the current content.
*
* @return {string}
*/
getData: function () {
if (this._fallbackText) {
return this._fallbackText;
}
var start;
var startValue = this._startText;
var startLength = startValue.length;
var end;
var endValue = this.getText();
var endLength = endValue.length;
for (start = 0; start < startLength; start++) {
if (startValue[start] !== endValue[start]) {
break;
}
}
var minEnd = startLength - start;
for (end = 1; end <= minEnd; end++) {
if (startValue[startLength - end] !== endValue[endLength - end]) {
break;
}
}
var sliceTail = end > 1 ? 1 - end : undefined;
this._fallbackText = endValue.slice(start, sliceTail);
return this._fallbackText;
}
});
PooledClass.addPoolingTo(FallbackCompositionState);
module.exports = FallbackCompositionState;
/***/ }),
/* 75 */
/*!***********************************************!*\
!*** ./~/react/lib/getTextContentAccessor.js ***!
\***********************************************/
/***/ (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.
*
* @providesModule getTextContentAccessor
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var contentKey = null;
/**
* Gets the key used to access text content on a DOM node.
*
* @return {?string} Key used to access text content.
* @internal
*/
function getTextContentAccessor() {
if (!contentKey && ExecutionEnvironment.canUseDOM) {
// Prefer textContent to innerText because many browsers support both but
// SVG <text> elements don't support innerText even when <div> does.
contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText';
}
return contentKey;
}
module.exports = getTextContentAccessor;
/***/ }),
/* 76 */
/*!**************************************************!*\
!*** ./~/react/lib/SyntheticCompositionEvent.js ***!
\**************************************************/
/***/ (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.
*
* @providesModule SyntheticCompositionEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = __webpack_require__(/*! ./SyntheticEvent */ 77);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
*/
var CompositionEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface);
module.exports = SyntheticCompositionEvent;
/***/ }),
/* 77 */
/*!***************************************!*\
!*** ./~/react/lib/SyntheticEvent.js ***!
\***************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule SyntheticEvent
* @typechecks static-only
*/
'use strict';
var PooledClass = __webpack_require__(/*! ./PooledClass */ 56);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ 15);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: emptyFunction.thatReturnsNull,
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return event.timeStamp || Date.now();
},
defaultPrevented: null,
isTrusted: null
};
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
*/
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
this.dispatchConfig = dispatchConfig;
this.dispatchMarker = dispatchMarker;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
this.target = nativeEventTarget;
} else {
this[propName] = nativeEvent[propName];
}
}
}
var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
if (defaultPrevented) {
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
} else {
this.isDefaultPrevented = emptyFunction.thatReturnsFalse;
}
this.isPropagationStopped = emptyFunction.thatReturnsFalse;
}
assign(SyntheticEvent.prototype, {
preventDefault: function () {
this.defaultPrevented = true;
var event = this.nativeEvent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `preventDefault` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
}
if (!event) {
return;
}
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function () {
var event = this.nativeEvent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(event, 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re calling `stopPropagation` on a ' + 'released/nullified synthetic event. This is a no-op. See ' + 'https://fb.me/react-event-pooling for more information.') : undefined;
}
if (!event) {
return;
}
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
this.isPropagationStopped = emptyFunction.thatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
this.isPersistent = emptyFunction.thatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: emptyFunction.thatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function () {
var Interface = this.constructor.Interface;
for (var propName in Interface) {
this[propName] = null;
}
this.dispatchConfig = null;
this.dispatchMarker = null;
this.nativeEvent = null;
}
});
SyntheticEvent.Interface = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function (Class, Interface) {
var Super = this;
var prototype = Object.create(Super.prototype);
assign(prototype, Class.prototype);
Class.prototype = prototype;
Class.prototype.constructor = Class;
Class.Interface = assign({}, Super.Interface, Interface);
Class.augmentClass = Super.augmentClass;
PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler);
module.exports = SyntheticEvent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 78 */
/*!********************************************!*\
!*** ./~/react/lib/SyntheticInputEvent.js ***!
\********************************************/
/***/ (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.
*
* @providesModule SyntheticInputEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = __webpack_require__(/*! ./SyntheticEvent */ 77);
/**
* @interface Event
* @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105
* /#events-inputevents
*/
var InputEventInterface = {
data: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface);
module.exports = SyntheticInputEvent;
/***/ }),
/* 79 */
/*!*****************************!*\
!*** ./~/fbjs/lib/keyOf.js ***!
\*****************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
"use strict";
var keyOf = function (oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ }),
/* 80 */
/*!******************************************!*\
!*** ./~/react/lib/ChangeEventPlugin.js ***!
\******************************************/
/***/ (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.
*
* @providesModule ChangeEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var EventPluginHub = __webpack_require__(/*! ./EventPluginHub */ 31);
var EventPropagators = __webpack_require__(/*! ./EventPropagators */ 73);
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var SyntheticEvent = __webpack_require__(/*! ./SyntheticEvent */ 77);
var getEventTarget = __webpack_require__(/*! ./getEventTarget */ 81);
var isEventSupported = __webpack_require__(/*! ./isEventSupported */ 40);
var isTextInputElement = __webpack_require__(/*! ./isTextInputElement */ 82);
var keyOf = __webpack_require__(/*! fbjs/lib/keyOf */ 79);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
change: {
phasedRegistrationNames: {
bubbled: keyOf({ onChange: null }),
captured: keyOf({ onChangeCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange]
}
};
/**
* For IE shims
*/
var activeElement = null;
var activeElementID = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
var nodeName = elem.nodeName && elem.nodeName.toLowerCase();
return nodeName === 'select' || nodeName === 'input' && elem.type === 'file';
}
var doesChangeEventBubble = false;
if (ExecutionEnvironment.canUseDOM) {
// See `handleChange` comment below
doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8);
}
function manualDispatchChangeEvent(nativeEvent) {
var event = SyntheticEvent.getPooled(eventTypes.change, activeElementID, nativeEvent, getEventTarget(nativeEvent));
EventPropagators.accumulateTwoPhaseDispatches(event);
// If change and propertychange bubbled, we'd just bind to it like all the
// other events and have it go through ReactBrowserEventEmitter. Since it
// doesn't, we manually listen for the events and so we have to enqueue and
// process the abstract event manually.
//
// Batching is necessary here in order to ensure that all event handlers run
// before the next rerender (including event handlers attached to ancestor
// elements instead of directly on the input). Without this, controlled
// components don't work properly in conjunction with event bubbling because
// the component is rerendered and the value reverted before all the event
// handlers can run. See https://github.com/facebook/react/issues/708.
ReactUpdates.batchedUpdates(runEventInBatch, event);
}
function runEventInBatch(event) {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue(false);
}
function startWatchingForChangeEventIE8(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementID = null;
}
function getTargetIDForChangeEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topChange) {
return topLevelTargetID;
}
}
function handleEventsForChangeEventIE8(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForChangeEventIE8();
startWatchingForChangeEventIE8(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForChangeEventIE8();
}
}
/**
* SECTION: handle `input` event
*/
var isInputEventSupported = false;
if (ExecutionEnvironment.canUseDOM) {
// IE9 claims to support the input event but fails to trigger it when
// deleting text, so we ignore its input events
isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 9);
}
/**
* (For old IE.) Replacement getter/setter for the `value` property that gets
* set on the active element.
*/
var newValueProp = {
get: function () {
return activeElementValueProp.get.call(this);
},
set: function (val) {
// Cast to a string so we can do equality checks.
activeElementValue = '' + val;
activeElementValueProp.set.call(this, val);
}
};
/**
* (For old IE.) Starts tracking propertychange events on the passed-in element
* and override the value property so that we can distinguish user events from
* value changes in JS.
*/
function startWatchingForValueChange(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value');
// Not guarded in a canDefineProperty check: IE8 supports defineProperty only
// on DOM elements
Object.defineProperty(activeElement, 'value', newValueProp);
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
* (For old IE.) Removes the event listeners from the currently-tracked element,
* if any exists.
*/
function stopWatchingForValueChange() {
if (!activeElement) {
return;
}
// delete restores the original property definition
delete activeElement.value;
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementID = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For old IE.) Handles a propertychange event, sending a `change` event if
* the value of the active element has changed.
*/
function handlePropertyChange(nativeEvent) {
if (nativeEvent.propertyName !== 'value') {
return;
}
var value = nativeEvent.srcElement.value;
if (value === activeElementValue) {
return;
}
activeElementValue = value;
manualDispatchChangeEvent(nativeEvent);
}
/**
* If a `change` event should be fired, returns the target's ID.
*/
function getTargetIDForInputEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topInput) {
// In modern browsers (i.e., not IE8 or IE9), the input event is exactly
// what we want so fall through here and trigger an abstract event
return topLevelTargetID;
}
}
// For IE8 and IE9.
function handleEventsForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topFocus) {
// In IE8, we can capture almost all .value changes by adding a
// propertychange handler and looking for events with propertyName
// equal to 'value'
// In IE9, propertychange fires for most input events but is buggy and
// doesn't fire when text is deleted, but conveniently, selectionchange
// appears to fire in all of the remaining cases so we catch those and
// forward the event if the value has changed
// In either case, we don't want to call the event handler if the value
// is changed from JS so we redefine a setter for `.value` that updates
// our activeElementValue variable, allowing us to ignore those changes
//
// stopWatching() should be a noop here but we call it just in case we
// missed a blur event somehow.
stopWatchingForValueChange();
startWatchingForValueChange(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetIDForInputEventIE(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) {
// On the selectionchange event, the target is just document which isn't
// helpful for us so just check activeElement instead.
//
// 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire
// propertychange on the first input event after setting `value` from a
// script and fires only keydown, keypress, keyup. Catching keyup usually
// gets it and catching keydown lets us fire an event for the first
// keystroke if user does a key repeat (it'll be a little delayed: right
// before the second keystroke). Other input methods (e.g., paste) seem to
// fire selectionchange normally.
if (activeElement && activeElement.value !== activeElementValue) {
activeElementValue = activeElement.value;
return activeElementID;
}
}
}
/**
* SECTION: handle `click` event
*/
function shouldUseClickEvent(elem) {
// Use the `click` event to detect changes to checkbox and radio inputs.
// This approach works across all browsers, whereas `change` does not fire
// until `blur` in IE8.
return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio');
}
function getTargetIDForClickEvent(topLevelType, topLevelTarget, topLevelTargetID) {
if (topLevelType === topLevelTypes.topClick) {
return topLevelTargetID;
}
}
/**
* This plugin creates an `onChange` event that normalizes change events
* across form elements. This event fires at a time when it's possible to
* change the element's value without seeing a flicker.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - select
*/
var ChangeEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var getTargetIDFunc, handleEventFunc;
if (shouldUseChangeEvent(topLevelTarget)) {
if (doesChangeEventBubble) {
getTargetIDFunc = getTargetIDForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(topLevelTarget)) {
if (isInputEventSupported) {
getTargetIDFunc = getTargetIDForInputEvent;
} else {
getTargetIDFunc = getTargetIDForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(topLevelTarget)) {
getTargetIDFunc = getTargetIDForClickEvent;
}
if (getTargetIDFunc) {
var targetID = getTargetIDFunc(topLevelType, topLevelTarget, topLevelTargetID);
if (targetID) {
var event = SyntheticEvent.getPooled(eventTypes.change, targetID, nativeEvent, nativeEventTarget);
event.type = 'change';
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(topLevelType, topLevelTarget, topLevelTargetID);
}
}
};
module.exports = ChangeEventPlugin;
/***/ }),
/* 81 */
/*!***************************************!*\
!*** ./~/react/lib/getEventTarget.js ***!
\***************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule getEventTarget
* @typechecks static-only
*/
'use strict';
/**
* Gets the target node from a native browser event by accounting for
* inconsistencies in browser DOM APIs.
*
* @param {object} nativeEvent Native browser event.
* @return {DOMEventTarget} Target node.
*/
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
module.exports = getEventTarget;
/***/ }),
/* 82 */
/*!*******************************************!*\
!*** ./~/react/lib/isTextInputElement.js ***!
\*******************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule isTextInputElement
*/
'use strict';
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
*/
var supportedInputTypes = {
'color': true,
'date': true,
'datetime': true,
'datetime-local': true,
'email': true,
'month': true,
'number': true,
'password': true,
'range': true,
'search': true,
'tel': true,
'text': true,
'time': true,
'url': true,
'week': true
};
function isTextInputElement(elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea');
}
module.exports = isTextInputElement;
/***/ }),
/* 83 */
/*!*********************************************!*\
!*** ./~/react/lib/ClientReactRootIndex.js ***!
\*********************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ClientReactRootIndex
* @typechecks
*/
'use strict';
var nextReactRootIndex = 0;
var ClientReactRootIndex = {
createReactRootIndex: function () {
return nextReactRootIndex++;
}
};
module.exports = ClientReactRootIndex;
/***/ }),
/* 84 */
/*!************************************************!*\
!*** ./~/react/lib/DefaultEventPluginOrder.js ***!
\************************************************/
/***/ (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.
*
* @providesModule DefaultEventPluginOrder
*/
'use strict';
var keyOf = __webpack_require__(/*! fbjs/lib/keyOf */ 79);
/**
* Module that is injectable into `EventPluginHub`, that specifies a
* deterministic ordering of `EventPlugin`s. A convenient way to reason about
* plugins, without having to package every one of them. This is better than
* having plugins be ordered in the same order that they are injected because
* that ordering would be influenced by the packaging order.
* `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that
* preventing default on events is convenient in `SimpleEventPlugin` handlers.
*/
var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })];
module.exports = DefaultEventPluginOrder;
/***/ }),
/* 85 */
/*!**********************************************!*\
!*** ./~/react/lib/EnterLeaveEventPlugin.js ***!
\**********************************************/
/***/ (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.
*
* @providesModule EnterLeaveEventPlugin
* @typechecks static-only
*/
'use strict';
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var EventPropagators = __webpack_require__(/*! ./EventPropagators */ 73);
var SyntheticMouseEvent = __webpack_require__(/*! ./SyntheticMouseEvent */ 86);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var keyOf = __webpack_require__(/*! fbjs/lib/keyOf */ 79);
var topLevelTypes = EventConstants.topLevelTypes;
var getFirstReactDOM = ReactMount.getFirstReactDOM;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({ onMouseEnter: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
},
mouseLeave: {
registrationName: keyOf({ onMouseLeave: null }),
dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver]
}
};
var extractedEvents = [null, null];
var EnterLeaveEventPlugin = {
eventTypes: eventTypes,
/**
* For almost every interaction we care about, there will be both a top-level
* `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that
* we do not extract duplicate events. However, moving the mouse into the
* browser from outside will not fire a `mouseout` event. In this case, we use
* the `mouseover` top-level event.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) {
return null;
}
if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) {
// Must not be a mouse in or mouse out - ignoring.
return null;
}
var win;
if (topLevelTarget.window === topLevelTarget) {
// `topLevelTarget` is probably a window object.
win = topLevelTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = topLevelTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from;
var to;
var fromID = '';
var toID = '';
if (topLevelType === topLevelTypes.topMouseOut) {
from = topLevelTarget;
fromID = topLevelTargetID;
to = getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement);
if (to) {
toID = ReactMount.getID(to);
} else {
to = win;
}
to = to || win;
} else {
from = win;
to = topLevelTarget;
toID = topLevelTargetID;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, fromID, nativeEvent, nativeEventTarget);
leave.type = 'mouseleave';
leave.target = from;
leave.relatedTarget = to;
var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, toID, nativeEvent, nativeEventTarget);
enter.type = 'mouseenter';
enter.target = to;
enter.relatedTarget = from;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
extractedEvents[0] = leave;
extractedEvents[1] = enter;
return extractedEvents;
}
};
module.exports = EnterLeaveEventPlugin;
/***/ }),
/* 86 */
/*!********************************************!*\
!*** ./~/react/lib/SyntheticMouseEvent.js ***!
\********************************************/
/***/ (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.
*
* @providesModule SyntheticMouseEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(/*! ./SyntheticUIEvent */ 87);
var ViewportMetrics = __webpack_require__(/*! ./ViewportMetrics */ 38);
var getEventModifierState = __webpack_require__(/*! ./getEventModifierState */ 88);
/**
* @interface MouseEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var MouseEventInterface = {
screenX: null,
screenY: null,
clientX: null,
clientY: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
getModifierState: getEventModifierState,
button: function (event) {
// Webkit, Firefox, IE9+
// which: 1 2 3
// button: 0 1 2 (standard)
var button = event.button;
if ('which' in event) {
return button;
}
// IE<9
// which: undefined
// button: 0 0 0
// button: 1 4 2 (onmouseup)
return button === 2 ? 2 : button === 4 ? 1 : 0;
},
buttons: null,
relatedTarget: function (event) {
return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement);
},
// "Proprietary" Interface.
pageX: function (event) {
return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft;
},
pageY: function (event) {
return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
/***/ }),
/* 87 */
/*!*****************************************!*\
!*** ./~/react/lib/SyntheticUIEvent.js ***!
\*****************************************/
/***/ (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.
*
* @providesModule SyntheticUIEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = __webpack_require__(/*! ./SyntheticEvent */ 77);
var getEventTarget = __webpack_require__(/*! ./getEventTarget */ 81);
/**
* @interface UIEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var UIEventInterface = {
view: function (event) {
if (event.view) {
return event.view;
}
var target = getEventTarget(event);
if (target != null && target.window === target) {
// target is a window object
return target;
}
var doc = target.ownerDocument;
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
if (doc) {
return doc.defaultView || doc.parentWindow;
} else {
return window;
}
},
detail: function (event) {
return event.detail || 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticEvent}
*/
function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
/***/ }),
/* 88 */
/*!**********************************************!*\
!*** ./~/react/lib/getEventModifierState.js ***!
\**********************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule getEventModifierState
* @typechecks static-only
*/
'use strict';
/**
* Translation from modifier key to the associated property in the event.
* @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
*/
var modifierKeyToProp = {
'Alt': 'altKey',
'Control': 'ctrlKey',
'Meta': 'metaKey',
'Shift': 'shiftKey'
};
// IE8 does not implement getModifierState so we simply map it to the only
// modifier keys exposed by the event itself, does not support Lock-keys.
// Currently, all major browsers except Chrome seems to support Lock-keys.
function modifierStateGetter(keyArg) {
var syntheticEvent = this;
var nativeEvent = syntheticEvent.nativeEvent;
if (nativeEvent.getModifierState) {
return nativeEvent.getModifierState(keyArg);
}
var keyProp = modifierKeyToProp[keyArg];
return keyProp ? !!nativeEvent[keyProp] : false;
}
function getEventModifierState(nativeEvent) {
return modifierStateGetter;
}
module.exports = getEventModifierState;
/***/ }),
/* 89 */
/*!**********************************************!*\
!*** ./~/react/lib/HTMLDOMPropertyConfig.js ***!
\**********************************************/
/***/ (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.
*
* @providesModule HTMLDOMPropertyConfig
*/
'use strict';
var DOMProperty = __webpack_require__(/*! ./DOMProperty */ 23);
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
var implementation = document.implementation;
hasSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1');
}
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),
Properties: {
/**
* Standard Properties
*/
accept: null,
acceptCharset: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusUtils
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
challenge: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
classID: MUST_USE_ATTRIBUTE,
// To set className on SVG elements, it's necessary to use .setAttribute;
// this works on HTML elements too in all browsers except IE8. Conveniently,
// IE8 doesn't support SVG and so we can simply use the attribute in
// browsers that support SVG and the property in browsers that don't,
// regardless of whether the element is HTML or SVG.
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
coords: null,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
'default': HAS_BOOLEAN_VALUE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formAction: MUST_USE_ATTRIBUTE,
formEncType: MUST_USE_ATTRIBUTE,
formMethod: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: MUST_USE_ATTRIBUTE,
frameBorder: MUST_USE_ATTRIBUTE,
headers: null,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
high: null,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
inputMode: MUST_USE_ATTRIBUTE,
integrity: null,
is: MUST_USE_ATTRIBUTE,
keyParams: MUST_USE_ATTRIBUTE,
keyType: MUST_USE_ATTRIBUTE,
kind: null,
label: null,
lang: null,
list: MUST_USE_ATTRIBUTE,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
low: null,
manifest: MUST_USE_ATTRIBUTE,
marginHeight: null,
marginWidth: null,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
media: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
minLength: MUST_USE_ATTRIBUTE,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
nonce: MUST_USE_ATTRIBUTE,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: null,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
reversed: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scoped: HAS_BOOLEAN_VALUE,
scrolling: null,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: null,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
sizes: MUST_USE_ATTRIBUTE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcLang: null,
srcSet: MUST_USE_ATTRIBUTE,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
summary: null,
tabIndex: null,
target: null,
title: null,
type: null,
useMap: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
wrap: null,
/**
* RDFa Properties
*/
about: MUST_USE_ATTRIBUTE,
datatype: MUST_USE_ATTRIBUTE,
inlist: MUST_USE_ATTRIBUTE,
prefix: MUST_USE_ATTRIBUTE,
// property is also supported for OpenGraph in meta tags.
property: MUST_USE_ATTRIBUTE,
resource: MUST_USE_ATTRIBUTE,
'typeof': MUST_USE_ATTRIBUTE,
vocab: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: MUST_USE_ATTRIBUTE,
autoCorrect: MUST_USE_ATTRIBUTE,
// autoSave allows WebKit/Blink to persist values of input fields on page reloads
autoSave: null,
// color is for Safari mask-icon link
color: null,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: MUST_USE_ATTRIBUTE,
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
itemType: MUST_USE_ATTRIBUTE,
// itemID and itemRef are for Microdata support as well but
// only specified in the the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: MUST_USE_ATTRIBUTE,
itemRef: MUST_USE_ATTRIBUTE,
// results show looking glass icon and recent searches on input
// search fields in WebKit/Blink
results: null,
// IE-only attribute that specifies security restrictions on an iframe
// as an alternative to the sandbox attribute on IE<10
security: MUST_USE_ATTRIBUTE,
// IE-only attribute that controls focus behavior
unselectable: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoComplete: 'autocomplete',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
autoSave: 'autosave',
// `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter.
// http://www.w3.org/TR/html5/forms.html#dom-fs-encoding
encType: 'encoding',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
/***/ }),
/* 90 */
/*!***************************************************!*\
!*** ./~/react/lib/ReactBrowserComponentMixin.js ***!
\***************************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactBrowserComponentMixin
*/
'use strict';
var ReactInstanceMap = __webpack_require__(/*! ./ReactInstanceMap */ 47);
var findDOMNode = __webpack_require__(/*! ./findDOMNode */ 91);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var didWarnKey = '_getDOMNodeDidWarn';
var ReactBrowserComponentMixin = {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function () {
process.env.NODE_ENV !== 'production' ? warning(this.constructor[didWarnKey], '%s.getDOMNode(...) is deprecated. Please use ' + 'ReactDOM.findDOMNode(instance) instead.', ReactInstanceMap.get(this).getName() || this.tagName || 'Unknown') : undefined;
this.constructor[didWarnKey] = true;
return findDOMNode(this);
}
};
module.exports = ReactBrowserComponentMixin;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 91 */
/*!************************************!*\
!*** ./~/react/lib/findDOMNode.js ***!
\************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule findDOMNode
* @typechecks static-only
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var ReactInstanceMap = __webpack_require__(/*! ./ReactInstanceMap */ 47);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
/**
* Returns the DOM node rendered by this element.
*
* @param {ReactComponent|DOMElement} componentOrElement
* @return {?DOMElement} The root node of this element.
*/
function findDOMNode(componentOrElement) {
if (process.env.NODE_ENV !== 'production') {
var owner = ReactCurrentOwner.current;
if (owner !== null) {
process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing getDOMNode or findDOMNode inside its render(). ' + 'render() should be a pure function of props and state. It should ' + 'never access something that requires stale data from the previous ' + 'render, such as refs. Move this logic to componentDidMount and ' + 'componentDidUpdate instead.', owner.getName() || 'A component') : undefined;
owner._warnedAboutRefsInRender = true;
}
}
if (componentOrElement == null) {
return null;
}
if (componentOrElement.nodeType === 1) {
return componentOrElement;
}
if (ReactInstanceMap.has(componentOrElement)) {
return ReactMount.getNodeFromInstance(componentOrElement);
}
!(componentOrElement.render == null || typeof componentOrElement.render !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : undefined;
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : undefined;
}
module.exports = findDOMNode;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 92 */
/*!*****************************************************!*\
!*** ./~/react/lib/ReactDefaultBatchingStrategy.js ***!
\*****************************************************/
/***/ (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.
*
* @providesModule ReactDefaultBatchingStrategy
*/
'use strict';
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var Transaction = __webpack_require__(/*! ./Transaction */ 57);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ 15);
var RESET_BATCHED_UPDATES = {
initialize: emptyFunction,
close: function () {
ReactDefaultBatchingStrategy.isBatchingUpdates = false;
}
};
var FLUSH_BATCHED_UPDATES = {
initialize: emptyFunction,
close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates)
};
var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES];
function ReactDefaultBatchingStrategyTransaction() {
this.reinitializeTransaction();
}
assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, {
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
}
});
var transaction = new ReactDefaultBatchingStrategyTransaction();
var ReactDefaultBatchingStrategy = {
isBatchingUpdates: false,
/**
* Call the provided function in a context within which calls to `setState`
* and friends are batched such that components aren't updated unnecessarily.
*/
batchedUpdates: function (callback, a, b, c, d, e) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b, c, d, e);
} else {
transaction.perform(callback, null, a, b, c, d, e);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
/***/ }),
/* 93 */
/*!******************************************!*\
!*** ./~/react/lib/ReactDOMComponent.js ***!
\******************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOMComponent
* @typechecks static-only
*/
/* global hasOwnProperty:true */
'use strict';
var AutoFocusUtils = __webpack_require__(/*! ./AutoFocusUtils */ 94);
var CSSPropertyOperations = __webpack_require__(/*! ./CSSPropertyOperations */ 96);
var DOMProperty = __webpack_require__(/*! ./DOMProperty */ 23);
var DOMPropertyOperations = __webpack_require__(/*! ./DOMPropertyOperations */ 22);
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var ReactBrowserEventEmitter = __webpack_require__(/*! ./ReactBrowserEventEmitter */ 29);
var ReactComponentBrowserEnvironment = __webpack_require__(/*! ./ReactComponentBrowserEnvironment */ 26);
var ReactDOMButton = __webpack_require__(/*! ./ReactDOMButton */ 104);
var ReactDOMInput = __webpack_require__(/*! ./ReactDOMInput */ 105);
var ReactDOMOption = __webpack_require__(/*! ./ReactDOMOption */ 109);
var ReactDOMSelect = __webpack_require__(/*! ./ReactDOMSelect */ 112);
var ReactDOMTextarea = __webpack_require__(/*! ./ReactDOMTextarea */ 113);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var ReactMultiChild = __webpack_require__(/*! ./ReactMultiChild */ 114);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var ReactUpdateQueue = __webpack_require__(/*! ./ReactUpdateQueue */ 53);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var canDefineProperty = __webpack_require__(/*! ./canDefineProperty */ 43);
var escapeTextContentForBrowser = __webpack_require__(/*! ./escapeTextContentForBrowser */ 21);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var isEventSupported = __webpack_require__(/*! ./isEventSupported */ 40);
var keyOf = __webpack_require__(/*! fbjs/lib/keyOf */ 79);
var setInnerHTML = __webpack_require__(/*! ./setInnerHTML */ 19);
var setTextContent = __webpack_require__(/*! ./setTextContent */ 20);
var shallowEqual = __webpack_require__(/*! fbjs/lib/shallowEqual */ 117);
var validateDOMNesting = __webpack_require__(/*! ./validateDOMNesting */ 70);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var deleteListener = ReactBrowserEventEmitter.deleteListener;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = { 'string': true, 'number': true };
var CHILDREN = keyOf({ children: null });
var STYLE = keyOf({ style: null });
var HTML = keyOf({ __html: null });
var ELEMENT_NODE_TYPE = 1;
function getDeclarationErrorAddendum(internalInstance) {
if (internalInstance) {
var owner = internalInstance._currentElement._owner || null;
if (owner) {
var name = owner.getName();
if (name) {
return ' This DOM node was rendered by `' + name + '`.';
}
}
}
return '';
}
var legacyPropsDescriptor;
if (process.env.NODE_ENV !== 'production') {
legacyPropsDescriptor = {
props: {
enumerable: false,
get: function () {
var component = this._reactInternalComponent;
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .props of a DOM node; instead, ' + 'recreate the props as `render` did originally or read the DOM ' + 'properties/attributes directly from this node (e.g., ' + 'this.refs.box.className).%s', getDeclarationErrorAddendum(component)) : undefined;
return component._currentElement.props;
}
}
};
}
function legacyGetDOMNode() {
if (process.env.NODE_ENV !== 'production') {
var component = this._reactInternalComponent;
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .getDOMNode() of a DOM node; ' + 'instead, use the node directly.%s', getDeclarationErrorAddendum(component)) : undefined;
}
return this;
}
function legacyIsMounted() {
var component = this._reactInternalComponent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .isMounted() of a DOM node.%s', getDeclarationErrorAddendum(component)) : undefined;
}
return !!component;
}
function legacySetStateEtc() {
if (process.env.NODE_ENV !== 'production') {
var component = this._reactInternalComponent;
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setState(), .replaceState(), or ' + '.forceUpdate() of a DOM node. This is a no-op.%s', getDeclarationErrorAddendum(component)) : undefined;
}
}
function legacySetProps(partialProps, callback) {
var component = this._reactInternalComponent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .setProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined;
}
if (!component) {
return;
}
ReactUpdateQueue.enqueueSetPropsInternal(component, partialProps);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(component, callback);
}
}
function legacyReplaceProps(partialProps, callback) {
var component = this._reactInternalComponent;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDOMComponent: Do not access .replaceProps() of a DOM node. ' + 'Instead, call ReactDOM.render again at the top level.%s', getDeclarationErrorAddendum(component)) : undefined;
}
if (!component) {
return;
}
ReactUpdateQueue.enqueueReplacePropsInternal(component, partialProps);
if (callback) {
ReactUpdateQueue.enqueueCallbackInternal(component, callback);
}
}
function friendlyStringify(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
return '[' + obj.map(friendlyStringify).join(', ') + ']';
} else {
var pairs = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key);
pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key]));
}
}
return '{' + pairs.join(', ') + '}';
}
} else if (typeof obj === 'string') {
return JSON.stringify(obj);
} else if (typeof obj === 'function') {
return '[function object]';
}
// Differs from JSON.stringify in that undefined becauses undefined and that
// inf and nan don't become null
return String(obj);
}
var styleMutationWarning = {};
function checkAndWarnForMutatedStyle(style1, style2, component) {
if (style1 == null || style2 == null) {
return;
}
if (shallowEqual(style1, style2)) {
return;
}
var componentName = component._tag;
var owner = component._currentElement._owner;
var ownerName;
if (owner) {
ownerName = owner.getName();
}
var hash = ownerName + '|' + componentName;
if (styleMutationWarning.hasOwnProperty(hash)) {
return;
}
styleMutationWarning[hash] = true;
process.env.NODE_ENV !== 'production' ? warning(false, '`%s` was passed a style object that has previously been mutated. ' + 'Mutating `style` is deprecated. Consider cloning it beforehand. Check ' + 'the `render` %s. Previous style: %s. Mutated style: %s.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : undefined;
}
/**
* @param {object} component
* @param {?object} props
*/
function assertValidProps(component, props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
if (process.env.NODE_ENV !== 'production') {
if (voidElementTags[component._tag]) {
process.env.NODE_ENV !== 'production' ? warning(props.children == null && props.dangerouslySetInnerHTML == null, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : undefined;
}
}
if (props.dangerouslySetInnerHTML != null) {
!(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : undefined;
!(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : undefined;
}
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!props.contentEditable || props.children == null, 'A component is `contentEditable` and contains `children` managed by ' + 'React. It is now your responsibility to guarantee that none of ' + 'those nodes are unexpectedly modified or duplicated. This is ' + 'probably not intentional.') : undefined;
}
!(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : undefined;
}
function enqueuePutListener(id, registrationName, listener, transaction) {
if (process.env.NODE_ENV !== 'production') {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : undefined;
}
var container = ReactMount.findReactContainerForID(id);
if (container) {
var doc = container.nodeType === ELEMENT_NODE_TYPE ? container.ownerDocument : container;
listenTo(registrationName, doc);
}
transaction.getReactMountReady().enqueue(putListener, {
id: id,
registrationName: registrationName,
listener: listener
});
}
function putListener() {
var listenerToPut = this;
ReactBrowserEventEmitter.putListener(listenerToPut.id, listenerToPut.registrationName, listenerToPut.listener);
}
// There are so many media events, it makes sense to just
// maintain a list rather than create a `trapBubbledEvent` for each
var mediaEvents = {
topAbort: 'abort',
topCanPlay: 'canplay',
topCanPlayThrough: 'canplaythrough',
topDurationChange: 'durationchange',
topEmptied: 'emptied',
topEncrypted: 'encrypted',
topEnded: 'ended',
topError: 'error',
topLoadedData: 'loadeddata',
topLoadedMetadata: 'loadedmetadata',
topLoadStart: 'loadstart',
topPause: 'pause',
topPlay: 'play',
topPlaying: 'playing',
topProgress: 'progress',
topRateChange: 'ratechange',
topSeeked: 'seeked',
topSeeking: 'seeking',
topStalled: 'stalled',
topSuspend: 'suspend',
topTimeUpdate: 'timeupdate',
topVolumeChange: 'volumechange',
topWaiting: 'waiting'
};
function trapBubbledEventsLocal() {
var inst = this;
// If a component renders to null or if another component fatals and causes
// the state of the tree to be corrupted, `node` here can be null.
!inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : undefined;
var node = ReactMount.getNode(inst._rootNodeID);
!node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : undefined;
switch (inst._tag) {
case 'iframe':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'video':
case 'audio':
inst._wrapperState.listeners = [];
// create listener for each media event
for (var event in mediaEvents) {
if (mediaEvents.hasOwnProperty(event)) {
inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node));
}
}
break;
case 'img':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)];
break;
case 'form':
inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)];
break;
}
}
function mountReadyInputWrapper() {
ReactDOMInput.mountReadyWrapper(this);
}
function postUpdateSelectWrapper() {
ReactDOMSelect.postUpdateWrapper(this);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special cased tags.
var omittedCloseTags = {
'area': true,
'base': true,
'br': true,
'col': true,
'embed': true,
'hr': true,
'img': true,
'input': true,
'keygen': true,
'link': true,
'meta': true,
'param': true,
'source': true,
'track': true,
'wbr': true
};
// NOTE: menuitem's close tag should be omitted, but that causes problems.
var newlineEatingTags = {
'listing': true,
'pre': true,
'textarea': true
};
// For HTML, certain tags cannot have children. This has the same purpose as
// `omittedCloseTags` except that `menuitem` should still have its closing tag.
var voidElementTags = assign({
'menuitem': true
}, omittedCloseTags);
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
var hasOwnProperty = ({}).hasOwnProperty;
function validateDangerousTag(tag) {
if (!hasOwnProperty.call(validatedTagCache, tag)) {
!VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : undefined;
validatedTagCache[tag] = true;
}
}
function processChildContextDev(context, inst) {
// Pass down our tag name to child components for validation purposes
context = assign({}, context);
var info = context[validateDOMNesting.ancestorInfoContextKey];
context[validateDOMNesting.ancestorInfoContextKey] = validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst);
return context;
}
function isCustomComponent(tagName, props) {
return tagName.indexOf('-') >= 0 || props.is != null;
}
/**
* Creates a new React class that is idempotent and capable of containing other
* React components. It accepts event listeners and DOM properties that are
* valid according to `DOMProperty`.
*
* - Event listeners: `onClick`, `onMouseDown`, etc.
* - DOM properties: `className`, `name`, `title`, etc.
*
* The `style` property functions differently from the DOM API. It accepts an
* object mapping of style properties to values.
*
* @constructor ReactDOMComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag) {
validateDangerousTag(tag);
this._tag = tag.toLowerCase();
this._renderedChildren = null;
this._previousStyle = null;
this._previousStyleCopy = null;
this._rootNodeID = null;
this._wrapperState = null;
this._topLevelWrapper = null;
this._nodeWithLegacyProperties = null;
if (process.env.NODE_ENV !== 'production') {
this._unprocessedContextDev = null;
this._processedContextDev = null;
}
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.Mixin = {
construct: function (element) {
this._currentElement = element;
},
/**
* Generates root tag markup then recurses. This method has side effects and
* is not idempotent.
*
* @internal
* @param {string} rootID The root DOM ID for this node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
* @return {string} The computed markup.
*/
mountComponent: function (rootID, transaction, context) {
this._rootNodeID = rootID;
var props = this._currentElement.props;
switch (this._tag) {
case 'iframe':
case 'img':
case 'form':
case 'video':
case 'audio':
this._wrapperState = {
listeners: null
};
transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this);
break;
case 'button':
props = ReactDOMButton.getNativeProps(this, props, context);
break;
case 'input':
ReactDOMInput.mountWrapper(this, props, context);
props = ReactDOMInput.getNativeProps(this, props, context);
break;
case 'option':
ReactDOMOption.mountWrapper(this, props, context);
props = ReactDOMOption.getNativeProps(this, props, context);
break;
case 'select':
ReactDOMSelect.mountWrapper(this, props, context);
props = ReactDOMSelect.getNativeProps(this, props, context);
context = ReactDOMSelect.processChildContext(this, props, context);
break;
case 'textarea':
ReactDOMTextarea.mountWrapper(this, props, context);
props = ReactDOMTextarea.getNativeProps(this, props, context);
break;
}
assertValidProps(this, props);
if (process.env.NODE_ENV !== 'production') {
if (context[validateDOMNesting.ancestorInfoContextKey]) {
validateDOMNesting(this._tag, this, context[validateDOMNesting.ancestorInfoContextKey]);
}
}
if (process.env.NODE_ENV !== 'production') {
this._unprocessedContextDev = context;
this._processedContextDev = processChildContextDev(context, this);
context = this._processedContextDev;
}
var mountImage;
if (transaction.useCreateElement) {
var ownerDocument = context[ReactMount.ownerDocumentContextKey];
var el = ownerDocument.createElement(this._currentElement.type);
DOMPropertyOperations.setAttributeForID(el, this._rootNodeID);
// Populate node cache
ReactMount.getID(el);
this._updateDOMProperties({}, props, transaction, el);
this._createInitialChildren(transaction, props, context, el);
mountImage = el;
} else {
var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props);
var tagContent = this._createContentMarkup(transaction, props, context);
if (!tagContent && omittedCloseTags[this._tag]) {
mountImage = tagOpen + '/>';
} else {
mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>';
}
}
switch (this._tag) {
case 'input':
transaction.getReactMountReady().enqueue(mountReadyInputWrapper, this);
// falls through
case 'button':
case 'select':
case 'textarea':
if (props.autoFocus) {
transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this);
}
break;
}
return mountImage;
},
/**
* Creates markup for the open tag and all attributes.
*
* This method has side effects because events get registered.
*
* Iterating over object properties is faster than iterating over arrays.
* @see http://jsperf.com/obj-vs-arr-iteration
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function (transaction, props) {
var ret = '<' + this._currentElement.type;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
if (propValue) {
enqueuePutListener(this._rootNodeID, propKey, propValue, transaction);
}
} else {
if (propKey === STYLE) {
if (propValue) {
if (process.env.NODE_ENV !== 'production') {
// See `_updateDOMProperties`. style block
this._previousStyle = propValue;
}
propValue = this._previousStyleCopy = assign({}, props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var markup = null;
if (this._tag != null && isCustomComponent(this._tag, props)) {
if (propKey !== CHILDREN) {
markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue);
}
} else {
markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (transaction.renderToStaticMarkup) {
return ret;
}
var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID);
return ret + ' ' + markupForID;
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} props
* @param {object} context
* @return {string} Content markup.
*/
_createContentMarkup: function (transaction, props, context) {
var ret = '';
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
ret = innerHTML.__html;
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
ret = escapeTextContentForBrowser(contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
ret = mountImages.join('');
}
}
if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
return '\n' + ret;
} else {
return ret;
}
},
_createInitialChildren: function (transaction, props, context, el) {
// Intentional use of != to avoid catching zero/false.
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
setInnerHTML(el, innerHTML.__html);
}
} else {
var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null;
var childrenToUse = contentToUse != null ? null : props.children;
if (contentToUse != null) {
// TODO: Validate that text is allowed as a child of this node
setTextContent(el, contentToUse);
} else if (childrenToUse != null) {
var mountImages = this.mountChildren(childrenToUse, transaction, context);
for (var i = 0; i < mountImages.length; i++) {
el.appendChild(mountImages[i]);
}
}
}
},
/**
* Receives a next element and updates the component.
*
* @internal
* @param {ReactElement} nextElement
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {object} context
*/
receiveComponent: function (nextElement, transaction, context) {
var prevElement = this._currentElement;
this._currentElement = nextElement;
this.updateComponent(transaction, prevElement, nextElement, context);
},
/**
* Updates a native DOM component after it has already been allocated and
* attached to the DOM. Reconciles the root DOM node, then recurses.
*
* @param {ReactReconcileTransaction} transaction
* @param {ReactElement} prevElement
* @param {ReactElement} nextElement
* @internal
* @overridable
*/
updateComponent: function (transaction, prevElement, nextElement, context) {
var lastProps = prevElement.props;
var nextProps = this._currentElement.props;
switch (this._tag) {
case 'button':
lastProps = ReactDOMButton.getNativeProps(this, lastProps);
nextProps = ReactDOMButton.getNativeProps(this, nextProps);
break;
case 'input':
ReactDOMInput.updateWrapper(this);
lastProps = ReactDOMInput.getNativeProps(this, lastProps);
nextProps = ReactDOMInput.getNativeProps(this, nextProps);
break;
case 'option':
lastProps = ReactDOMOption.getNativeProps(this, lastProps);
nextProps = ReactDOMOption.getNativeProps(this, nextProps);
break;
case 'select':
lastProps = ReactDOMSelect.getNativeProps(this, lastProps);
nextProps = ReactDOMSelect.getNativeProps(this, nextProps);
break;
case 'textarea':
ReactDOMTextarea.updateWrapper(this);
lastProps = ReactDOMTextarea.getNativeProps(this, lastProps);
nextProps = ReactDOMTextarea.getNativeProps(this, nextProps);
break;
}
if (process.env.NODE_ENV !== 'production') {
// If the context is reference-equal to the old one, pass down the same
// processed object so the update bailout in ReactReconciler behaves
// correctly (and identically in dev and prod). See #5005.
if (this._unprocessedContextDev !== context) {
this._unprocessedContextDev = context;
this._processedContextDev = processChildContextDev(context, this);
}
context = this._processedContextDev;
}
assertValidProps(this, nextProps);
this._updateDOMProperties(lastProps, nextProps, transaction, null);
this._updateDOMChildren(lastProps, nextProps, transaction, context);
if (!canDefineProperty && this._nodeWithLegacyProperties) {
this._nodeWithLegacyProperties.props = nextProps;
}
if (this._tag === 'select') {
// <select> value update needs to occur after <option> children
// reconciliation
transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this);
}
},
/**
* Reconciles the properties by detecting differences in property values and
* updating the DOM as necessary. This function is probably the single most
* critical path for performance optimization.
*
* TODO: Benchmark whether checking for changed values in memory actually
* improves performance (especially statically positioned elements).
* TODO: Benchmark the effects of putting this at the top since 99% of props
* do not change for a given reconciliation.
* TODO: Benchmark areas that can be improved with caching.
*
* @private
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {?DOMElement} node
*/
_updateDOMProperties: function (lastProps, nextProps, transaction, node) {
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = this._previousStyleCopy;
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
this._previousStyleCopy = null;
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (lastProps[propKey]) {
// Only call deleteListener if there was a listener previously or
// else willDeleteListener gets called when there wasn't actually a
// listener (e.g., onClick={null})
deleteListener(this._rootNodeID, propKey);
}
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
for (propKey in nextProps) {
var nextProp = nextProps[propKey];
var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps[propKey];
if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp) {
continue;
}
if (propKey === STYLE) {
if (nextProp) {
if (process.env.NODE_ENV !== 'production') {
checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this);
this._previousStyle = nextProp;
}
nextProp = this._previousStyleCopy = assign({}, nextProp);
} else {
this._previousStyleCopy = null;
}
if (lastProp) {
// Unset styles on `lastProp` but not on `nextProp`.
for (styleName in lastProp) {
if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
// Update styles that changed since `lastProp`.
for (styleName in nextProp) {
if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = nextProp[styleName];
}
}
} else {
// Relies on `updateStylesByID` not mutating `styleUpdates`.
styleUpdates = nextProp;
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
if (nextProp) {
enqueuePutListener(this._rootNodeID, propKey, nextProp, transaction);
} else if (lastProp) {
deleteListener(this._rootNodeID, propKey);
}
} else if (isCustomComponent(this._tag, nextProps)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
if (propKey === CHILDREN) {
nextProp = null;
}
DOMPropertyOperations.setValueForAttribute(node, propKey, nextProp);
} else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (nextProp != null) {
DOMPropertyOperations.setValueForProperty(node, propKey, nextProp);
} else {
DOMPropertyOperations.deleteValueForProperty(node, propKey);
}
}
}
if (styleUpdates) {
if (!node) {
node = ReactMount.getNode(this._rootNodeID);
}
CSSPropertyOperations.setValueForStyles(node, styleUpdates);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {object} nextProps
* @param {ReactReconcileTransaction} transaction
* @param {object} context
*/
_updateDOMChildren: function (lastProps, nextProps, transaction, context) {
var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null;
var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null;
var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html;
var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html;
// Note the use of `!=` which checks for null or undefined.
var lastChildren = lastContent != null ? null : lastProps.children;
var nextChildren = nextContent != null ? null : nextProps.children;
// If we're switching from children to content/html or vice versa, remove
// the old content
var lastHasContentOrHtml = lastContent != null || lastHtml != null;
var nextHasContentOrHtml = nextContent != null || nextHtml != null;
if (lastChildren != null && nextChildren == null) {
this.updateChildren(null, transaction, context);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
this.updateMarkup('' + nextHtml);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction, context);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function () {
switch (this._tag) {
case 'iframe':
case 'img':
case 'form':
case 'video':
case 'audio':
var listeners = this._wrapperState.listeners;
if (listeners) {
for (var i = 0; i < listeners.length; i++) {
listeners[i].remove();
}
}
break;
case 'input':
ReactDOMInput.unmountWrapper(this);
break;
case 'html':
case 'head':
case 'body':
/**
* Components like <html> <head> and <body> can't be removed or added
* easily in a cross-browser way, however it's valuable to be able to
* take advantage of React's reconciliation for styling and <title>
* management. So we just document it and throw in dangerous cases.
*/
true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : undefined;
break;
}
this.unmountChildren();
ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID);
ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._wrapperState = null;
if (this._nodeWithLegacyProperties) {
var node = this._nodeWithLegacyProperties;
node._reactInternalComponent = null;
this._nodeWithLegacyProperties = null;
}
},
getPublicInstance: function () {
if (!this._nodeWithLegacyProperties) {
var node = ReactMount.getNode(this._rootNodeID);
node._reactInternalComponent = this;
node.getDOMNode = legacyGetDOMNode;
node.isMounted = legacyIsMounted;
node.setState = legacySetStateEtc;
node.replaceState = legacySetStateEtc;
node.forceUpdate = legacySetStateEtc;
node.setProps = legacySetProps;
node.replaceProps = legacyReplaceProps;
if (process.env.NODE_ENV !== 'production') {
if (canDefineProperty) {
Object.defineProperties(node, legacyPropsDescriptor);
} else {
// updateComponent will update this property on subsequent renders
node.props = this._currentElement.props;
}
} else {
// updateComponent will update this property on subsequent renders
node.props = this._currentElement.props;
}
this._nodeWithLegacyProperties = node;
}
return this._nodeWithLegacyProperties;
}
};
ReactPerf.measureMethods(ReactDOMComponent, 'ReactDOMComponent', {
mountComponent: 'mountComponent',
updateComponent: 'updateComponent'
});
assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin);
module.exports = ReactDOMComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 94 */
/*!***************************************!*\
!*** ./~/react/lib/AutoFocusUtils.js ***!
\***************************************/
/***/ (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.
*
* @providesModule AutoFocusUtils
* @typechecks static-only
*/
'use strict';
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var findDOMNode = __webpack_require__(/*! ./findDOMNode */ 91);
var focusNode = __webpack_require__(/*! fbjs/lib/focusNode */ 95);
var Mixin = {
componentDidMount: function () {
if (this.props.autoFocus) {
focusNode(findDOMNode(this));
}
}
};
var AutoFocusUtils = {
Mixin: Mixin,
focusDOMComponent: function () {
focusNode(ReactMount.getNode(this._rootNodeID));
}
};
module.exports = AutoFocusUtils;
/***/ }),
/* 95 */
/*!*********************************!*\
!*** ./~/fbjs/lib/focusNode.js ***!
\*********************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule focusNode
*/
'use strict';
/**
* @param {DOMElement} node input/textarea to focus
*/
function focusNode(node) {
// IE8 can throw "Can't move focus to the control because it is invisible,
// not enabled, or of a type that does not accept the focus." for all kinds of
// reasons that are too expensive and fragile to test.
try {
node.focus();
} catch (e) {}
}
module.exports = focusNode;
/***/ }),
/* 96 */
/*!**********************************************!*\
!*** ./~/react/lib/CSSPropertyOperations.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule CSSPropertyOperations
* @typechecks static-only
*/
'use strict';
var CSSProperty = __webpack_require__(/*! ./CSSProperty */ 97);
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var camelizeStyleName = __webpack_require__(/*! fbjs/lib/camelizeStyleName */ 98);
var dangerousStyleValue = __webpack_require__(/*! ./dangerousStyleValue */ 100);
var hyphenateStyleName = __webpack_require__(/*! fbjs/lib/hyphenateStyleName */ 101);
var memoizeStringOnly = __webpack_require__(/*! fbjs/lib/memoizeStringOnly */ 103);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var processStyleName = memoizeStringOnly(function (styleName) {
return hyphenateStyleName(styleName);
});
var hasShorthandPropertyBug = false;
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
var tempStyle = document.createElement('div').style;
try {
// IE8 throws "Invalid argument." if resetting shorthand style properties.
tempStyle.font = '';
} catch (e) {
hasShorthandPropertyBug = true;
}
// IE8 only supports accessing cssFloat (standard) as styleFloat
if (document.documentElement.style.cssFloat === undefined) {
styleFloatAccessor = 'styleFloat';
}
}
if (process.env.NODE_ENV !== 'production') {
// 'msTransform' is correct, but the other prefixes should be capitalized
var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/;
// style values shouldn't contain a semicolon
var badStyleValueWithSemicolonPattern = /;\s*$/;
var warnedStyleNames = {};
var warnedStyleValues = {};
var warnHyphenatedStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?', name, camelizeStyleName(name)) : undefined;
};
var warnBadVendoredStyleName = function (name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?', name, name.charAt(0).toUpperCase() + name.slice(1)) : undefined;
};
var warnStyleValueWithSemicolon = function (name, value) {
if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) {
return;
}
warnedStyleValues[value] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon. ' + 'Try "%s: %s" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '')) : undefined;
};
/**
* @param {string} name
* @param {*} value
*/
var warnValidStyle = function (name, value) {
if (name.indexOf('-') > -1) {
warnHyphenatedStyleName(name);
} else if (badVendoredStyleNamePattern.test(name)) {
warnBadVendoredStyleName(name);
} else if (badStyleValueWithSemicolonPattern.test(value)) {
warnStyleValueWithSemicolon(name, value);
}
};
}
/**
* Operations for dealing with CSS properties.
*/
var CSSPropertyOperations = {
/**
* Serializes a mapping of style properties for use as inline styles:
*
* > createMarkupForStyles({width: '200px', height: 0})
* "width:200px;height:0;"
*
* Undefined values are ignored so that declarative programming is easier.
* The result should be HTML-escaped before insertion into the DOM.
*
* @param {object} styles
* @return {?string}
*/
createMarkupForStyles: function (styles) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var styleValue = styles[styleName];
if (process.env.NODE_ENV !== 'production') {
warnValidStyle(styleName, styleValue);
}
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue) + ';';
}
}
return serialized || null;
},
/**
* Sets the value for multiple styles on a node. If a value is specified as
* '' (empty string), the corresponding style property will be unset.
*
* @param {DOMElement} node
* @param {object} styles
*/
setValueForStyles: function (node, styles) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if (process.env.NODE_ENV !== 'production') {
warnValidStyle(styleName, styles[styleName]);
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
if (styleName === 'float') {
styleName = styleFloatAccessor;
}
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName];
if (expansion) {
// Shorthand property that IE8 won't like unsetting, so unset each
// component to placate it
for (var individualStyleName in expansion) {
style[individualStyleName] = '';
}
} else {
style[styleName] = '';
}
}
}
}
};
ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', {
setValueForStyles: 'setValueForStyles'
});
module.exports = CSSPropertyOperations;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 97 */
/*!************************************!*\
!*** ./~/react/lib/CSSProperty.js ***!
\************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule CSSProperty
*/
'use strict';
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
animationIterationCount: true,
boxFlex: true,
boxFlexGroup: true,
boxOrdinalGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexPositive: true,
flexShrink: true,
flexNegative: true,
flexOrder: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
tabSize: true,
widows: true,
zIndex: true,
zoom: true,
// SVG-related properties
fillOpacity: true,
stopOpacity: true,
strokeDashoffset: true,
strokeOpacity: true,
strokeWidth: true
};
/**
* @param {string} prefix vendor-specific prefix, eg: Webkit
* @param {string} key style name, eg: transitionDuration
* @return {string} style name prefixed with `prefix`, properly camelCased, eg:
* WebkitTransitionDuration
*/
function prefixKey(prefix, key) {
return prefix + key.charAt(0).toUpperCase() + key.substring(1);
}
/**
* Support style names that may come passed in prefixed by adding permutations
* of vendor prefixes.
*/
var prefixes = ['Webkit', 'ms', 'Moz', 'O'];
// Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an
// infinite loop, because it iterates over the newly added props too.
Object.keys(isUnitlessNumber).forEach(function (prop) {
prefixes.forEach(function (prefix) {
isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop];
});
});
/**
* Most style properties can be unset by doing .style[prop] = '' but IE8
* doesn't like doing that with shorthand properties so for the properties that
* IE8 breaks on, which are listed here, we instead unset each of the
* individual properties. See http://bugs.jquery.com/ticket/12385.
* The 4-value 'clock' properties like margin, padding, border-width seem to
* behave without any problems. Curiously, list-style works too without any
* special prodding.
*/
var shorthandPropertyExpansions = {
background: {
backgroundAttachment: true,
backgroundColor: true,
backgroundImage: true,
backgroundPositionX: true,
backgroundPositionY: true,
backgroundRepeat: true
},
backgroundPosition: {
backgroundPositionX: true,
backgroundPositionY: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
},
outline: {
outlineWidth: true,
outlineStyle: true,
outlineColor: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
/***/ }),
/* 98 */
/*!*****************************************!*\
!*** ./~/fbjs/lib/camelizeStyleName.js ***!
\*****************************************/
/***/ (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.
*
* @providesModule camelizeStyleName
* @typechecks
*/
'use strict';
var camelize = __webpack_require__(/*! ./camelize */ 99);
var msPattern = /^-ms-/;
/**
* Camelcases a hyphenated CSS property name, for example:
*
* > camelizeStyleName('background-color')
* < "backgroundColor"
* > camelizeStyleName('-moz-transition')
* < "MozTransition"
* > camelizeStyleName('-ms-transition')
* < "msTransition"
*
* As Andi Smith suggests
* (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix
* is converted to lowercase `ms`.
*
* @param {string} string
* @return {string}
*/
function camelizeStyleName(string) {
return camelize(string.replace(msPattern, 'ms-'));
}
module.exports = camelizeStyleName;
/***/ }),
/* 99 */
/*!********************************!*\
!*** ./~/fbjs/lib/camelize.js ***!
\********************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule camelize
* @typechecks
*/
"use strict";
var _hyphenPattern = /-(.)/g;
/**
* Camelcases a hyphenated string, for example:
*
* > camelize('background-color')
* < "backgroundColor"
*
* @param {string} string
* @return {string}
*/
function camelize(string) {
return string.replace(_hyphenPattern, function (_, character) {
return character.toUpperCase();
});
}
module.exports = camelize;
/***/ }),
/* 100 */
/*!********************************************!*\
!*** ./~/react/lib/dangerousStyleValue.js ***!
\********************************************/
/***/ (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.
*
* @providesModule dangerousStyleValue
* @typechecks static-only
*/
'use strict';
var CSSProperty = __webpack_require__(/*! ./CSSProperty */ 97);
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
var isEmpty = value == null || typeof value === 'boolean' || value === '';
if (isEmpty) {
return '';
}
var isNonNumeric = isNaN(value);
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value; // cast to string
}
if (typeof value === 'string') {
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
/***/ }),
/* 101 */
/*!******************************************!*\
!*** ./~/fbjs/lib/hyphenateStyleName.js ***!
\******************************************/
/***/ (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.
*
* @providesModule hyphenateStyleName
* @typechecks
*/
'use strict';
var hyphenate = __webpack_require__(/*! ./hyphenate */ 102);
var msPattern = /^ms-/;
/**
* Hyphenates a camelcased CSS property name, for example:
*
* > hyphenateStyleName('backgroundColor')
* < "background-color"
* > hyphenateStyleName('MozTransition')
* < "-moz-transition"
* > hyphenateStyleName('msTransition')
* < "-ms-transition"
*
* As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
* is converted to `-ms-`.
*
* @param {string} string
* @return {string}
*/
function hyphenateStyleName(string) {
return hyphenate(string).replace(msPattern, '-ms-');
}
module.exports = hyphenateStyleName;
/***/ }),
/* 102 */
/*!*********************************!*\
!*** ./~/fbjs/lib/hyphenate.js ***!
\*********************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule hyphenate
* @typechecks
*/
'use strict';
var _uppercasePattern = /([A-Z])/g;
/**
* Hyphenates a camelcased string, for example:
*
* > hyphenate('backgroundColor')
* < "background-color"
*
* For CSS style names, use `hyphenateStyleName` instead which works properly
* with all vendor prefixes, including `ms`.
*
* @param {string} string
* @return {string}
*/
function hyphenate(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
module.exports = hyphenate;
/***/ }),
/* 103 */
/*!*****************************************!*\
!*** ./~/fbjs/lib/memoizeStringOnly.js ***!
\*****************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule memoizeStringOnly
* @typechecks static-only
*/
'use strict';
/**
* Memoizes the return value of a function that accepts one string argument.
*
* @param {function} callback
* @return {function}
*/
function memoizeStringOnly(callback) {
var cache = {};
return function (string) {
if (!cache.hasOwnProperty(string)) {
cache[string] = callback.call(this, string);
}
return cache[string];
};
}
module.exports = memoizeStringOnly;
/***/ }),
/* 104 */
/*!***************************************!*\
!*** ./~/react/lib/ReactDOMButton.js ***!
\***************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ReactDOMButton
*/
'use strict';
var mouseListenerNames = {
onClick: true,
onDoubleClick: true,
onMouseDown: true,
onMouseMove: true,
onMouseUp: true,
onClickCapture: true,
onDoubleClickCapture: true,
onMouseDownCapture: true,
onMouseMoveCapture: true,
onMouseUpCapture: true
};
/**
* Implements a <button> native component that does not receive mouse events
* when `disabled` is set.
*/
var ReactDOMButton = {
getNativeProps: function (inst, props, context) {
if (!props.disabled) {
return props;
}
// Copy the props, except the mouse listeners
var nativeProps = {};
for (var key in props) {
if (props.hasOwnProperty(key) && !mouseListenerNames[key]) {
nativeProps[key] = props[key];
}
}
return nativeProps;
}
};
module.exports = ReactDOMButton;
/***/ }),
/* 105 */
/*!**************************************!*\
!*** ./~/react/lib/ReactDOMInput.js ***!
\**************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOMInput
*/
'use strict';
var ReactDOMIDOperations = __webpack_require__(/*! ./ReactDOMIDOperations */ 27);
var LinkedValueUtils = __webpack_require__(/*! ./LinkedValueUtils */ 106);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var instancesByReactID = {};
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMInput.updateWrapper(this);
}
}
/**
* Implements an <input> native component that allows setting these optional
* props: `checked`, `value`, `defaultChecked`, and `defaultValue`.
*
* If `checked` or `value` are not supplied (or null/undefined), user actions
* that affect the checked state or value will trigger updates to the element.
*
* If they are supplied (and not null/undefined), the rendered element will not
* trigger updates to the element. Instead, the props must change in order for
* the rendered element to be updated.
*
* The rendered element will be initialized as unchecked (or `defaultChecked`)
* with an empty value (or `defaultValue`).
*
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html
*/
var ReactDOMInput = {
getNativeProps: function (inst, props, context) {
var value = LinkedValueUtils.getValue(props);
var checked = LinkedValueUtils.getChecked(props);
var nativeProps = assign({}, props, {
defaultChecked: undefined,
defaultValue: undefined,
value: value != null ? value : inst._wrapperState.initialValue,
checked: checked != null ? checked : inst._wrapperState.initialChecked,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner);
}
var defaultValue = props.defaultValue;
inst._wrapperState = {
initialChecked: props.defaultChecked || false,
initialValue: defaultValue != null ? defaultValue : null,
onChange: _handleChange.bind(inst)
};
},
mountReadyWrapper: function (inst) {
// Can't be in mountWrapper or else server rendering leaks.
instancesByReactID[inst._rootNodeID] = inst;
},
unmountWrapper: function (inst) {
delete instancesByReactID[inst._rootNodeID];
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
// TODO: Shouldn't this be getChecked(props)?
var checked = props.checked;
if (checked != null) {
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'checked', checked || false);
}
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
// Here we use asap to wait until all updates have propagated, which
// is important when using controlled components within layers:
// https://github.com/facebook/react/issues/1698
ReactUpdates.asap(forceUpdateIfMounted, this);
var name = props.name;
if (props.type === 'radio' && name != null) {
var rootNode = ReactMount.getNode(this._rootNodeID);
var queryRoot = rootNode;
while (queryRoot.parentNode) {
queryRoot = queryRoot.parentNode;
}
// If `rootNode.form` was non-null, then we could try `form.elements`,
// but that sometimes behaves strangely in IE8. We could also try using
// `form.getElementsByName`, but that will only return direct children
// and won't include inputs that use the HTML5 `form=` attribute. Since
// the input might not even be in a form, let's just use the global
// `querySelectorAll` to ensure we don't miss anything.
var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]');
for (var i = 0; i < group.length; i++) {
var otherNode = group[i];
if (otherNode === rootNode || otherNode.form !== rootNode.form) {
continue;
}
// This will throw if radio buttons rendered by different copies of React
// and the same name are rendered into the same form (same as #1939).
// That's probably okay; we don't support it just as we don't support
// mixing React with non-React.
var otherID = ReactMount.getID(otherNode);
!otherID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : undefined;
var otherInstance = instancesByReactID[otherID];
!otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Unknown radio button ID %s.', otherID) : invariant(false) : undefined;
// If this is a controlled radio button group, forcing the input that
// was previously checked to update will cause it to be come re-checked
// as appropriate.
ReactUpdates.asap(forceUpdateIfMounted, otherInstance);
}
}
return returnValue;
}
module.exports = ReactDOMInput;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 106 */
/*!*****************************************!*\
!*** ./~/react/lib/LinkedValueUtils.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule LinkedValueUtils
* @typechecks static-only
*/
'use strict';
var ReactPropTypes = __webpack_require__(/*! ./ReactPropTypes */ 107);
var ReactPropTypeLocations = __webpack_require__(/*! ./ReactPropTypeLocations */ 65);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(inputProps) {
!(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : undefined;
}
function _assertValueLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : undefined;
}
function _assertCheckedLink(inputProps) {
_assertSingleLink(inputProps);
!(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : undefined;
}
var propTypes = {
value: function (props, propName, componentName) {
if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
checked: function (props, propName, componentName) {
if (!props[propName] || props.onChange || props.readOnly || props.disabled) {
return null;
}
return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.');
},
onChange: ReactPropTypes.func
};
var loggedTypeFailures = {};
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
checkPropTypes: function (tagName, props, owner) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
}
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 addendum = getDeclarationErrorAddendum(owner);
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : undefined;
}
}
},
/**
* @param {object} inputProps Props for form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function (inputProps) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.value;
}
return inputProps.value;
},
/**
* @param {object} inputProps Props for form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function (inputProps) {
if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.value;
}
return inputProps.checked;
},
/**
* @param {object} inputProps Props for form component
* @param {SyntheticEvent} event change event to handle
*/
executeOnChange: function (inputProps, event) {
if (inputProps.valueLink) {
_assertValueLink(inputProps);
return inputProps.valueLink.requestChange(event.target.value);
} else if (inputProps.checkedLink) {
_assertCheckedLink(inputProps);
return inputProps.checkedLink.requestChange(event.target.checked);
} else if (inputProps.onChange) {
return inputProps.onChange.call(undefined, event);
}
}
};
module.exports = LinkedValueUtils;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 107 */
/*!***************************************!*\
!*** ./~/react/lib/ReactPropTypes.js ***!
\***************************************/
/***/ (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.
*
* @providesModule ReactPropTypes
*/
'use strict';
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactPropTypeLocationNames = __webpack_require__(/*! ./ReactPropTypeLocationNames */ 66);
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ 15);
var getIteratorFn = __webpack_require__(/*! ./getIteratorFn */ 108);
/**
* 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'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.'));
}
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) {
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 Error('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) {
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error('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 + ']', 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error('Invalid ' + locationName + ' `' + propFullName + '` 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 Error('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)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOf, expected an instance of array.');
});
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (propValue === expectedValues[i]) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error('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) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error('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, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
return createChainableTypeChecker(function () {
return new Error('Invalid argument supplied to oneOfType, expected an instance of array.');
});
}
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, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED') == null) {
return null;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error('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 Error('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 Error('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, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
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;
}
}
// 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';
}
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;
/***/ }),
/* 108 */
/*!**************************************!*\
!*** ./~/react/lib/getIteratorFn.js ***!
\**************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule getIteratorFn
* @typechecks static-only
*/
'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;
/***/ }),
/* 109 */
/*!***************************************!*\
!*** ./~/react/lib/ReactDOMOption.js ***!
\***************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOMOption
*/
'use strict';
var ReactChildren = __webpack_require__(/*! ./ReactChildren */ 110);
var ReactDOMSelect = __webpack_require__(/*! ./ReactDOMSelect */ 112);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var valueContextKey = ReactDOMSelect.valueContextKey;
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = {
mountWrapper: function (inst, props, context) {
// TODO (yungsters): Remove support for `selected` in <option>.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : undefined;
}
// Look up whether this option is 'selected' via context
var selectValue = context[valueContextKey];
// If context key is null (e.g., no specified value or after initial mount)
// or missing (e.g., for <datalist>), we don't change props.selected
var selected = null;
if (selectValue != null) {
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var i = 0; i < selectValue.length; i++) {
if ('' + selectValue[i] === '' + props.value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === '' + props.value;
}
}
inst._wrapperState = { selected: selected };
},
getNativeProps: function (inst, props, context) {
var nativeProps = assign({ selected: undefined, children: undefined }, props);
// Read state only from initial mount because <select> updates value
// manually; we need the initial state only for server rendering
if (inst._wrapperState.selected != null) {
nativeProps.selected = inst._wrapperState.selected;
}
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
ReactChildren.forEach(props.children, function (child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : undefined;
}
});
if (content) {
nativeProps.children = content;
}
return nativeProps;
}
};
module.exports = ReactDOMOption;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 110 */
/*!**************************************!*\
!*** ./~/react/lib/ReactChildren.js ***!
\**************************************/
/***/ (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.
*
* @providesModule ReactChildren
*/
'use strict';
var PooledClass = __webpack_require__(/*! ./PooledClass */ 56);
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ 15);
var traverseAllChildren = __webpack_require__(/*! ./traverseAllChildren */ 111);
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var fourArgumentPooler = PooledClass.fourArgumentPooler;
var userProvidedKeyEscapeRegex = /\/(?!\/)/g;
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, '//');
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* traversal. Allows avoiding binding callbacks.
*
* @constructor ForEachBookKeeping
* @param {!function} forEachFunction Function to perform traversal with.
* @param {?*} forEachContext Context to perform context with.
*/
function ForEachBookKeeping(forEachFunction, forEachContext) {
this.func = forEachFunction;
this.context = forEachContext;
this.count = 0;
}
ForEachBookKeeping.prototype.destructor = function () {
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(bookKeeping, child, name) {
var func = bookKeeping.func;
var context = bookKeeping.context;
func.call(context, child, bookKeeping.count++);
}
/**
* Iterates through children that are typically specified as `props.children`.
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/
function forEachChildren(children, forEachFunc, forEachContext) {
if (children == null) {
return children;
}
var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext);
traverseAllChildren(children, forEachSingleChild, traverseContext);
ForEachBookKeeping.release(traverseContext);
}
/**
* PooledClass representing the bookkeeping associated with performing a child
* mapping. Allows avoiding binding callbacks.
*
* @constructor MapBookKeeping
* @param {!*} mapResult Object containing the ordered map of results.
* @param {!function} mapFunction Function to perform mapping with.
* @param {?*} mapContext Context to perform mapping with.
*/
function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) {
this.result = mapResult;
this.keyPrefix = keyPrefix;
this.func = mapFunction;
this.context = mapContext;
this.count = 0;
}
MapBookKeeping.prototype.destructor = function () {
this.result = null;
this.keyPrefix = null;
this.func = null;
this.context = null;
this.count = 0;
};
PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler);
function mapSingleChildIntoContext(bookKeeping, child, childKey) {
var result = bookKeeping.result;
var keyPrefix = bookKeeping.keyPrefix;
var func = bookKeeping.func;
var context = bookKeeping.context;
var mappedChild = func.call(context, child, bookKeeping.count++);
if (Array.isArray(mappedChild)) {
mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument);
} else if (mappedChild != null) {
if (ReactElement.isValidElement(mappedChild)) {
mappedChild = ReactElement.cloneAndReplaceKey(mappedChild,
// Keep both the (mapped) and old keys if they differ, just as
// traverseAllChildren used to do for objects as children
keyPrefix + (mappedChild !== child ? 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`.
*
* 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`.
*
* @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.
*/
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;
/***/ }),
/* 111 */
/*!********************************************!*\
!*** ./~/react/lib/traverseAllChildren.js ***!
\********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule traverseAllChildren
*/
'use strict';
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactInstanceHandles = __webpack_require__(/*! ./ReactInstanceHandles */ 45);
var getIteratorFn = __webpack_require__(/*! ./getIteratorFn */ 108);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var SUBSEPARATOR = ':';
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
'.': '=1',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=.:]/g;
var didWarnAboutMaps = false;
function userProvidedKeyEscaper(match) {
return userProvidedKeyEscaperLookup[match];
}
/**
* 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) {
if (component && component.key != null) {
// Explicit key
return wrapUserProvidedKey(component.key);
}
// Implicit key determined by the index in the set
return index.toString(36);
}
/**
* Escape a component key so that it is safe to use in a reactid.
*
* @param {*} text Component key to be escaped.
* @return {string} An escaped string.
*/
function escapeUserProvidedKey(text) {
return ('' + text).replace(userProvidedKeyEscapeRegex, userProvidedKeyEscaper);
}
/**
* Wrap a `key` value explicitly provided by the user to distinguish it from
* implicitly-generated keys generated by a component's index in its parent.
*
* @param {string} key Value of a user-provided `key` attribute
* @return {string}
*/
function wrapUserProvidedKey(key) {
return '$' + escapeUserProvidedKey(key);
}
/**
* @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' || ReactElement.isValidElement(children)) {
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 (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, 'Using Maps as children is not yet fully supported. It is an ' + 'experimental feature that might be removed. Convert it to a ' + 'sequence / iterable of keyed ReactElements instead.') : undefined;
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 + wrapUserProvidedKey(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0);
subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext);
}
}
}
} else if (type === 'object') {
var addendum = '';
if (process.env.NODE_ENV !== 'production') {
addendum = ' If you meant to render a collection of children, use an array ' + 'instead or wrap the object using createFragment(object) from the ' + 'React add-ons.';
if (children._isReactElement) {
addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.';
}
if (ReactCurrentOwner.current) {
var name = ReactCurrentOwner.current.getName();
if (name) {
addendum += ' Check the render method of `' + name + '`.';
}
}
}
var childrenString = String(children);
true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : undefined;
}
}
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;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 112 */
/*!***************************************!*\
!*** ./~/react/lib/ReactDOMSelect.js ***!
\***************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOMSelect
*/
'use strict';
var LinkedValueUtils = __webpack_require__(/*! ./LinkedValueUtils */ 106);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var valueContextKey = '__ReactDOMSelect_value$' + Math.random().toString(36).slice(2);
function updateOptionsIfPendingUpdateAndMounted() {
if (this._rootNodeID && this._wrapperState.pendingUpdate) {
this._wrapperState.pendingUpdate = false;
var props = this._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
updateOptions(this, Boolean(props.multiple), value);
}
}
}
function getDeclarationErrorAddendum(owner) {
if (owner) {
var name = owner.getName();
if (name) {
return ' Check the render method of `' + name + '`.';
}
}
return '';
}
var valuePropNames = ['value', 'defaultValue'];
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function checkSelectPropTypes(inst, props) {
var owner = inst._currentElement._owner;
LinkedValueUtils.checkPropTypes('select', props, owner);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
if (props.multiple) {
process.env.NODE_ENV !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
} else {
process.env.NODE_ENV !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : undefined;
}
}
}
/**
* @param {ReactDOMComponent} inst
* @param {boolean} multiple
* @param {*} propValue A stringable (with `multiple`, a list of stringables).
* @private
*/
function updateOptions(inst, multiple, propValue) {
var selectedValue, i;
var options = ReactMount.getNode(inst._rootNodeID).options;
if (multiple) {
selectedValue = {};
for (i = 0; i < propValue.length; i++) {
selectedValue['' + propValue[i]] = true;
}
for (i = 0; i < options.length; i++) {
var selected = selectedValue.hasOwnProperty(options[i].value);
if (options[i].selected !== selected) {
options[i].selected = selected;
}
}
} else {
// Do not set `select.value` as exact behavior isn't consistent across all
// browsers for all cases.
selectedValue = '' + propValue;
for (i = 0; i < options.length; i++) {
if (options[i].value === selectedValue) {
options[i].selected = true;
return;
}
}
if (options.length) {
options[0].selected = true;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* stringable. If `multiple` is true, the prop must be an array of stringables.
*
* If `value` is not supplied (or null/undefined), user actions that change the
* selected option will trigger updates to the rendered options.
*
* If it is supplied (and not null/undefined), the rendered options will not
* update in response to user actions. Instead, the `value` prop must change in
* order for the rendered options to update.
*
* If `defaultValue` is provided, any options with the supplied values will be
* selected.
*/
var ReactDOMSelect = {
valueContextKey: valueContextKey,
getNativeProps: function (inst, props, context) {
return assign({}, props, {
onChange: inst._wrapperState.onChange,
value: undefined
});
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
checkSelectPropTypes(inst, props);
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
pendingUpdate: false,
initialValue: value != null ? value : props.defaultValue,
onChange: _handleChange.bind(inst),
wasMultiple: Boolean(props.multiple)
};
},
processChildContext: function (inst, props, context) {
// Pass down initial value so initial generated markup has correct
// `selected` attributes
var childContext = assign({}, context);
childContext[valueContextKey] = inst._wrapperState.initialValue;
return childContext;
},
postUpdateWrapper: function (inst) {
var props = inst._currentElement.props;
// After the initial mount, we control selected-ness manually so don't pass
// the context value down
inst._wrapperState.initialValue = undefined;
var wasMultiple = inst._wrapperState.wasMultiple;
inst._wrapperState.wasMultiple = Boolean(props.multiple);
var value = LinkedValueUtils.getValue(props);
if (value != null) {
inst._wrapperState.pendingUpdate = false;
updateOptions(inst, Boolean(props.multiple), value);
} else if (wasMultiple !== Boolean(props.multiple)) {
// For simplicity, reapply `defaultValue` if `multiple` is toggled.
if (props.defaultValue != null) {
updateOptions(inst, Boolean(props.multiple), props.defaultValue);
} else {
// Revert the select back to its default unselected state.
updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : '');
}
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
this._wrapperState.pendingUpdate = true;
ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this);
return returnValue;
}
module.exports = ReactDOMSelect;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 113 */
/*!*****************************************!*\
!*** ./~/react/lib/ReactDOMTextarea.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOMTextarea
*/
'use strict';
var LinkedValueUtils = __webpack_require__(/*! ./LinkedValueUtils */ 106);
var ReactDOMIDOperations = __webpack_require__(/*! ./ReactDOMIDOperations */ 27);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
function forceUpdateIfMounted() {
if (this._rootNodeID) {
// DOM component is still mounted; update
ReactDOMTextarea.updateWrapper(this);
}
}
/**
* Implements a <textarea> native component that allows setting `value`, and
* `defaultValue`. This differs from the traditional DOM API because value is
* usually set as PCDATA children.
*
* If `value` is not supplied (or null/undefined), user actions that affect the
* value will trigger updates to the element.
*
* If `value` is supplied (and not null/undefined), the rendered element will
* not trigger updates to the element. Instead, the `value` prop must change in
* order for the rendered element to be updated.
*
* The rendered element will be initialized with an empty value, the prop
* `defaultValue` if specified, or the children content (deprecated).
*/
var ReactDOMTextarea = {
getNativeProps: function (inst, props, context) {
!(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : undefined;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
var nativeProps = assign({}, props, {
defaultValue: undefined,
value: undefined,
children: inst._wrapperState.initialValue,
onChange: inst._wrapperState.onChange
});
return nativeProps;
},
mountWrapper: function (inst, props) {
if (process.env.NODE_ENV !== 'production') {
LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner);
}
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = props.children;
if (children != null) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : undefined;
}
!(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : undefined;
if (Array.isArray(children)) {
!(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : undefined;
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = LinkedValueUtils.getValue(props);
inst._wrapperState = {
// We save the initial value so that `ReactDOMComponent` doesn't update
// `textContent` (unnecessary since we update value).
// The initial value can be a boolean or object so that's why it's
// forced to be a string.
initialValue: '' + (value != null ? value : defaultValue),
onChange: _handleChange.bind(inst)
};
},
updateWrapper: function (inst) {
var props = inst._currentElement.props;
var value = LinkedValueUtils.getValue(props);
if (value != null) {
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
ReactDOMIDOperations.updatePropertyByID(inst._rootNodeID, 'value', '' + value);
}
}
};
function _handleChange(event) {
var props = this._currentElement.props;
var returnValue = LinkedValueUtils.executeOnChange(props, event);
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
module.exports = ReactDOMTextarea;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 114 */
/*!****************************************!*\
!*** ./~/react/lib/ReactMultiChild.js ***!
\****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactMultiChild
* @typechecks static-only
*/
'use strict';
var ReactComponentEnvironment = __webpack_require__(/*! ./ReactComponentEnvironment */ 64);
var ReactMultiChildUpdateTypes = __webpack_require__(/*! ./ReactMultiChildUpdateTypes */ 16);
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var ReactReconciler = __webpack_require__(/*! ./ReactReconciler */ 50);
var ReactChildReconciler = __webpack_require__(/*! ./ReactChildReconciler */ 115);
var flattenChildren = __webpack_require__(/*! ./flattenChildren */ 116);
/**
* Updating children of a component may trigger recursive updates. The depth is
* used to batch recursive updates to render markup more efficiently.
*
* @type {number}
* @private
*/
var updateDepth = 0;
/**
* Queue of update configuration objects.
*
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
*
* @type {array<object>}
* @private
*/
var updateQueue = [];
/**
* Queue of markup to be rendered.
*
* @type {array<string>}
* @private
*/
var markupQueue = [];
/**
* Enqueues markup to be rendered and inserted at a supplied index.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function enqueueInsertMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
content: null,
fromIndex: null,
toIndex: toIndex
});
}
/**
* Enqueues moving an existing element to another index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
content: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
/**
* Enqueues removing an element at an index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
content: null,
fromIndex: fromIndex,
toIndex: null
});
}
/**
* Enqueues setting the markup of a node.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @private
*/
function enqueueSetMarkup(parentID, markup) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.SET_MARKUP,
markupIndex: null,
content: markup,
fromIndex: null,
toIndex: null
});
}
/**
* Enqueues setting the text content.
*
* @param {string} parentID ID of the parent component.
* @param {string} textContent Text content to set.
* @private
*/
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
content: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponentEnvironment.processChildrenUpdates(updateQueue, markupQueue);
clearQueue();
}
}
/**
* Clears any enqueued updates.
*
* @private
*/
function clearQueue() {
updateQueue.length = 0;
markupQueue.length = 0;
}
/**
* ReactMultiChild are capable of reconciling multiple children.
*
* @class ReactMultiChild
* @internal
*/
var ReactMultiChild = {
/**
* Provides common functionality for components that must reconcile multiple
* children. This is used by `ReactDOMComponent` to mount, update, and
* unmount child components.
*
* @lends {ReactMultiChild.prototype}
*/
Mixin: {
_reconcilerInstantiateChildren: function (nestedChildren, transaction, context) {
if (process.env.NODE_ENV !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
} finally {
ReactCurrentOwner.current = null;
}
}
}
return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context);
},
_reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, transaction, context) {
var nextChildren;
if (process.env.NODE_ENV !== 'production') {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
nextChildren = flattenChildren(nextNestedChildrenElements);
} finally {
ReactCurrentOwner.current = null;
}
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context);
}
}
nextChildren = flattenChildren(nextNestedChildrenElements);
return ReactChildReconciler.updateChildren(prevChildren, nextChildren, transaction, context);
},
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildren Nested child maps.
* @return {array} An array of mounted representations.
* @internal
*/
mountChildren: function (nestedChildren, transaction, context) {
var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context);
this._renderedChildren = children;
var mountImages = [];
var index = 0;
for (var name in children) {
if (children.hasOwnProperty(name)) {
var child = children[name];
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context);
child._mountIndex = index++;
mountImages.push(mountImage);
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function (nextContent) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren);
// TODO: The setTextContent operation should be enough
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChild(prevChildren[name]);
}
}
// Set new text content.
this.setTextContent(nextContent);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Replaces any rendered children with a markup string.
*
* @param {string} nextMarkup String of markup.
* @internal
*/
updateMarkup: function (nextMarkup) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
ReactChildReconciler.unmountChildren(prevChildren);
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChildByName(prevChildren[name], name);
}
}
this.setMarkup(nextMarkup);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function (nextNestedChildrenElements, transaction, context) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildrenElements, transaction, context);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
if (errorThrown) {
clearQueue();
} else {
processQueue();
}
}
}
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildrenElements Nested child element maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function (nextNestedChildrenElements, transaction, context) {
var prevChildren = this._renderedChildren;
var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, transaction, context);
this._renderedChildren = nextChildren;
if (!nextChildren && !prevChildren) {
return;
}
var name;
// `nextIndex` will increment for each child in `nextChildren`, but
// `lastIndex` will be the last index visited in `prevChildren`.
var lastIndex = 0;
var nextIndex = 0;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var nextChild = nextChildren[name];
if (prevChild === nextChild) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChild(prevChild);
}
// The child must be instantiated before it's mounted.
this._mountChildByNameAtIndex(nextChild, name, nextIndex, transaction, context);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
this._unmountChild(prevChildren[name]);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @internal
*/
unmountChildren: function () {
var renderedChildren = this._renderedChildren;
ReactChildReconciler.unmountChildren(renderedChildren);
this._renderedChildren = null;
},
/**
* Moves a child component to the supplied index.
*
* @param {ReactComponent} child Component to move.
* @param {number} toIndex Destination index of the element.
* @param {number} lastIndex Last index visited of the siblings of `child`.
* @protected
*/
moveChild: function (child, toIndex, lastIndex) {
// If the index of `child` is less than `lastIndex`, then it needs to
// be moved. Otherwise, we do not need to move it because a child will be
// inserted or moved before `child`.
if (child._mountIndex < lastIndex) {
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function (child, mountImage) {
enqueueInsertMarkup(this._rootNodeID, mountImage, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function (child) {
enqueueRemove(this._rootNodeID, child._mountIndex);
},
/**
* Sets this text content string.
*
* @param {string} textContent Text content to set.
* @protected
*/
setTextContent: function (textContent) {
enqueueTextContent(this._rootNodeID, textContent);
},
/**
* Sets this markup string.
*
* @param {string} markup Markup to set.
* @protected
*/
setMarkup: function (markup) {
enqueueSetMarkup(this._rootNodeID, markup);
},
/**
* Mounts a child with the supplied name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to mount.
* @param {string} name Name of the child.
* @param {number} index Index at which to insert the child.
* @param {ReactReconcileTransaction} transaction
* @private
*/
_mountChildByNameAtIndex: function (child, name, index, transaction, context) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = ReactReconciler.mountComponent(child, rootID, transaction, context);
child._mountIndex = index;
this.createChild(child, mountImage);
},
/**
* Unmounts a rendered child.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @private
*/
_unmountChild: function (child) {
this.removeChild(child);
child._mountIndex = null;
}
}
};
module.exports = ReactMultiChild;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 115 */
/*!*********************************************!*\
!*** ./~/react/lib/ReactChildReconciler.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactChildReconciler
* @typechecks static-only
*/
'use strict';
var ReactReconciler = __webpack_require__(/*! ./ReactReconciler */ 50);
var instantiateReactComponent = __webpack_require__(/*! ./instantiateReactComponent */ 62);
var shouldUpdateReactComponent = __webpack_require__(/*! ./shouldUpdateReactComponent */ 67);
var traverseAllChildren = __webpack_require__(/*! ./traverseAllChildren */ 111);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
function instantiateChild(childInstances, child, name) {
// We found a component instance.
var keyUnique = childInstances[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (child != null && keyUnique) {
childInstances[name] = instantiateReactComponent(child, null);
}
}
/**
* ReactChildReconciler provides helpers for initializing or updating a set of
* children. Its output is suitable for passing it onto ReactMultiChild which
* does diffed reordering and insertion.
*/
var ReactChildReconciler = {
/**
* Generates a "mount image" for each of the supplied children. In the case
* of `ReactDOMComponent`, a mount image is a string of markup.
*
* @param {?object} nestedChildNodes Nested child maps.
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function (nestedChildNodes, transaction, context) {
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
return childInstances;
},
/**
* Updates the rendered children and returns a new set of children.
*
* @param {?object} prevChildren Previously initialized set of children.
* @param {?object} nextChildren Flat child element maps.
* @param {ReactReconcileTransaction} transaction
* @param {object} context
* @return {?object} A new set of child instances.
* @internal
*/
updateChildren: function (prevChildren, nextChildren, transaction, context) {
// We currently don't have a way to track moves here but if we use iterators
// instead of for..in we can zip the iterators and check if an item has
// moved.
// TODO: If nothing has changed, return the prevChildren object so that we
// can quickly bailout if nothing has changed.
if (!nextChildren && !prevChildren) {
return null;
}
var name;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement;
var nextElement = nextChildren[name];
if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) {
ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context);
nextChildren[name] = prevChild;
} else {
if (prevChild) {
ReactReconciler.unmountComponent(prevChild, name);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement, null);
nextChildren[name] = nextChildInstance;
}
}
// Unmount children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) {
ReactReconciler.unmountComponent(prevChildren[name]);
}
}
return nextChildren;
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @param {?object} renderedChildren Previously initialized set of children.
* @internal
*/
unmountChildren: function (renderedChildren) {
for (var name in renderedChildren) {
if (renderedChildren.hasOwnProperty(name)) {
var renderedChild = renderedChildren[name];
ReactReconciler.unmountComponent(renderedChild);
}
}
}
};
module.exports = ReactChildReconciler;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 116 */
/*!****************************************!*\
!*** ./~/react/lib/flattenChildren.js ***!
\****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule flattenChildren
*/
'use strict';
var traverseAllChildren = __webpack_require__(/*! ./traverseAllChildren */ 111);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
/**
* @param {function} traverseContext Context passed through traversal.
* @param {?ReactComponent} child React child component.
* @param {!string} name String name of key path to child.
*/
function flattenSingleChildIntoContext(traverseContext, child, name) {
// We found a component instance.
var result = traverseContext;
var keyUnique = result[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', name) : undefined;
}
if (keyUnique && child != null) {
result[name] = child;
}
}
/**
* Flattens children that are typically specified as `props.children`. Any null
* children will not be included in the resulting object.
* @return {!object} flattened children keyed by name.
*/
function flattenChildren(children) {
if (children == null) {
return children;
}
var result = {};
traverseAllChildren(children, flattenSingleChildIntoContext, result);
return result;
}
module.exports = flattenChildren;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 117 */
/*!************************************!*\
!*** ./~/fbjs/lib/shallowEqual.js ***!
\************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule shallowEqual
* @typechecks
*
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Performs equality by iterating through keys on an object and returning false
* when any key has values which are not strictly equal between the arguments.
* Returns true when the values of all keys are strictly equal.
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
// Test for A's keys different from B.
var bHasOwnProperty = hasOwnProperty.bind(objB);
for (var i = 0; i < keysA.length; i++) {
if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
/***/ }),
/* 118 */
/*!*******************************************!*\
!*** ./~/react/lib/ReactEventListener.js ***!
\*******************************************/
/***/ (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.
*
* @providesModule ReactEventListener
* @typechecks static-only
*/
'use strict';
var EventListener = __webpack_require__(/*! fbjs/lib/EventListener */ 119);
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var PooledClass = __webpack_require__(/*! ./PooledClass */ 56);
var ReactInstanceHandles = __webpack_require__(/*! ./ReactInstanceHandles */ 45);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var getEventTarget = __webpack_require__(/*! ./getEventTarget */ 81);
var getUnboundedScrollPosition = __webpack_require__(/*! fbjs/lib/getUnboundedScrollPosition */ 120);
var DOCUMENT_FRAGMENT_NODE_TYPE = 11;
/**
* Finds the parent React component of `node`.
*
* @param {*} node
* @return {?DOMEventTarget} Parent container, or `null` if the specified node
* is not nested.
*/
function findParent(node) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
var nodeID = ReactMount.getID(node);
var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
var container = ReactMount.findReactContainerForID(rootID);
var parent = ReactMount.getFirstReactDOM(container);
return parent;
}
// Used to store ancestor hierarchy in top level callback
function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) {
this.topLevelType = topLevelType;
this.nativeEvent = nativeEvent;
this.ancestors = [];
}
assign(TopLevelCallbackBookKeeping.prototype, {
destructor: function () {
this.topLevelType = null;
this.nativeEvent = null;
this.ancestors.length = 0;
}
});
PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler);
function handleTopLevelImpl(bookKeeping) {
// TODO: Re-enable event.path handling
//
// if (bookKeeping.nativeEvent.path && bookKeeping.nativeEvent.path.length > 1) {
// // New browsers have a path attribute on native events
// handleTopLevelWithPath(bookKeeping);
// } else {
// // Legacy browsers don't have a path attribute on native events
// handleTopLevelWithoutPath(bookKeeping);
// }
void handleTopLevelWithPath; // temporarily unused
handleTopLevelWithoutPath(bookKeeping);
}
// Legacy browsers don't have a path attribute on native events
function handleTopLevelWithoutPath(bookKeeping) {
var topLevelTarget = ReactMount.getFirstReactDOM(getEventTarget(bookKeeping.nativeEvent)) || window;
// Loop through the hierarchy, in case there's any nested components.
// It's important that we build the array of ancestors before calling any
// event handlers, because event handlers can modify the DOM, leading to
// inconsistencies with ReactMount's node cache. See #1105.
var ancestor = topLevelTarget;
while (ancestor) {
bookKeeping.ancestors.push(ancestor);
ancestor = findParent(ancestor);
}
for (var i = 0; i < bookKeeping.ancestors.length; i++) {
topLevelTarget = bookKeeping.ancestors[i];
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, topLevelTarget, topLevelTargetID, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
// New browsers have a path attribute on native events
function handleTopLevelWithPath(bookKeeping) {
var path = bookKeeping.nativeEvent.path;
var currentNativeTarget = path[0];
var eventsFired = 0;
for (var i = 0; i < path.length; i++) {
var currentPathElement = path[i];
if (currentPathElement.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE) {
currentNativeTarget = path[i + 1];
}
// TODO: slow
var reactParent = ReactMount.getFirstReactDOM(currentPathElement);
if (reactParent === currentPathElement) {
var currentPathElementID = ReactMount.getID(currentPathElement);
var newRootID = ReactInstanceHandles.getReactRootIDFromNodeID(currentPathElementID);
bookKeeping.ancestors.push(currentPathElement);
var topLevelTargetID = ReactMount.getID(currentPathElement) || '';
eventsFired++;
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, currentPathElement, topLevelTargetID, bookKeeping.nativeEvent, currentNativeTarget);
// Jump to the root of this React render tree
while (currentPathElementID !== newRootID) {
i++;
currentPathElement = path[i];
currentPathElementID = ReactMount.getID(currentPathElement);
}
}
}
if (eventsFired === 0) {
ReactEventListener._handleTopLevel(bookKeeping.topLevelType, window, '', bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent));
}
}
function scrollValueMonitor(cb) {
var scrollPosition = getUnboundedScrollPosition(window);
cb(scrollPosition);
}
var ReactEventListener = {
_enabled: true,
_handleTopLevel: null,
WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null,
setHandleTopLevel: function (handleTopLevel) {
ReactEventListener._handleTopLevel = handleTopLevel;
},
setEnabled: function (enabled) {
ReactEventListener._enabled = !!enabled;
},
isEnabled: function () {
return ReactEventListener._enabled;
},
/**
* Traps top-level events by using event bubbling.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapBubbledEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
/**
* Traps a top-level event by using event capturing.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {string} handlerBaseName Event name (e.g. "click").
* @param {object} handle Element on which to attach listener.
* @return {?object} An object with a remove function which will forcefully
* remove the listener.
* @internal
*/
trapCapturedEvent: function (topLevelType, handlerBaseName, handle) {
var element = handle;
if (!element) {
return null;
}
return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType));
},
monitorScrollValue: function (refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
},
dispatchEvent: function (topLevelType, nativeEvent) {
if (!ReactEventListener._enabled) {
return;
}
var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent);
try {
// Event queue being processed in the same cycle allows
// `preventDefault`.
ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping);
} finally {
TopLevelCallbackBookKeeping.release(bookKeeping);
}
}
};
module.exports = ReactEventListener;
/***/ }),
/* 119 */
/*!*************************************!*\
!*** ./~/fbjs/lib/EventListener.js ***!
\*************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @providesModule EventListener
* @typechecks
*/
'use strict';
var emptyFunction = __webpack_require__(/*! ./emptyFunction */ 15);
/**
* Upstream version of event listener. Does not take into account specific
* nature of platform.
*/
var EventListener = {
/**
* Listen to DOM events during the bubble phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
listen: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, false);
return {
remove: function () {
target.removeEventListener(eventType, callback, false);
}
};
} else if (target.attachEvent) {
target.attachEvent('on' + eventType, callback);
return {
remove: function () {
target.detachEvent('on' + eventType, callback);
}
};
}
},
/**
* Listen to DOM events during the capture phase.
*
* @param {DOMEventTarget} target DOM element to register listener on.
* @param {string} eventType Event type, e.g. 'click' or 'mouseover'.
* @param {function} callback Callback function.
* @return {object} Object with a `remove` method.
*/
capture: function (target, eventType, callback) {
if (target.addEventListener) {
target.addEventListener(eventType, callback, true);
return {
remove: function () {
target.removeEventListener(eventType, callback, true);
}
};
} else {
if (process.env.NODE_ENV !== 'production') {
console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.');
}
return {
remove: emptyFunction
};
}
},
registerDefault: function () {}
};
module.exports = EventListener;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 120 */
/*!**************************************************!*\
!*** ./~/fbjs/lib/getUnboundedScrollPosition.js ***!
\**************************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule getUnboundedScrollPosition
* @typechecks
*/
'use strict';
/**
* Gets the scroll position of the supplied element or window.
*
* The return values are unbounded, unlike `getScrollPosition`. This means they
* may be negative or exceed the element boundaries (which is possible using
* inertial scrolling).
*
* @param {DOMWindow|DOMElement} scrollable
* @return {object} Map with `x` and `y` keys.
*/
function getUnboundedScrollPosition(scrollable) {
if (scrollable === window) {
return {
x: window.pageXOffset || document.documentElement.scrollLeft,
y: window.pageYOffset || document.documentElement.scrollTop
};
}
return {
x: scrollable.scrollLeft,
y: scrollable.scrollTop
};
}
module.exports = getUnboundedScrollPosition;
/***/ }),
/* 121 */
/*!***************************************!*\
!*** ./~/react/lib/ReactInjection.js ***!
\***************************************/
/***/ (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.
*
* @providesModule ReactInjection
*/
'use strict';
var DOMProperty = __webpack_require__(/*! ./DOMProperty */ 23);
var EventPluginHub = __webpack_require__(/*! ./EventPluginHub */ 31);
var ReactComponentEnvironment = __webpack_require__(/*! ./ReactComponentEnvironment */ 64);
var ReactClass = __webpack_require__(/*! ./ReactClass */ 122);
var ReactEmptyComponent = __webpack_require__(/*! ./ReactEmptyComponent */ 68);
var ReactBrowserEventEmitter = __webpack_require__(/*! ./ReactBrowserEventEmitter */ 29);
var ReactNativeComponent = __webpack_require__(/*! ./ReactNativeComponent */ 69);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var ReactRootIndex = __webpack_require__(/*! ./ReactRootIndex */ 46);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
NativeComponent: ReactNativeComponent.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
/***/ }),
/* 122 */
/*!***********************************!*\
!*** ./~/react/lib/ReactClass.js ***!
\***********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactClass
*/
'use strict';
var ReactComponent = __webpack_require__(/*! ./ReactComponent */ 123);
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactPropTypeLocations = __webpack_require__(/*! ./ReactPropTypeLocations */ 65);
var ReactPropTypeLocationNames = __webpack_require__(/*! ./ReactPropTypeLocationNames */ 66);
var ReactNoopUpdateQueue = __webpack_require__(/*! ./ReactNoopUpdateQueue */ 124);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ 58);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var keyMirror = __webpack_require__(/*! fbjs/lib/keyMirror */ 17);
var keyOf = __webpack_require__(/*! fbjs/lib/keyOf */ 79);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
var MIXINS_KEY = keyOf({ mixins: null });
/**
* Policies that describe methods in `ReactClassInterface`.
*/
var SpecPolicy = keyMirror({
/**
* These methods may be defined only once by the class specification or mixin.
*/
DEFINE_ONCE: null,
/**
* These methods may be defined by both the class specification and mixins.
* Subsequent definitions will be chained. These methods must return void.
*/
DEFINE_MANY: null,
/**
* These methods are overriding the base class.
*/
OVERRIDE_BASE: null,
/**
* These methods are similar to DEFINE_MANY, except we assume they return
* objects. We try to merge the keys of the return values of all the mixed in
* functions. If there is a key conflict we throw.
*/
DEFINE_MANY_MERGED: null
});
var injectedMixins = [];
var warnedSetProps = false;
function warnSetProps() {
if (!warnedSetProps) {
warnedSetProps = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'setProps(...) and replaceProps(...) are deprecated. ' + 'Instead, call render again at the top level.') : undefined;
}
}
/**
* Composite components are higher-level components that compose other composite
* or native 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: SpecPolicy.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: SpecPolicy.DEFINE_MANY,
/**
* Definition of prop types for this component.
*
* @type {object}
* @optional
*/
propTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types for this component.
*
* @type {object}
* @optional
*/
contextTypes: SpecPolicy.DEFINE_MANY,
/**
* Definition of context types this component sets for its children.
*
* @type {object}
* @optional
*/
childContextTypes: SpecPolicy.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: SpecPolicy.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: SpecPolicy.DEFINE_MANY_MERGED,
/**
* @return {object}
* @optional
*/
getChildContext: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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: SpecPolicy.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 (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext);
}
Constructor.childContextTypes = assign({}, Constructor.childContextTypes, childContextTypes);
},
contextTypes: function (Constructor, contextTypes) {
if (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.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 (process.env.NODE_ENV !== 'production') {
validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop);
}
Constructor.propTypes = assign({}, Constructor.propTypes, propTypes);
},
statics: function (Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
},
autobind: function () {} };
// noop
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 not in __DEV__
process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : undefined;
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactClassMixin.hasOwnProperty(name)) {
!(specPolicy === SpecPolicy.OVERRIDE_BASE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : undefined;
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
!(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : undefined;
}
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building React classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
}
!(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
!!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : undefined;
var proto = Constructor.prototype;
// 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];
validateMethodOverride(proto, 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 isAlreadyDefined = proto.hasOwnProperty(name);
var isFunction = typeof property === 'function';
var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactClassInterface[name];
// These cases should already be caught by validateMethodOverride.
!(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : undefined;
// For methods which are defined more than once, call the existing
// methods before calling the new property, merging if appropriate.
if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) {
proto[name] = createMergedResultFunction(proto[name], property);
} else if (specPolicy === SpecPolicy.DEFINE_MANY) {
proto[name] = createChainedFunction(proto[name], property);
}
} else {
proto[name] = property;
if (process.env.NODE_ENV !== 'production') {
// Add verbose displayName to the function, which helps when looking
// at profiling tools.
if (typeof property === 'function' && spec.displayName) {
proto[name].displayName = spec.displayName + '_' + name;
}
}
}
}
}
}
}
function mixStaticSpecIntoComponent(Constructor, statics) {
if (!statics) {
return;
}
for (var name in statics) {
var property = statics[name];
if (!statics.hasOwnProperty(name)) {
continue;
}
var isReserved = (name in RESERVED_SPEC_KEYS);
!!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name) : invariant(false) : undefined;
var isInherited = (name in Constructor);
!!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : undefined;
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') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : undefined;
for (var key in two) {
if (two.hasOwnProperty(key)) {
!(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key) : invariant(false) : undefined;
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 (process.env.NODE_ENV !== 'production') {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
/* eslint-disable block-scoped-var, no-undef */
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) {
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : undefined;
} else if (!args.length) {
process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName) : undefined;
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
/* eslint-enable */
};
}
return boundMethod;
}
/**
* Binds all auto-bound methods in a component.
*
* @param {object} component Component whose method is going to be bound.
*/
function bindAutoBindMethods(component) {
for (var autoBindKey in component.__reactAutoBindMap) {
if (component.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
var method = component.__reactAutoBindMap[autoBindKey];
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);
}
},
/**
* 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);
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
* @deprecated
*/
setProps: function (partialProps, callback) {
if (process.env.NODE_ENV !== 'production') {
warnSetProps();
}
this.updater.enqueueSetProps(this, partialProps);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
},
/**
* Replace all the props.
*
* @param {object} newProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
* @deprecated
*/
replaceProps: function (newProps, callback) {
if (process.env.NODE_ENV !== 'production') {
warnSetProps();
}
this.updater.enqueueReplaceProps(this, newProps);
if (callback) {
this.updater.enqueueCallback(this, callback);
}
}
};
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.
*
* @param {object} spec Class specification (which must define `render`).
* @return {function} Component constructor function.
* @public
*/
createClass: function (spec) {
var Constructor = function (props, context, updater) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted.
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : undefined;
}
// Wire up auto-binding
if (this.__reactAutoBindMap) {
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 (process.env.NODE_ENV !== 'production') {
// We allow auto-mocks to proceed as if they're returning null.
if (typeof 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)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : undefined;
this.state = initialState;
};
Constructor.prototype = new ReactClassComponent();
Constructor.prototype.constructor = Constructor;
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 (process.env.NODE_ENV !== 'production') {
// This is a tag to indicate that the use of these method names is ok,
// since it's used with createClass. If it's not, then it's likely a
// mistake so we'll warn you to use the static property, property
// initializer or constructor respectively.
if (Constructor.getDefaultProps) {
Constructor.getDefaultProps.isReactClassApproved = {};
}
if (Constructor.prototype.getInitialState) {
Constructor.prototype.getInitialState.isReactClassApproved = {};
}
}
!Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component') : undefined;
process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : undefined;
}
// 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;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 123 */
/*!***************************************!*\
!*** ./~/react/lib/ReactComponent.js ***!
\***************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactComponent
*/
'use strict';
var ReactNoopUpdateQueue = __webpack_require__(/*! ./ReactNoopUpdateQueue */ 124);
var canDefineProperty = __webpack_require__(/*! ./canDefineProperty */ 43);
var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ 58);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
/**
* 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) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : undefined;
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : undefined;
}
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, 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 {?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);
}
};
/**
* 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 (process.env.NODE_ENV !== 'production') {
var deprecatedAPIs = {
getDOMNode: ['getDOMNode', 'Use ReactDOM.findDOMNode(component) instead.'],
isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'],
replaceProps: ['replaceProps', 'Instead, call render again at the top level.'],
replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'],
setProps: ['setProps', 'Instead, call render again at the top level.']
};
var defineDeprecationWarning = function (methodName, info) {
if (canDefineProperty) {
Object.defineProperty(ReactComponent.prototype, methodName, {
get: function () {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : undefined;
return undefined;
}
});
}
};
for (var fnName in deprecatedAPIs) {
if (deprecatedAPIs.hasOwnProperty(fnName)) {
defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
}
}
}
module.exports = ReactComponent;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 124 */
/*!*********************************************!*\
!*** ./~/react/lib/ReactNoopUpdateQueue.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactNoopUpdateQueue
*/
'use strict';
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
function warnTDZ(publicInstance, callerName) {
if (process.env.NODE_ENV !== 'production') {
process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): Can only update a mounted or mounting component. ' + 'This usually means you called %s() on an unmounted component. ' + 'This is a no-op. Please check the code for the %s component.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : undefined;
}
}
/**
* 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) {
warnTDZ(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) {
warnTDZ(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) {
warnTDZ(publicInstance, 'setState');
},
/**
* Sets a subset of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialProps Subset of the next props.
* @internal
*/
enqueueSetProps: function (publicInstance, partialProps) {
warnTDZ(publicInstance, 'setProps');
},
/**
* Replaces all of the props.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} props New props.
* @internal
*/
enqueueReplaceProps: function (publicInstance, props) {
warnTDZ(publicInstance, 'replaceProps');
}
};
module.exports = ReactNoopUpdateQueue;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 125 */
/*!**************************************************!*\
!*** ./~/react/lib/ReactReconcileTransaction.js ***!
\**************************************************/
/***/ (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.
*
* @providesModule ReactReconcileTransaction
* @typechecks static-only
*/
'use strict';
var CallbackQueue = __webpack_require__(/*! ./CallbackQueue */ 55);
var PooledClass = __webpack_require__(/*! ./PooledClass */ 56);
var ReactBrowserEventEmitter = __webpack_require__(/*! ./ReactBrowserEventEmitter */ 29);
var ReactDOMFeatureFlags = __webpack_require__(/*! ./ReactDOMFeatureFlags */ 41);
var ReactInputSelection = __webpack_require__(/*! ./ReactInputSelection */ 126);
var Transaction = __webpack_require__(/*! ./Transaction */ 57);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
/**
* Ensures that, when possible, the selection range (currently selected text
* input) is not disturbed by performing the transaction.
*/
var SELECTION_RESTORATION = {
/**
* @return {Selection} Selection information.
*/
initialize: ReactInputSelection.getSelectionInformation,
/**
* @param {Selection} sel Selection information returned from `initialize`.
*/
close: ReactInputSelection.restoreSelection
};
/**
* Suppresses events (blur/focus) that could be inadvertently dispatched due to
* high level DOM manipulations (like temporarily removing a text input from the
* DOM).
*/
var EVENT_SUPPRESSION = {
/**
* @return {boolean} The enabled status of `ReactBrowserEventEmitter` before
* the reconciliation.
*/
initialize: function () {
var currentlyEnabled = ReactBrowserEventEmitter.isEnabled();
ReactBrowserEventEmitter.setEnabled(false);
return currentlyEnabled;
},
/**
* @param {boolean} previouslyEnabled Enabled status of
* `ReactBrowserEventEmitter` before the reconciliation occurred. `close`
* restores the previous value.
*/
close: function (previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
/**
* After DOM is flushed, invoke all registered `onDOMReady` callbacks.
*/
close: function () {
this.reactMountReady.notifyAll();
}
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING];
/**
* Currently:
* - The order that these are listed in the transaction is critical:
* - Suppresses events.
* - Restores selection range.
*
* Future:
* - Restore document/overflow scroll positions that were unintentionally
* modified via DOM insertions above the top viewport boundary.
* - Implement/integrate with customized constraint based layout system and keep
* track of which dimensions must be remeasured.
*
* @class ReactReconcileTransaction
*/
function ReactReconcileTransaction(forceHTML) {
this.reinitializeTransaction();
// Only server-side rendering really needs this option (see
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
// `ReactTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = !forceHTML && ReactDOMFeatureFlags.useCreateElement;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap procedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
/***/ }),
/* 126 */
/*!********************************************!*\
!*** ./~/react/lib/ReactInputSelection.js ***!
\********************************************/
/***/ (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.
*
* @providesModule ReactInputSelection
*/
'use strict';
var ReactDOMSelection = __webpack_require__(/*! ./ReactDOMSelection */ 127);
var containsNode = __webpack_require__(/*! fbjs/lib/containsNode */ 59);
var focusNode = __webpack_require__(/*! fbjs/lib/focusNode */ 95);
var getActiveElement = __webpack_require__(/*! fbjs/lib/getActiveElement */ 129);
function isInDocument(node) {
return containsNode(document.documentElement, node);
}
/**
* @ReactInputSelection: React input selection module. Based on Selection.js,
* but modified to be suitable for react and has a couple of bug fixes (doesn't
* assume buttons have range selections allowed).
* Input selection module for React.
*/
var ReactInputSelection = {
hasSelectionCapabilities: function (elem) {
var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true');
},
getSelectionInformation: function () {
var focusedElem = getActiveElement();
return {
focusedElem: focusedElem,
selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null
};
},
/**
* @restoreSelection: If any selection information was potentially lost,
* restore it. This is useful when performing operations that could remove dom
* nodes and place them back in, resulting in focus being lost.
*/
restoreSelection: function (priorSelectionInformation) {
var curFocusedElem = getActiveElement();
var priorFocusedElem = priorSelectionInformation.focusedElem;
var priorSelectionRange = priorSelectionInformation.selectionRange;
if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) {
if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange);
}
focusNode(priorFocusedElem);
}
},
/**
* @getSelection: Gets the selection bounds of a focused textarea, input or
* contentEditable node.
* -@input: Look up selection bounds of this input
* -@return {start: selectionStart, end: selectionEnd}
*/
getSelection: function (input) {
var selection;
if ('selectionStart' in input) {
// Modern browser with input or textarea.
selection = {
start: input.selectionStart,
end: input.selectionEnd
};
} else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
// IE8 input.
var range = document.selection.createRange();
// There can only be one selection per document in IE, so it must
// be in our element.
if (range.parentElement() === input) {
selection = {
start: -range.moveStart('character', -input.value.length),
end: -range.moveEnd('character', -input.value.length)
};
}
} else {
// Content editable or old IE textarea.
selection = ReactDOMSelection.getOffsets(input);
}
return selection || { start: 0, end: 0 };
},
/**
* @setSelection: Sets the selection bounds of a textarea or input and focuses
* the input.
* -@input Set selection bounds of this input or textarea
* -@offsets Object of same form that is returned from get*
*/
setSelection: function (input, offsets) {
var start = offsets.start;
var end = offsets.end;
if (typeof end === 'undefined') {
end = start;
}
if ('selectionStart' in input) {
input.selectionStart = start;
input.selectionEnd = Math.min(end, input.value.length);
} else if (document.selection && (input.nodeName && input.nodeName.toLowerCase() === 'input')) {
var range = input.createTextRange();
range.collapse(true);
range.moveStart('character', start);
range.moveEnd('character', end - start);
range.select();
} else {
ReactDOMSelection.setOffsets(input, offsets);
}
}
};
module.exports = ReactInputSelection;
/***/ }),
/* 127 */
/*!******************************************!*\
!*** ./~/react/lib/ReactDOMSelection.js ***!
\******************************************/
/***/ (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.
*
* @providesModule ReactDOMSelection
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var getNodeForCharacterOffset = __webpack_require__(/*! ./getNodeForCharacterOffset */ 128);
var getTextContentAccessor = __webpack_require__(/*! ./getTextContentAccessor */ 75);
/**
* While `isCollapsed` is available on the Selection object and `collapsed`
* is available on the Range object, IE11 sometimes gets them wrong.
* If the anchor/focus nodes and offsets are the same, the range is collapsed.
*/
function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) {
return anchorNode === focusNode && anchorOffset === focusOffset;
}
/**
* Get the appropriate anchor and focus node/offset pairs for IE.
*
* The catch here is that IE's selection API doesn't provide information
* about whether the selection is forward or backward, so we have to
* behave as though it's always forward.
*
* IE text differs from modern selection in that it behaves as though
* block elements end with a new line. This means character offsets will
* differ between the two APIs.
*
* @param {DOMElement} node
* @return {object}
*/
function getIEOffsets(node) {
var selection = document.selection;
var selectedRange = selection.createRange();
var selectedLength = selectedRange.text.length;
// Duplicate selection so we can move range without breaking user selection.
var fromStart = selectedRange.duplicate();
fromStart.moveToElementText(node);
fromStart.setEndPoint('EndToStart', selectedRange);
var startOffset = fromStart.text.length;
var endOffset = startOffset + selectedLength;
return {
start: startOffset,
end: endOffset
};
}
/**
* @param {DOMElement} node
* @return {?object}
*/
function getModernOffsets(node) {
var selection = window.getSelection && window.getSelection();
if (!selection || selection.rangeCount === 0) {
return null;
}
var anchorNode = selection.anchorNode;
var anchorOffset = selection.anchorOffset;
var focusNode = selection.focusNode;
var focusOffset = selection.focusOffset;
var currentRange = selection.getRangeAt(0);
// In Firefox, range.startContainer and range.endContainer can be "anonymous
// divs", e.g. the up/down buttons on an <input type="number">. Anonymous
// divs do not seem to expose properties, triggering a "Permission denied
// error" if any of its properties are accessed. The only seemingly possible
// way to avoid erroring is to access a property that typically works for
// non-anonymous divs and catch any error that may otherwise arise. See
// https://bugzilla.mozilla.org/show_bug.cgi?id=208427
try {
/* eslint-disable no-unused-expressions */
currentRange.startContainer.nodeType;
currentRange.endContainer.nodeType;
/* eslint-enable no-unused-expressions */
} catch (e) {
return null;
}
// If the node and offset values are the same, the selection is collapsed.
// `Selection.isCollapsed` is available natively, but IE sometimes gets
// this value wrong.
var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset);
var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length;
var tempRange = currentRange.cloneRange();
tempRange.selectNodeContents(node);
tempRange.setEnd(currentRange.startContainer, currentRange.startOffset);
var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset);
var start = isTempRangeCollapsed ? 0 : tempRange.toString().length;
var end = start + rangeLength;
// Detect whether the selection is backward.
var detectionRange = document.createRange();
detectionRange.setStart(anchorNode, anchorOffset);
detectionRange.setEnd(focusNode, focusOffset);
var isBackward = detectionRange.collapsed;
return {
start: isBackward ? end : start,
end: isBackward ? start : end
};
}
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setIEOffsets(node, offsets) {
var range = document.selection.createRange().duplicate();
var start, end;
if (typeof offsets.end === 'undefined') {
start = offsets.start;
end = start;
} else if (offsets.start > offsets.end) {
start = offsets.end;
end = offsets.start;
} else {
start = offsets.start;
end = offsets.end;
}
range.moveToElementText(node);
range.moveStart('character', start);
range.setEndPoint('EndToStart', range);
range.moveEnd('character', end - start);
range.select();
}
/**
* In modern non-IE browsers, we can support both forward and backward
* selections.
*
* Note: IE10+ supports the Selection object, but it does not support
* the `extend` method, which means that even in modern IE, it's not possible
* to programatically create a backward selection. Thus, for all IE
* versions, we use the old IE API to create our selections.
*
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
function setModernOffsets(node, offsets) {
if (!window.getSelection) {
return;
}
var selection = window.getSelection();
var length = node[getTextContentAccessor()].length;
var start = Math.min(offsets.start, length);
var end = typeof offsets.end === 'undefined' ? start : Math.min(offsets.end, length);
// IE 11 uses modern selection, but doesn't support the extend method.
// Flip backward selections, so we can set with a single range.
if (!selection.extend && start > end) {
var temp = end;
end = start;
start = temp;
}
var startMarker = getNodeForCharacterOffset(node, start);
var endMarker = getNodeForCharacterOffset(node, end);
if (startMarker && endMarker) {
var range = document.createRange();
range.setStart(startMarker.node, startMarker.offset);
selection.removeAllRanges();
if (start > end) {
selection.addRange(range);
selection.extend(endMarker.node, endMarker.offset);
} else {
range.setEnd(endMarker.node, endMarker.offset);
selection.addRange(range);
}
}
}
var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window);
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
/***/ }),
/* 128 */
/*!**************************************************!*\
!*** ./~/react/lib/getNodeForCharacterOffset.js ***!
\**************************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule getNodeForCharacterOffset
*/
'use strict';
/**
* Given any node return the first leaf node without children.
*
* @param {DOMElement|DOMTextNode} node
* @return {DOMElement|DOMTextNode}
*/
function getLeafNode(node) {
while (node && node.firstChild) {
node = node.firstChild;
}
return node;
}
/**
* Get the next sibling within a container. This will walk up the
* DOM if a node's siblings have been exhausted.
*
* @param {DOMElement|DOMTextNode} node
* @return {?DOMElement|DOMTextNode}
*/
function getSiblingNode(node) {
while (node) {
if (node.nextSibling) {
return node.nextSibling;
}
node = node.parentNode;
}
}
/**
* Get object describing the nodes which contain characters at offset.
*
* @param {DOMElement|DOMTextNode} root
* @param {number} offset
* @return {?object}
*/
function getNodeForCharacterOffset(root, offset) {
var node = getLeafNode(root);
var nodeStart = 0;
var nodeEnd = 0;
while (node) {
if (node.nodeType === 3) {
nodeEnd = nodeStart + node.textContent.length;
if (nodeStart <= offset && nodeEnd >= offset) {
return {
node: node,
offset: offset - nodeStart
};
}
nodeStart = nodeEnd;
}
node = getLeafNode(getSiblingNode(node));
}
}
module.exports = getNodeForCharacterOffset;
/***/ }),
/* 129 */
/*!****************************************!*\
!*** ./~/fbjs/lib/getActiveElement.js ***!
\****************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule getActiveElement
* @typechecks
*/
/* eslint-disable fb-www/typeof-undefined */
/**
* Same as document.activeElement but wraps in a try-catch block. In IE it is
* not safe to call document.activeElement if there is nothing focused.
*
* The activeElement will be null only if the document or document body is not
* yet defined.
*/
'use strict';
function getActiveElement() /*?DOMElement*/{
if (typeof document === 'undefined') {
return null;
}
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
/***/ }),
/* 130 */
/*!******************************************!*\
!*** ./~/react/lib/SelectEventPlugin.js ***!
\******************************************/
/***/ (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.
*
* @providesModule SelectEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var EventPropagators = __webpack_require__(/*! ./EventPropagators */ 73);
var ExecutionEnvironment = __webpack_require__(/*! fbjs/lib/ExecutionEnvironment */ 9);
var ReactInputSelection = __webpack_require__(/*! ./ReactInputSelection */ 126);
var SyntheticEvent = __webpack_require__(/*! ./SyntheticEvent */ 77);
var getActiveElement = __webpack_require__(/*! fbjs/lib/getActiveElement */ 129);
var isTextInputElement = __webpack_require__(/*! ./isTextInputElement */ 82);
var keyOf = __webpack_require__(/*! fbjs/lib/keyOf */ 79);
var shallowEqual = __webpack_require__(/*! fbjs/lib/shallowEqual */ 117);
var topLevelTypes = EventConstants.topLevelTypes;
var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11;
var eventTypes = {
select: {
phasedRegistrationNames: {
bubbled: keyOf({ onSelect: null }),
captured: keyOf({ onSelectCapture: null })
},
dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange]
}
};
var activeElement = null;
var activeElementID = null;
var lastSelection = null;
var mouseDown = false;
// Track whether a listener exists for this plugin. If none exist, we do
// not extract events.
var hasListener = false;
var ON_SELECT_KEY = keyOf({ onSelect: null });
/**
* Get an object which is a unique representation of the current selection.
*
* The return value will not be consistent across nodes or browsers, but
* two identical selections on the same node will return identical objects.
*
* @param {DOMElement} node
* @return {object}
*/
function getSelection(node) {
if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) {
return {
start: node.selectionStart,
end: node.selectionEnd
};
} else if (window.getSelection) {
var selection = window.getSelection();
return {
anchorNode: selection.anchorNode,
anchorOffset: selection.anchorOffset,
focusNode: selection.focusNode,
focusOffset: selection.focusOffset
};
} else if (document.selection) {
var range = document.selection.createRange();
return {
parentElement: range.parentElement(),
text: range.text,
top: range.boundingTop,
left: range.boundingLeft
};
}
}
/**
* Poll selection to see whether it's changed.
*
* @param {object} nativeEvent
* @return {?SyntheticEvent}
*/
function constructSelectEvent(nativeEvent, nativeEventTarget) {
// Ensure we have the right element, and that the user is not dragging a
// selection (this matches native `select` event behavior). In HTML5, select
// fires only on input and textarea thus if there's no focused element we
// won't dispatch.
if (mouseDown || activeElement == null || activeElement !== getActiveElement()) {
return null;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementID, nativeEvent, nativeEventTarget);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
return null;
}
/**
* This plugin creates an `onSelect` event that normalizes select events
* across form elements.
*
* Supported elements are:
* - input (see `isTextInputElement`)
* - textarea
* - contentEditable
*
* This differs from native browser implementations in the following ways:
* - Fires on contentEditable fields as well as inputs.
* - Fires for collapsed selection.
* - Fires after user input.
*/
var SelectEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
if (!hasListener) {
return null;
}
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(topLevelTarget) || topLevelTarget.contentEditable === 'true') {
activeElement = topLevelTarget;
activeElementID = topLevelTargetID;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementID = null;
lastSelection = null;
break;
// Don't fire the event while the user is dragging. This matches the
// semantics of the native select event.
case topLevelTypes.topMouseDown:
mouseDown = true;
break;
case topLevelTypes.topContextMenu:
case topLevelTypes.topMouseUp:
mouseDown = false;
return constructSelectEvent(nativeEvent, nativeEventTarget);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't). IE's event fires out of order with respect
// to key and input events on deletion, so we discard it.
//
// Firefox doesn't support selectionchange, so check selection status
// after each key entry. The selection changes after keydown and before
// keyup, but we check on keydown as well in the case of holding down a
// key, when multiple keydown events are fired but only one keyup is.
// This is also our approach for IE handling, for the reason above.
case topLevelTypes.topSelectionChange:
if (skipSelectionChangeEvent) {
break;
}
// falls through
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent, nativeEventTarget);
}
return null;
},
didPutListener: function (id, registrationName, listener) {
if (registrationName === ON_SELECT_KEY) {
hasListener = true;
}
}
};
module.exports = SelectEventPlugin;
/***/ }),
/* 131 */
/*!*********************************************!*\
!*** ./~/react/lib/ServerReactRootIndex.js ***!
\*********************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ServerReactRootIndex
* @typechecks
*/
'use strict';
/**
* Size of the reactRoot ID space. We generate random numbers for React root
* IDs and if there's a collision the events and DOM update system will
* get confused. In the future we need a way to generate GUIDs but for
* now this will work on a smaller scale.
*/
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
var ServerReactRootIndex = {
createReactRootIndex: function () {
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
}
};
module.exports = ServerReactRootIndex;
/***/ }),
/* 132 */
/*!******************************************!*\
!*** ./~/react/lib/SimpleEventPlugin.js ***!
\******************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule SimpleEventPlugin
*/
'use strict';
var EventConstants = __webpack_require__(/*! ./EventConstants */ 30);
var EventListener = __webpack_require__(/*! fbjs/lib/EventListener */ 119);
var EventPropagators = __webpack_require__(/*! ./EventPropagators */ 73);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var SyntheticClipboardEvent = __webpack_require__(/*! ./SyntheticClipboardEvent */ 133);
var SyntheticEvent = __webpack_require__(/*! ./SyntheticEvent */ 77);
var SyntheticFocusEvent = __webpack_require__(/*! ./SyntheticFocusEvent */ 134);
var SyntheticKeyboardEvent = __webpack_require__(/*! ./SyntheticKeyboardEvent */ 135);
var SyntheticMouseEvent = __webpack_require__(/*! ./SyntheticMouseEvent */ 86);
var SyntheticDragEvent = __webpack_require__(/*! ./SyntheticDragEvent */ 138);
var SyntheticTouchEvent = __webpack_require__(/*! ./SyntheticTouchEvent */ 139);
var SyntheticUIEvent = __webpack_require__(/*! ./SyntheticUIEvent */ 87);
var SyntheticWheelEvent = __webpack_require__(/*! ./SyntheticWheelEvent */ 140);
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ 15);
var getEventCharCode = __webpack_require__(/*! ./getEventCharCode */ 136);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var keyOf = __webpack_require__(/*! fbjs/lib/keyOf */ 79);
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
abort: {
phasedRegistrationNames: {
bubbled: keyOf({ onAbort: true }),
captured: keyOf({ onAbortCapture: true })
}
},
blur: {
phasedRegistrationNames: {
bubbled: keyOf({ onBlur: true }),
captured: keyOf({ onBlurCapture: true })
}
},
canPlay: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlay: true }),
captured: keyOf({ onCanPlayCapture: true })
}
},
canPlayThrough: {
phasedRegistrationNames: {
bubbled: keyOf({ onCanPlayThrough: true }),
captured: keyOf({ onCanPlayThroughCapture: true })
}
},
click: {
phasedRegistrationNames: {
bubbled: keyOf({ onClick: true }),
captured: keyOf({ onClickCapture: true })
}
},
contextMenu: {
phasedRegistrationNames: {
bubbled: keyOf({ onContextMenu: true }),
captured: keyOf({ onContextMenuCapture: true })
}
},
copy: {
phasedRegistrationNames: {
bubbled: keyOf({ onCopy: true }),
captured: keyOf({ onCopyCapture: true })
}
},
cut: {
phasedRegistrationNames: {
bubbled: keyOf({ onCut: true }),
captured: keyOf({ onCutCapture: true })
}
},
doubleClick: {
phasedRegistrationNames: {
bubbled: keyOf({ onDoubleClick: true }),
captured: keyOf({ onDoubleClickCapture: true })
}
},
drag: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrag: true }),
captured: keyOf({ onDragCapture: true })
}
},
dragEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnd: true }),
captured: keyOf({ onDragEndCapture: true })
}
},
dragEnter: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragEnter: true }),
captured: keyOf({ onDragEnterCapture: true })
}
},
dragExit: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragExit: true }),
captured: keyOf({ onDragExitCapture: true })
}
},
dragLeave: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragLeave: true }),
captured: keyOf({ onDragLeaveCapture: true })
}
},
dragOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragOver: true }),
captured: keyOf({ onDragOverCapture: true })
}
},
dragStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onDragStart: true }),
captured: keyOf({ onDragStartCapture: true })
}
},
drop: {
phasedRegistrationNames: {
bubbled: keyOf({ onDrop: true }),
captured: keyOf({ onDropCapture: true })
}
},
durationChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onDurationChange: true }),
captured: keyOf({ onDurationChangeCapture: true })
}
},
emptied: {
phasedRegistrationNames: {
bubbled: keyOf({ onEmptied: true }),
captured: keyOf({ onEmptiedCapture: true })
}
},
encrypted: {
phasedRegistrationNames: {
bubbled: keyOf({ onEncrypted: true }),
captured: keyOf({ onEncryptedCapture: true })
}
},
ended: {
phasedRegistrationNames: {
bubbled: keyOf({ onEnded: true }),
captured: keyOf({ onEndedCapture: true })
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({ onError: true }),
captured: keyOf({ onErrorCapture: true })
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({ onFocus: true }),
captured: keyOf({ onFocusCapture: true })
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({ onInput: true }),
captured: keyOf({ onInputCapture: true })
}
},
keyDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyDown: true }),
captured: keyOf({ onKeyDownCapture: true })
}
},
keyPress: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyPress: true }),
captured: keyOf({ onKeyPressCapture: true })
}
},
keyUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onKeyUp: true }),
captured: keyOf({ onKeyUpCapture: true })
}
},
load: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoad: true }),
captured: keyOf({ onLoadCapture: true })
}
},
loadedData: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedData: true }),
captured: keyOf({ onLoadedDataCapture: true })
}
},
loadedMetadata: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadedMetadata: true }),
captured: keyOf({ onLoadedMetadataCapture: true })
}
},
loadStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onLoadStart: true }),
captured: keyOf({ onLoadStartCapture: true })
}
},
// Note: We do not allow listening to mouseOver events. Instead, use the
// onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`.
mouseDown: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseDown: true }),
captured: keyOf({ onMouseDownCapture: true })
}
},
mouseMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseMove: true }),
captured: keyOf({ onMouseMoveCapture: true })
}
},
mouseOut: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOut: true }),
captured: keyOf({ onMouseOutCapture: true })
}
},
mouseOver: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseOver: true }),
captured: keyOf({ onMouseOverCapture: true })
}
},
mouseUp: {
phasedRegistrationNames: {
bubbled: keyOf({ onMouseUp: true }),
captured: keyOf({ onMouseUpCapture: true })
}
},
paste: {
phasedRegistrationNames: {
bubbled: keyOf({ onPaste: true }),
captured: keyOf({ onPasteCapture: true })
}
},
pause: {
phasedRegistrationNames: {
bubbled: keyOf({ onPause: true }),
captured: keyOf({ onPauseCapture: true })
}
},
play: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlay: true }),
captured: keyOf({ onPlayCapture: true })
}
},
playing: {
phasedRegistrationNames: {
bubbled: keyOf({ onPlaying: true }),
captured: keyOf({ onPlayingCapture: true })
}
},
progress: {
phasedRegistrationNames: {
bubbled: keyOf({ onProgress: true }),
captured: keyOf({ onProgressCapture: true })
}
},
rateChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onRateChange: true }),
captured: keyOf({ onRateChangeCapture: true })
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({ onReset: true }),
captured: keyOf({ onResetCapture: true })
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({ onScroll: true }),
captured: keyOf({ onScrollCapture: true })
}
},
seeked: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeked: true }),
captured: keyOf({ onSeekedCapture: true })
}
},
seeking: {
phasedRegistrationNames: {
bubbled: keyOf({ onSeeking: true }),
captured: keyOf({ onSeekingCapture: true })
}
},
stalled: {
phasedRegistrationNames: {
bubbled: keyOf({ onStalled: true }),
captured: keyOf({ onStalledCapture: true })
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({ onSubmit: true }),
captured: keyOf({ onSubmitCapture: true })
}
},
suspend: {
phasedRegistrationNames: {
bubbled: keyOf({ onSuspend: true }),
captured: keyOf({ onSuspendCapture: true })
}
},
timeUpdate: {
phasedRegistrationNames: {
bubbled: keyOf({ onTimeUpdate: true }),
captured: keyOf({ onTimeUpdateCapture: true })
}
},
touchCancel: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchCancel: true }),
captured: keyOf({ onTouchCancelCapture: true })
}
},
touchEnd: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchEnd: true }),
captured: keyOf({ onTouchEndCapture: true })
}
},
touchMove: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchMove: true }),
captured: keyOf({ onTouchMoveCapture: true })
}
},
touchStart: {
phasedRegistrationNames: {
bubbled: keyOf({ onTouchStart: true }),
captured: keyOf({ onTouchStartCapture: true })
}
},
volumeChange: {
phasedRegistrationNames: {
bubbled: keyOf({ onVolumeChange: true }),
captured: keyOf({ onVolumeChangeCapture: true })
}
},
waiting: {
phasedRegistrationNames: {
bubbled: keyOf({ onWaiting: true }),
captured: keyOf({ onWaitingCapture: true })
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({ onWheel: true }),
captured: keyOf({ onWheelCapture: true })
}
}
};
var topLevelEventsToDispatchConfig = {
topAbort: eventTypes.abort,
topBlur: eventTypes.blur,
topCanPlay: eventTypes.canPlay,
topCanPlayThrough: eventTypes.canPlayThrough,
topClick: eventTypes.click,
topContextMenu: eventTypes.contextMenu,
topCopy: eventTypes.copy,
topCut: eventTypes.cut,
topDoubleClick: eventTypes.doubleClick,
topDrag: eventTypes.drag,
topDragEnd: eventTypes.dragEnd,
topDragEnter: eventTypes.dragEnter,
topDragExit: eventTypes.dragExit,
topDragLeave: eventTypes.dragLeave,
topDragOver: eventTypes.dragOver,
topDragStart: eventTypes.dragStart,
topDrop: eventTypes.drop,
topDurationChange: eventTypes.durationChange,
topEmptied: eventTypes.emptied,
topEncrypted: eventTypes.encrypted,
topEnded: eventTypes.ended,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topLoadedData: eventTypes.loadedData,
topLoadedMetadata: eventTypes.loadedMetadata,
topLoadStart: eventTypes.loadStart,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topPause: eventTypes.pause,
topPlay: eventTypes.play,
topPlaying: eventTypes.playing,
topProgress: eventTypes.progress,
topRateChange: eventTypes.rateChange,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSeeked: eventTypes.seeked,
topSeeking: eventTypes.seeking,
topStalled: eventTypes.stalled,
topSubmit: eventTypes.submit,
topSuspend: eventTypes.suspend,
topTimeUpdate: eventTypes.timeUpdate,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topVolumeChange: eventTypes.volumeChange,
topWaiting: eventTypes.waiting,
topWheel: eventTypes.wheel
};
for (var type in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[type].dependencies = [type];
}
var ON_CLICK_KEY = keyOf({ onClick: null });
var onClickListeners = {};
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function (topLevelType, topLevelTarget, topLevelTargetID, nativeEvent, nativeEventTarget) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topAbort:
case topLevelTypes.topCanPlay:
case topLevelTypes.topCanPlayThrough:
case topLevelTypes.topDurationChange:
case topLevelTypes.topEmptied:
case topLevelTypes.topEncrypted:
case topLevelTypes.topEnded:
case topLevelTypes.topError:
case topLevelTypes.topInput:
case topLevelTypes.topLoad:
case topLevelTypes.topLoadedData:
case topLevelTypes.topLoadedMetadata:
case topLevelTypes.topLoadStart:
case topLevelTypes.topPause:
case topLevelTypes.topPlay:
case topLevelTypes.topPlaying:
case topLevelTypes.topProgress:
case topLevelTypes.topRateChange:
case topLevelTypes.topReset:
case topLevelTypes.topSeeked:
case topLevelTypes.topSeeking:
case topLevelTypes.topStalled:
case topLevelTypes.topSubmit:
case topLevelTypes.topSuspend:
case topLevelTypes.topTimeUpdate:
case topLevelTypes.topVolumeChange:
case topLevelTypes.topWaiting:
// HTML Events
// @see http://www.w3.org/TR/html5/index.html#events-0
EventConstructor = SyntheticEvent;
break;
case topLevelTypes.topKeyPress:
// FireFox creates a keypress event for function keys too. This removes
// the unwanted keypress events. Enter is however both printable and
// non-printable. One would expect Tab to be as well (but it isn't).
if (getEventCharCode(nativeEvent) === 0) {
return null;
}
/* falls through */
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
EventConstructor = SyntheticKeyboardEvent;
break;
case topLevelTypes.topBlur:
case topLevelTypes.topFocus:
EventConstructor = SyntheticFocusEvent;
break;
case topLevelTypes.topClick:
// Firefox creates a click event on right mouse clicks. This removes the
// unwanted click events.
if (nativeEvent.button === 2) {
return null;
}
/* falls through */
case topLevelTypes.topContextMenu:
case topLevelTypes.topDoubleClick:
case topLevelTypes.topMouseDown:
case topLevelTypes.topMouseMove:
case topLevelTypes.topMouseOut:
case topLevelTypes.topMouseOver:
case topLevelTypes.topMouseUp:
EventConstructor = SyntheticMouseEvent;
break;
case topLevelTypes.topDrag:
case topLevelTypes.topDragEnd:
case topLevelTypes.topDragEnter:
case topLevelTypes.topDragExit:
case topLevelTypes.topDragLeave:
case topLevelTypes.topDragOver:
case topLevelTypes.topDragStart:
case topLevelTypes.topDrop:
EventConstructor = SyntheticDragEvent;
break;
case topLevelTypes.topTouchCancel:
case topLevelTypes.topTouchEnd:
case topLevelTypes.topTouchMove:
case topLevelTypes.topTouchStart:
EventConstructor = SyntheticTouchEvent;
break;
case topLevelTypes.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
!EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : undefined;
var event = EventConstructor.getPooled(dispatchConfig, topLevelTargetID, nativeEvent, nativeEventTarget);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
},
didPutListener: function (id, registrationName, listener) {
// Mobile Safari does not fire properly bubble click events on
// non-interactive elements, which means delegated click listeners do not
// fire. The workaround for this bug involves attaching an empty click
// listener on the target node.
if (registrationName === ON_CLICK_KEY) {
var node = ReactMount.getNode(id);
if (!onClickListeners[id]) {
onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction);
}
}
},
willDeleteListener: function (id, registrationName) {
if (registrationName === ON_CLICK_KEY) {
onClickListeners[id].remove();
delete onClickListeners[id];
}
}
};
module.exports = SimpleEventPlugin;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 133 */
/*!************************************************!*\
!*** ./~/react/lib/SyntheticClipboardEvent.js ***!
\************************************************/
/***/ (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.
*
* @providesModule SyntheticClipboardEvent
* @typechecks static-only
*/
'use strict';
var SyntheticEvent = __webpack_require__(/*! ./SyntheticEvent */ 77);
/**
* @interface Event
* @see http://www.w3.org/TR/clipboard-apis/
*/
var ClipboardEventInterface = {
clipboardData: function (event) {
return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
/***/ }),
/* 134 */
/*!********************************************!*\
!*** ./~/react/lib/SyntheticFocusEvent.js ***!
\********************************************/
/***/ (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.
*
* @providesModule SyntheticFocusEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(/*! ./SyntheticUIEvent */ 87);
/**
* @interface FocusEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var FocusEventInterface = {
relatedTarget: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
/***/ }),
/* 135 */
/*!***********************************************!*\
!*** ./~/react/lib/SyntheticKeyboardEvent.js ***!
\***********************************************/
/***/ (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.
*
* @providesModule SyntheticKeyboardEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(/*! ./SyntheticUIEvent */ 87);
var getEventCharCode = __webpack_require__(/*! ./getEventCharCode */ 136);
var getEventKey = __webpack_require__(/*! ./getEventKey */ 137);
var getEventModifierState = __webpack_require__(/*! ./getEventModifierState */ 88);
/**
* @interface KeyboardEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var KeyboardEventInterface = {
key: getEventKey,
location: null,
ctrlKey: null,
shiftKey: null,
altKey: null,
metaKey: null,
repeat: null,
locale: null,
getModifierState: getEventModifierState,
// Legacy Interface
charCode: function (event) {
// `charCode` is the result of a KeyPress event and represents the value of
// the actual printable character.
// KeyPress is deprecated, but its replacement is not yet final and not
// implemented in any major browser. Only KeyPress has charCode.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
return 0;
},
keyCode: function (event) {
// `keyCode` is the result of a KeyDown/Up event and represents the value of
// physical keyboard key.
// The actual meaning of the value depends on the users' keyboard layout
// which cannot be detected. Assuming that it is a US keyboard layout
// provides a surprisingly accurate mapping for US and European users.
// Due to this, it is left to the user to implement at this time.
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
},
which: function (event) {
// `which` is an alias for either `keyCode` or `charCode` depending on the
// type of the event.
if (event.type === 'keypress') {
return getEventCharCode(event);
}
if (event.type === 'keydown' || event.type === 'keyup') {
return event.keyCode;
}
return 0;
}
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
/***/ }),
/* 136 */
/*!*****************************************!*\
!*** ./~/react/lib/getEventCharCode.js ***!
\*****************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule getEventCharCode
* @typechecks static-only
*/
'use strict';
/**
* `charCode` represents the actual "character code" and is safe to use with
* `String.fromCharCode`. As such, only keys that correspond to printable
* characters produce a valid `charCode`, the only exception to this is Enter.
* The Tab-key is considered non-printable and does not have a `charCode`,
* presumably because it does not produce a tab-character in browsers.
*
* @param {object} nativeEvent Native browser event.
* @return {number} Normalized `charCode` property.
*/
function getEventCharCode(nativeEvent) {
var charCode;
var keyCode = nativeEvent.keyCode;
if ('charCode' in nativeEvent) {
charCode = nativeEvent.charCode;
// FF does not set `charCode` for the Enter-key, check against `keyCode`.
if (charCode === 0 && keyCode === 13) {
charCode = 13;
}
} else {
// IE8 does not implement `charCode`, but `keyCode` has the correct value.
charCode = keyCode;
}
// Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
// Must not discard the (non-)printable Enter-key.
if (charCode >= 32 || charCode === 13) {
return charCode;
}
return 0;
}
module.exports = getEventCharCode;
/***/ }),
/* 137 */
/*!************************************!*\
!*** ./~/react/lib/getEventKey.js ***!
\************************************/
/***/ (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.
*
* @providesModule getEventKey
* @typechecks static-only
*/
'use strict';
var getEventCharCode = __webpack_require__(/*! ./getEventCharCode */ 136);
/**
* Normalization of deprecated HTML5 `key` values
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var normalizeKey = {
'Esc': 'Escape',
'Spacebar': ' ',
'Left': 'ArrowLeft',
'Up': 'ArrowUp',
'Right': 'ArrowRight',
'Down': 'ArrowDown',
'Del': 'Delete',
'Win': 'OS',
'Menu': 'ContextMenu',
'Apps': 'ContextMenu',
'Scroll': 'ScrollLock',
'MozPrintableKey': 'Unidentified'
};
/**
* Translation from legacy `keyCode` to HTML5 `key`
* Only special keys supported, all others depend on keyboard layout or browser
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
*/
var translateToKey = {
8: 'Backspace',
9: 'Tab',
12: 'Clear',
13: 'Enter',
16: 'Shift',
17: 'Control',
18: 'Alt',
19: 'Pause',
20: 'CapsLock',
27: 'Escape',
32: ' ',
33: 'PageUp',
34: 'PageDown',
35: 'End',
36: 'Home',
37: 'ArrowLeft',
38: 'ArrowUp',
39: 'ArrowRight',
40: 'ArrowDown',
45: 'Insert',
46: 'Delete',
112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6',
118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12',
144: 'NumLock',
145: 'ScrollLock',
224: 'Meta'
};
/**
* @param {object} nativeEvent Native browser event.
* @return {string} Normalized `key` property.
*/
function getEventKey(nativeEvent) {
if (nativeEvent.key) {
// Normalize inconsistent values reported by browsers due to
// implementations of a working draft specification.
// FireFox implements `key` but returns `MozPrintableKey` for all
// printable characters (normalized to `Unidentified`), ignore it.
var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
if (key !== 'Unidentified') {
return key;
}
}
// Browser does not implement `key`, polyfill as much of it as we can.
if (nativeEvent.type === 'keypress') {
var charCode = getEventCharCode(nativeEvent);
// The enter-key is technically both printable and non-printable and can
// thus be captured by `keypress`, no other non-printable key should.
return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
}
if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
// While user keyboard layout determines the actual meaning of each
// `keyCode` value, almost all function keys have a universal value.
return translateToKey[nativeEvent.keyCode] || 'Unidentified';
}
return '';
}
module.exports = getEventKey;
/***/ }),
/* 138 */
/*!*******************************************!*\
!*** ./~/react/lib/SyntheticDragEvent.js ***!
\*******************************************/
/***/ (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.
*
* @providesModule SyntheticDragEvent
* @typechecks static-only
*/
'use strict';
var SyntheticMouseEvent = __webpack_require__(/*! ./SyntheticMouseEvent */ 86);
/**
* @interface DragEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var DragEventInterface = {
dataTransfer: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
/***/ }),
/* 139 */
/*!********************************************!*\
!*** ./~/react/lib/SyntheticTouchEvent.js ***!
\********************************************/
/***/ (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.
*
* @providesModule SyntheticTouchEvent
* @typechecks static-only
*/
'use strict';
var SyntheticUIEvent = __webpack_require__(/*! ./SyntheticUIEvent */ 87);
var getEventModifierState = __webpack_require__(/*! ./getEventModifierState */ 88);
/**
* @interface TouchEvent
* @see http://www.w3.org/TR/touch-events/
*/
var TouchEventInterface = {
touches: null,
targetTouches: null,
changedTouches: null,
altKey: null,
metaKey: null,
ctrlKey: null,
shiftKey: null,
getModifierState: getEventModifierState
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticUIEvent}
*/
function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
/***/ }),
/* 140 */
/*!********************************************!*\
!*** ./~/react/lib/SyntheticWheelEvent.js ***!
\********************************************/
/***/ (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.
*
* @providesModule SyntheticWheelEvent
* @typechecks static-only
*/
'use strict';
var SyntheticMouseEvent = __webpack_require__(/*! ./SyntheticMouseEvent */ 86);
/**
* @interface WheelEvent
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var WheelEventInterface = {
deltaX: function (event) {
return 'deltaX' in event ? event.deltaX :
// Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
},
deltaY: function (event) {
return 'deltaY' in event ? event.deltaY :
// Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
'wheelDeltaY' in event ? -event.wheelDeltaY :
// Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
'wheelDelta' in event ? -event.wheelDelta : 0;
},
deltaZ: null,
// Browsers without "deltaMode" is reporting in raw wheel delta where one
// notch on the scroll is always +/- 120, roughly equivalent to pixels.
// A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
// ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
deltaMode: null
};
/**
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @extends {SyntheticMouseEvent}
*/
function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
/***/ }),
/* 141 */
/*!*********************************************!*\
!*** ./~/react/lib/SVGDOMPropertyConfig.js ***!
\*********************************************/
/***/ (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.
*
* @providesModule SVGDOMPropertyConfig
*/
'use strict';
var DOMProperty = __webpack_require__(/*! ./DOMProperty */ 23);
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var NS = {
xlink: 'http://www.w3.org/1999/xlink',
xml: 'http://www.w3.org/XML/1998/namespace'
};
var SVGDOMPropertyConfig = {
Properties: {
clipPath: MUST_USE_ATTRIBUTE,
cx: MUST_USE_ATTRIBUTE,
cy: MUST_USE_ATTRIBUTE,
d: MUST_USE_ATTRIBUTE,
dx: MUST_USE_ATTRIBUTE,
dy: MUST_USE_ATTRIBUTE,
fill: MUST_USE_ATTRIBUTE,
fillOpacity: MUST_USE_ATTRIBUTE,
fontFamily: MUST_USE_ATTRIBUTE,
fontSize: MUST_USE_ATTRIBUTE,
fx: MUST_USE_ATTRIBUTE,
fy: MUST_USE_ATTRIBUTE,
gradientTransform: MUST_USE_ATTRIBUTE,
gradientUnits: MUST_USE_ATTRIBUTE,
markerEnd: MUST_USE_ATTRIBUTE,
markerMid: MUST_USE_ATTRIBUTE,
markerStart: MUST_USE_ATTRIBUTE,
offset: MUST_USE_ATTRIBUTE,
opacity: MUST_USE_ATTRIBUTE,
patternContentUnits: MUST_USE_ATTRIBUTE,
patternUnits: MUST_USE_ATTRIBUTE,
points: MUST_USE_ATTRIBUTE,
preserveAspectRatio: MUST_USE_ATTRIBUTE,
r: MUST_USE_ATTRIBUTE,
rx: MUST_USE_ATTRIBUTE,
ry: MUST_USE_ATTRIBUTE,
spreadMethod: MUST_USE_ATTRIBUTE,
stopColor: MUST_USE_ATTRIBUTE,
stopOpacity: MUST_USE_ATTRIBUTE,
stroke: MUST_USE_ATTRIBUTE,
strokeDasharray: MUST_USE_ATTRIBUTE,
strokeLinecap: MUST_USE_ATTRIBUTE,
strokeOpacity: MUST_USE_ATTRIBUTE,
strokeWidth: MUST_USE_ATTRIBUTE,
textAnchor: MUST_USE_ATTRIBUTE,
transform: MUST_USE_ATTRIBUTE,
version: MUST_USE_ATTRIBUTE,
viewBox: MUST_USE_ATTRIBUTE,
x1: MUST_USE_ATTRIBUTE,
x2: MUST_USE_ATTRIBUTE,
x: MUST_USE_ATTRIBUTE,
xlinkActuate: MUST_USE_ATTRIBUTE,
xlinkArcrole: MUST_USE_ATTRIBUTE,
xlinkHref: MUST_USE_ATTRIBUTE,
xlinkRole: MUST_USE_ATTRIBUTE,
xlinkShow: MUST_USE_ATTRIBUTE,
xlinkTitle: MUST_USE_ATTRIBUTE,
xlinkType: MUST_USE_ATTRIBUTE,
xmlBase: MUST_USE_ATTRIBUTE,
xmlLang: MUST_USE_ATTRIBUTE,
xmlSpace: MUST_USE_ATTRIBUTE,
y1: MUST_USE_ATTRIBUTE,
y2: MUST_USE_ATTRIBUTE,
y: MUST_USE_ATTRIBUTE
},
DOMAttributeNamespaces: {
xlinkActuate: NS.xlink,
xlinkArcrole: NS.xlink,
xlinkHref: NS.xlink,
xlinkRole: NS.xlink,
xlinkShow: NS.xlink,
xlinkTitle: NS.xlink,
xlinkType: NS.xlink,
xmlBase: NS.xml,
xmlLang: NS.xml,
xmlSpace: NS.xml
},
DOMAttributeNames: {
clipPath: 'clip-path',
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
patternContentUnits: 'patternContentUnits',
patternUnits: 'patternUnits',
preserveAspectRatio: 'preserveAspectRatio',
spreadMethod: 'spreadMethod',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox',
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space'
}
};
module.exports = SVGDOMPropertyConfig;
/***/ }),
/* 142 */
/*!*****************************************!*\
!*** ./~/react/lib/ReactDefaultPerf.js ***!
\*****************************************/
/***/ (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.
*
* @providesModule ReactDefaultPerf
* @typechecks static-only
*/
'use strict';
var DOMProperty = __webpack_require__(/*! ./DOMProperty */ 23);
var ReactDefaultPerfAnalysis = __webpack_require__(/*! ./ReactDefaultPerfAnalysis */ 143);
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
var ReactPerf = __webpack_require__(/*! ./ReactPerf */ 18);
var performanceNow = __webpack_require__(/*! fbjs/lib/performanceNow */ 144);
function roundFloat(val) {
return Math.floor(val * 100) / 100;
}
function addValue(obj, key, val) {
obj[key] = (obj[key] || 0) + val;
}
var ReactDefaultPerf = {
_allMeasurements: [], // last item in the list is the current one
_mountStack: [0],
_injected: false,
start: function () {
if (!ReactDefaultPerf._injected) {
ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure);
}
ReactDefaultPerf._allMeasurements.length = 0;
ReactPerf.enableMeasure = true;
},
stop: function () {
ReactPerf.enableMeasure = false;
},
getLastMeasurements: function () {
return ReactDefaultPerf._allMeasurements;
},
printExclusive: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements);
console.table(summary.map(function (item) {
return {
'Component class name': item.componentName,
'Total inclusive time (ms)': roundFloat(item.inclusive),
'Exclusive mount time (ms)': roundFloat(item.exclusive),
'Exclusive render time (ms)': roundFloat(item.render),
'Mount time per instance (ms)': roundFloat(item.exclusive / item.count),
'Render time per instance (ms)': roundFloat(item.render / item.count),
'Instances': item.count
};
}));
// TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct
// number.
},
printInclusive: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements);
console.table(summary.map(function (item) {
return {
'Owner > component': item.componentName,
'Inclusive time (ms)': roundFloat(item.time),
'Instances': item.count
};
}));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
getMeasurementsSummaryMap: function (measurements) {
var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true);
return summary.map(function (item) {
return {
'Owner > component': item.componentName,
'Wasted time (ms)': item.time,
'Instances': item.count
};
});
},
printWasted: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
console.table(ReactDefaultPerf.getMeasurementsSummaryMap(measurements));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
printDOM: function (measurements) {
measurements = measurements || ReactDefaultPerf._allMeasurements;
var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements);
console.table(summary.map(function (item) {
var result = {};
result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id;
result.type = item.type;
result.args = JSON.stringify(item.args);
return result;
}));
console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms');
},
_recordWrite: function (id, fnName, totalTime, args) {
// TODO: totalTime isn't that useful since it doesn't count paints/reflows
var writes = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].writes;
writes[id] = writes[id] || [];
writes[id].push({
type: fnName,
time: totalTime,
args: args
});
},
measure: function (moduleName, fnName, func) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var totalTime;
var rv;
var start;
if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') {
// A "measurement" is a set of metrics recorded for each flush. We want
// to group the metrics for a given flush together so we can look at the
// components that rendered and the DOM operations that actually
// happened to determine the amount of "wasted work" performed.
ReactDefaultPerf._allMeasurements.push({
exclusive: {},
inclusive: {},
render: {},
counts: {},
writes: {},
displayNames: {},
totalTime: 0,
created: {}
});
start = performanceNow();
rv = func.apply(this, args);
ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1].totalTime = performanceNow() - start;
return rv;
} else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactBrowserEventEmitter' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations') {
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (fnName === '_mountImageIntoNode') {
var mountID = ReactMount.getID(args[1]);
ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]);
} else if (fnName === 'dangerouslyProcessChildrenUpdates') {
// special format
args[0].forEach(function (update) {
var writeArgs = {};
if (update.fromIndex !== null) {
writeArgs.fromIndex = update.fromIndex;
}
if (update.toIndex !== null) {
writeArgs.toIndex = update.toIndex;
}
if (update.textContent !== null) {
writeArgs.textContent = update.textContent;
}
if (update.markupIndex !== null) {
writeArgs.markup = args[1][update.markupIndex];
}
ReactDefaultPerf._recordWrite(update.parentID, update.type, totalTime, writeArgs);
});
} else {
// basic format
var id = args[0];
if (typeof id === 'object') {
id = ReactMount.getID(args[0]);
}
ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1));
}
return rv;
} else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()?
fnName === '_renderValidatedComponent')) {
if (this._currentElement.type === ReactMount.TopLevelWrapper) {
return func.apply(this, args);
}
var rootNodeID = fnName === 'mountComponent' ? args[0] : this._rootNodeID;
var isRender = fnName === '_renderValidatedComponent';
var isMount = fnName === 'mountComponent';
var mountStack = ReactDefaultPerf._mountStack;
var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1];
if (isRender) {
addValue(entry.counts, rootNodeID, 1);
} else if (isMount) {
entry.created[rootNodeID] = true;
mountStack.push(0);
}
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (isRender) {
addValue(entry.render, rootNodeID, totalTime);
} else if (isMount) {
var subMountTime = mountStack.pop();
mountStack[mountStack.length - 1] += totalTime;
addValue(entry.exclusive, rootNodeID, totalTime - subMountTime);
addValue(entry.inclusive, rootNodeID, totalTime);
} else {
addValue(entry.inclusive, rootNodeID, totalTime);
}
entry.displayNames[rootNodeID] = {
current: this.getName(),
owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>'
};
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
/***/ }),
/* 143 */
/*!*************************************************!*\
!*** ./~/react/lib/ReactDefaultPerfAnalysis.js ***!
\*************************************************/
/***/ (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.
*
* @providesModule ReactDefaultPerfAnalysis
*/
'use strict';
var assign = __webpack_require__(/*! ./Object.assign */ 39);
// Don't try to save users less than 1.2ms (a number I made up)
var DONT_CARE_THRESHOLD = 1.2;
var DOM_OPERATION_TYPES = {
'_mountImageIntoNode': 'set innerHTML',
INSERT_MARKUP: 'set innerHTML',
MOVE_EXISTING: 'move',
REMOVE_NODE: 'remove',
SET_MARKUP: 'set innerHTML',
TEXT_CONTENT: 'set textContent',
'setValueForProperty': 'update attribute',
'setValueForAttribute': 'update attribute',
'deleteValueForProperty': 'remove attribute',
'setValueForStyles': 'update styles',
'replaceNodeWithMarkup': 'replace',
'updateTextContent': 'set textContent'
};
function getTotalTime(measurements) {
// TODO: return number of DOM ops? could be misleading.
// TODO: measure dropped frames after reconcile?
// TODO: log total time of each reconcile and the top-level component
// class that triggered it.
var totalTime = 0;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
totalTime += measurement.totalTime;
}
return totalTime;
}
function getDOMSummary(measurements) {
var items = [];
measurements.forEach(function (measurement) {
Object.keys(measurement.writes).forEach(function (id) {
measurement.writes[id].forEach(function (write) {
items.push({
id: id,
type: DOM_OPERATION_TYPES[write.type] || write.type,
args: write.args
});
});
});
});
return items;
}
function getExclusiveSummary(measurements) {
var candidates = {};
var displayName;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
displayName = measurement.displayNames[id].current;
candidates[displayName] = candidates[displayName] || {
componentName: displayName,
inclusive: 0,
exclusive: 0,
render: 0,
count: 0
};
if (measurement.render[id]) {
candidates[displayName].render += measurement.render[id];
}
if (measurement.exclusive[id]) {
candidates[displayName].exclusive += measurement.exclusive[id];
}
if (measurement.inclusive[id]) {
candidates[displayName].inclusive += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[displayName].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (displayName in candidates) {
if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) {
arr.push(candidates[displayName]);
}
}
arr.sort(function (a, b) {
return b.exclusive - a.exclusive;
});
return arr;
}
function getInclusiveSummary(measurements, onlyClean) {
var candidates = {};
var inclusiveKey;
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
var cleanComponents;
if (onlyClean) {
cleanComponents = getUnchangedComponents(measurement);
}
for (var id in allIDs) {
if (onlyClean && !cleanComponents[id]) {
continue;
}
var displayName = measurement.displayNames[id];
// Inclusive time is not useful for many components without knowing where
// they are instantiated. So we aggregate inclusive time with both the
// owner and current displayName as the key.
inclusiveKey = displayName.owner + ' > ' + displayName.current;
candidates[inclusiveKey] = candidates[inclusiveKey] || {
componentName: inclusiveKey,
time: 0,
count: 0
};
if (measurement.inclusive[id]) {
candidates[inclusiveKey].time += measurement.inclusive[id];
}
if (measurement.counts[id]) {
candidates[inclusiveKey].count += measurement.counts[id];
}
}
}
// Now make a sorted array with the results.
var arr = [];
for (inclusiveKey in candidates) {
if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) {
arr.push(candidates[inclusiveKey]);
}
}
arr.sort(function (a, b) {
return b.time - a.time;
});
return arr;
}
function getUnchangedComponents(measurement) {
// For a given reconcile, look at which components did not actually
// render anything to the DOM and return a mapping of their ID to
// the amount of time it took to render the entire subtree.
var cleanComponents = {};
var dirtyLeafIDs = Object.keys(measurement.writes);
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// For each component that rendered, see if a component that triggered
// a DOM op is in its subtree.
for (var i = 0; i < dirtyLeafIDs.length; i++) {
if (dirtyLeafIDs[i].indexOf(id) === 0) {
isDirty = true;
break;
}
}
// check if component newly created
if (measurement.created[id]) {
isDirty = true;
}
if (!isDirty && measurement.counts[id] > 0) {
cleanComponents[id] = true;
}
}
return cleanComponents;
}
var ReactDefaultPerfAnalysis = {
getExclusiveSummary: getExclusiveSummary,
getInclusiveSummary: getInclusiveSummary,
getDOMSummary: getDOMSummary,
getTotalTime: getTotalTime
};
module.exports = ReactDefaultPerfAnalysis;
/***/ }),
/* 144 */
/*!**************************************!*\
!*** ./~/fbjs/lib/performanceNow.js ***!
\**************************************/
/***/ (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.
*
* @providesModule performanceNow
* @typechecks
*/
'use strict';
var performance = __webpack_require__(/*! ./performance */ 145);
var performanceNow;
/**
* Detect if we can use `window.performance.now()` and gracefully fallback to
* `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now
* because of Facebook's testing infrastructure.
*/
if (performance.now) {
performanceNow = function () {
return performance.now();
};
} else {
performanceNow = function () {
return Date.now();
};
}
module.exports = performanceNow;
/***/ }),
/* 145 */
/*!***********************************!*\
!*** ./~/fbjs/lib/performance.js ***!
\***********************************/
/***/ (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.
*
* @providesModule performance
* @typechecks
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(/*! ./ExecutionEnvironment */ 9);
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance = window.performance || window.msPerformance || window.webkitPerformance;
}
module.exports = performance || {};
/***/ }),
/* 146 */
/*!*************************************!*\
!*** ./~/react/lib/ReactVersion.js ***!
\*************************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule ReactVersion
*/
'use strict';
module.exports = '0.14.9';
/***/ }),
/* 147 */
/*!***************************************************!*\
!*** ./~/react/lib/renderSubtreeIntoContainer.js ***!
\***************************************************/
/***/ (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.
*
* @providesModule renderSubtreeIntoContainer
*/
'use strict';
var ReactMount = __webpack_require__(/*! ./ReactMount */ 28);
module.exports = ReactMount.renderSubtreeIntoContainer;
/***/ }),
/* 148 */
/*!***************************************!*\
!*** ./~/react/lib/ReactDOMServer.js ***!
\***************************************/
/***/ (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.
*
* @providesModule ReactDOMServer
*/
'use strict';
var ReactDefaultInjection = __webpack_require__(/*! ./ReactDefaultInjection */ 71);
var ReactServerRendering = __webpack_require__(/*! ./ReactServerRendering */ 149);
var ReactVersion = __webpack_require__(/*! ./ReactVersion */ 146);
ReactDefaultInjection.inject();
var ReactDOMServer = {
renderToString: ReactServerRendering.renderToString,
renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
version: ReactVersion
};
module.exports = ReactDOMServer;
/***/ }),
/* 149 */
/*!*********************************************!*\
!*** ./~/react/lib/ReactServerRendering.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
'use strict';
var ReactDefaultBatchingStrategy = __webpack_require__(/*! ./ReactDefaultBatchingStrategy */ 92);
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactInstanceHandles = __webpack_require__(/*! ./ReactInstanceHandles */ 45);
var ReactMarkupChecksum = __webpack_require__(/*! ./ReactMarkupChecksum */ 48);
var ReactServerBatchingStrategy = __webpack_require__(/*! ./ReactServerBatchingStrategy */ 150);
var ReactServerRenderingTransaction = __webpack_require__(/*! ./ReactServerRenderingTransaction */ 151);
var ReactUpdates = __webpack_require__(/*! ./ReactUpdates */ 54);
var emptyObject = __webpack_require__(/*! fbjs/lib/emptyObject */ 58);
var instantiateReactComponent = __webpack_require__(/*! ./instantiateReactComponent */ 62);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* @param {ReactElement} element
* @return {string} the HTML markup
*/
function renderToString(element) {
!ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToString(): You must pass a valid ReactElement.') : invariant(false) : undefined;
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element, null);
var markup = componentInstance.mountComponent(id, transaction, emptyObject);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
/**
* @param {ReactElement} element
* @return {string} the HTML markup, without the extra React ID and checksum
* (for generating static pages)
*/
function renderToStaticMarkup(element) {
!ReactElement.isValidElement(element) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'renderToStaticMarkup(): You must pass a valid ReactElement.') : invariant(false) : undefined;
var transaction;
try {
ReactUpdates.injection.injectBatchingStrategy(ReactServerBatchingStrategy);
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function () {
var componentInstance = instantiateReactComponent(element, null);
return componentInstance.mountComponent(id, transaction, emptyObject);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
// Revert to the DOM batching strategy since these two renderers
// currently share these stateful modules.
ReactUpdates.injection.injectBatchingStrategy(ReactDefaultBatchingStrategy);
}
}
module.exports = {
renderToString: renderToString,
renderToStaticMarkup: renderToStaticMarkup
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 150 */
/*!****************************************************!*\
!*** ./~/react/lib/ReactServerBatchingStrategy.js ***!
\****************************************************/
/***/ (function(module, exports) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactServerBatchingStrategy
* @typechecks
*/
'use strict';
var ReactServerBatchingStrategy = {
isBatchingUpdates: false,
batchedUpdates: function (callback) {
// Don't do anything here. During the server rendering we don't want to
// schedule any updates. We will simply ignore them.
}
};
module.exports = ReactServerBatchingStrategy;
/***/ }),
/* 151 */
/*!********************************************************!*\
!*** ./~/react/lib/ReactServerRenderingTransaction.js ***!
\********************************************************/
/***/ (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.
*
* @providesModule ReactServerRenderingTransaction
* @typechecks
*/
'use strict';
var PooledClass = __webpack_require__(/*! ./PooledClass */ 56);
var CallbackQueue = __webpack_require__(/*! ./CallbackQueue */ 55);
var Transaction = __webpack_require__(/*! ./Transaction */ 57);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var emptyFunction = __webpack_require__(/*! fbjs/lib/emptyFunction */ 15);
/**
* Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks
* during the performing of the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function () {
this.reactMountReady.reset();
},
close: emptyFunction
};
/**
* Executed within the scope of the `Transaction` instance. Consider these as
* being member methods, but with an implied ordering while being isolated from
* each other.
*/
var TRANSACTION_WRAPPERS = [ON_DOM_READY_QUEUEING];
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = false;
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap procedures.
*/
getTransactionWrappers: function () {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function () {
return this.reactMountReady;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be reused.
*/
destructor: function () {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
}
};
assign(ReactServerRenderingTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
/***/ }),
/* 152 */
/*!****************************************!*\
!*** ./~/react/lib/ReactIsomorphic.js ***!
\****************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactIsomorphic
*/
'use strict';
var ReactChildren = __webpack_require__(/*! ./ReactChildren */ 110);
var ReactComponent = __webpack_require__(/*! ./ReactComponent */ 123);
var ReactClass = __webpack_require__(/*! ./ReactClass */ 122);
var ReactDOMFactories = __webpack_require__(/*! ./ReactDOMFactories */ 153);
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactElementValidator = __webpack_require__(/*! ./ReactElementValidator */ 154);
var ReactPropTypes = __webpack_require__(/*! ./ReactPropTypes */ 107);
var ReactVersion = __webpack_require__(/*! ./ReactVersion */ 146);
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var onlyChild = __webpack_require__(/*! ./onlyChild */ 156);
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if (process.env.NODE_ENV !== 'production') {
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild
},
Component: ReactComponent,
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,
// Hook for JSX spread, don't use this for anything else.
__spread: assign
};
module.exports = React;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 153 */
/*!******************************************!*\
!*** ./~/react/lib/ReactDOMFactories.js ***!
\******************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactDOMFactories
* @typechecks static-only
*/
'use strict';
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactElementValidator = __webpack_require__(/*! ./ReactElementValidator */ 154);
var mapObject = __webpack_require__(/*! fbjs/lib/mapObject */ 155);
/**
* Create a factory that creates HTML tag elements.
*
* @param {string} tag Tag name (e.g. `div`).
* @private
*/
function createDOMFactory(tag) {
if (process.env.NODE_ENV !== 'production') {
return ReactElementValidator.createFactory(tag);
}
return ReactElement.createFactory(tag);
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOMFactories = mapObject({
a: 'a',
abbr: 'abbr',
address: 'address',
area: 'area',
article: 'article',
aside: 'aside',
audio: 'audio',
b: 'b',
base: 'base',
bdi: 'bdi',
bdo: 'bdo',
big: 'big',
blockquote: 'blockquote',
body: 'body',
br: 'br',
button: 'button',
canvas: 'canvas',
caption: 'caption',
cite: 'cite',
code: 'code',
col: 'col',
colgroup: 'colgroup',
data: 'data',
datalist: 'datalist',
dd: 'dd',
del: 'del',
details: 'details',
dfn: 'dfn',
dialog: 'dialog',
div: 'div',
dl: 'dl',
dt: 'dt',
em: 'em',
embed: 'embed',
fieldset: 'fieldset',
figcaption: 'figcaption',
figure: 'figure',
footer: 'footer',
form: 'form',
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
head: 'head',
header: 'header',
hgroup: 'hgroup',
hr: 'hr',
html: 'html',
i: 'i',
iframe: 'iframe',
img: 'img',
input: 'input',
ins: 'ins',
kbd: 'kbd',
keygen: 'keygen',
label: 'label',
legend: 'legend',
li: 'li',
link: 'link',
main: 'main',
map: 'map',
mark: 'mark',
menu: 'menu',
menuitem: 'menuitem',
meta: 'meta',
meter: 'meter',
nav: 'nav',
noscript: 'noscript',
object: 'object',
ol: 'ol',
optgroup: 'optgroup',
option: 'option',
output: 'output',
p: 'p',
param: 'param',
picture: 'picture',
pre: 'pre',
progress: 'progress',
q: 'q',
rp: 'rp',
rt: 'rt',
ruby: 'ruby',
s: 's',
samp: 'samp',
script: 'script',
section: 'section',
select: 'select',
small: 'small',
source: 'source',
span: 'span',
strong: 'strong',
style: 'style',
sub: 'sub',
summary: 'summary',
sup: 'sup',
table: 'table',
tbody: 'tbody',
td: 'td',
textarea: 'textarea',
tfoot: 'tfoot',
th: 'th',
thead: 'thead',
time: 'time',
title: 'title',
tr: 'tr',
track: 'track',
u: 'u',
ul: 'ul',
'var': 'var',
video: 'video',
wbr: 'wbr',
// SVG
circle: 'circle',
clipPath: 'clipPath',
defs: 'defs',
ellipse: 'ellipse',
g: 'g',
image: 'image',
line: 'line',
linearGradient: 'linearGradient',
mask: 'mask',
path: 'path',
pattern: 'pattern',
polygon: 'polygon',
polyline: 'polyline',
radialGradient: 'radialGradient',
rect: 'rect',
stop: 'stop',
svg: 'svg',
text: 'text',
tspan: 'tspan'
}, createDOMFactory);
module.exports = ReactDOMFactories;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 154 */
/*!**********************************************!*\
!*** ./~/react/lib/ReactElementValidator.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule ReactElementValidator
*/
/**
* ReactElementValidator provides a wrapper around a element factory
* which validates the props passed to the element. This is intended to be
* used only in DEV and could be replaced by a static type checker for languages
* that support it.
*/
'use strict';
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var ReactPropTypeLocations = __webpack_require__(/*! ./ReactPropTypeLocations */ 65);
var ReactPropTypeLocationNames = __webpack_require__(/*! ./ReactPropTypeLocationNames */ 66);
var ReactCurrentOwner = __webpack_require__(/*! ./ReactCurrentOwner */ 5);
var canDefineProperty = __webpack_require__(/*! ./canDefineProperty */ 43);
var getIteratorFn = __webpack_require__(/*! ./getIteratorFn */ 108);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
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 = {};
var loggedTypeFailures = {};
/**
* 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.
*
* @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 addenda = getAddendaForKeyUse('uniqueKey', element, parentType);
if (addenda === null) {
// we already showed the warning
return;
}
process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : undefined;
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} messageType A key used for de-duping warnings.
* @param {ReactElement} element Component that requires a key.
* @param {*} parentType element's parent's type.
* @returns {?object} A set of addenda to use in the warning message, or null
* if the warning has already been shown before (and shouldn't be shown again).
*/
function getAddendaForKeyUse(messageType, element, parentType) {
var addendum = getDeclarationErrorAddendum();
if (!addendum) {
var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
if (parentName) {
addendum = ' Check the top-level render call using <' + parentName + '>.';
}
}
var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {});
if (memoizer[addendum]) {
return null;
}
memoizer[addendum] = true;
var addenda = {
parentOrOwner: addendum,
url: ' See https://fb.me/react-warning-keys for more information.',
childOwner: null
};
// 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.
if (element && element._owner && element._owner !== ReactCurrentOwner.current) {
// Give the component that originally created this child.
addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.';
}
return addenda;
}
/**
* 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);
}
}
}
}
}
}
/**
* Assert that the props are valid
*
* @param {string} componentName Name of the component for error messages.
* @param {object} propTypes Map of prop name to a ReactPropType
* @param {object} props
* @param {string} location e.g. "prop", "context", "child context"
* @private
*/
function checkPropTypes(componentName, propTypes, props, location) {
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
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 propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : undefined;
error = propTypes[propName](props, propName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error = ex;
}
process.env.NODE_ENV !== 'production' ? warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : undefined;
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 addendum = getDeclarationErrorAddendum();
process.env.NODE_ENV !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : undefined;
}
}
}
}
/**
* 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) {
checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop);
}
if (typeof componentClass.getDefaultProps === 'function') {
process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : undefined;
}
}
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.
process.env.NODE_ENV !== 'production' ? warning(validType, '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()) : undefined;
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 (process.env.NODE_ENV !== 'production') {
if (canDefineProperty) {
Object.defineProperty(validatedFactory, 'type', {
enumerable: false,
get: function () {
process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : undefined;
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;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 155 */
/*!*********************************!*\
!*** ./~/fbjs/lib/mapObject.js ***!
\*********************************/
/***/ (function(module, exports) {
/**
* 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.
*
* @providesModule mapObject
*/
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Executes the provided `callback` once for each enumerable own property in the
* object and constructs a new object from the results. The `callback` is
* invoked with three arguments:
*
* - the property value
* - the property name
* - the object being traversed
*
* Properties that are added after the call to `mapObject` will not be visited
* by `callback`. If the values of existing properties are changed, the value
* passed to `callback` will be the value at the time `mapObject` visits them.
* Properties that are deleted before being visited are not visited.
*
* @grep function objectMap()
* @grep function objMap()
*
* @param {?object} object
* @param {function} callback
* @param {*} context
* @return {?object}
*/
function mapObject(object, callback, context) {
if (!object) {
return null;
}
var result = {};
for (var name in object) {
if (hasOwnProperty.call(object, name)) {
result[name] = callback.call(context, object[name], name, object);
}
}
return result;
}
module.exports = mapObject;
/***/ }),
/* 156 */
/*!**********************************!*\
!*** ./~/react/lib/onlyChild.js ***!
\**********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule onlyChild
*/
'use strict';
var ReactElement = __webpack_require__(/*! ./ReactElement */ 42);
var invariant = __webpack_require__(/*! fbjs/lib/invariant */ 13);
/**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection. 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 {ReactComponent} The first and only `ReactComponent` contained in the
* structure.
*/
function onlyChild(children) {
!ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : undefined;
return children;
}
module.exports = onlyChild;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 157 */
/*!***********************************!*\
!*** ./~/react/lib/deprecated.js ***!
\***********************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule deprecated
*/
'use strict';
var assign = __webpack_require__(/*! ./Object.assign */ 39);
var warning = __webpack_require__(/*! fbjs/lib/warning */ 25);
/**
* This will log a single deprecation notice per function and forward the call
* on to the new API.
*
* @param {string} fnName The name of the function
* @param {string} newModule The module that fn will exist in
* @param {string} newPackage The module that fn will exist in
* @param {*} ctx The context this forwarded call should run in
* @param {function} fn The function to forward on to
* @return {function} The function that will warn once and then call fn
*/
function deprecated(fnName, newModule, newPackage, ctx, fn) {
var warned = false;
if (process.env.NODE_ENV !== 'production') {
var newFn = function () {
process.env.NODE_ENV !== 'production' ? warning(warned,
// Require examples in this string must be split to prevent React's
// build tools from mistaking them for real requires.
// Otherwise the build tools will attempt to build a '%s' module.
'React.%s is deprecated. Please use %s.%s from require' + '(\'%s\') ' + 'instead.', fnName, newModule, fnName, newPackage) : undefined;
warned = true;
return fn.apply(ctx, arguments);
};
// We need to make sure all properties of the original fn are copied over.
// In particular, this is needed to support PropTypes
return assign(newFn, fn);
}
return fn;
}
module.exports = deprecated;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../process/browser.js */ 4)))
/***/ }),
/* 158 */
/*!******************************!*\
!*** ./~/react-dom/index.js ***!
\******************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
module.exports = __webpack_require__(/*! react/lib/ReactDOM */ 3);
/***/ }),
/* 159 */
/*!********************************!*\
!*** ./app/components/Main.js ***!
\********************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var React = __webpack_require__(/*! react */ 1);
var axios = __webpack_require__(/*! axios */ 160);
//Require subb-components
var Search = __webpack_require__(/*! ./children/Search */ 179);
var Saved = __webpack_require__(/*! ./children/Saved */ 180);
var Results = __webpack_require__(/*! ./children/Results */ 181);
var helpers = __webpack_require__(/*! ./utils/helpers */ 182);
var Main = React.createClass({
displayName: "Main",
getInitialState: function getInitialState() {
return {
topic: "",
startYear: "",
endYear: "",
results: [],
savedArticles: []
};
},
setTerm: function setTerm(tpc, stYr, endYr) {
this.setState({
topic: tpc,
startYear: stYr,
endYear: endYr
});
},
saveArticle: function saveArticle(title, date, url) {
helpers.postArticle(title, date, url);
this.getArticle();
},
deleteArticle: function deleteArticle(article) {
console.log(article);
axios.delete('/api/saved/' + article._id).then(function (response) {
this.setState({
savedArticles: response.data
});
return response;
}.bind(this));
this.getArticle();
},
getArticle: function getArticle() {
axios.get('/api/saved').then(function (response) {
this.setState({
savedArticles: response.data
});
}.bind(this));
},
componentDidUpdate: function componentDidUpdate(prevProps, prevState) {
if (prevState.topic != this.state.topic) {
console.log("UPDATED");
helpers.runQuery(this.state.topic, this.state.startYear, this.state.endYear).then(function (data) {
console.log(data);
if (data != this.state.results) {
this.setState({
results: data
});
}
}.bind(this));
}
},
componentDidMount: function componentDidMount() {
axios.get('/api/saved').then(function (response) {
this.setState({
savedArticles: response.data
});
}.bind(this));
},
render: function render() {
return React.createElement(
"div",
{ className: "container" },
React.createElement(
"div",
{ className: "row" },
React.createElement(
"div",
{ className: "jumbotron" },
React.createElement(
"h2",
{ className: "text-center" },
"New York Times Article Search and Save"
),
React.createElement(
"p",
{ className: "text-center" },
"Search for and save articles of interest!"
)
)
),
React.createElement(
"div",
{ className: "row" },
React.createElement(Search, { setTerm: this.setTerm })
),
React.createElement(
"div",
{ className: "row" },
React.createElement(Results, { results: this.state.results, saveArticle: this.saveArticle })
),
React.createElement(
"div",
{ className: "row" },
React.createElement(Saved, { savedArticles: this.state.savedArticles, deleteArticle: this.deleteArticle })
)
);
}
});
module.exports = Main;
/***/ }),
/* 160 */
/*!**************************!*\
!*** ./~/axios/index.js ***!
\**************************/
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! ./lib/axios */ 161);
/***/ }),
/* 161 */
/*!******************************!*\
!*** ./~/axios/lib/axios.js ***!
\******************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var defaults = __webpack_require__(/*! ./defaults */ 162);
var utils = __webpack_require__(/*! ./utils */ 163);
var dispatchRequest = __webpack_require__(/*! ./core/dispatchRequest */ 165);
var InterceptorManager = __webpack_require__(/*! ./core/InterceptorManager */ 174);
var isAbsoluteURL = __webpack_require__(/*! ./helpers/isAbsoluteURL */ 175);
var combineURLs = __webpack_require__(/*! ./helpers/combineURLs */ 176);
var bind = __webpack_require__(/*! ./helpers/bind */ 177);
var transformData = __webpack_require__(/*! ./helpers/transformData */ 169);
function Axios(defaultConfig) {
this.defaults = utils.merge({}, defaultConfig);
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = utils.merge({
url: arguments[0]
}, arguments[1]);
}
config = utils.merge(defaults, this.defaults, { method: 'get' }, config);
// Support baseURL config
if (config.baseURL && !isAbsoluteURL(config.url)) {
config.url = combineURLs(config.baseURL, config.url);
}
// Don't allow overriding defaults.withCredentials
config.withCredentials = config.withCredentials || this.defaults.withCredentials;
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers || {}
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
var defaultInstance = new Axios(defaults);
var axios = module.exports = bind(Axios.prototype.request, defaultInstance);
axios.request = bind(Axios.prototype.request, defaultInstance);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose properties from defaultInstance
axios.defaults = defaultInstance.defaults;
axios.interceptors = defaultInstance.interceptors;
// Factory for creating new instances
axios.create = function create(defaultConfig) {
return new Axios(defaultConfig);
};
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(/*! ./helpers/spread */ 178);
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
axios[method] = bind(Axios.prototype[method], defaultInstance);
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
axios[method] = bind(Axios.prototype[method], defaultInstance);
});
/***/ }),
/* 162 */
/*!*********************************!*\
!*** ./~/axios/lib/defaults.js ***!
\*********************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(/*! ./utils */ 163);
var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ 164);
var PROTECTION_PREFIX = /^\)\]\}',?\n/;
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
module.exports = {
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
data = data.replace(PROTECTION_PREFIX, '');
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
return data;
}],
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
patch: utils.merge(DEFAULT_CONTENT_TYPE),
post: utils.merge(DEFAULT_CONTENT_TYPE),
put: utils.merge(DEFAULT_CONTENT_TYPE)
},
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
/***/ }),
/* 163 */
/*!******************************!*\
!*** ./~/axios/lib/utils.js ***!
\******************************/
/***/ (function(module, exports) {
'use strict';
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* typeof document.createElement -> undefined
*/
function isStandardBrowserEnv() {
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined' &&
typeof document.createElement === 'function'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object' && !isArray(obj)) {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
trim: trim
};
/***/ }),
/* 164 */
/*!****************************************************!*\
!*** ./~/axios/lib/helpers/normalizeHeaderName.js ***!
\****************************************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(/*! ../utils */ 163);
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/***/ }),
/* 165 */
/*!*********************************************!*\
!*** ./~/axios/lib/core/dispatchRequest.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
/**
* Dispatch a request to the server using whichever adapter
* is supported by the current environment.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
return new Promise(function executor(resolve, reject) {
try {
var adapter;
if (typeof config.adapter === 'function') {
// For custom adapter support
adapter = config.adapter;
} else if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(/*! ../adapters/xhr */ 166);
} else if (typeof process !== 'undefined') {
// For node use HTTP adapter
adapter = __webpack_require__(/*! ../adapters/http */ 166);
}
if (typeof adapter === 'function') {
adapter(resolve, reject, config);
}
} catch (e) {
reject(e);
}
});
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../../process/browser.js */ 4)))
/***/ }),
/* 166 */
/*!*************************************!*\
!*** ./~/axios/lib/adapters/xhr.js ***!
\*************************************/
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
var utils = __webpack_require__(/*! ./../utils */ 163);
var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ 167);
var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ 168);
var transformData = __webpack_require__(/*! ./../helpers/transformData */ 169);
var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ 170);
var btoa = (typeof window !== 'undefined' && window.btoa) || __webpack_require__(/*! ./../helpers/btoa */ 171);
var settle = __webpack_require__(/*! ../helpers/settle */ 172);
module.exports = function xhrAdapter(resolve, reject, config) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
var loadEvent = 'onreadystatechange';
var xDomain = false;
// For IE 8/9 CORS support
// Only supports POST and GET calls and doesn't returns the response headers.
// DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest.
if (process.env.NODE_ENV !== 'test' && typeof window !== 'undefined' && window.XDomainRequest && !('withCredentials' in request) && !isURLSameOrigin(config.url)) {
request = new window.XDomainRequest();
loadEvent = 'onload';
xDomain = true;
request.onprogress = function handleProgress() {};
request.ontimeout = function handleTimeout() {};
}
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request[loadEvent] = function handleLoad() {
if (!request || (request.readyState !== 4 && !xDomain)) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
if (request.status === 0) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
var response = {
data: transformData(
responseData,
responseHeaders,
config.transformResponse
),
// IE sends 1223 instead of 204 (https://github.com/mzabriskie/axios/issues/201)
status: request.status === 1223 ? 204 : request.status,
statusText: request.status === 1223 ? 'No Content' : request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new Error('Network Error'));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var err = new Error('timeout of ' + config.timeout + 'ms exceeded');
err.timeout = config.timeout;
err.code = 'ECONNABORTED';
reject(err);
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(/*! ./../helpers/cookies */ 173);
// Add xsrf header
var xsrfValue = config.withCredentials || isURLSameOrigin(config.url) ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (config.withCredentials) {
request.withCredentials = true;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
if (request.responseType !== 'json') {
throw e;
}
}
}
// Handle progress if needed
if (config.progress) {
if (config.method === 'post' || config.method === 'put') {
request.upload.addEventListener('progress', config.progress);
} else if (config.method === 'get') {
request.addEventListener('progress', config.progress);
}
}
if (requestData === undefined) {
requestData = null;
}
// Send the request
request.send(requestData);
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(/*! ./../../../process/browser.js */ 4)))
/***/ }),
/* 167 */
/*!*****************************************!*\
!*** ./~/axios/lib/helpers/buildURL.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(/*! ./../utils */ 163);
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
}
if (!utils.isArray(val)) {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ }),
/* 168 */
/*!*********************************************!*\
!*** ./~/axios/lib/helpers/parseHeaders.js ***!
\*********************************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(/*! ./../utils */ 163);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
/***/ }),
/* 169 */
/*!**********************************************!*\
!*** ./~/axios/lib/helpers/transformData.js ***!
\**********************************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(/*! ./../utils */ 163);
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
/***/ }),
/* 170 */
/*!************************************************!*\
!*** ./~/axios/lib/helpers/isURLSameOrigin.js ***!
\************************************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(/*! ./../utils */ 163);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ }),
/* 171 */
/*!*************************************!*\
!*** ./~/axios/lib/helpers/btoa.js ***!
\*************************************/
/***/ (function(module, exports) {
'use strict';
// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function E() {
this.message = 'String contains an invalid character';
}
E.prototype = new Error;
E.prototype.code = 5;
E.prototype.name = 'InvalidCharacterError';
function btoa(input) {
var str = String(input);
var output = '';
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars;
// if the next str index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
str.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = str.charCodeAt(idx += 3 / 4);
if (charCode > 0xFF) {
throw new E();
}
block = block << 8 | charCode;
}
return output;
}
module.exports = btoa;
/***/ }),
/* 172 */
/*!***************************************!*\
!*** ./~/axios/lib/helpers/settle.js ***!
\***************************************/
/***/ (function(module, exports) {
'use strict';
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
// Note: status is not exposed by XDomainRequest
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(response);
}
};
/***/ }),
/* 173 */
/*!****************************************!*\
!*** ./~/axios/lib/helpers/cookies.js ***!
\****************************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(/*! ./../utils */ 163);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/* 174 */
/*!************************************************!*\
!*** ./~/axios/lib/core/InterceptorManager.js ***!
\************************************************/
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(/*! ./../utils */ 163);
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ }),
/* 175 */
/*!**********************************************!*\
!*** ./~/axios/lib/helpers/isAbsoluteURL.js ***!
\**********************************************/
/***/ (function(module, exports) {
'use strict';
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/***/ }),
/* 176 */
/*!********************************************!*\
!*** ./~/axios/lib/helpers/combineURLs.js ***!
\********************************************/
/***/ (function(module, exports) {
'use strict';
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '');
};
/***/ }),
/* 177 */
/*!*************************************!*\
!*** ./~/axios/lib/helpers/bind.js ***!
\*************************************/
/***/ (function(module, exports) {
'use strict';
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ }),
/* 178 */
/*!***************************************!*\
!*** ./~/axios/lib/helpers/spread.js ***!
\***************************************/
/***/ (function(module, exports) {
'use strict';
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ }),
/* 179 */
/*!*******************************************!*\
!*** ./app/components/children/Search.js ***!
\*******************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var React = __webpack_require__(/*! react */ 1);
var Search = React.createClass({
displayName: "Search",
getInitialState: function getInitialState() {
return {
topic: "",
startYear: "",
endYear: ""
};
},
handleChange: function handleChange(event) {
var newState = {};
newState[event.target.id] = event.target.value;
this.setState(newState);
},
handleClick: function handleClick() {
this.props.setTerm(this.state.topic, this.state.startYear, this.state.endYear);
},
render: function render() {
return React.createElement(
"div",
{ className: "panel panel-default" },
React.createElement(
"div",
{ className: "panel-heading" },
React.createElement(
"h3",
{ className: "panel-title text-center" },
"Search"
)
),
React.createElement(
"div",
{ className: "panel-body text-center" },
React.createElement(
"form",
null,
React.createElement(
"div",
{ className: "form-group" },
React.createElement(
"h4",
null,
"Topic"
),
React.createElement("input", { type: "text", className: "form-control text-center", id: "topic", onChange: this.handleChange, required: true }),
React.createElement("br", null),
React.createElement(
"h4",
null,
"Start Year"
),
React.createElement("input", { type: "text", className: "form-control text-center", id: "startYear", onChange: this.handleChange, required: true }),
React.createElement("br", null),
React.createElement(
"h4",
null,
"End Year"
),
React.createElement("input", { type: "text", className: "form-control text-center", id: "endYear", onChange: this.handleChange, required: true }),
React.createElement("br", null),
React.createElement(
"button",
{ type: "button", className: "btn btn-primary", onClick: this.handleClick },
"Search"
)
)
)
)
);
}
});
module.exports = Search;
/***/ }),
/* 180 */
/*!******************************************!*\
!*** ./app/components/children/Saved.js ***!
\******************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var React = __webpack_require__(/*! react */ 1);
var Saved = React.createClass({
displayName: "Saved",
getInitialState: function getInitialState() {
return {
savedArticles: []
};
},
clickToDelete: function clickToDelete(result) {
this.props.deleteArticle(result);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
var that = this;
console.log(nextProps);
var myResults = nextProps.savedArticles.map(function (search, i) {
var boundClick = that.clickToDelete.bind(that, search);
return React.createElement(
"div",
{ className: "list-group-item", key: i },
React.createElement(
"a",
{ href: search.url, target: "_blank" },
search.title
),
React.createElement("br", null),
search.date,
React.createElement("br", null),
React.createElement(
"button",
{ type: "button", className: "btn btn-success", style: { 'float': 'right', 'marginTop': '-39px' }, onClick: boundClick },
"Delete"
)
);
});
this.setState({ savedArticles: myResults });
},
render: function render() {
return React.createElement(
"div",
{ className: "panel panel-default" },
React.createElement(
"div",
{ className: "panel-heading" },
React.createElement(
"h3",
{ className: "panel-title text-center" },
"Saved Articles"
)
),
React.createElement(
"div",
{ className: "panel-body" },
this.state.savedArticles
)
);
}
});
module.exports = Saved;
/***/ }),
/* 181 */
/*!********************************************!*\
!*** ./app/components/children/Results.js ***!
\********************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var React = __webpack_require__(/*! react */ 1);
var Results = React.createClass({
displayName: "Results",
getInitialState: function getInitialState() {
return {
title: "",
date: "",
url: "",
results: []
};
},
clickToSave: function clickToSave(result) {
this.props.saveArticle(result.headline.main, result.pub_date, result.web_url);
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
var that = this;
var newResults = nextProps.results.map(function (search, i) {
var boundClick = that.clickToSave.bind(that, search);
return React.createElement(
"div",
{ className: "list-group-item", key: i },
React.createElement(
"a",
{ href: search.web_url, target: "_blank" },
search.headline.main
),
React.createElement("br", null),
search.pub_date,
React.createElement("br", null),
React.createElement(
"button",
{ type: "button", className: "btn btn-success", style: { 'float': 'right', 'marginTop': '-39px' }, onClick: boundClick },
"Save"
)
);
});
this.setState({ results: newResults });
},
render: function render() {
return React.createElement(
"div",
{ className: "panel panel-default" },
React.createElement(
"div",
{ className: "panel-heading" },
React.createElement(
"h3",
{ className: "panel-title text-center" },
"Results"
)
),
React.createElement(
"div",
{ className: "panel-body" },
this.state.results
)
);
}
});
module.exports = Results;
/***/ }),
/* 182 */
/*!*****************************************!*\
!*** ./app/components/utils/helpers.js ***!
\*****************************************/
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var axios = __webpack_require__(/*! axios */ 160);
var nytimesAPI = "4f14f6be03334883a5c41c827be80938";
var helpers = {
//This function runs the query to NYT
runQuery: function runQuery(topic, startYear, endYear) {
var queryURL = "https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=" + nytimesAPI + "&q=" + topic + "&begin_date=" + startYear + "0101&end_date=" + endYear + "0101";
return axios.get(queryURL).then(function (response) {
var newResults = [];
var fullResults = response.data.response.docs;
var counter = 0;
for (var i = 0; i < fullResults.length; i++) {
if (counter > 4) {
return newResults;
}
if (fullResults[counter].headline.main && fullResults[counter].pub_date && fullResults[counter].web_url) {
newResults.push(fullResults[counter]);
counter++;
}
}
return newResults;
});
},
// This function posts saved articles to our database.
postArticle: function postArticle(title, date, url) {
axios.post('/api/saved', { title: title, date: date, url: url }).then(function (results) {
console.log("Posted to database");
return results;
});
}
};
module.exports = helpers;
/***/ })
/******/ ]);
//# sourceMappingURL=bundle.js.map | mit |
thisishuey/frogban-mean | app/controllers/users/users.authentication.server.controller.js | 1945 | 'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User');
/**
* Signup
*/
exports.signup = function(req, res) {
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
// Init Variables
var user = new User(req.body);
var message = null;
// Add missing user fields
user.provider = 'local';
user.displayName = user.firstName + ' ' + user.lastName;
// Then save the user
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.jsonp(user);
}
});
}
});
};
/**
* Signin after passport authentication
*/
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.jsonp(user);
}
});
}
})(req, res, next);
};
/**
* Signout
*/
exports.signout = function(req, res) {
req.logout();
res.redirect('/');
};
/**
* OAuth callback
*/
exports.oauthCallback = function(strategy) {
return function(req, res, next) {
passport.authenticate(strategy, function(err, user, redirectURL) {
if (err || !user) {
return res.redirect('/#!/signin');
}
req.login(user, function(err) {
if (err) {
return res.redirect('/#!/signin');
}
return res.redirect(redirectURL || '/');
});
})(req, res, next);
};
};
| mit |
BlueBearGaming/BlueBear | src/BlueBear/GameChessBundle/Event/Listener/PawnEventListener.php | 1668 | <?php
namespace BlueBear\GameChessBundle\Event\Listener;
class PawnEventListener extends PieceEventListener
{
protected function addPossibleActions()
{
$x = $this->piece->getX();
$y = $this->piece->getY();
$this->piece->isWhite() ? $y-- : $y++; // Pawn only moves to the opposite side of the board
$this->handlePossibleMovement($x, $y);
// Adding possible captures in diagonal
$this->handlePossibleCapture($x + 1, $y);
$this->handlePossibleCapture($x - 1, $y);
// If pawn has never moved, it can move up to the second row
if (($this->piece->getY() == 6 && $this->piece->isWhite())
|| ($this->piece->getY() == 1 && !$this->piece->isWhite())
) {
$this->piece->isWhite() ? $y-- : $y++;
$this->handlePossibleMovement($x, $y);
}
// @todo take "en passant"
}
protected function findMoves()
{
$moves = [];
$x = $this->piece->getX();
$y = $this->piece->getY();
$this->piece->isWhite() ? $y-- : $y++; // Pawn only moves to the opposite side of the board
$moves[] = ['x' => $x, 'y' => $y];
$moves[] = ['x' => $x + 1, 'y' => $y];
$moves[] = ['x' => $x - 1, 'y' => $y];
// If pawn has never moved, it can move up to the second row
if (($this->piece->getY() == 6 && $this->piece->isWhite())
|| ($this->piece->getY() == 1 && !$this->piece->isWhite())
) {
$this->piece->isWhite() ? $y-- : $y++;
$moves[] = ['x' => $x, 'y' => $y];
}
// @todo take "en passant"
return $moves;
}
}
| mit |
Rolstenhouse/sarif-sdk | src/Sarif.UnitTests/Converters/AndroidStudioProblemTests.cs | 21803 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using FluentAssertions;
using Microsoft.CodeAnalysis.Sarif.Driver;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.CodeAnalysis.Sarif.Converters
{
[TestClass]
public class AndroidStudioProblemTests
{
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AndroidStudioProblem_RejectsNullProblemClass()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.ProblemClass = null;
new AndroidStudioProblem(builder);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AndroidStudioProblem_RejectsLinePresentButNotFile()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.File = null;
builder.Line = 42;
new AndroidStudioProblem(builder);
}
[TestMethod]
public void AndroidStudioProblem_AcceptsFileAsLocationInformation()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.File = "File";
builder.Module = null;
builder.Package = null;
builder.EntryPointName = null;
// Assert does not throw:
new AndroidStudioProblem(builder);
}
[TestMethod]
public void AndroidStudioProblem_AcceptsModuleAsLocationInformation()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.File = null;
builder.Module = "Mod";
builder.Package = null;
builder.EntryPointName = null;
// Assert does not throw:
new AndroidStudioProblem(builder);
}
[TestMethod]
public void AndroidStudioProblem_AcceptsPackageAsLocationInformation()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.File = null;
builder.Module = null;
builder.Package = "Pack";
builder.EntryPointName = null;
// Assert does not throw:
new AndroidStudioProblem(builder);
}
[TestMethod]
public void AndroidStudioProblem_AcceptsEntryPointAsLocationInformation()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.File = null;
builder.Module = null;
builder.Package = null;
builder.EntryPointName = "Entry";
builder.EntryPointType = "class";
// Assert does not throw:
new AndroidStudioProblem(builder);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AndroidStudioProblem_RejectsLackOfLocationInformation()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.File = null;
builder.Module = null;
builder.Package = null;
builder.EntryPointName = null;
// Error: No location info, should throw
new AndroidStudioProblem(builder);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AndroidStudioProblem_RequiresEntryPointTypeIfEntryPointNameSet()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.EntryPointType = "Class";
// Error: No location info, should throw
new AndroidStudioProblem(builder);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void AndroidStudioProblem_RequiresEntryPointNameIfEntryPointTypeSet()
{
AndroidStudioProblem.Builder builder = GetDefaultProblemBuilder();
builder.EntryPointName = "Frobinate.java";
// Error: No location info, should throw
new AndroidStudioProblem(builder);
}
[TestMethod]
public void AndroidStudioProblem_DefaultConstructedBuilderIsEmpty()
{
var uut = new AndroidStudioProblem.Builder();
Assert.IsTrue(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithFileIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.File = "file";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithLineIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.Line = 42;
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithModuleIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.Module = "mod";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithPackageIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.Package = "package";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithEntryPointTypeIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.EntryPointType = "TYPE";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithEntryPointNameIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.EntryPointName = "Some name";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithSeverityIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.Severity = "Sev";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithAttributeKeyIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.AttributeKey = "Key";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithProblemClassIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.ProblemClass = "Foo";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithHintsIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.Hints = ImmutableArray<string>.Empty;
Assert.IsFalse(uut.IsEmpty);
uut.Hints = ImmutableArray.Create("a", "b", "c");
Assert.IsFalse(uut.IsEmpty);
uut.Hints = default(ImmutableArray<string>);
Assert.IsTrue(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_BuilderWithDescritionIsNotEmpty()
{
var uut = new AndroidStudioProblem.Builder();
uut.Description = "You broke things";
Assert.IsFalse(uut.IsEmpty);
}
[TestMethod]
public void AndroidStudioProblem_ParseSelfClosingNodeConsumesNode()
{
var xmlStr = "<root><problem /><following /></root>";
using (XmlReader xml = Utilities.CreateXmlReaderFromString(xmlStr))
{
xml.ReadStartElement("root");
Assert.IsNull(Parse(xml));
Assert.AreEqual("following", xml.LocalName);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseEmptyNodeConsumesNode()
{
var xmlStr = "<root><problem></problem><following /></root>";
using (XmlReader xml = Utilities.CreateXmlReaderFromString(xmlStr))
{
xml.ReadStartElement("root");
Assert.IsNull(Parse(xml));
Assert.AreEqual("following", xml.LocalName);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseValidProblem()
{
XElement xml = CreateDefaultProblem();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
AssertThatProblemHasDefaultProblemProperties(uut);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotDependOnElementOrder()
{
XElement xml = CreateDefaultProblem();
IList<XElement> elements = xml.Elements().Shuffle();
xml.Elements().Remove();
xml.Add(elements);
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
AssertThatProblemHasDefaultProblemProperties(uut);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequireFile()
{
XElement xml = CreateDefaultProblem();
xml.Elements("file").Remove();
xml.Elements("line").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.IsNull(uut.File);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequireLine()
{
XElement xml = CreateDefaultProblem();
xml.Elements("line").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.AreEqual(0, uut.Line);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseClampsInvalidLineToOne_Zero()
{
XElement xml = CreateDefaultProblem();
xml.Elements("line").First().Value = XmlConvert.ToString(0);
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
Parse(xmlReader).Line.Should().Be(1);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseClampsInvalidLineToOne_Negative()
{
XElement xml = CreateDefaultProblem();
xml.Elements("line").First().Value = XmlConvert.ToString(-1);
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
Parse(xmlReader).Line.Should().Be(1);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequireModule()
{
XElement xml = CreateDefaultProblem();
xml.Elements("module").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.IsNull(uut.Module);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequirePackage()
{
XElement xml = CreateDefaultProblem();
xml.Elements("package").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.IsNull(uut.Package);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequireEntryPoint()
{
XElement xml = CreateDefaultProblem();
xml.Elements("entry_point").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.IsNull(uut.EntryPointType);
Assert.IsNull(uut.EntryPointName);
}
}
[TestMethod]
[ExpectedException(typeof(XmlException))]
public void AndroidStudioProblem_ParseRequiresEntryPoint_Type()
{
XElement xml = CreateDefaultProblem();
xml.Elements("entry_point").Attributes("TYPE").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
Parse(xmlReader);
}
}
[TestMethod]
[ExpectedException(typeof(XmlException))]
public void AndroidStudioProblem_ParseRequiresEntryPoint_Name()
{
XElement xml = CreateDefaultProblem();
xml.Elements("entry_point").Attributes("FQNAME").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
Parse(xmlReader);
}
}
[TestMethod]
[ExpectedException(typeof(XmlException))]
public void AndroidStudioProblem_ParseRequiresProblemClass()
{
XElement xml = CreateDefaultProblem();
xml.Elements("problem_class").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
Parse(xmlReader);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequireSeverity()
{
XElement xml = CreateDefaultProblem();
xml.Elements("problem_class").Attributes("severity").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.IsNull(uut.Severity);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequireAttributeKey()
{
XElement xml = CreateDefaultProblem();
xml.Elements("problem_class").Attributes("attribute_key").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.IsNull(uut.AttributeKey);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequireHints()
{
XElement xml = CreateDefaultProblem();
xml.Elements("hints").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.IsFalse(uut.Hints.IsDefault);
Assert.IsTrue(uut.Hints.IsEmpty);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseDoesNotRequireDescription()
{
XElement xml = CreateDefaultProblem();
xml.Elements("description").Remove();
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
Assert.IsNull(uut.Description);
}
}
[TestMethod]
public void AndroidStudioProblem_ParseIgnoresUnknownData()
{
XElement xml = CreateDefaultProblem();
xml.Add(new XElement("some_unknown_element"));
xml.Elements().Skip(2).First().AddAfterSelf(new XElement("some_other_unknown_element"));
xml.Element("file").Add(new XAttribute("some_ignored_attribute", "and data"));
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
AndroidStudioProblem uut = Parse(xmlReader);
AssertThatProblemHasDefaultProblemProperties(uut);
}
}
[TestMethod]
[ExpectedException(typeof(XmlException))]
public void AndroidStudioProblem_ParseRejectsNonProblem()
{
XElement xml = CreateDefaultProblem();
xml.Name = "not_a_problem";
using (XmlReader xmlReader = xml.CreateNameTableReader())
{
Parse(xmlReader);
}
}
[TestMethod]
public void AndroidStudioProblem_ReadHintsSelfClosingNodeConsumesNode()
{
var xmlStr = "<root><hints /><following /></root>";
using (XmlReader xml = Utilities.CreateXmlReaderFromString(xmlStr))
{
xml.ReadStartElement("root");
ImmutableArray<string> result = ReadHints(xml);
Assert.AreEqual("following", xml.LocalName);
Assert.IsTrue(result.IsEmpty);
Assert.IsFalse(result.IsDefault);
}
}
[TestMethod]
public void AndroidStudioProblem_ReadHintsEmptyNodeConsumesNode()
{
var xmlStr = "<root><hints></hints><following /></root>";
using (XmlReader xml = Utilities.CreateXmlReaderFromString(xmlStr))
{
xml.ReadStartElement("root");
ImmutableArray<string> result = ReadHints(xml);
Assert.AreEqual("following", xml.LocalName);
Assert.IsTrue(result.IsEmpty);
Assert.IsFalse(result.IsDefault);
}
}
[TestMethod]
[ExpectedException(typeof(XmlException))]
public void AndroidStudioProblem_ReadHintsRejectsNonHintChildren()
{
var xmlStr = "<root><hints><hint value=\"val\" /><not_a_hint /></hints><following /></root>";
using (XmlReader xml = Utilities.CreateXmlReaderFromString(xmlStr))
{
xml.ReadStartElement("root");
ReadHints(xml);
}
}
[TestMethod]
[ExpectedException(typeof(XmlException))]
public void AndroidStudioProblem_ReadHintsRejectsMissingValueHints()
{
var xmlStr = "<root><hints><hint /></hints><following /></root>";
using (XmlReader xml = Utilities.CreateXmlReaderFromString(xmlStr))
{
xml.ReadStartElement("root");
ReadHints(xml);
}
}
[TestMethod]
public void AndroidStudioProblem_ReadHintsAcceptsEmptyStringHints()
{
var xmlStr = "<root><hints><hint value=\"\" /></hints><following /></root>";
using (XmlReader xml = Utilities.CreateXmlReaderFromString(xmlStr))
{
xml.ReadStartElement("root");
ImmutableArray<string> results = ReadHints(xml);
results.Should().BeEmpty();
}
}
[TestMethod]
public void AndroidStudioProblem_ReadHintsAcceptsValidHints()
{
var xmlStr = "<root><hints><hint value=\"content_first\" /><hint value=\"content_second\" /></hints><following /></root>";
using (XmlReader xml = Utilities.CreateXmlReaderFromString(xmlStr))
{
xml.ReadStartElement("root");
ImmutableArray<string> results = ReadHints(xml);
results.Should().Equal(new[] { "content_first", "content_second" });
}
}
private static XElement CreateDefaultProblem()
{
return new XElement("problem",
new XElement("file", "file://$PROJECT_DIR$/file.java"),
new XElement("line", 42),
new XElement("module", "mod"),
new XElement("package", "pack"),
new XElement("entry_point", new XAttribute("TYPE", "file"), new XAttribute("FQNAME", "fqname")),
new XElement("problem_class", new XAttribute("severity", "WARNING"), new XAttribute("attribute_key", "WARNING_ATTRIBUTES"),
"Assertions"),
new XElement("hints",
new XElement("hint", new XAttribute("value", "some hint content"))
),
new XElement("description", "Method is never used.")
);
}
private static void AssertThatProblemHasDefaultProblemProperties(AndroidStudioProblem uut)
{
Assert.AreEqual("file://$PROJECT_DIR$/file.java", uut.File);
Assert.AreEqual(42, uut.Line);
Assert.AreEqual("mod", uut.Module);
Assert.AreEqual("pack", uut.Package);
Assert.AreEqual("file", uut.EntryPointType);
Assert.AreEqual("fqname", uut.EntryPointName);
Assert.AreEqual("WARNING", uut.Severity);
Assert.AreEqual("WARNING_ATTRIBUTES", uut.AttributeKey);
Assert.AreEqual("Assertions", uut.ProblemClass);
uut.Hints.Should().Equal(new[] { "some hint content" });
Assert.AreEqual("Method is never used.", uut.Description);
}
private static AndroidStudioProblem Parse(XmlReader reader)
{
return AndroidStudioProblem.Parse(reader, new AndroidStudioStrings(reader.NameTable));
}
private static ImmutableArray<string> ReadHints(XmlReader reader)
{
return AndroidStudioProblem.ReadHints(reader, new AndroidStudioStrings(reader.NameTable));
}
internal static AndroidStudioProblem.Builder GetDefaultProblemBuilder()
{
return new AndroidStudioProblem.Builder
{
ProblemClass = "A Problematic Problem",
File = "Unused"
};
}
internal static AndroidStudioProblem GetDefaultProblem()
{
return new AndroidStudioProblem(GetDefaultProblemBuilder());
}
}
}
| mit |
gitoneman/react-home | node_modules/react-datagrid/node_modules/ustring/node_modules/functionally/test/OnceTests.js | 1027 | describe('Once', function(){
var once = require('../index').once
it('should only run once', function(){
var counter = 0
var inc = once(function(){
counter++
})
counter
.should
.equal(0)
inc()
counter
.should
.equal(1)
inc()
inc()
inc()
counter
.should
.equal(1)
})
it('should return same result', function(){
var arr = [{}, {}, {}]
var counter = 0
var get = once(function(){
counter++
return arr[counter]
})
get()
.should
.equal(arr[1])
get()
.should
.equal(arr[1])
})
it('should be called with all args', function(){
var args = [1,2,3]
var res = once(function(){
return arguments
})
res.apply(this, args)
.should
.eql(args)
})
}) | mit |
crisbeto/material2 | src/cdk/keycodes/keycodes.ts | 3758 | /**
* @license
* Copyright Google LLC 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
*/
export const MAC_ENTER = 3;
export const BACKSPACE = 8;
export const TAB = 9;
export const NUM_CENTER = 12;
export const ENTER = 13;
export const SHIFT = 16;
export const CONTROL = 17;
export const ALT = 18;
export const PAUSE = 19;
export const CAPS_LOCK = 20;
export const ESCAPE = 27;
export const SPACE = 32;
export const PAGE_UP = 33;
export const PAGE_DOWN = 34;
export const END = 35;
export const HOME = 36;
export const LEFT_ARROW = 37;
export const UP_ARROW = 38;
export const RIGHT_ARROW = 39;
export const DOWN_ARROW = 40;
export const PLUS_SIGN = 43;
export const PRINT_SCREEN = 44;
export const INSERT = 45;
export const DELETE = 46;
export const ZERO = 48;
export const ONE = 49;
export const TWO = 50;
export const THREE = 51;
export const FOUR = 52;
export const FIVE = 53;
export const SIX = 54;
export const SEVEN = 55;
export const EIGHT = 56;
export const NINE = 57;
export const FF_SEMICOLON = 59; // Firefox (Gecko) fires this for semicolon instead of 186
export const FF_EQUALS = 61; // Firefox (Gecko) fires this for equals instead of 187
export const QUESTION_MARK = 63;
export const AT_SIGN = 64;
export const A = 65;
export const B = 66;
export const C = 67;
export const D = 68;
export const E = 69;
export const F = 70;
export const G = 71;
export const H = 72;
export const I = 73;
export const J = 74;
export const K = 75;
export const L = 76;
export const M = 77;
export const N = 78;
export const O = 79;
export const P = 80;
export const Q = 81;
export const R = 82;
export const S = 83;
export const T = 84;
export const U = 85;
export const V = 86;
export const W = 87;
export const X = 88;
export const Y = 89;
export const Z = 90;
export const META = 91; // WIN_KEY_LEFT
export const MAC_WK_CMD_LEFT = 91;
export const MAC_WK_CMD_RIGHT = 93;
export const CONTEXT_MENU = 93;
export const NUMPAD_ZERO = 96;
export const NUMPAD_ONE = 97;
export const NUMPAD_TWO = 98;
export const NUMPAD_THREE = 99;
export const NUMPAD_FOUR = 100;
export const NUMPAD_FIVE = 101;
export const NUMPAD_SIX = 102;
export const NUMPAD_SEVEN = 103;
export const NUMPAD_EIGHT = 104;
export const NUMPAD_NINE = 105;
export const NUMPAD_MULTIPLY = 106;
export const NUMPAD_PLUS = 107;
export const NUMPAD_MINUS = 109;
export const NUMPAD_PERIOD = 110;
export const NUMPAD_DIVIDE = 111;
export const F1 = 112;
export const F2 = 113;
export const F3 = 114;
export const F4 = 115;
export const F5 = 116;
export const F6 = 117;
export const F7 = 118;
export const F8 = 119;
export const F9 = 120;
export const F10 = 121;
export const F11 = 122;
export const F12 = 123;
export const NUM_LOCK = 144;
export const SCROLL_LOCK = 145;
export const FIRST_MEDIA = 166;
export const FF_MINUS = 173;
export const MUTE = 173; // Firefox (Gecko) fires 181 for MUTE
export const VOLUME_DOWN = 174; // Firefox (Gecko) fires 182 for VOLUME_DOWN
export const VOLUME_UP = 175; // Firefox (Gecko) fires 183 for VOLUME_UP
export const FF_MUTE = 181;
export const FF_VOLUME_DOWN = 182;
export const LAST_MEDIA = 183;
export const FF_VOLUME_UP = 183;
export const SEMICOLON = 186; // Firefox (Gecko) fires 59 for SEMICOLON
export const EQUALS = 187; // Firefox (Gecko) fires 61 for EQUALS
export const COMMA = 188;
export const DASH = 189; // Firefox (Gecko) fires 173 for DASH/MINUS
export const PERIOD = 190;
export const SLASH = 191;
export const APOSTROPHE = 192;
export const TILDE = 192;
export const OPEN_SQUARE_BRACKET = 219;
export const BACKSLASH = 220;
export const CLOSE_SQUARE_BRACKET = 221;
export const SINGLE_QUOTE = 222;
export const MAC_META = 224;
| mit |
007slm/hexo | test/scripts/helper/index.js | 182 | describe('Helper', function(){
require('./date');
require('./gravatar');
require('./is');
require('./number');
require('./tag');
require('./toc');
require('./url');
}); | mit |
ToonTownInfiniteRepo/ToontownInfinite | toontown/toon/PlayerDetailPanel.py | 5307 | from pandac.PandaModules import *
from toontown.toonbase.ToontownGlobals import *
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from direct.showbase import DirectObject
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.directnotify import DirectNotifyGlobal
import DistributedToon
from toontown.friends import FriendInviter
import ToonTeleportPanel
from toontown.toonbase import TTLocalizer
from toontown.hood import ZoneUtil
from toontown.toonbase.ToontownBattleGlobals import Tracks, Levels
globalAvatarDetail = None
def showPlayerDetail(avId, avName, playerId = None):
global globalAvatarDetail
if globalAvatarDetail != None:
globalAvatarDetail.cleanup()
globalAvatarDetail = None
globalAvatarDetail = PlayerDetailPanel(avId, avName, playerId)
return
def hidePlayerDetail():
global globalAvatarDetail
if globalAvatarDetail != None:
globalAvatarDetail.cleanup()
globalAvatarDetail = None
return
def unloadPlayerDetail():
global globalAvatarDetail
if globalAvatarDetail != None:
globalAvatarDetail.cleanup()
globalAvatarDetail = None
return
class PlayerDetailPanel(DirectFrame):
notify = DirectNotifyGlobal.directNotify.newCategory('ToonAvatarDetailPanel')
def __init__(self, avId, avName, playerId = None, parent = aspect2dp, **kw):
self.playerId = playerId
self.isPlayer = 0
self.playerInfo = None
if playerId:
self.isPlayer = 1
if base.cr.playerFriendsManager.playerId2Info.has_key(playerId):
self.playerInfo = base.cr.playerFriendsManager.playerId2Info[playerId]
if not self.playerInfo.onlineYesNo:
avId = None
else:
avId = None
self.avId = avId
self.avName = avName
self.avatar = None
self.createdAvatar = None
buttons = loader.loadModel('phase_3/models/gui/dialog_box_buttons_gui')
gui = loader.loadModel('phase_3.5/models/gui/avatar_panel_gui')
detailPanel = gui.find('**/avatarInfoPanel')
textScale = 0.132
textWrap = 10.4
if self.playerId:
textScale = 0.1
textWrap = 18.0
optiondefs = (('pos', (0.525, 0.0, 0.525), None),
('scale', 0.5, None),
('relief', None, None),
('image', detailPanel, None),
('image_color', GlobalDialogColor, None),
('text', '', None),
('text_wordwrap', textWrap, None),
('text_scale', textScale, None),
('text_pos', (-0.125, 0.75), None))
self.defineoptions(kw, optiondefs)
DirectFrame.__init__(self, parent)
self.dataText = DirectLabel(self, text='', text_scale=0.085, text_align=TextNode.ALeft, text_wordwrap=15, relief=None, pos=(-0.85, 0.0, 0.725))
if self.avId:
self.avText = DirectLabel(self, text=TTLocalizer.PlayerToonName % {'toonname': self.avName}, text_scale=0.09, text_align=TextNode.ALeft, text_wordwrap=15, relief=None, pos=(-0.85, 0.0, 0.56))
guiButton = loader.loadModel('phase_3/models/gui/quit_button')
self.gotoToonButton = DirectButton(parent=self, relief=None, image=(guiButton.find('**/QuitBtn_UP'), guiButton.find('**/QuitBtn_DN'), guiButton.find('**/QuitBtn_RLVR')), image_scale=1.15, text=TTLocalizer.PlayerShowToon, text_scale=0.08, text_pos=(0.0, -0.02), textMayChange=0, pos=(0.43, 0, 0.415), command=self.__showToon)
ToonTeleportPanel.hideTeleportPanel()
FriendInviter.hideFriendInviter()
self.bCancel = DirectButton(self, image=(buttons.find('**/CloseBtn_UP'), buttons.find('**/CloseBtn_DN'), buttons.find('**/CloseBtn_Rllvr')), relief=None, text=TTLocalizer.AvatarDetailPanelCancel, text_scale=0.05, text_pos=(0.12, -0.01), pos=(-0.865, 0.0, -0.765), scale=2.0, command=self.__handleCancel)
self.bCancel.show()
self.initialiseoptions(PlayerDetailPanel)
self.__showData()
buttons.removeNode()
gui.removeNode()
return
def cleanup(self):
if self.createdAvatar:
self.avatar.delete()
self.createdAvatar = None
self.destroy()
return
def __handleCancel(self):
unloadPlayerDetail()
def __showData(self):
if self.isPlayer and self.playerInfo:
if self.playerInfo.onlineYesNo:
someworld = self.playerInfo.location
else:
someworld = TTLocalizer.OfflineLocation
text = TTLocalizer.AvatarDetailPanelPlayer % {'player': self.playerInfo.playerName,
'world': someworld}
else:
text = TTLocalizer.AvatarDetailPanelOffline
self.dataText['text'] = text
def __showToon(self):
messenger.send('wakeup')
hasManager = hasattr(base.cr, 'playerFriendsManager')
handle = base.cr.identifyFriend(self.avId)
if not handle and hasManager:
handle = base.cr.playerFriendsManager.getAvHandleFromId(self.avId)
if handle != None:
self.notify.info("Clicked on name in friend's list. doId = %s" % handle.doId)
messenger.send('clickedNametagPlayer', [handle, self.playerId, 0])
return
| mit |
JimBobSquarePants/Umbraco-CMS | src/Umbraco.Core/Services/InstallationService.cs | 588 | using System.Threading.Tasks;
using Umbraco.Cms.Core.Persistence.Repositories;
namespace Umbraco.Cms.Core.Services
{
public class InstallationService : IInstallationService
{
private readonly IInstallationRepository _installationRepository;
public InstallationService(IInstallationRepository installationRepository)
{
_installationRepository = installationRepository;
}
public async Task LogInstall(InstallLog installLog)
{
await _installationRepository.SaveInstallLogAsync(installLog);
}
}
}
| mit |
neo4j-examples/movies-with-neo4j | spec/controllers/movies_controller_spec.rb | 1019 | require 'rails_helper'
describe MoviesController do
let(:movies) { Movie.all.to_a }
let(:people_in_movies) { Movie.people_in_movies }
describe 'GET #index' do
it 'returns http success' do
get :index
expect(response).to have_http_status(:success)
end
it 'assigns movies' do
get :index
expect(assigns(:movies)).to eq movies
end
it 'assigns people_in_movies' do
get :index
expect(assigns(:people_in_movies)).to eq people_in_movies
end
end
describe 'GET #show' do
let(:movie_matrix) { Movie.find_by title: 'The Matrix' }
it 'finds movie by title' do
get :show, title: movie_matrix.title
expect(response).to have_http_status(:success)
end
it 'renders the :show template' do
get :show, title: movie_matrix.title
expect(response).to render_template :show
end
it 'assigns movie' do
get :show, title: movie_matrix.title
expect(assigns(:movie)).to eq movie_matrix
end
end
end
| mit |
etsy/phan | .phan/plugins/InlineHTMLPlugin.php | 5919 | <?php
declare(strict_types=1);
use ast\Node;
use Phan\AST\Parser;
use Phan\CLI;
use Phan\CodeBase;
use Phan\Config;
use Phan\Language\Context;
use Phan\Library\StringUtil;
use Phan\PluginV3;
use Phan\PluginV3\AfterAnalyzeFileCapability;
use Phan\PluginV3\PluginAwarePostAnalysisVisitor;
use Phan\PluginV3\PostAnalyzeNodeCapability;
use Phan\PluginV3\UnloadablePluginException;
/**
* This plugin checks for accidental whitespace in regular php files.
* Note that this is slow due to needing token_get_all.
*
* TODO: Cache and reuse the results
*/
class InlineHTMLPlugin extends PluginV3 implements
AfterAnalyzeFileCapability,
PostAnalyzeNodeCapability
{
private const InlineHTML = 'PhanPluginInlineHTML';
private const InlineHTMLLeading = 'PhanPluginInlineHTMLLeading';
private const InlineHTMLTrailing = 'PhanPluginInlineHTMLTrailing';
/** @var array<string,true> set of files that have echo statements */
public static $file_set_to_analyze = [];
/** @var ?string */
private $whitelist_regex;
/** @var ?string */
private $blacklist_regex;
public function __construct()
{
$plugin_config = Config::getValue('plugin_config');
$this->whitelist_regex = $plugin_config['inline_html_whitelist_regex'] ?? null;
$this->blacklist_regex = $plugin_config['inline_html_blacklist_regex'] ?? null;
}
private function shouldCheckFile(string $path): bool
{
if (is_string($this->blacklist_regex)) {
if (CLI::isPathMatchedByRegex($this->blacklist_regex, $path)) {
return false;
}
}
if (is_string($this->whitelist_regex)) {
return CLI::isPathMatchedByRegex($this->whitelist_regex, $path);
}
return true;
}
/**
* @param CodeBase $code_base
* The code base in which the node exists
*
* @param Context $context @phan-unused-param
* A context with the file name for $file_contents and the scope after analyzing $node.
*
* @param string $file_contents the unmodified file contents @phan-unused-param
* @param Node $node the node @phan-unused-param
* @override
* @throws Error if a process fails to shut down
*/
public function afterAnalyzeFile(
CodeBase $code_base,
Context $context,
string $file_contents,
Node $node
): void {
$file = $context->getFile();
if (!isset(self::$file_set_to_analyze[$file])) {
// token_get_all is noticeably slow when there are a lot of files, so we check for the existence of echo statements in the parsed AST as a heuristic to avoid calling token_get_all.
return;
}
if (!self::shouldCheckFile($file)) {
return;
}
$file_contents = Parser::removeShebang($file_contents);
$tokens = token_get_all($file_contents);
foreach ($tokens as $i => $token) {
if (!is_array($token)) {
continue;
}
if ($token[0] !== T_INLINE_HTML) {
continue;
}
$N = count($tokens);
$this->warnAboutInlineHTML($code_base, $context, $token, $i, $N);
if ($i < $N - 1) {
// Make sure to always check if the last token is inline HTML
$token = $tokens[$N - 1] ?? null;
if (!is_array($token)) {
break;
}
if ($token[0] !== T_INLINE_HTML) {
break;
}
$this->warnAboutInlineHTML($code_base, $context, $token, $N - 1, $N);
}
break;
}
}
/**
* @param array{0:int,1:string,2:int} $token a token from token_get_all
*/
private function warnAboutInlineHTML(CodeBase $code_base, Context $context, array $token, int $i, int $n): void
{
if ($i === 0) {
$issue = self::InlineHTMLLeading;
$message = 'Saw inline HTML at the start of the file: {STRING_LITERAL}';
} elseif ($i >= $n - 1) {
$issue = self::InlineHTMLTrailing;
$message = 'Saw inline HTML at the end of the file: {STRING_LITERAL}';
} else {
$issue = self::InlineHTML;
$message = 'Saw inline HTML between the first and last token: {STRING_LITERAL}';
}
$this->emitIssue(
$code_base,
clone($context)->withLineNumberStart($token[2]),
$issue,
$message,
[StringUtil::jsonEncode(self::truncate($token[1]))]
);
}
private static function truncate(string $token): string
{
if (strlen($token) > 20) {
return mb_substr($token, 0, 20) . "...";
}
return $token;
}
/**
* @return string - name of PluginAwarePostAnalysisVisitor subclass
*
* @override
*/
public static function getPostAnalyzeNodeVisitorClassName(): string
{
return InlineHTMLVisitor::class;
}
}
/**
* Records existence of AST_ECHO within a file, marking the file as one that should be checked.
*
* php-ast (and the underlying AST implementation) doesn't provide a way to distinguish inline HTML from other types of echos.
*/
class InlineHTMLVisitor extends PluginAwarePostAnalysisVisitor
{
/**
* @override
* @param Node $node @unused-param
* @return void
*/
public function visitEcho(Node $node)
{
InlineHTMLPlugin::$file_set_to_analyze[$this->context->getFile()] = true;
}
}
// Every plugin needs to return an instance of itself at the
// end of the file in which it's defined.
if (!function_exists('token_get_all')) {
throw new UnloadablePluginException("InlineHTMLPlugin requires the tokenizer extension, which is not enabled (this plugin uses token_get_all())");
}
return new InlineHTMLPlugin();
| mit |
GridProtectionAlliance/gsf | Source/Libraries/GSF.TimeSeries/Transport/TSSC/TsscPointMetadata.cs | 9564 | //******************************************************************************************************
// TsscPointMetadata.cs - Gbtc
//
// Copyright © 2016, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 12/02/2016 - Steven E. Chisholm
// Generated original version of source code.
//
//******************************************************************************************************
using System;
namespace GSF.TimeSeries.Transport.TSSC
{
/// <summary>
/// The metadata kept for each pointID.
/// </summary>
internal class TsscPointMetadata
{
public ushort PrevNextPointId1;
public uint PrevQuality1;
public uint PrevQuality2;
public uint PrevValue1;
public uint PrevValue2;
public uint PrevValue3;
private readonly byte[] m_commandStats;
private int m_commandsSentSinceLastChange = 0;
//Bit codes for the 4 modes of encoding.
private byte m_mode;
//(Mode 1 means no prefix.)
private byte m_mode21;
private byte m_mode31;
private byte m_mode301;
private byte m_mode41;
private byte m_mode401;
private byte m_mode4001;
private int m_startupMode = 0;
private readonly Action<int, int> m_writeBits;
private readonly Func<int> m_readBit;
private readonly Func<int> m_readBits5;
public TsscPointMetadata(Action<int, int> writeBits, Func<int> readBit, Func<int> readBits5)
{
m_commandsSentSinceLastChange = 0;
m_commandStats = new byte[32];
m_mode = 4;
m_mode41 = TsscCodeWords.Value1;
m_mode401 = TsscCodeWords.Value2;
m_mode4001 = TsscCodeWords.Value3;
m_writeBits = writeBits ?? NotImplementedMethod2;
m_readBit = readBit ?? NotImplementedMethod1;
m_readBits5 = readBits5 ?? NotImplementedMethod1;
}
private int NotImplementedMethod1()
{
throw new NotImplementedException();
}
private void NotImplementedMethod2(int a, int b)
{
throw new NotImplementedException();
}
public void WriteCode(int code)
{
switch (m_mode)
{
case 1:
m_writeBits(code, 5);
break;
case 2:
if (code == m_mode21)
{
m_writeBits(1, 1);
}
else
{
m_writeBits(code, 6);
}
break;
case 3:
if (code == m_mode31)
{
m_writeBits(1, 1);
}
else if (code == m_mode301)
{
m_writeBits(1, 2);
}
else
{
m_writeBits(code, 7);
}
break;
case 4:
if (code == m_mode41)
{
m_writeBits(1, 1);
}
else if (code == m_mode401)
{
m_writeBits(1, 2);
}
else if (code == m_mode4001)
{
m_writeBits(1, 3);
}
else
{
m_writeBits(code, 8);
}
break;
default:
throw new Exception("Coding Error");
}
UpdatedCodeStatistics(code);
}
public int ReadCode()
{
int code = 0;
switch (m_mode)
{
case 1:
code = m_readBits5();
break;
case 2:
if (m_readBit() == 1)
{
code = m_mode21;
}
else
{
code = m_readBits5();
}
break;
case 3:
if (m_readBit() == 1)
{
code = m_mode31;
}
else if (m_readBit() == 1)
{
code = m_mode301;
}
else
{
code = m_readBits5();
}
break;
case 4:
if (m_readBit() == 1)
{
code = m_mode41;
}
else if (m_readBit() == 1)
{
code = m_mode401;
}
else if (m_readBit() == 1)
{
code = m_mode4001;
}
else
{
code = m_readBits5();
}
break;
default:
throw new Exception("Unsupported compression mode");
}
UpdatedCodeStatistics(code);
return code;
}
private void UpdatedCodeStatistics(int code)
{
m_commandsSentSinceLastChange++;
m_commandStats[code]++;
if (m_startupMode == 0 && m_commandsSentSinceLastChange > 5)
{
m_startupMode++;
AdaptCommands();
}
else if (m_startupMode == 1 && m_commandsSentSinceLastChange > 20)
{
m_startupMode++;
AdaptCommands();
}
else if (m_startupMode == 2 && m_commandsSentSinceLastChange > 100)
{
AdaptCommands();
}
}
private void AdaptCommands()
{
byte code1 = 0;
int count1 = 0;
byte code2 = 1;
int count2 = 0;
byte code3 = 2;
int count3 = 0;
int total = 0;
for (int x = 0; x < m_commandStats.Length; x++)
{
int cnt = m_commandStats[x];
m_commandStats[x] = 0;
total += cnt;
if (cnt > count3)
{
if (cnt > count1)
{
code3 = code2;
count3 = count2;
code2 = code1;
count2 = count1;
code1 = (byte)x;
count1 = cnt;
}
else if (cnt > count2)
{
code3 = code2;
count3 = count2;
code2 = (byte)x;
count2 = cnt;
}
else
{
code3 = (byte)x;
count3 = cnt;
}
}
}
int mode1Size = total * 5;
int mode2Size = count1 * 1 + (total - count1) * 6;
int mode3Size = count1 * 1 + count2 * 2 + (total - count1 - count2) * 7;
int mode4Size = count1 * 1 + count2 * 2 + count3 * 3 + (total - count1 - count2 - count3) * 8;
int minSize = int.MaxValue;
minSize = Math.Min(minSize, mode1Size);
minSize = Math.Min(minSize, mode2Size);
minSize = Math.Min(minSize, mode3Size);
minSize = Math.Min(minSize, mode4Size);
if (minSize == mode1Size)
{
m_mode = 1;
}
else if (minSize == mode2Size)
{
m_mode = 2;
m_mode21 = code1;
}
else if (minSize == mode3Size)
{
m_mode = 3;
m_mode31 = code1;
m_mode301 = code2;
}
else if (minSize == mode4Size)
{
m_mode = 4;
m_mode41 = code1;
m_mode401 = code2;
m_mode4001 = code3;
}
else
{
throw new Exception("Coding Error");
}
m_commandsSentSinceLastChange = 0;
}
}
}
| mit |
jiyuren/LolliPin | app/src/main/java/com/github/orangegangsters/lollipin/CustomPinActivity.java | 3118 | package com.github.orangegangsters.lollipin;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.widget.Toast;
import com.github.orangegangsters.lollipin.lib.managers.AppLockActivity;
import lollipin.orangegangsters.github.com.lollipin.R;
import uk.me.lewisdeane.ldialogs.BaseDialog;
import uk.me.lewisdeane.ldialogs.CustomDialog;
/**
* Created by oliviergoutay on 1/14/15.
*/
public class CustomPinActivity extends AppLockActivity {
@Override
public void showForgotDialog() {
Resources res = getResources();
// Create the builder with required paramaters - Context, Title, Positive Text
CustomDialog.Builder builder = new CustomDialog.Builder(this,
res.getString(R.string.activity_dialog_title),
res.getString(R.string.activity_dialog_accept));
builder.content(res.getString(R.string.activity_dialog_content));
builder.negativeText(res.getString(R.string.activity_dialog_decline));
//Set theme
builder.darkTheme(false);
builder.typeface(Typeface.SANS_SERIF);
builder.positiveColor(res.getColor(R.color.light_blue_500)); // int res, or int colorRes parameter versions available as well.
builder.negativeColor(res.getColor(R.color.light_blue_500));
builder.rightToLeft(false); // Enables right to left positioning for languages that may require so.
builder.titleAlignment(BaseDialog.Alignment.CENTER);
builder.buttonAlignment(BaseDialog.Alignment.CENTER);
builder.setButtonStacking(false);
//Set text sizes
builder.titleTextSize((int) res.getDimension(R.dimen.activity_dialog_title_size));
builder.contentTextSize((int) res.getDimension(R.dimen.activity_dialog_content_size));
builder.positiveButtonTextSize((int) res.getDimension(R.dimen.activity_dialog_positive_button_size));
builder.negativeButtonTextSize((int) res.getDimension(R.dimen.activity_dialog_negative_button_size));
//Build the dialog.
CustomDialog customDialog = builder.build();
customDialog.setCanceledOnTouchOutside(false);
customDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
customDialog.setClickListener(new CustomDialog.ClickListener() {
@Override
public void onConfirmClick() {
Toast.makeText(getApplicationContext(), "Yes", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelClick() {
Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
});
// Show the dialog.
customDialog.show();
}
@Override
public void onPinFailure(int attempts) {
}
@Override
public void onPinSuccess(int attempts) {
}
@Override
public int getPinLength() {
return super.getPinLength();//you can override this method to change the pin length from the default 4
}
}
| mit |
undecided/crashdown-auth-hmac | spec/crash_log/rack_test_request_spec.rb | 2019 | require 'spec_helper'
require "net/http"
require 'time'
require 'active_support'
require 'rack/test'
require "delorean"
describe CrashLog::AuthHMAC do
include Rack::Test::Methods
def app
lambda do |env|
[200, {"Content-Type" => "text/html", "Content-Length" => 13}, "Hello, World!"]
end
end
it 'says hello world' do
get '/'
last_response.status.should == 200
last_response.body.should == 'Hello, World!'
end
it 'can process rack test requests' do
# HMAC uses date to validate request signature, we need to fix the date so
# that it matches.
Delorean.time_travel_to(Time.utc(2012,10,04,8,31,16))
env = current_session.__send__(:env_for, '/events', {:method => "POST", 'CONTENT_TYPE' => "application/json; charset=UTF-8"})
signature = CrashLog::AuthHMAC.signature(env, "2Xbz25UpU8nQxaSAKuixJQMDxuiqryxzArzSJJ8Ci3Mr")
signature.should == "Rqj0DdG4/jNrzOXdybz13CaKzXU="
end
it 'can handle hash requests' do
Delorean.time_travel_to(Date.parse("Thu, 10 Jul 2008 03:29:56 GMT"))
request_hash = {
'REQUEST_METHOD' => 'PUT',
'content-type' => 'text/plain',
'content-md5' => 'blahblah',
'date' => "Thu, 10 Jul 2008 03:29:56 GMT",
'PATH_INFO' => '/notify'
}
standard_request = Net::HTTP::Put.new("/notify",
'content-type' => 'text/plain',
'content-md5' => 'blahblah',
'date' => "Thu, 10 Jul 2008 03:29:56 GMT")
sig = CrashLog::AuthHMAC.signature(request_hash, 'secret')
sig.should == CrashLog::AuthHMAC.signature(standard_request, 'secret')
end
it 'accepts real request without content md5' do
Delorean.time_travel_to(Date.parse("Thu, 04 Oct 2012 08:31:16 GMT"))
request = Net::HTTP::Post.new("/events",
'content-type' => 'application/json; charset=UTF-8',
'date' => "Thu, 04 Oct 2012 08:31:16 GMT")
sig = CrashLog::AuthHMAC.signature(request, '2Xbz25UpU8nQxaSAKuixJQMDxuiqryxzArzSJJ8Ci3Mr')
sig.should == 'Rqj0DdG4/jNrzOXdybz13CaKzXU='
end
end
| mit |
randylubin/acting-karaoke | node_modules/hark/example/demo.bundle.js | 11205 | ;(function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){
localStorage.debug = true;
var hark = require('../hark.js');
var bows = require('bows');
(function() {
//Audio Tag Demo
var stream = document.querySelector('audio');
var speechEvents = hark(stream);
var notification = document.querySelector('#mlkSpeaking');
var log = bows('MLK Demo');
speechEvents.on('speaking', function() {
log('speaking');
notification.style.display = 'block';
});
speechEvents.on('volume_change', function(volume, threshold) {
//log('volume change', volume, threshold);
});
speechEvents.on('stopped_speaking', function() {
log('stopped_speaking');
notification.style.display = 'none';
});
})();
(function() {
//Microphone demo
var getUserMedia = require('getusermedia');
var attachmediastream = require('attachmediastream');
var notification = document.querySelector('#userSpeaking');
var log = bows('Microphone Demo');
getUserMedia(function(err, stream) {
if (err) throw err
attachmediastream(document.querySelector('video'), stream);
var speechEvents = hark(stream);
speechEvents.on('speaking', function() {
notification.style.display = 'block';
log('speaking');
});
speechEvents.on('volume_change', function(volume, threshold) {
log(volume, threshold)
});
speechEvents.on('stopped_speaking', function() {
notification.style.display = 'none';
log('stopped_speaking');
});
});
})();
},{"../hark.js":2,"bows":3,"getusermedia":4,"attachmediastream":5}],4:[function(require,module,exports){
// getUserMedia helper by @HenrikJoreteg
var func = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
module.exports = function (contstraints, cb) {
var options;
var haveOpts = arguments.length === 2;
var defaultOpts = {video: true, audio: true};
// make contstraints optional
if (!haveOpts) {
cb = contstraints;
contstraints = defaultOpts;
}
// treat lack of browser support like an error
if (!func) return cb(new Error('notSupported'));
func.call(navigator, contstraints, function (stream) {
cb(null, stream);
}, function (err) {
cb(err);
});
};
},{}],5:[function(require,module,exports){
module.exports = function (element, stream, play) {
var autoPlay = (play === false) ? false : true;
if (autoPlay) element.autoplay = true;
// handle mozilla case
if (window.mozGetUserMedia) {
element.mozSrcObject = stream;
if (autoPlay) element.play();
} else {
if (typeof element.srcObject !== 'undefined') {
element.srcObject = stream;
} else if (typeof element.mozSrcObject !== 'undefined') {
element.mozSrcObject = stream;
} else if (typeof element.src !== 'undefined') {
element.src = URL.createObjectURL(stream);
} else {
return false;
}
}
return true;
};
},{}],2:[function(require,module,exports){
var WildEmitter = require('wildemitter');
function getMaxVolume (analyser, fftBins) {
var maxVolume = -Infinity;
analyser.getFloatFrequencyData(fftBins);
for(var i=0, ii=fftBins.length; i < ii; i++) {
if (fftBins[i] > maxVolume && fftBins[i] < 0) {
maxVolume = fftBins[i];
}
};
return maxVolume;
}
module.exports = function(stream, options) {
var harker = new WildEmitter();
// make it not break in non-supported browsers
if (!window.webkitAudioContext) return harker;
//Config
var options = options || {},
smoothing = (options.smoothing || 0.5),
interval = (options.interval || 100),
threshold = options.threshold,
play = options.play;
//Setup Audio Context
var audioContext = new webkitAudioContext();
var sourceNode, fftBins, analyser;
analyser = audioContext.createAnalyser();
analyser.fftSize = 512;
analyser.smoothingTimeConstant = smoothing;
fftBins = new Float32Array(analyser.fftSize);
if (stream.jquery) stream = stream[0];
if (stream instanceof HTMLAudioElement) {
//Audio Tag
sourceNode = audioContext.createMediaElementSource(stream);
if (typeof play === 'undefined') play = true;
threshold = threshold || -65;
} else {
//WebRTC Stream
sourceNode = audioContext.createMediaStreamSource(stream);
threshold = threshold || -45;
}
sourceNode.connect(analyser);
if (play) analyser.connect(audioContext.destination);
harker.speaking = false;
harker.setThreshold = function(t) {
threshold = t;
};
harker.setInterval = function(i) {
interval = i;
};
// Poll the analyser node to determine if speaking
// and emit events if changed
var looper = function() {
setTimeout(function() {
var currentVolume = getMaxVolume(analyser, fftBins);
harker.emit('volume_change', currentVolume, threshold);
if (currentVolume > threshold) {
if (!harker.speaking) {
harker.speaking = true;
harker.emit('speaking');
}
} else {
if (harker.speaking) {
harker.speaking = false;
harker.emit('stopped_speaking');
}
}
looper();
}, interval);
};
looper();
return harker;
}
},{"wildemitter":6}],6:[function(require,module,exports){
/*
WildEmitter.js is a slim little event emitter by @henrikjoreteg largely based
on @visionmedia's Emitter from UI Kit.
Why? I wanted it standalone.
I also wanted support for wildcard emitters like this:
emitter.on('*', function (eventName, other, event, payloads) {
});
emitter.on('somenamespace*', function (eventName, payloads) {
});
Please note that callbacks triggered by wildcard registered events also get
the event name as the first argument.
*/
module.exports = WildEmitter;
function WildEmitter() {
this.callbacks = {};
}
// Listen on the given `event` with `fn`. Store a group name if present.
WildEmitter.prototype.on = function (event, groupName, fn) {
var hasGroup = (arguments.length === 3),
group = hasGroup ? arguments[1] : undefined,
func = hasGroup ? arguments[2] : arguments[1];
func._groupName = group;
(this.callbacks[event] = this.callbacks[event] || []).push(func);
return this;
};
// Adds an `event` listener that will be invoked a single
// time then automatically removed.
WildEmitter.prototype.once = function (event, groupName, fn) {
var self = this,
hasGroup = (arguments.length === 3),
group = hasGroup ? arguments[1] : undefined,
func = hasGroup ? arguments[2] : arguments[1];
function on() {
self.off(event, on);
func.apply(this, arguments);
}
this.on(event, group, on);
return this;
};
// Unbinds an entire group
WildEmitter.prototype.releaseGroup = function (groupName) {
var item, i, len, handlers;
for (item in this.callbacks) {
handlers = this.callbacks[item];
for (i = 0, len = handlers.length; i < len; i++) {
if (handlers[i]._groupName === groupName) {
//console.log('removing');
// remove it and shorten the array we're looping through
handlers.splice(i, 1);
i--;
len--;
}
}
}
return this;
};
// Remove the given callback for `event` or all
// registered callbacks.
WildEmitter.prototype.off = function (event, fn) {
var callbacks = this.callbacks[event],
i;
if (!callbacks) return this;
// remove all handlers
if (arguments.length === 1) {
delete this.callbacks[event];
return this;
}
// remove specific handler
i = callbacks.indexOf(fn);
callbacks.splice(i, 1);
return this;
};
// Emit `event` with the given args.
// also calls any `*` handlers
WildEmitter.prototype.emit = function (event) {
var args = [].slice.call(arguments, 1),
callbacks = this.callbacks[event],
specialCallbacks = this.getWildcardCallbacks(event),
i,
len,
item;
if (callbacks) {
for (i = 0, len = callbacks.length; i < len; ++i) {
if (callbacks[i]) {
callbacks[i].apply(this, args);
} else {
break;
}
}
}
if (specialCallbacks) {
for (i = 0, len = specialCallbacks.length; i < len; ++i) {
if (specialCallbacks[i]) {
specialCallbacks[i].apply(this, [event].concat(args));
} else {
break;
}
}
}
return this;
};
// Helper for for finding special wildcard event handlers that match the event
WildEmitter.prototype.getWildcardCallbacks = function (eventName) {
var item,
split,
result = [];
for (item in this.callbacks) {
split = item.split('*');
if (item === '*' || (split.length === 2 && eventName.slice(0, split[1].length) === split[1])) {
result = result.concat(this.callbacks[item]);
}
}
return result;
};
},{}],3:[function(require,module,exports){
(function(window) {
var logger = require('andlog'),
goldenRatio = 0.618033988749895,
hue = 0,
padLength = 15,
yieldColor,
bows;
yieldColor = function() {
hue += goldenRatio;
hue = hue % 1;
return hue * 360;
};
bows = function(str) {
var msg;
msg = "%c" + (str.slice(0, padLength));
msg += Array(padLength + 3 - msg.length).join(' ') + '|';
return logger.log.bind(logger, msg, "color: hsl(" + (yieldColor()) + ",99%,40%); font-weight: bold");
};
bows.config = function(config) {
if (config.padLength) {
return padLength = config.padLength;
}
};
if (typeof module !== 'undefined') {
module.exports = bows;
} else {
window.bows = bows;
}
}).call(this);
},{"andlog":7}],7:[function(require,module,exports){
// follow @HenrikJoreteg and @andyet if you like this ;)
(function () {
var inNode = typeof window === 'undefined',
ls = !inNode && window.localStorage,
out = {};
if (inNode) {
module.exports = console;
return;
}
if (ls && ls.debug && window.console) {
out = window.console;
} else {
var methods = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),
l = methods.length,
fn = function () {};
while (l--) {
out[methods[l]] = fn;
}
}
if (typeof exports !== 'undefined') {
module.exports = out;
} else {
window.console = out;
}
})();
},{}]},{},[1])
; | mit |
catarse/catarse_admin | legacy/src/vms/payments-list-vm.js | 313 | import h from '../h';
import { commonPayment } from '../api';
import models from '../models';
export const getPaymentsListVM = () => {
const listVM = commonPayment.paginationVM(models.commonPayments, 'created_at.desc', { Prefer: 'count=exact' });
return h.createBasicPaginationVMWithAutoRedraw(listVM);
} | mit |
assunluis80/Web-Starter-Template | assets/scripts/vendors/kendo_ui/cultures/kendo.culture.km-KH.js | 3401 | /**
* Copyright 2015 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["km-KH"] = {
name: "km-KH",
numberFormat: {
pattern: ["- n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,0],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,0],
symbol: "%"
},
currency: {
name: "Riel",
abbr: "KHR",
pattern: ["-n$","n$"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "៛"
}
},
calendars: {
standard: {
days: {
names: ["ថ្ងៃអាទិត្យ","ថ្ងៃច័ន្ទ","ថ្ងៃអង្គារ","ថ្ងៃពុធ","ថ្ងៃព្រហស្បតិ៍","ថ្ងៃសុក្រ","ថ្ងៃសៅរ៍"],
namesAbbr: ["អាទិ.","ច.","អ.","ពុ","ព្រហ.","សុ.","ស."],
namesShort: ["អា","ច","អ","ពុ","ព","សុ","ស"]
},
months: {
names: ["មករា","កុម្ភៈ","មិនា","មេសា","ឧសភា","មិថុនា","កក្កដា","សីហា","កញ្ញា","តុលា","វិច្ឆិកា","ធ្នូ"],
namesAbbr: ["១","២","៣","៤","៥","៦","៧","៨","៩","១០","១១","១២"]
},
AM: ["ព្រឹក","ព្រឹក","ព្រឹក"],
PM: ["ល្ងាច","ល្ងាច","ល្ងាច"],
patterns: {
d: "dd/MM/yy",
D: "d MMMM yyyy",
F: "d MMMM yyyy HH:mm:ss",
g: "dd/MM/yy H:mm",
G: "dd/MM/yy HH:mm:ss",
m: "d MMMM",
M: "d MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "'ខែ' MM 'ឆ្នាំ' yyyy",
Y: "'ខែ' MM 'ឆ្នាំ' yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | mit |
unaio/una | upgrade/files/11.0.2-11.0.3/files/template/scripts/BxBaseMenuMoreAuto.php | 4243 | <?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup UnaBaseView UNA Base Representation Classes
*
* @{
*/
define('BX_DEF_MENU_ITEM_MORE_AUTO', 'more-auto');
class BxBaseMenuMoreAuto extends BxTemplMenu
{
protected $_sTmplNameItemMore;
protected $_sTmplNameItemMorePopup;
protected $_bMoreAuto;
protected $_iMoreAutoItemsStatic;
protected $_bMoreAutoItemsStaticOnly;
protected $_sJsObjectMoreAuto;
protected $_aHtmlIds;
public function __construct($aObject, $oTemplate = false)
{
parent::__construct($aObject, $oTemplate);
$this->_sTmplNameItemMore = 'menu_item_more.html';
$this->_sTmplNameItemMorePopup = 'menu_item_more_popup.html';
$this->_bMoreAuto = null;
$this->_iMoreAutoItemsStatic = 1;
$this->_bMoreAutoItemsStaticOnly = false;
$this->_sJsObjectMoreAuto = 'oMenuMoreAuto' . bx_gen_method_name($this->_sObject);
$sPrefix = str_replace('_', '-', $this->_sObject);
$this->_aHtmlIds = array(
'main' => $sPrefix,
'more_auto_popup' => $sPrefix . '-ma-popup',
);
}
public function getCode()
{
$sResult = parent::getCode();
if($this->_isMoreAuto()) {
$this->_oTemplate->addJs(array('BxDolMenuMoreAuto.js'));
if(!empty($sResult))
$sResult = $this->_oTemplate->parseHtmlByName('menu_more_auto.html', array(
'menu' => $sResult
));
}
return $sResult;
}
protected function _isMoreAuto()
{
if(is_bool($this->_bMoreAuto))
return $this->_bMoreAuto;
$aResult = $this->getMenuItems();
$sItem = BX_DEF_MENU_ITEM_MORE_AUTO;
if(!empty($this->_aObject['menu_items'][$sItem]) && is_array($this->_aObject['menu_items'][$sItem]) && (int)$this->_aObject['menu_items'][$sItem]['active'] == 1)
$this->_bMoreAuto = true;
else
$this->_bMoreAuto = false;
return $this->_bMoreAuto;
}
protected function _getTemplateVars()
{
$bMoreAuto = $this->_isMoreAuto();
$aResult = array_merge(parent::_getTemplateVars(), array(
'html_id' => $this->_getHtmlIdMain(),
'bx_if:show_more_auto_class' => array(
'condition' => $bMoreAuto,
'content' => array()
),
'js_code' => $bMoreAuto ? $this->_getJsCodeMoreAuto() : ''
));
return $aResult;
}
protected function _getJsCodeMoreAuto()
{
$sJsObject = $this->_getJsObjectMoreAuto();
$aJsParams = array(
'sObject' => $this->_sObject,
'iItemsStatic' => $this->_iMoreAutoItemsStatic,
'bItemsStaticOnly' => $this->_bMoreAutoItemsStaticOnly ? 1 : 0,
'aHtmlIds' => $this->_getHtmlIds()
);
return $this->_oTemplate->_wrapInTagJsCode("if(!" . $sJsObject . ") {var " . $sJsObject . " = new BxDolMenuMoreAuto(" . json_encode($aJsParams) . "); " . $sJsObject . ".init();}");
}
protected function _getMenuItem ($aItem)
{
$aItem['popup'] = '';
if($aItem['name'] != BX_DEF_MENU_ITEM_MORE_AUTO)
return parent::_getMenuItem($aItem);
$aItem['onclick'] = $this->_getJsObjectMoreAuto() . '.more(this);';
$aItem['popup'] = BxTemplFunctions::getInstance()->transBox($this->_aHtmlIds['more_auto_popup'], $this->_oTemplate->parseHtmlByName($this->_getTmplNameItemMorePopup(), array(
'content' => ''
)), true);
return parent::_getMenuItem($aItem);
}
protected function _getHtmlIds()
{
return $this->_aHtmlIds;
}
protected function _getHtmlIdMain()
{
return $this->_aHtmlIds['main'];
}
protected function _getJsObjectMoreAuto()
{
return $this->_sJsObjectMoreAuto;
}
protected function _getTmplNameItemMore()
{
return $this->_sTmplNameItemMore;
}
protected function _getTmplNameItemMorePopup()
{
return $this->_sTmplNameItemMorePopup;
}
}
/** @} */
| mit |
RLReed/libdetran | src/geometry/test/test_Segment.cc | 1144 | //----------------------------------*-C++-*----------------------------------//
/*!
* \file test_Segment.cc
* \author Jeremy Roberts
* \date Jun 22, 2012
* \brief Test of Segment class
* \note Copyright (C) 2012 Jeremy Roberts.
*/
//---------------------------------------------------------------------------//
// LIST OF TEST FUNCTIONS
#define TEST_LIST \
FUNC(test_Segment)
// Detran headers
#include "TestDriver.hh"
#include "Segment.hh"
// Setup
/* ... */
using namespace detran_geometry;
using namespace detran_utilities;
using namespace detran_test;
using namespace std;
int main(int argc, char *argv[])
{
RUN(argc, argv);
}
//----------------------------------------------//
// TEST DEFINITIONS
//----------------------------------------------//
int test_Segment(int argc, char *argv[])
{
Segment s(0, 1.0);
TEST(s.region() == 0);
TEST(soft_equiv(s.length(), 1.0));
return 0;
}
//---------------------------------------------------------------------------//
// end of test_Segment.cc
//---------------------------------------------------------------------------//
| mit |
gale9010/f3f-timer | usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/SerialInputOutputManager.java | 5726 | /* Copyright 2011-2013 Google Inc.
* Copyright 2013 mike wakerly <opensource@hoho.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* Project home page: https://github.com/mik3y/usb-serial-for-android
*/
package com.hoho.android.usbserial.util;
import android.hardware.usb.UsbRequest;
import android.util.Log;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Utility class which services a {@link UsbSerialPort} in its {@link #run()}
* method.
*
* @author mike wakerly (opensource@hoho.com)
*/
public class SerialInputOutputManager implements Runnable {
private static final String TAG = SerialInputOutputManager.class.getSimpleName();
private static final boolean DEBUG = true;
private static final int READ_WAIT_MILLIS = 200;
private static final int BUFSIZ = 4096;
private final UsbSerialPort mDriver;
private final ByteBuffer mReadBuffer = ByteBuffer.allocate(BUFSIZ);
// Synchronized by 'mWriteBuffer'
private final ByteBuffer mWriteBuffer = ByteBuffer.allocate(BUFSIZ);
private enum State {
STOPPED,
RUNNING,
STOPPING
}
// Synchronized by 'this'
private State mState = State.STOPPED;
// Synchronized by 'this'
private Listener mListener;
public interface Listener {
/**
* Called when new incoming data is available.
*/
public void onNewData(byte[] data);
/**
* Called when {@link SerialInputOutputManager#run()} aborts due to an
* error.
*/
public void onRunError(Exception e);
}
/**
* Creates a new instance with no listener.
*/
public SerialInputOutputManager(UsbSerialPort driver) {
this(driver, null);
}
/**
* Creates a new instance with the provided listener.
*/
public SerialInputOutputManager(UsbSerialPort driver, Listener listener) {
mDriver = driver;
mListener = listener;
}
public synchronized void setListener(Listener listener) {
mListener = listener;
}
public synchronized Listener getListener() {
return mListener;
}
public void writeSync(byte[] data) {
synchronized (mWriteBuffer) {
mWriteBuffer.put(data);
}
}
public void writeAsync(byte[] data) throws IOException {
mDriver.write(data, READ_WAIT_MILLIS);
}
public synchronized void stop() {
if (getState() == State.RUNNING) {
Log.i(TAG, "Stop requested");
mState = State.STOPPING;
}
}
private synchronized State getState() {
return mState;
}
/**
* Continuously services the read and write buffers until {@link #stop()} is
* called, or until a driver exception is raised.
*
* NOTE(mikey): Uses inefficient read/write-with-timeout.
* TODO(mikey): Read asynchronously with {@link UsbRequest#queue(ByteBuffer, int)}
*/
@Override
public void run() {
synchronized (this) {
if (getState() != State.STOPPED) {
throw new IllegalStateException("Already running.");
}
mState = State.RUNNING;
}
Log.i(TAG, "Running ..");
try {
while (true) {
if (getState() != State.RUNNING) {
Log.i(TAG, "Stopping mState=" + getState());
break;
}
step();
}
} catch (Exception e) {
Log.w(TAG, "Run ending due to exception: " + e.getMessage(), e);
final Listener listener = getListener();
if (listener != null) {
listener.onRunError(e);
}
} finally {
synchronized (this) {
mState = State.STOPPED;
Log.i(TAG, "Stopped.");
}
}
}
private void step() throws IOException {
// Handle incoming data.
int len = mDriver.read(mReadBuffer.array(), READ_WAIT_MILLIS);
if (len > 0) {
if (DEBUG) Log.d(TAG, "Read data len=" + len);
final Listener listener = getListener();
if (listener != null) {
final byte[] data = new byte[len];
mReadBuffer.get(data, 0, len);
listener.onNewData(data);
}
mReadBuffer.clear();
}
// Handle outgoing data.
byte[] outBuff = null;
synchronized (mWriteBuffer) {
len = mWriteBuffer.position();
if (len > 0) {
outBuff = new byte[len];
mWriteBuffer.rewind();
mWriteBuffer.get(outBuff, 0, len);
mWriteBuffer.clear();
}
}
if (outBuff != null) {
if (DEBUG) {
Log.d(TAG, "Writing data len=" + len);
}
mDriver.write(outBuff, READ_WAIT_MILLIS);
}
}
}
| mit |
GeorgioWan/bonsaiERP | app/helpers/tags_helper.rb | 315 | module TagsHelper
# Presents a list for json
def tags_list
@tags_list ||= Tag.list.order("name").map { |val|
{ id: val.id, name: val.name, label: val.to_s, bgcolor: val.bgcolor }
}
end
def tags_list_hash
@tags_list_hash ||= Hash[tags_list.map { |el|
[el[:id], el]
}]
end
end
| mit |
navalev/azure-sdk-for-java | sdk/cosmosdb/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/cosmosdb/v2019_08_01/implementation/CollectionPartitionRegionsInner.java | 11156 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.cosmosdb.v2019_08_01.implementation;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.CloudException;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in CollectionPartitionRegions.
*/
public class CollectionPartitionRegionsInner {
/** The Retrofit service to perform REST calls. */
private CollectionPartitionRegionsService service;
/** The service client containing this operation class. */
private CosmosDBImpl client;
/**
* Initializes an instance of CollectionPartitionRegionsInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public CollectionPartitionRegionsInner(Retrofit retrofit, CosmosDBImpl client) {
this.service = retrofit.create(CollectionPartitionRegionsService.class);
this.client = client;
}
/**
* The interface defining all the services for CollectionPartitionRegions to be
* used by Retrofit to perform actually REST calls.
*/
interface CollectionPartitionRegionsService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.cosmosdb.v2019_08_01.CollectionPartitionRegions listMetrics" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/region/{region}/databases/{databaseRid}/collections/{collectionRid}/partitions/metrics")
Observable<Response<ResponseBody>> listMetrics(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("region") String region, @Path("databaseRid") String databaseRid, @Path("collectionRid") String collectionRid, @Query("api-version") String apiVersion, @Query("$filter") String filter, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Retrieves the metrics determined by the given filter for the given collection and region, split by partition.
*
* @param resourceGroupName Name of an Azure resource group.
* @param accountName Cosmos DB database account name.
* @param region Cosmos DB region, with spaces between words and each word capitalized.
* @param databaseRid Cosmos DB database rid.
* @param collectionRid Cosmos DB collection rid.
* @param filter An OData filter expression that describes a subset of metrics to return. The parameters that can be filtered are name.value (name of the metric, can have an or of multiple names), startTime, endTime, and timeGrain. The supported operator is eq.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the List<PartitionMetricInner> object if successful.
*/
public List<PartitionMetricInner> listMetrics(String resourceGroupName, String accountName, String region, String databaseRid, String collectionRid, String filter) {
return listMetricsWithServiceResponseAsync(resourceGroupName, accountName, region, databaseRid, collectionRid, filter).toBlocking().single().body();
}
/**
* Retrieves the metrics determined by the given filter for the given collection and region, split by partition.
*
* @param resourceGroupName Name of an Azure resource group.
* @param accountName Cosmos DB database account name.
* @param region Cosmos DB region, with spaces between words and each word capitalized.
* @param databaseRid Cosmos DB database rid.
* @param collectionRid Cosmos DB collection rid.
* @param filter An OData filter expression that describes a subset of metrics to return. The parameters that can be filtered are name.value (name of the metric, can have an or of multiple names), startTime, endTime, and timeGrain. The supported operator is eq.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<PartitionMetricInner>> listMetricsAsync(String resourceGroupName, String accountName, String region, String databaseRid, String collectionRid, String filter, final ServiceCallback<List<PartitionMetricInner>> serviceCallback) {
return ServiceFuture.fromResponse(listMetricsWithServiceResponseAsync(resourceGroupName, accountName, region, databaseRid, collectionRid, filter), serviceCallback);
}
/**
* Retrieves the metrics determined by the given filter for the given collection and region, split by partition.
*
* @param resourceGroupName Name of an Azure resource group.
* @param accountName Cosmos DB database account name.
* @param region Cosmos DB region, with spaces between words and each word capitalized.
* @param databaseRid Cosmos DB database rid.
* @param collectionRid Cosmos DB collection rid.
* @param filter An OData filter expression that describes a subset of metrics to return. The parameters that can be filtered are name.value (name of the metric, can have an or of multiple names), startTime, endTime, and timeGrain. The supported operator is eq.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the List<PartitionMetricInner> object
*/
public Observable<List<PartitionMetricInner>> listMetricsAsync(String resourceGroupName, String accountName, String region, String databaseRid, String collectionRid, String filter) {
return listMetricsWithServiceResponseAsync(resourceGroupName, accountName, region, databaseRid, collectionRid, filter).map(new Func1<ServiceResponse<List<PartitionMetricInner>>, List<PartitionMetricInner>>() {
@Override
public List<PartitionMetricInner> call(ServiceResponse<List<PartitionMetricInner>> response) {
return response.body();
}
});
}
/**
* Retrieves the metrics determined by the given filter for the given collection and region, split by partition.
*
* @param resourceGroupName Name of an Azure resource group.
* @param accountName Cosmos DB database account name.
* @param region Cosmos DB region, with spaces between words and each word capitalized.
* @param databaseRid Cosmos DB database rid.
* @param collectionRid Cosmos DB collection rid.
* @param filter An OData filter expression that describes a subset of metrics to return. The parameters that can be filtered are name.value (name of the metric, can have an or of multiple names), startTime, endTime, and timeGrain. The supported operator is eq.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the List<PartitionMetricInner> object
*/
public Observable<ServiceResponse<List<PartitionMetricInner>>> listMetricsWithServiceResponseAsync(String resourceGroupName, String accountName, String region, String databaseRid, String collectionRid, String filter) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (accountName == null) {
throw new IllegalArgumentException("Parameter accountName is required and cannot be null.");
}
if (region == null) {
throw new IllegalArgumentException("Parameter region is required and cannot be null.");
}
if (databaseRid == null) {
throw new IllegalArgumentException("Parameter databaseRid is required and cannot be null.");
}
if (collectionRid == null) {
throw new IllegalArgumentException("Parameter collectionRid is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
if (filter == null) {
throw new IllegalArgumentException("Parameter filter is required and cannot be null.");
}
return service.listMetrics(this.client.subscriptionId(), resourceGroupName, accountName, region, databaseRid, collectionRid, this.client.apiVersion(), filter, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<PartitionMetricInner>>>>() {
@Override
public Observable<ServiceResponse<List<PartitionMetricInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<PartitionMetricInner>> result = listMetricsDelegate(response);
List<PartitionMetricInner> items = null;
if (result.body() != null) {
items = result.body().items();
}
ServiceResponse<List<PartitionMetricInner>> clientResponse = new ServiceResponse<List<PartitionMetricInner>>(items, result.response());
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<PartitionMetricInner>> listMetricsDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<PartitionMetricInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<PartitionMetricInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| mit |
jroyal/drafthouse-seat-finder | vendor/github.com/ryanbradynd05/go-tmdb/lists_test.go | 976 | package tmdb
import (
. "gopkg.in/check.v1"
)
const oscarWinnerListID string = "509ec17b19c2950a0600050d"
func (s *TmdbSuite) TestGetListInfo(c *C) {
result, err := s.tmdb.GetListInfo(oscarWinnerListID)
s.baseTest(&result, err, c)
c.Assert(result.ID, Equals, oscarWinnerListID)
c.Assert(result.CreatedBy, Equals, "Travis Bell")
c.Assert(result.Iso639_1, Equals, "en")
c.Assert(result.ItemCount, Equals, 86)
c.Assert(result.Name, Equals, "Best Picture Winners - The Academy Awards")
}
func (s *TmdbSuite) TestGetListItemStatus(c *C) {
fightClubResult, err := s.tmdb.GetListItemStatus(oscarWinnerListID, 550)
s.baseTest(&fightClubResult, err, c)
c.Assert(fightClubResult.ID, Equals, oscarWinnerListID)
c.Assert(fightClubResult.ItemPresent, Equals, false)
argoResult, err := s.tmdb.GetListItemStatus(oscarWinnerListID, 68734)
s.baseTest(&argoResult, err, c)
c.Assert(argoResult.ID, Equals, oscarWinnerListID)
c.Assert(argoResult.ItemPresent, Equals, true)
}
| mit |
IOCoin/iocoin | src/qt/locale/bitcoin_af_ZA.ts | 108866 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="af_ZA" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About I/OCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>I/OCoin</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The I/OCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Dubbel-klik om die adres of etiket te wysig</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Skep 'n nuwe adres</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Maak 'n kopie van die huidige adres na die stelsel klipbord</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your I/OCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a I/OCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified I/OCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Verwyder</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Tik Wagwoord in</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nuwe wagwoord</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Herhaal nuwe wagwoord</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Tik die nuwe wagwoord vir die beursie in.<br/>Gebruik asseblief 'n wagwoord van <b>ten minste 10 ewekansige karakters</b>, of <b>agt (8) of meer woorde.</b></translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Enkripteer beursie</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Hierdie operasie benodig 'n wagwoord om die beursie oop te sluit.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Sluit beursie oop</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Hierdie operasie benodig 'n wagwoord om die beursie oop te sluit.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Sluit beursie oop</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Verander wagwoord</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Tik asseblief die ou en nuwe wagwoord vir die beursie in.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Bevestig beursie enkripsie.</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Die beursie is nou bewaak</translation>
</message>
<message>
<location line="-58"/>
<source>I/OCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Die beursie kon nie bewaak word nie</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Beursie bewaaking het misluk as gevolg van 'n interne fout. Die beursie is nie bewaak nie!</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Die wagwoord stem nie ooreen nie</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Beursie oopsluiting het misluk</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Die wagwoord wat ingetik was om die beursie oop te sluit, was verkeerd.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Beursie dekripsie het misluk</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+280"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+242"/>
<source>Synchronizing with network...</source>
<translation>Sinchroniseer met die netwerk ...</translation>
</message>
<message>
<location line="-308"/>
<source>&Overview</source>
<translation>&Oorsig</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Wys algemene oorsig van die beursie</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Transaksies</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Besoek transaksie geskiedenis</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>S&luit af</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Sluit af</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about I/OCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Wys inligting oor Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opsies</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+250"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-247"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Send coins to a I/OCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for I/OCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-200"/>
<source>I/OCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Beursie</translation>
</message>
<message>
<location line="+178"/>
<source>&About I/OCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>&File</source>
<translation>&Lêer</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Instellings</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Hulp</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Blad nutsbalk</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>I/OCoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to I/OCoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-284"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+288"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid I/OCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. I/OCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Maak kopie van adres</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Nuwe ontvangende adres</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nuwe stuurende adres</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Wysig ontvangende adres</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Wysig stuurende adres</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid I/OCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Kon nie die beursie oopsluit nie.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>I/OCoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opsies</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start I/OCoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start I/OCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the I/OCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the I/OCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting I/OCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show I/OCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting I/OCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Vorm</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the I/OCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Beursie</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Onlangse transaksies</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the I/OCoin-Qt help message to get a list with possible I/OCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>I/OCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>I/OCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the I/OCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the I/OCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Stuur Munstukke</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Bedrag:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 I/O</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Stuur aan vele ontvangers op eens</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Balans:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 I/O</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>S&tuur</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid I/OCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(geen etiket)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Teken boodskap</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this I/OCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified I/OCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a I/OCoin address (e.g. iphU6HbZCuDsx1nGWncuwxYdHcF74zLv8U)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter I/OCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Van</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Na</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>eie adres</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiket</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Krediet</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>nie aanvaar nie</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debiet</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaksie fooi</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Netto bedrag</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Boodskap</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaksie ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 110 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>waar</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>onwaar</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>onbekend</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipe</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Ontvang met</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ontvang van</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Gestuur na</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betalings Aan/na jouself</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Gemyn</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n.v.t)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Datum en tyd wat die transaksie ontvang was.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipe transaksie.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Alles</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Vandag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Hierdie week</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Hierdie maand</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Verlede maand</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Hierdie jaar</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Reeks...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Ontvang met</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Gestuur na</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Aan/na jouself</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Gemyn</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Ander</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Min bedrag</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Maak kopie van adres</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopieer bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipe</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Reeks:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>aan</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>I/OCoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Gebruik:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or iocoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Opsies:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: iocoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: iocoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Onderhou op die meeste <n> konneksies na eweknieë (standaard: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Gebruik die toets netwerk</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong I/OCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=iocoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "I/OCoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Hierdie help boodskap</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. I/OCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>I/OCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Laai adresse...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of I/OCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart I/OCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Ongeldige bedrag</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Onvoldoende fondse</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Laai blok indeks...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. I/OCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Laai beursie...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Klaar gelaai</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Fout</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS> | mit |
samgreenwood/swapshop | app/views/users/show.blade.php | 1440 | @extends('layouts.master')
@section('content')
<h1>My Swapshop</h1>
<div class="row-fluid">
<div class="span6">
<h2>Listings</h2>
<table class='table table-first-column-number data-table display full dataTable'>
<thead>
<tr>
<th style="padding-left: 1em;">#</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Operations</th>
</tr>
</thead>
<tbody>
@foreach(Auth::user()->listings as $listing)
<tr>
<td>{{$listing->id}}</td>
<td>{{$listing->product->name}}</td>
<td>{{$listing->price}}</td>
<td>{{$listing->quantity}}</td>
<td>{{Html::linkRoute('manufacturers.products.listings.edit','Edit',[$listing->product->manufacturer->id, $listing->product->id, $listing->id])}} | Delete</td>
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="span6">
<h2>Purchases</h2>
<table class='table table-first-column-number data-table display full dataTable'>
<thead>
<tr>
<th style="padding-left: 1em;">#</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
@foreach(Auth::user()->purchases as $purchase)
<tr>
<td>{{$purchase->id}}</td>
<td>{{$purchase->listing->product->name}}</td>
<td>${{number_format($purchase->listing->price,2)}}</td>
<td>{{$purchase->quantity}}</td>
<td>${{ number_format($purchase->quantity * $purchase->listing->price,2) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
@stop
| mit |
dwbutler/logstash-logger | lib/logstash-logger.rb | 267 | require 'logstash-logger/version'
require 'logstash/event'
require 'logstash-logger/device'
require 'logstash-logger/logger'
require 'logstash-logger/formatter'
require 'logstash-logger/configuration'
require 'logstash-logger/railtie' if defined?(Rails::Railtie)
| mit |
cssinjs/jss | packages/jss/benchmark/tests/add-rule.js | 432 | import {create, sheets} from 'jss'
import styles from '../fixtures/regular.json'
function teardown() {
this.sheet.detach()
this.sheets.reset()
delete this.sheet
}
suite('Add rule', () => {
benchmark(
'.insertRule()',
function benchmark() {
this.sheets = sheets
this.sheet = this.sheet || create().createStyleSheet().attach()
this.sheet.addRule('modal', styles.modal)
},
{teardown}
)
})
| mit |
Diullei/Storm | Storm.Test/SputnikV1/11_Expressions/11.13_Assignment_Operators/11.13.2_Compound_Assignment/S11.13.2_A4.5_T2.1.js | 1514 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.13.2_A4.5_T2.1;
* @section: 11.13.2, 11.6.2;
* @assertion: The production x -= y is the same as x = x - y;
* @description: Type(x) is different from Type(y) and both types vary between Number (primitive or object) and Boolean (primitive and object);
*/
//CHECK#1
x = true;
x -= 1;
if (x !== 0) {
$ERROR('#1: x = true; x -= 1; x === 0. Actual: ' + (x));
}
//CHECK#2
x = 1;
x -= true;
if (x !== 0) {
$ERROR('#2: x = 1; x -= true; x === 0. Actual: ' + (x));
}
//CHECK#3
x = new Boolean(true);
x -= 1;
if (x !== 0) {
$ERROR('#3: x = new Boolean(true); x -= 1; x === 0. Actual: ' + (x));
}
//CHECK#4
x = 1;
x -= new Boolean(true);
if (x !== 0) {
$ERROR('#4: x = 1; x -= new Boolean(true); x === 0. Actual: ' + (x));
}
//CHECK#5
x = true;
x -= new Number(1);
if (x !== 0) {
$ERROR('#5: x = true; x -= new Number(1); x === 0. Actual: ' + (x));
}
//CHECK#6
x = new Number(1);
x -= true;
if (x !== 0) {
$ERROR('#6: x = new Number(1); x -= true; x === 0. Actual: ' + (x));
}
//CHECK#7
x = new Boolean(true);
x -= new Number(1);
if (x !== 0) {
$ERROR('#7: x = new Boolean(true); x -= new Number(1); x === 0. Actual: ' + (x));
}
//CHECK#8
x = new Number(1);
x -= new Boolean(true);
if (x !== 0) {
$ERROR('#8: x = new Number(1); x -= new Boolean(true); x === 0. Actual: ' + (x));
}
| mit |
vlfedotov/django-business-logic | business_logic/models/stop.py | 634 | # -*- coding: utf-8 -*-
#
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..exceptions import StopInterpretationException, BreakLoopException
class StopInterpretation(models.Model):
class Meta:
verbose_name = _('Stop instruction')
verbose_name_plural = _('Stop instructions')
def interpret(self, ctx):
raise StopInterpretationException()
class BreakLoop(models.Model):
class Meta:
verbose_name = _('Break instruction')
verbose_name_plural = _('Break instructions')
def interpret(self, ctx):
raise BreakLoopException()
| mit |
rterp/LimitUpTrading | commons/interactive-brokers-integration-tests/src/main/java/com/sumzerotrading/broker/ib/MainClass.java | 2787 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sumzerotrading.broker.ib;
import com.sumzerotrading.broker.order.OrderEvent;
import com.sumzerotrading.broker.order.OrderEventListener;
import com.sumzerotrading.broker.order.TradeDirection;
import com.sumzerotrading.broker.order.TradeOrder;
import com.sumzerotrading.data.StockTicker;
import com.sumzerotrading.data.Ticker;
import com.sumzerotrading.ib.IBConnectionUtil;
import com.sumzerotrading.ib.IBSocket;
import com.sumzerotrading.marketdata.ILevel1Quote;
import com.sumzerotrading.marketdata.Level1QuoteListener;
import com.sumzerotrading.marketdata.ib.IBQuoteEngine;
import static java.lang.Thread.sleep;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author RobTerpilowski
*/
public class MainClass implements OrderEventListener, Level1QuoteListener {
@Override
public void quoteRecieved(ILevel1Quote quote) {
System.out.println("Quote: " + quote);
}
public void start() throws Exception {
IBConnectionUtil util = new IBConnectionUtil("localhost", 7999, 1);
IBSocket socket;
InteractiveBrokersBroker broker;
List<OrderEvent> eventList = new ArrayList<>();
Ticker qqqTicker = new StockTicker("QQQ");
socket = util.getIBSocket();
broker = new InteractiveBrokersBroker(socket);
broker.addOrderEventListener(this);
broker.connect();
IBQuoteEngine ibQuoteEngine = new IBQuoteEngine(socket);
ibQuoteEngine.startEngine();
ibQuoteEngine.subscribeLevel1(qqqTicker, this);
String orderId = broker.getNextOrderId();
System.out.println("Order id: " + orderId);
TradeOrder order = new TradeOrder(orderId, qqqTicker, 100, TradeDirection.BUY);
broker.placeOrder(order);
Thread thread = new Thread(() -> {
sleep(10000);
String orderId2 = broker.getNextOrderId();
System.out.println("Order id: " + orderId);
TradeOrder order2 = new TradeOrder(orderId2, qqqTicker, 200, TradeDirection.BUY);
broker.placeOrder(order2);
new Thread(() -> {
sleep(20000);
System.exit(0);
}).start();
});
thread.start();
}
@Override
public void orderEvent(OrderEvent event) {
System.out.println("Event: " + event);
}
public void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (Exception ex) {
}
}
public static void main(String[] args) throws Exception {
new MainClass().start();
}
}
| mit |
michaelgeorgeattard/ionic-app-scripts | src/webpack/common-chunks-plugins.spec.ts | 3190 | import * as commonChunksPlugins from './common-chunks-plugins';
import { join } from 'path';
describe('common-chunks-plugins', () => {
describe('checkIfModuleIsIonicDependency', () => {
it('should return false when userRequest is null', () => {
const result = commonChunksPlugins.checkIfModuleIsIonicDependency({});
expect(result).toEqual(false);
});
it('should return false when userRequest is an unknown 3rd party module', () => {
const result = commonChunksPlugins.checkIfModuleIsIonicDependency({
userRequest: join(commonChunksPlugins.NODE_MODULES, 'moment', 'index.js')
});
expect(result).toEqual(false);
});
it('should return true when userRequest is an known 3rd party module', () => {
const angularResult = commonChunksPlugins.checkIfModuleIsIonicDependency({
userRequest: join(commonChunksPlugins.ANGULAR, 'src', 'something.js')
});
const rxjsResult = commonChunksPlugins.checkIfModuleIsIonicDependency({
userRequest: join(commonChunksPlugins.RXJS, 'src', 'something.js')
});
const ionicResult = commonChunksPlugins.checkIfModuleIsIonicDependency({
userRequest: join(commonChunksPlugins.IONIC, 'src', 'something.js')
});
const zoneResult = commonChunksPlugins.checkIfModuleIsIonicDependency({
userRequest: join(commonChunksPlugins.ZONEJS, 'src', 'something.js')
});
expect(angularResult).toEqual(true);
expect(rxjsResult).toEqual(true);
expect(ionicResult).toEqual(true);
expect(zoneResult).toEqual(true);
});
});
describe('checkIfModuleIsNodeModuleButNotIonicDepenedency', () => {
it('should return false when userRequest is null', () => {
const result = commonChunksPlugins.checkIfModuleIsNodeModuleButNotIonicDepenedency({});
expect(result).toEqual(false);
});
it('should return true when userRequest is an unknown 3rd party module', () => {
const result = commonChunksPlugins.checkIfModuleIsNodeModuleButNotIonicDepenedency({
userRequest: join(commonChunksPlugins.NODE_MODULES, 'moment', 'index.js')
});
expect(result).toEqual(true);
});
it('should return false when userRequest is a known 3rd party module', () => {
const angularResult = commonChunksPlugins.checkIfModuleIsNodeModuleButNotIonicDepenedency({
userRequest: join(commonChunksPlugins.ANGULAR, 'src', 'something.js')
});
const rxjsResult = commonChunksPlugins.checkIfModuleIsNodeModuleButNotIonicDepenedency({
userRequest: join(commonChunksPlugins.RXJS, 'src', 'something.js')
});
const ionicResult = commonChunksPlugins.checkIfModuleIsNodeModuleButNotIonicDepenedency({
userRequest: join(commonChunksPlugins.IONIC, 'src', 'something.js')
});
const zoneResult = commonChunksPlugins.checkIfModuleIsNodeModuleButNotIonicDepenedency({
userRequest: join(commonChunksPlugins.ZONEJS, 'src', 'something.js')
});
expect(angularResult).toEqual(false);
expect(rxjsResult).toEqual(false);
expect(ionicResult).toEqual(false);
expect(zoneResult).toEqual(false);
});
});
});
| mit |
bburnichon/PHPExiftool | lib/PHPExiftool/Driver/Tag/DICOM/T2Preparation.php | 791 | <?php
/*
* This file is part of the PHPExifTool package.
*
* (c) Alchemy <support@alchemy.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class T2Preparation extends AbstractTag
{
protected $Id = '0018,9021';
protected $Name = 'T2Preparation';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'T2 Preparation';
}
| mit |
ARIES-IIT-R/Smart-Mirror | identify.py | 3978 | import cv2
import sys
import os
import time
from PIL import Image
import glob
import csv
import string
import random
import imageUpload as imup
import MSFaceAPI as msface
baseDir = '/home/aishwarya/Documents/Smart-Mirror/'
tmpDir = '/home/aishwarya/Documents/Smart-Mirror/tmp/'
cloudinary_dataset = 'http://res.cloudinary.com/aish/image/upload/v1488457817/SmartMirror/dataset/'
cloudinary_tmp = 'http://res.cloudinary.com/aish/image/upload/v1488457817/SmartMirror/tmp/'
# for capturing the faces using opencv and store the cropped face image in dataset directory
def face_capture(imgPath):
# Camera 0 is the integrated web cam on my netbook
camera_port = 1
cascPath = 'haarcascade_frontalface_default.xml'
faceCascade = cv2.CascadeClassifier(cascPath)
#Number of frames to throw away while the camera adjusts to light levels
ramp_frames = 50
cam = cv2.VideoCapture(camera_port)
face_cnt=0;
while True:
for i in xrange(ramp_frames):
s, im = cam.read()
print("Taking image... ")
ret,image = cam.read()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(120, 120),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
# Draw a rectangle around the faces
max_area = 0
mx = 0
my = 0
mh = 0
mw = 0
for (x, y, w, h) in faces:
#cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
if w*h > max_area:
mx = x
my = y
mh = h
mw = w
max_area=w*h
cv2.imshow('Video', image)
image_crop = image[my:my+mh,mx:mx+mw]
cv2.imwrite(imgPath, image_crop)
face_cnt=face_cnt+1
if face_cnt==1:
break
# When everything is done, release the capture
cam.release()
cv2.destroyAllWindows()
def face_upload(imgPath,fileName):
try:
print 'Uploading...'
imup.upload_image(imgPath,fileName)
except Exception as e:
print("Error: %s" % e.message)
def face_identify(imageUrl):
faceId=''
personId=''
personName=''
try:
faceId=msface.face_detect(imageUrl)
except Exception as e:
print("Error: %s" % e.message)
if faceId=='':
return personName
try:
personId=msface.face_identify(faceId)
except Exception as e:
print("Error: %s" % e.message)
if personId=='':
return personName
with open('users.csv', "rb") as f:
rd = csv.reader(f,delimiter=',')
cnt=0
for r in rd:
if cnt>0:
if personId==r[0]:
personName=r[1]
return personName
cnt=cnt+1
def id_generator(size=20, chars=string.ascii_lowercase + string.digits + string.ascii_uppercase):
return ''.join(random.choice(chars) for _ in range(size))
if __name__ == '__main__':
imageName=id_generator()+'.jpg'
print('file name %s' % imageName)
imgPath=tmpDir+imageName
imgUrl=cloudinary_tmp+imageName
try:
print('Face Capturing Started')
face_capture(imgPath)
print('Face Capturing Completed')
except Exception as e:
print("Error: %s" % e.message)
try:
print('Uploading Started')
face_upload(imgPath, imageName)
print('Upload Completed')
except Exception as e:
print("Error: %s" % e.message)
try:
print('Face Identification Started')
pname=face_identify(imgUrl)
print('Face Identification Completed')
print('Face Identified as: %s' % pname)
except Exception as e:
print("Error: %s" % e.message)
| mit |
mockingbirdnest/Principia | base/bundle.hpp | 2234 |
#pragma once
#include <functional>
#include <list>
#include <optional>
#include <thread>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/status/status.h"
#include "absl/synchronization/notification.h"
#include "absl/synchronization/mutex.h"
namespace principia {
namespace base {
// A bundle manages a number of threads that execute independently. A thread is
// created for each call to |Add|. When one of the |Join*| is called, no more
// calls to |Add| are allowed, and |Join*| returns the first error status (if
// any) produced by the tasks.
class Bundle final {
public:
using Task = std::function<absl::Status()>;
// If a |task| returns an erroneous |absl::Status|, |Join| returns that
// status.
void Add(Task task) LOCKS_EXCLUDED(lock_);
// Returns the first non-OK status encountered, or OK. All worker threads are
// joined; no calls to member functions may follow this call.
absl::Status Join() LOCKS_EXCLUDED(lock_, status_lock_);
// Same as above, but returns a |kDeadlineExceeded| status if it fails to
// complete within the given interval.
absl::Status JoinWithin(std::chrono::steady_clock::duration Δt)
LOCKS_EXCLUDED(lock_, status_lock_);
// Same as above with absolute time.
absl::Status JoinBefore(std::chrono::system_clock::time_point t)
LOCKS_EXCLUDED(lock_, status_lock_);
private:
// Run on a separate thread to execute task and record its status.
void Toil(Task const& task) LOCKS_EXCLUDED(lock_, status_lock_);
void JoinAll() LOCKS_EXCLUDED(lock_);
absl::Mutex status_lock_;
absl::Status status_ GUARDED_BY(status_lock_);
absl::Mutex lock_;
// Whether |Join| has been called. When set to true, |Add| should not be
// called.
std::atomic_bool joining_ = false;
absl::Notification all_done_;
// The number of workers currently executing. Can only be incremented when
// |joining_| is false.
std::atomic_int number_of_active_workers_ = 0;
std::list<std::thread> workers_ GUARDED_BY(lock_);
static_assert(std::atomic_bool::is_always_lock_free, "bool not lock-free");
static_assert(std::atomic_int::is_always_lock_free, "int not lock-free");
};
} // namespace base
} // namespace principia
| mit |
Kriechi/pathod | test/test_app.py | 2906 | import tutils
class TestApp(tutils.DaemonTests):
SSL = False
def test_index(self):
r = self.getpath("/")
assert r.status_code == 200
assert r.content
def test_about(self):
r = self.getpath("/about")
assert r.ok
def test_download(self):
r = self.getpath("/download")
assert r.ok
def test_docs(self):
assert self.getpath("/docs/pathod").status_code == 200
assert self.getpath("/docs/pathoc").status_code == 200
assert self.getpath("/docs/language").status_code == 200
assert self.getpath("/docs/libpathod").status_code == 200
assert self.getpath("/docs/test").status_code == 200
def test_log(self):
assert self.getpath("/log").status_code == 200
assert self.get("200:da").status_code == 200
id = self.d.log()[0]["id"]
assert self.getpath("/log").status_code == 200
assert self.getpath("/log/%s" % id).status_code == 200
assert self.getpath("/log/9999999").status_code == 404
def test_log_binary(self):
assert self.get("200:h@10b=@10b:da")
def test_response_preview(self):
r = self.getpath("/response_preview", params=dict(spec="200"))
assert r.status_code == 200
assert 'Response' in r.content
r = self.getpath("/response_preview", params=dict(spec="foo"))
assert r.status_code == 200
assert 'Error' in r.content
r = self.getpath("/response_preview", params=dict(spec="200:b@100m"))
assert r.status_code == 200
assert "too large" in r.content
r = self.getpath("/response_preview", params=dict(spec="200:b@5k"))
assert r.status_code == 200
assert 'Response' in r.content
r = self.getpath(
"/response_preview",
params=dict(
spec="200:b<nonexistent"))
assert r.status_code == 200
assert 'File access denied' in r.content
r = self.getpath("/response_preview", params=dict(spec="200:b<file"))
assert r.status_code == 200
assert 'testfile' in r.content
def test_request_preview(self):
r = self.getpath("/request_preview", params=dict(spec="get:/"))
assert r.status_code == 200
assert 'Request' in r.content
r = self.getpath("/request_preview", params=dict(spec="foo"))
assert r.status_code == 200
assert 'Error' in r.content
r = self.getpath("/request_preview", params=dict(spec="get:/:b@100m"))
assert r.status_code == 200
assert "too large" in r.content
r = self.getpath("/request_preview", params=dict(spec="get:/:b@5k"))
assert r.status_code == 200
assert 'Request' in r.content
r = self.getpath("/request_preview", params=dict(spec=""))
assert r.status_code == 200
assert 'empty spec' in r.content
| mit |
Franky666/programmiersprachen-raytracer | external/boost_1_59_0/libs/test/doc/examples/example57.run-fail.cpp | 477 | // (C) Copyright Gennadiy Rozental 2011-2015.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//[example_code
#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE( test )
{
int i = 1;
int j = 4;
BOOST_CHECK_GE( i, j );
}
//]
| mit |
rollerworks/rollerworks-datagrid | src/DatagridView.php | 2684 | <?php
declare(strict_types=1);
/*
* This file is part of the RollerworksDatagrid package.
*
* (c) Sebastiaan Stok <s.stok@rollerscapes.net>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Rollerworks\Component\Datagrid;
use Rollerworks\Component\Datagrid\Column\HeaderView;
use Rollerworks\Component\Datagrid\Exception\InvalidArgumentException;
/**
* DatagridView provides all the information to render a Datagrid.
*
* This class should only be initialized be directly.
*
* @author Sebastiaan Stok <s.stok@rollerscapes.net>
*/
class DatagridView extends BaseView implements \IteratorAggregate, \Countable
{
/**
* READ-ONLY: The Datagrid name.
*
* @var string
*/
public $name;
/**
* READ-ONLY: The Datagrid Header views.
*
* @var HeaderView[]
*/
public $columns = [];
/**
* READ-ONLY: The Datagrid rows.
*
* @var DatagridRowView[]
*/
public $rows = [];
public function __construct(DatagridInterface $datagrid)
{
$this->name = $datagrid->getName();
}
/**
* Initialize the datagrid view.
*/
public function init(DatagridInterface $datagrid)
{
if (null === $data = $datagrid->getData()) {
throw new InvalidArgumentException('No data provided for the view.');
}
$columns = $datagrid->getColumns();
foreach ($columns as $column) {
$this->columns[$column->getName()] = $column->createHeaderView($this);
}
if (!isset($this->vars['row_vars'])) {
$this->vars['row_vars'] = [];
}
foreach ($data as $id => $value) {
$this->rows[$id] = $row = new DatagridRowView($this, $columns, $value, $id);
$row->vars = $this->vars['row_vars'];
}
}
public function hasColumn(string $name): bool
{
return isset($this->columns[$name]);
}
public function getColumn(string $name): HeaderView
{
if (isset($this->columns[$name])) {
return $this->columns[$name];
}
throw new InvalidArgumentException(sprintf('Column "%s" does not exist in datagrid.', $name));
}
/**
* Returns the number of elements in the collection.
*
* @return int
*/
public function count()
{
return count($this->rows);
}
/**
* Returns an iterator to iterate over rows (implements \IteratorAggregate).
*
* @return \ArrayIterator The iterator
*/
public function getIterator()
{
return new \ArrayIterator($this->rows);
}
}
| mit |
it-studio/centralnews | src/CentralNews/Exception/InvalidArgumentException.php | 98 | <?php
namespace CentralNews\Exception;
class InvalidArgumentException extends Exception
{
} | mit |
samsonasik/Slim | Slim/App.php | 16123 | <?php
/**
* Slim Framework (http://slimframework.com)
*
* @link https://github.com/codeguy/Slim
* @copyright Copyright (c) 2011-2015 Josh Lockhart
* @license https://github.com/codeguy/Slim/blob/master/LICENSE (MIT License)
*/
namespace Slim;
use Exception;
use Closure;
use InvalidArgumentException;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Interop\Container\ContainerInterface;
use FastRoute\Dispatcher;
use Slim\Exception\Exception as SlimException;
use Slim\Http\Uri;
use Slim\Http\Headers;
use Slim\Http\Body;
use Slim\Http\Request;
use Slim\Interfaces\Http\EnvironmentInterface;
use Slim\Interfaces\RouteGroupInterface;
use Slim\Interfaces\RouteInterface;
use Slim\Interfaces\RouterInterface;
/**
* App
*
* This is the primary class with which you instantiate,
* configure, and run a Slim Framework application.
* The \Slim\App class also accepts Slim Framework middleware.
*
* @property-read array $settings App settings
* @property-read EnvironmentInterface $environment
* @property-read RequestInterface $request
* @property-read ResponseInterface $response
* @property-read RouterInterface $router
* @property-read callable $errorHandler
* @property-read callable $notFoundHandler function($request, $response)
* @property-read callable $notAllowedHandler function($request, $response, $allowedHttpMethods)
*/
class App
{
use CallableResolverAwareTrait;
use MiddlewareAwareTrait {
add as addMiddleware;
}
/**
* Current version
*
* @var string
*/
const VERSION = '3.0.0';
/**
* Container
*
* @var ContainerInterface
*/
private $container;
/********************************************************************************
* Constructor
*******************************************************************************/
/**
* Create new application
*
* @param ContainerInterface|array $container Either a ContainerInterface or an associative array of application settings
* @throws InvalidArgumentException when no container is provided that implements ContainerInterface
*/
public function __construct($container = [])
{
if (is_array($container)) {
$container = new Container($container);
}
if (!$container instanceof ContainerInterface) {
throw new InvalidArgumentException('Expected a ContainerInterface');
}
$this->container = $container;
}
/**
* Enable access to the DI container by consumers of $app
*
* @return ContainerInterface
*/
public function getContainer()
{
return $this->container;
}
/**
* Add middleware
*
* This method prepends new middleware to the app's middleware stack.
*
* @param mixed $callable The callback routine
*
* @return static
*/
public function add($callable)
{
$callable = $this->resolveCallable($callable);
if ($callable instanceof Closure) {
$callable = $callable->bindTo($this->container);
}
return $this->addMiddleware($callable);
}
/********************************************************************************
* Container proxy methods
*******************************************************************************/
public function __get($name)
{
return $this->container->get($name);
}
public function __isset($name)
{
return $this->container->has($name);
}
/********************************************************************************
* Router proxy methods
*******************************************************************************/
/**
* Add GET route
*
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return \Slim\Interfaces\RouteInterface
*/
public function get($pattern, $callable)
{
return $this->map(['GET'], $pattern, $callable);
}
/**
* Add POST route
*
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return \Slim\Interfaces\RouteInterface
*/
public function post($pattern, $callable)
{
return $this->map(['POST'], $pattern, $callable);
}
/**
* Add PUT route
*
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return \Slim\Interfaces\RouteInterface
*/
public function put($pattern, $callable)
{
return $this->map(['PUT'], $pattern, $callable);
}
/**
* Add PATCH route
*
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return \Slim\Interfaces\RouteInterface
*/
public function patch($pattern, $callable)
{
return $this->map(['PATCH'], $pattern, $callable);
}
/**
* Add DELETE route
*
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return \Slim\Interfaces\RouteInterface
*/
public function delete($pattern, $callable)
{
return $this->map(['DELETE'], $pattern, $callable);
}
/**
* Add OPTIONS route
*
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return \Slim\Interfaces\RouteInterface
*/
public function options($pattern, $callable)
{
return $this->map(['OPTIONS'], $pattern, $callable);
}
/**
* Add route for any HTTP method
*
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return \Slim\Interfaces\RouteInterface
*/
public function any($pattern, $callable)
{
return $this->map(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], $pattern, $callable);
}
/**
* Add route with multiple methods
*
* @param string[] $methods Numeric array of HTTP method names
* @param string $pattern The route URI pattern
* @param mixed $callable The route callback routine
*
* @return RouteInterface
*/
public function map(array $methods, $pattern, $callable)
{
$callable = is_string($callable) ? $this->resolveCallable($callable) : $callable;
if ($callable instanceof Closure) {
$callable = $callable->bindTo($this);
}
$route = $this->container->get('router')->map($methods, $pattern, $callable);
if (is_callable([$route, 'setContainer'])) {
$route->setContainer($this->container);
}
if (is_callable([$route, 'setOutputBuffering'])) {
$route->setOutputBuffering($this->container->get('settings')['outputBuffering']);
}
return $route;
}
/**
* Route Groups
*
* This method accepts a route pattern and a callback. All route
* declarations in the callback will be prepended by the group(s)
* that it is in.
*
* @param string $pattern
* @param callable $callable
*
* @return RouteGroupInterface
*/
public function group($pattern, $callable)
{
/** @var RouteGroup $group */
$group = $this->container->get('router')->pushGroup($pattern, $callable);
$group->setContainer($this->container);
$group($this);
$this->container->get('router')->popGroup();
return $group;
}
/********************************************************************************
* Runner
*******************************************************************************/
/**
* Run application
*
* This method traverses the application middleware stack and then sends the
* resultant Response object to the HTTP client.
*
* @param bool|false $silent
* @return ResponseInterface
*/
public function run($silent = false)
{
// Finalize routes here for middleware stack
$this->container->get('router')->finalize();
$request = $this->container->get('request');
$response = $this->container->get('response');
// Dispatch the Router first if the setting for this is on
if ($this->container->get('settings')['determineRouteBeforeAppMiddleware'] === true) {
// Dispatch router (note: you won't be able to alter routes after this)
$request = $this->dispatchRouterAndPrepareRoute($request);
}
// Traverse middleware stack
try {
$response = $this->callMiddlewareStack($request, $response);
} catch (SlimException $e) {
$response = $e->getResponse();
} catch (Exception $e) {
/** @var callable $errorHandler */
$errorHandler = $this->container->get('errorHandler');
$response = $errorHandler($request, $response, $e);
}
$response = $this->finalize($response);
if (!$silent) {
$this->respond($response);
}
return $response;
}
/**
* Send the response the client
*
* @param ResponseInterface $response
*/
public function respond(ResponseInterface $response)
{
static $responded = false;
if (!$responded) {
// Send response
if (!headers_sent()) {
// Status
header(sprintf(
'HTTP/%s %s %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
));
// Headers
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
}
// Body
if (!$this->isEmptyResponse($response)) {
$body = $response->getBody();
$body->rewind();
$settings = $this->container->get('settings');
while (!$body->eof()) {
echo $body->read($settings['responseChunkSize']);
if (connection_status() != CONNECTION_NORMAL) {
break;
}
}
}
$responded = true;
}
}
/**
* Invoke application
*
* This method implements the middleware interface. It receives
* Request and Response objects, and it returns a Response object
* after compiling the routes registered in the Router and dispatching
* the Request object to the appropriate Route callback routine.
*
* @param ServerRequestInterface $request The most recent Request object
* @param ResponseInterface $response The most recent Response object
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
{
// Get the route info
$routeInfo = $request->getAttribute('routeInfo');
// If router hasn't been dispatched or the URI changed then dispatch
if (null === $routeInfo || ($routeInfo['request'] !== [$request->getMethod(), (string) $request->getUri()])) {
$request = $this->dispatchRouterAndPrepareRoute($request);
$routeInfo = $request->getAttribute('routeInfo');
}
if ($routeInfo[0] === Dispatcher::FOUND) {
return $routeInfo[1]($request, $response);
} elseif ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
/** @var callable $notAllowedHandler */
$notAllowedHandler = $this->container->get('notAllowedHandler');
return $notAllowedHandler($request, $response, $routeInfo[1]);
}
/** @var callable $notFoundHandler */
$notFoundHandler = $this->container->get('notFoundHandler');
return $notFoundHandler($request, $response);
}
/**
* Perform a sub-request from within an application route
*
* This method allows you to prepare and initiate a sub-request, run within
* the context of the current request. This WILL NOT issue a remote HTTP
* request. Instead, it will route the provided URL, method, headers,
* cookies, body, and server variables against the set of registered
* application routes. The result response object is returned.
*
* @param string $method The request method (e.g., GET, POST, PUT, etc.)
* @param string $path The request URI path
* @param string $query The request URI query string
* @param array $headers The request headers (key-value array)
* @param array $cookies The request cookies (key-value array)
* @param string $bodyContent The request body
* @param ResponseInterface $response The response object (optional)
* @return ResponseInterface
*/
public function subRequest($method, $path, $query = '', array $headers = [], array $cookies = [], $bodyContent = '', ResponseInterface $response = null)
{
$env = $this->container->get('environment');
$uri = Uri::createFromEnvironment($env)->withPath($path)->withQuery($query);
$headers = new Headers($headers);
$serverParams = $env->all();
$body = new Body(fopen('php://temp', 'r+'));
$body->write($bodyContent);
$body->rewind();
$request = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
if (!$response) {
$response = $this->container->get('response');
}
return $this($request, $response);
}
/**
* Dispatch the router to find the route. Prepare the route for use.
*
* @param ServerRequestInterface $request
* @return ServerRequestInterface
*/
protected function dispatchRouterAndPrepareRoute(ServerRequestInterface $request)
{
$routeInfo = $this->container->get('router')->dispatch($request);
if ($routeInfo[0] === Dispatcher::FOUND) {
$routeArguments = [];
foreach ($routeInfo[2] as $k => $v) {
$routeArguments[$k] = urldecode($v);
}
$routeInfo[1][0]->prepare($request, $routeArguments);
// add route to the request's attributes in case a middleware or handler needs access to the route
$request = $request->withAttribute('route', $routeInfo[1][0]);
}
$routeInfo['request'] = [$request->getMethod(), (string) $request->getUri()];
return $request->withAttribute('routeInfo', $routeInfo);
}
/**
* Finalize response
*
* @param ResponseInterface $response
* @return ResponseInterface
*/
protected function finalize(ResponseInterface $response)
{
if ($this->isEmptyResponse($response)) {
return $response->withoutHeader('Content-Type')->withoutHeader('Content-Length');
}
$size = $response->getBody()->getSize();
if ($size !== null) {
$response = $response->withHeader('Content-Length', (string) $size);
}
return $response;
}
/**
* Helper method, which returns true if the provided response must not output a body and false
* if the response could have a body.
*
* @see https://tools.ietf.org/html/rfc7231
*
* @param ResponseInterface $response
* @return bool
*/
protected function isEmptyResponse(ResponseInterface $response)
{
return in_array($response->getStatusCode(), [204, 205, 304]);
}
}
| mit |
YevgeniyShunevych/Atata | src/Atata/ContentSource.cs | 3028 | using OpenQA.Selenium;
namespace Atata
{
/// <summary>
/// Specifies the content source of a component.
/// </summary>
public enum ContentSource
{
/// <summary>
/// Uses <see cref="IWebElement.Text"/> property of component scope <see cref="IWebElement"/> element.
/// </summary>
Text,
/// <summary>
/// Uses <c>textContent</c> attribute of component scope <see cref="IWebElement"/> element.
/// </summary>
[Term("textContent")]
TextContent,
/// <summary>
/// Uses <c>innerHTML</c> attribute of component scope <see cref="IWebElement"/> element.
/// </summary>
[Term("Inner HTML")]
InnerHtml,
/// <summary>
/// Uses <c>value</c> attribute of component scope <see cref="IWebElement"/> element.
/// </summary>
Value,
/// <summary>
/// Uses the concatenation of child nested text values.
/// Executes the script that gets <c>childNodes</c> of component scope <see cref="IWebElement"/> element,
/// filters only <c>Node.TEXT_NODE</c> and concatenates the <c>textContent</c> values of these nodes.
/// </summary>
ChildTextNodes,
/// <summary>
/// Uses the concatenation of child nested text values trimming each text.
/// Executes the script that gets <c>childNodes</c> of component scope <see cref="IWebElement"/> element,
/// filters only <c>Node.TEXT_NODE</c>, gets <c>textContent</c> of each node, trims each value and concatenates them.
/// </summary>
ChildTextNodesTrimmed,
/// <summary>
/// Uses the concatenation of child nested text values trimming each text part and joining with <c>" "</c> separator.
/// Executes the script that gets <c>childNodes</c> of component scope <see cref="IWebElement"/> element,
/// filters only <c>Node.TEXT_NODE</c>, gets <c>textContent</c> of each node, trims each value and concatenates them delimiting with <c>" "</c> character.
/// </summary>
ChildTextNodesTrimmedAndSpaceJoined,
/// <summary>
/// Uses the first child nested text value.
/// Executes the script that gets <c>childNodes</c> of component scope <see cref="IWebElement"/> element,
/// finds the first <c>Node.TEXT_NODE</c> and returns the <c>textContent</c> value of this node.
/// Returns an empty string if there are no text nodes.
/// </summary>
FirstChildTextNode,
/// <summary>
/// Uses the last child nested text value.
/// Executes the script that gets <c>childNodes</c> of component scope <see cref="IWebElement"/> element,
/// finds the last <c>Node.TEXT_NODE</c> and returns the <c>textContent</c> value of this node.
/// Returns an empty string if there are no text nodes.
/// </summary>
LastChildTextNode
}
}
| mit |
NineWorlds/serenity-android | serenity-app/src/test/java/us/nineworlds/serenity/TestSerenityApplication.java | 3114 | /**
* The MIT License (MIT)
* Copyright (c) 2012 David Carver
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package us.nineworlds.serenity;
import android.content.SharedPreferences;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.birbit.android.jobqueue.JobManager;
import com.google.firebase.analytics.FirebaseAnalytics;
import java.lang.reflect.Method;
import org.greenrobot.eventbus.EventBus;
import org.robolectric.TestLifecycleApplication;
import toothpick.Scope;
import toothpick.Toothpick;
import us.nineworlds.serenity.common.annotations.InjectionConstants;
import us.nineworlds.serenity.core.logger.Logger;
import us.nineworlds.serenity.core.util.AndroidHelper;
import us.nineworlds.serenity.injection.modules.AndroidModule;
import us.nineworlds.serenity.injection.modules.LoginModule;
import us.nineworlds.serenity.injection.modules.SerenityModule;
import us.nineworlds.serenity.injection.modules.ExoplayerVideoModule;
import static org.mockito.Mockito.mock;
public class TestSerenityApplication extends SerenityApplication implements TestLifecycleApplication {
public TestSerenityApplication() {
super();
}
protected void inject() {
Scope scope = Toothpick.openScope(InjectionConstants.APPLICATION_SCOPE);
scope.installModules(new AndroidModule(this), new SerenityModule(), new LoginModule(), new ExoplayerVideoModule() );
jobManager = mock(JobManager.class);
androidHelper = mock(AndroidHelper.class);
preferences = scope.getInstance(SharedPreferences.class);
localBroadcastManager = scope.getInstance(LocalBroadcastManager.class);
logger = mock(Logger.class);
eventBus = mock(EventBus.class);
}
@Override public void onCreate() {
super.onCreate();
FirebaseAnalytics.getInstance(this).setAnalyticsCollectionEnabled(false);
}
@Override protected void discoverServers() {
}
@Override protected void setDefaultPreferences() {
}
@Override
public void afterTest(Method arg0) {
}
@Override
public void beforeTest(Method arg0) {
}
@Override
public void prepareTest(Object arg0) {
}
}
| mit |
basicincome/unpcoin-core | src/unpay-cli.cpp | 2737 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Copyright (c) 2009-2013 The Unpay developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "init.h"
#include "rpcclient.h"
#include "rpcprotocol.h"
#include "ui_interface.h" /* for _(...) */
#include "chainparams.h"
#include <boost/filesystem/operations.hpp>
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
static bool AppInitRPC(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try {
ReadConfigFile(mapArgs, mapMultiArgs);
} catch(std::exception &e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
if (argc<2 || mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to RPC client
std::string strUsage = _("Unpay Core RPC client version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" unpay-cli [options] <command> [params] " + _("Send command to Unpay Core") + "\n" +
" unpay-cli [options] help " + _("List commands") + "\n" +
" unpay-cli [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessageCli(true);
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
return true;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
try
{
if(!AppInitRPC(argc, argv))
return abs(RPC_MISC_ERROR);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInitRPC()");
return abs(RPC_MISC_ERROR);
} catch (...) {
PrintExceptionContinue(NULL, "AppInitRPC()");
return abs(RPC_MISC_ERROR);
}
int ret = abs(RPC_MISC_ERROR);
try
{
ret = CommandLineRPC(argc, argv);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
}
return ret;
}
| mit |
Mitali-Sodhi/CodeLingo | Dataset/cpp/VectorInsertAndErase.cpp | 1136 | //: C07:VectorInsertAndErase.cpp {-bor}
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Erasing an element from a vector.
//{L} Noisy
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
#include "Noisy.h"
using namespace std;
int main() {
vector<Noisy> v;
v.reserve(11);
cout << "11 spaces have been reserved" << endl;
generate_n(back_inserter(v), 10, NoisyGen());
ostream_iterator<Noisy> out(cout, " ");
cout << endl;
copy(v.begin(), v.end(), out);
cout << "Inserting an element:" << endl;
vector<Noisy>::iterator it =
v.begin() + v.size() / 2; // Middle
v.insert(it, Noisy());
cout << endl;
copy(v.begin(), v.end(), out);
cout << "\nErasing an element:" << endl;
// Cannot use the previous value of it:
it = v.begin() + v.size() / 2;
v.erase(it);
cout << endl;
copy(v.begin(), v.end(), out);
cout << endl;
} ///:~
| mit |
navalev/azure-sdk-for-java | sdk/network/mgmt-v2019_07_01/src/main/java/com/microsoft/azure/management/network/v2019_07_01/implementation/VirtualNetworkGatewayConnectionsInner.java | 146427 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_07_01.implementation;
import com.microsoft.azure.arm.collection.InnerSupportsGet;
import com.microsoft.azure.arm.collection.InnerSupportsDelete;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.management.network.v2019_07_01.ErrorException;
import com.microsoft.azure.management.network.v2019_07_01.TagsObject;
import com.microsoft.azure.management.network.v2019_07_01.VpnPacketCaptureStartParameters;
import com.microsoft.azure.management.network.v2019_07_01.VpnPacketCaptureStopParameters;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.PATCH;
import retrofit2.http.Path;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
import com.microsoft.azure.LongRunningFinalState;
import com.microsoft.azure.LongRunningOperationOptions;
import com.microsoft.azure.LongRunningFinalState;
import com.microsoft.azure.LongRunningOperationOptions;
/**
* An instance of this class provides access to all the operations defined
* in VirtualNetworkGatewayConnections.
*/
public class VirtualNetworkGatewayConnectionsInner implements InnerSupportsGet<VirtualNetworkGatewayConnectionInner>, InnerSupportsDelete<Void> {
/** The Retrofit service to perform REST calls. */
private VirtualNetworkGatewayConnectionsService service;
/** The service client containing this operation class. */
private NetworkManagementClientImpl client;
/**
* Initializes an instance of VirtualNetworkGatewayConnectionsInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public VirtualNetworkGatewayConnectionsInner(Retrofit retrofit, NetworkManagementClientImpl client) {
this.service = retrofit.create(VirtualNetworkGatewayConnectionsService.class);
this.client = client;
}
/**
* The interface defining all the services for VirtualNetworkGatewayConnections to be
* used by Retrofit to perform actually REST calls.
*/
interface VirtualNetworkGatewayConnectionsService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections createOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}")
Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Body VirtualNetworkGatewayConnectionInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections beginCreateOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}")
Observable<Response<ResponseBody>> beginCreateOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Body VirtualNetworkGatewayConnectionInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections getByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}")
Observable<Response<ResponseBody>> getByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections delete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections beginDelete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> beginDelete(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections updateTags" })
@PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}")
Observable<Response<ResponseBody>> updateTags(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TagsObject parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections beginUpdateTags" })
@PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}")
Observable<Response<ResponseBody>> beginUpdateTags(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TagsObject parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections setSharedKey" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey")
Observable<Response<ResponseBody>> setSharedKey(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Body ConnectionSharedKeyInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections beginSetSharedKey" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey")
Observable<Response<ResponseBody>> beginSetSharedKey(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Body ConnectionSharedKeyInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections getSharedKey" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey")
Observable<Response<ResponseBody>> getSharedKey(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections listByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections")
Observable<Response<ResponseBody>> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections resetSharedKey" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset")
Observable<Response<ResponseBody>> resetSharedKey(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ConnectionResetSharedKeyInner parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections beginResetSharedKey" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset")
Observable<Response<ResponseBody>> beginResetSharedKey(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ConnectionResetSharedKeyInner parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections startPacketCapture" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/startPacketCapture")
Observable<Response<ResponseBody>> startPacketCapture(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body VpnPacketCaptureStartParameters parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections beginStartPacketCapture" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/startPacketCapture")
Observable<Response<ResponseBody>> beginStartPacketCapture(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body VpnPacketCaptureStartParameters parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections stopPacketCapture" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/stopPacketCapture")
Observable<Response<ResponseBody>> stopPacketCapture(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body VpnPacketCaptureStopParameters parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections beginStopPacketCapture" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/stopPacketCapture")
Observable<Response<ResponseBody>> beginStopPacketCapture(@Path("resourceGroupName") String resourceGroupName, @Path("virtualNetworkGatewayConnectionName") String virtualNetworkGatewayConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body VpnPacketCaptureStopParameters parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_07_01.VirtualNetworkGatewayConnections listByResourceGroupNext" })
@GET
Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Creates or updates a virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param parameters Parameters supplied to the create or update virtual network gateway connection operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VirtualNetworkGatewayConnectionInner object if successful.
*/
public VirtualNetworkGatewayConnectionInner createOrUpdate(String resourceGroupName, String virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).toBlocking().last().body();
}
/**
* Creates or updates a virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param parameters Parameters supplied to the create or update virtual network gateway connection operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VirtualNetworkGatewayConnectionInner> createOrUpdateAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionInner parameters, final ServiceCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), serviceCallback);
}
/**
* Creates or updates a virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param parameters Parameters supplied to the create or update virtual network gateway connection operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<VirtualNetworkGatewayConnectionInner> createOrUpdateAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() {
@Override
public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) {
return response.body();
}
});
}
/**
* Creates or updates a virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param parameters Parameters supplied to the create or update virtual network gateway connection operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-07-01";
Observable<Response<ResponseBody>> observable = service.createOrUpdate(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<VirtualNetworkGatewayConnectionInner>() { }.getType());
}
/**
* Creates or updates a virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param parameters Parameters supplied to the create or update virtual network gateway connection operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VirtualNetworkGatewayConnectionInner object if successful.
*/
public VirtualNetworkGatewayConnectionInner beginCreateOrUpdate(String resourceGroupName, String virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).toBlocking().single().body();
}
/**
* Creates or updates a virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param parameters Parameters supplied to the create or update virtual network gateway connection operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VirtualNetworkGatewayConnectionInner> beginCreateOrUpdateAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionInner parameters, final ServiceCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), serviceCallback);
}
/**
* Creates or updates a virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param parameters Parameters supplied to the create or update virtual network gateway connection operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VirtualNetworkGatewayConnectionInner object
*/
public Observable<VirtualNetworkGatewayConnectionInner> beginCreateOrUpdateAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() {
@Override
public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) {
return response.body();
}
});
}
/**
* Creates or updates a virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param parameters Parameters supplied to the create or update virtual network gateway connection operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VirtualNetworkGatewayConnectionInner object
*/
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnectionInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-07-01";
return service.beginCreateOrUpdate(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>>>() {
@Override
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VirtualNetworkGatewayConnectionInner> clientResponse = beginCreateOrUpdateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<VirtualNetworkGatewayConnectionInner> beginCreateOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<VirtualNetworkGatewayConnectionInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<VirtualNetworkGatewayConnectionInner>() { }.getType())
.register(201, new TypeToken<VirtualNetworkGatewayConnectionInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets the specified virtual network gateway connection by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VirtualNetworkGatewayConnectionInner object if successful.
*/
public VirtualNetworkGatewayConnectionInner getByResourceGroup(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().single().body();
}
/**
* Gets the specified virtual network gateway connection by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VirtualNetworkGatewayConnectionInner> getByResourceGroupAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Gets the specified virtual network gateway connection by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VirtualNetworkGatewayConnectionInner object
*/
public Observable<VirtualNetworkGatewayConnectionInner> getByResourceGroupAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() {
@Override
public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) {
return response.body();
}
});
}
/**
* Gets the specified virtual network gateway connection by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VirtualNetworkGatewayConnectionInner object
*/
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
return service.getByResourceGroup(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>>>() {
@Override
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VirtualNetworkGatewayConnectionInner> clientResponse = getByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<VirtualNetworkGatewayConnectionInner> getByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<VirtualNetworkGatewayConnectionInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<VirtualNetworkGatewayConnectionInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Deletes the specified virtual network Gateway connection.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void delete(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
deleteWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().last().body();
}
/**
* Deletes the specified virtual network Gateway connection.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> deleteAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Deletes the specified virtual network Gateway connection.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<Void> deleteAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return deleteWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes the specified virtual network Gateway connection.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
Observable<Response<ResponseBody>> observable = service.delete(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
}
/**
* Deletes the specified virtual network Gateway connection.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void beginDelete(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().single().body();
}
/**
* Deletes the specified virtual network Gateway connection.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Deletes the specified virtual network Gateway connection.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<Void> beginDeleteAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return beginDeleteWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes the specified virtual network Gateway connection.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
return service.beginDelete(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = beginDeleteDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.register(204, new TypeToken<Void>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VirtualNetworkGatewayConnectionInner object if successful.
*/
public VirtualNetworkGatewayConnectionInner updateTags(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().last().body();
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VirtualNetworkGatewayConnectionInner> updateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<VirtualNetworkGatewayConnectionInner> updateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() {
@Override
public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) {
return response.body();
}
});
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
final Map<String, String> tags = null;
TagsObject parameters = new TagsObject();
parameters.withTags(null);
Observable<Response<ResponseBody>> observable = service.updateTags(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<VirtualNetworkGatewayConnectionInner>() { }.getType());
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VirtualNetworkGatewayConnectionInner object if successful.
*/
public VirtualNetworkGatewayConnectionInner updateTags(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags).toBlocking().last().body();
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param tags Resource tags.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VirtualNetworkGatewayConnectionInner> updateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags, final ServiceCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags), serviceCallback);
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<VirtualNetworkGatewayConnectionInner> updateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() {
@Override
public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) {
return response.body();
}
});
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
Validator.validate(tags);
final String apiVersion = "2019-07-01";
TagsObject parameters = new TagsObject();
parameters.withTags(tags);
Observable<Response<ResponseBody>> observable = service.updateTags(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<VirtualNetworkGatewayConnectionInner>() { }.getType());
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VirtualNetworkGatewayConnectionInner object if successful.
*/
public VirtualNetworkGatewayConnectionInner beginUpdateTags(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().single().body();
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VirtualNetworkGatewayConnectionInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VirtualNetworkGatewayConnectionInner object
*/
public Observable<VirtualNetworkGatewayConnectionInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() {
@Override
public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) {
return response.body();
}
});
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VirtualNetworkGatewayConnectionInner object
*/
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> beginUpdateTagsWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
final Map<String, String> tags = null;
TagsObject parameters = new TagsObject();
parameters.withTags(null);
return service.beginUpdateTags(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>>>() {
@Override
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VirtualNetworkGatewayConnectionInner> clientResponse = beginUpdateTagsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VirtualNetworkGatewayConnectionInner object if successful.
*/
public VirtualNetworkGatewayConnectionInner beginUpdateTags(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags).toBlocking().single().body();
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param tags Resource tags.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VirtualNetworkGatewayConnectionInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags, final ServiceCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags), serviceCallback);
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VirtualNetworkGatewayConnectionInner object
*/
public Observable<VirtualNetworkGatewayConnectionInner> beginUpdateTagsAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) {
return beginUpdateTagsWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, tags).map(new Func1<ServiceResponse<VirtualNetworkGatewayConnectionInner>, VirtualNetworkGatewayConnectionInner>() {
@Override
public VirtualNetworkGatewayConnectionInner call(ServiceResponse<VirtualNetworkGatewayConnectionInner> response) {
return response.body();
}
});
}
/**
* Updates a virtual network gateway connection tags.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VirtualNetworkGatewayConnectionInner object
*/
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> beginUpdateTagsWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, Map<String, String> tags) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
Validator.validate(tags);
final String apiVersion = "2019-07-01";
TagsObject parameters = new TagsObject();
parameters.withTags(tags);
return service.beginUpdateTags(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>>>() {
@Override
public Observable<ServiceResponse<VirtualNetworkGatewayConnectionInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VirtualNetworkGatewayConnectionInner> clientResponse = beginUpdateTagsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<VirtualNetworkGatewayConnectionInner> beginUpdateTagsDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<VirtualNetworkGatewayConnectionInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<VirtualNetworkGatewayConnectionInner>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
* @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ConnectionSharedKeyInner object if successful.
*/
public ConnectionSharedKeyInner setSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters) {
return setSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).toBlocking().last().body();
}
/**
* The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
* @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ConnectionSharedKeyInner> setSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters, final ServiceCallback<ConnectionSharedKeyInner> serviceCallback) {
return ServiceFuture.fromResponse(setSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), serviceCallback);
}
/**
* The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
* @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ConnectionSharedKeyInner> setSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters) {
return setSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).map(new Func1<ServiceResponse<ConnectionSharedKeyInner>, ConnectionSharedKeyInner>() {
@Override
public ConnectionSharedKeyInner call(ServiceResponse<ConnectionSharedKeyInner> response) {
return response.body();
}
});
}
/**
* The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
* @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<ConnectionSharedKeyInner>> setSharedKeyWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-07-01";
Observable<Response<ResponseBody>> observable = service.setSharedKey(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<ConnectionSharedKeyInner>() { }.getType());
}
/**
* The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
* @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ConnectionSharedKeyInner object if successful.
*/
public ConnectionSharedKeyInner beginSetSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters) {
return beginSetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).toBlocking().single().body();
}
/**
* The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
* @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ConnectionSharedKeyInner> beginSetSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters, final ServiceCallback<ConnectionSharedKeyInner> serviceCallback) {
return ServiceFuture.fromResponse(beginSetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters), serviceCallback);
}
/**
* The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
* @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ConnectionSharedKeyInner object
*/
public Observable<ConnectionSharedKeyInner> beginSetSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters) {
return beginSetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, parameters).map(new Func1<ServiceResponse<ConnectionSharedKeyInner>, ConnectionSharedKeyInner>() {
@Override
public ConnectionSharedKeyInner call(ServiceResponse<ConnectionSharedKeyInner> response) {
return response.body();
}
});
}
/**
* The Put VirtualNetworkGatewayConnectionSharedKey operation sets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection name.
* @param parameters Parameters supplied to the Begin Set Virtual Network Gateway connection Shared key operation throughNetwork resource provider.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ConnectionSharedKeyInner object
*/
public Observable<ServiceResponse<ConnectionSharedKeyInner>> beginSetSharedKeyWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, ConnectionSharedKeyInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-07-01";
return service.beginSetSharedKey(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ConnectionSharedKeyInner>>>() {
@Override
public Observable<ServiceResponse<ConnectionSharedKeyInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ConnectionSharedKeyInner> clientResponse = beginSetSharedKeyDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<ConnectionSharedKeyInner> beginSetSharedKeyDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<ConnectionSharedKeyInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<ConnectionSharedKeyInner>() { }.getType())
.register(201, new TypeToken<ConnectionSharedKeyInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual network gateway connection shared key through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection shared key name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ConnectionSharedKeyInner object if successful.
*/
public ConnectionSharedKeyInner getSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return getSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().single().body();
}
/**
* The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual network gateway connection shared key through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection shared key name.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ConnectionSharedKeyInner> getSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<ConnectionSharedKeyInner> serviceCallback) {
return ServiceFuture.fromResponse(getSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual network gateway connection shared key through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection shared key name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ConnectionSharedKeyInner object
*/
public Observable<ConnectionSharedKeyInner> getSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return getSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<ConnectionSharedKeyInner>, ConnectionSharedKeyInner>() {
@Override
public ConnectionSharedKeyInner call(ServiceResponse<ConnectionSharedKeyInner> response) {
return response.body();
}
});
}
/**
* The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves information about the specified virtual network gateway connection shared key through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection shared key name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ConnectionSharedKeyInner object
*/
public Observable<ServiceResponse<ConnectionSharedKeyInner>> getSharedKeyWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
return service.getSharedKey(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ConnectionSharedKeyInner>>>() {
@Override
public Observable<ServiceResponse<ConnectionSharedKeyInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ConnectionSharedKeyInner> clientResponse = getSharedKeyDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<ConnectionSharedKeyInner> getSharedKeyDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<ConnectionSharedKeyInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<ConnectionSharedKeyInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<VirtualNetworkGatewayConnectionInner> object if successful.
*/
public PagedList<VirtualNetworkGatewayConnectionInner> listByResourceGroup(final String resourceGroupName) {
ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single();
return new PagedList<VirtualNetworkGatewayConnectionInner>(response.body()) {
@Override
public Page<VirtualNetworkGatewayConnectionInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
* @param resourceGroupName The name of the resource group.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<VirtualNetworkGatewayConnectionInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupSinglePageAsync(resourceGroupName),
new Func1<String, Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VirtualNetworkGatewayConnectionInner> object
*/
public Observable<Page<VirtualNetworkGatewayConnectionInner>> listByResourceGroupAsync(final String resourceGroupName) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName)
.map(new Func1<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>, Page<VirtualNetworkGatewayConnectionInner>>() {
@Override
public Page<VirtualNetworkGatewayConnectionInner> call(ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>> response) {
return response.body();
}
});
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VirtualNetworkGatewayConnectionInner> object
*/
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) {
return listByResourceGroupSinglePageAsync(resourceGroupName)
.concatMap(new Func1<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>, Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> call(ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
ServiceResponse<PageImpl<VirtualNetworkGatewayConnectionInner>> * @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<VirtualNetworkGatewayConnectionInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<VirtualNetworkGatewayConnectionInner>> result = listByResourceGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<VirtualNetworkGatewayConnectionInner>> listByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<VirtualNetworkGatewayConnectionInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<VirtualNetworkGatewayConnectionInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name.
* @param keyLength The virtual network connection reset shared key length, should between 1 and 128.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ConnectionResetSharedKeyInner object if successful.
*/
public ConnectionResetSharedKeyInner resetSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength) {
return resetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, keyLength).toBlocking().last().body();
}
/**
* The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name.
* @param keyLength The virtual network connection reset shared key length, should between 1 and 128.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ConnectionResetSharedKeyInner> resetSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength, final ServiceCallback<ConnectionResetSharedKeyInner> serviceCallback) {
return ServiceFuture.fromResponse(resetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, keyLength), serviceCallback);
}
/**
* The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name.
* @param keyLength The virtual network connection reset shared key length, should between 1 and 128.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ConnectionResetSharedKeyInner> resetSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength) {
return resetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, keyLength).map(new Func1<ServiceResponse<ConnectionResetSharedKeyInner>, ConnectionResetSharedKeyInner>() {
@Override
public ConnectionResetSharedKeyInner call(ServiceResponse<ConnectionResetSharedKeyInner> response) {
return response.body();
}
});
}
/**
* The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name.
* @param keyLength The virtual network connection reset shared key length, should between 1 and 128.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<ConnectionResetSharedKeyInner>> resetSharedKeyWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
ConnectionResetSharedKeyInner parameters = new ConnectionResetSharedKeyInner();
parameters.withKeyLength(keyLength);
Observable<Response<ResponseBody>> observable = service.resetSharedKey(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<ConnectionResetSharedKeyInner>() { }.getType());
}
/**
* The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name.
* @param keyLength The virtual network connection reset shared key length, should between 1 and 128.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the ConnectionResetSharedKeyInner object if successful.
*/
public ConnectionResetSharedKeyInner beginResetSharedKey(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength) {
return beginResetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, keyLength).toBlocking().single().body();
}
/**
* The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name.
* @param keyLength The virtual network connection reset shared key length, should between 1 and 128.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<ConnectionResetSharedKeyInner> beginResetSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength, final ServiceCallback<ConnectionResetSharedKeyInner> serviceCallback) {
return ServiceFuture.fromResponse(beginResetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, keyLength), serviceCallback);
}
/**
* The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name.
* @param keyLength The virtual network connection reset shared key length, should between 1 and 128.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ConnectionResetSharedKeyInner object
*/
public Observable<ConnectionResetSharedKeyInner> beginResetSharedKeyAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength) {
return beginResetSharedKeyWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, keyLength).map(new Func1<ServiceResponse<ConnectionResetSharedKeyInner>, ConnectionResetSharedKeyInner>() {
@Override
public ConnectionResetSharedKeyInner call(ServiceResponse<ConnectionResetSharedKeyInner> response) {
return response.body();
}
});
}
/**
* The VirtualNetworkGatewayConnectionResetSharedKey operation resets the virtual network gateway connection shared key for passed virtual network gateway connection in the specified resource group through Network resource provider.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The virtual network gateway connection reset shared key Name.
* @param keyLength The virtual network connection reset shared key length, should between 1 and 128.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the ConnectionResetSharedKeyInner object
*/
public Observable<ServiceResponse<ConnectionResetSharedKeyInner>> beginResetSharedKeyWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, int keyLength) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
ConnectionResetSharedKeyInner parameters = new ConnectionResetSharedKeyInner();
parameters.withKeyLength(keyLength);
return service.beginResetSharedKey(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ConnectionResetSharedKeyInner>>>() {
@Override
public Observable<ServiceResponse<ConnectionResetSharedKeyInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<ConnectionResetSharedKeyInner> clientResponse = beginResetSharedKeyDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<ConnectionResetSharedKeyInner> beginResetSharedKeyDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<ConnectionResetSharedKeyInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<ConnectionResetSharedKeyInner>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the String object if successful.
*/
public String startPacketCapture(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return startPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().last().body();
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<String> startPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(startPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<String> startPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return startPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<String>> startPacketCaptureWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
final String filterData = null;
VpnPacketCaptureStartParameters parameters = new VpnPacketCaptureStartParameters();
parameters.withFilterData(null);
Observable<Response<ResponseBody>> observable = service.startPacketCapture(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<String>() { }.getType());
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param filterData Start Packet capture parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the String object if successful.
*/
public String startPacketCapture(String resourceGroupName, String virtualNetworkGatewayConnectionName, String filterData) {
return startPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, filterData).toBlocking().last().body();
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param filterData Start Packet capture parameters.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<String> startPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String filterData, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(startPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, filterData), serviceCallback);
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param filterData Start Packet capture parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<String> startPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String filterData) {
return startPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, filterData).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param filterData Start Packet capture parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<String>> startPacketCaptureWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String filterData) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
VpnPacketCaptureStartParameters parameters = null;
if (filterData != null) {
parameters = new VpnPacketCaptureStartParameters();
parameters.withFilterData(filterData);
}
Observable<Response<ResponseBody>> observable = service.startPacketCapture(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<String>() { }.getType());
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the String object if successful.
*/
public String beginStartPacketCapture(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().single().body();
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<String> beginStartPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the String object
*/
public Observable<String> beginStartPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the String object
*/
public Observable<ServiceResponse<String>> beginStartPacketCaptureWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
final String filterData = null;
VpnPacketCaptureStartParameters parameters = new VpnPacketCaptureStartParameters();
parameters.withFilterData(null);
return service.beginStartPacketCapture(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() {
@Override
public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) {
try {
ServiceResponse<String> clientResponse = beginStartPacketCaptureDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param filterData Start Packet capture parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the String object if successful.
*/
public String beginStartPacketCapture(String resourceGroupName, String virtualNetworkGatewayConnectionName, String filterData) {
return beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, filterData).toBlocking().single().body();
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param filterData Start Packet capture parameters.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<String> beginStartPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String filterData, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, filterData), serviceCallback);
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param filterData Start Packet capture parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the String object
*/
public Observable<String> beginStartPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String filterData) {
return beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, filterData).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
/**
* Starts packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway connection.
* @param filterData Start Packet capture parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the String object
*/
public Observable<ServiceResponse<String>> beginStartPacketCaptureWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String filterData) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
VpnPacketCaptureStartParameters parameters = null;
if (filterData != null) {
parameters = new VpnPacketCaptureStartParameters();
parameters.withFilterData(filterData);
}
return service.beginStartPacketCapture(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() {
@Override
public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) {
try {
ServiceResponse<String> clientResponse = beginStartPacketCaptureDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<String> beginStartPacketCaptureDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<String, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<String>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the String object if successful.
*/
public String stopPacketCapture(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return stopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().last().body();
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<String> stopPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(stopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<String> stopPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return stopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<String>> stopPacketCaptureWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
final String sasUrl = null;
VpnPacketCaptureStopParameters parameters = new VpnPacketCaptureStopParameters();
parameters.withSasUrl(null);
Observable<Response<ResponseBody>> observable = service.stopPacketCapture(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<String>() { }.getType());
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param sasUrl SAS url for packet capture on virtual network gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the String object if successful.
*/
public String stopPacketCapture(String resourceGroupName, String virtualNetworkGatewayConnectionName, String sasUrl) {
return stopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, sasUrl).toBlocking().last().body();
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param sasUrl SAS url for packet capture on virtual network gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<String> stopPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String sasUrl, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(stopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, sasUrl), serviceCallback);
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param sasUrl SAS url for packet capture on virtual network gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<String> stopPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String sasUrl) {
return stopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, sasUrl).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param sasUrl SAS url for packet capture on virtual network gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<String>> stopPacketCaptureWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String sasUrl) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
VpnPacketCaptureStopParameters parameters = new VpnPacketCaptureStopParameters();
parameters.withSasUrl(sasUrl);
Observable<Response<ResponseBody>> observable = service.stopPacketCapture(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<String>() { }.getType());
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the String object if successful.
*/
public String beginStopPacketCapture(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).toBlocking().single().body();
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<String> beginStopPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName), serviceCallback);
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the String object
*/
public Observable<String> beginStopPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
return beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the String object
*/
public Observable<ServiceResponse<String>> beginStopPacketCaptureWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
final String sasUrl = null;
VpnPacketCaptureStopParameters parameters = new VpnPacketCaptureStopParameters();
parameters.withSasUrl(null);
return service.beginStopPacketCapture(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() {
@Override
public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) {
try {
ServiceResponse<String> clientResponse = beginStopPacketCaptureDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param sasUrl SAS url for packet capture on virtual network gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the String object if successful.
*/
public String beginStopPacketCapture(String resourceGroupName, String virtualNetworkGatewayConnectionName, String sasUrl) {
return beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, sasUrl).toBlocking().single().body();
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param sasUrl SAS url for packet capture on virtual network gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<String> beginStopPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String sasUrl, final ServiceCallback<String> serviceCallback) {
return ServiceFuture.fromResponse(beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, sasUrl), serviceCallback);
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param sasUrl SAS url for packet capture on virtual network gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the String object
*/
public Observable<String> beginStopPacketCaptureAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String sasUrl) {
return beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayConnectionName, sasUrl).map(new Func1<ServiceResponse<String>, String>() {
@Override
public String call(ServiceResponse<String> response) {
return response.body();
}
});
}
/**
* Stops packet capture on virtual network gateway connection in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param virtualNetworkGatewayConnectionName The name of the virtual network gateway Connection.
* @param sasUrl SAS url for packet capture on virtual network gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the String object
*/
public Observable<ServiceResponse<String>> beginStopPacketCaptureWithServiceResponseAsync(String resourceGroupName, String virtualNetworkGatewayConnectionName, String sasUrl) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (virtualNetworkGatewayConnectionName == null) {
throw new IllegalArgumentException("Parameter virtualNetworkGatewayConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-07-01";
VpnPacketCaptureStopParameters parameters = new VpnPacketCaptureStopParameters();
parameters.withSasUrl(sasUrl);
return service.beginStopPacketCapture(resourceGroupName, virtualNetworkGatewayConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() {
@Override
public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) {
try {
ServiceResponse<String> clientResponse = beginStopPacketCaptureDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<String> beginStopPacketCaptureDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<String, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<String>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<VirtualNetworkGatewayConnectionInner> object if successful.
*/
public PagedList<VirtualNetworkGatewayConnectionInner> listByResourceGroupNext(final String nextPageLink) {
ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<VirtualNetworkGatewayConnectionInner>(response.body()) {
@Override
public Page<VirtualNetworkGatewayConnectionInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<VirtualNetworkGatewayConnectionInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<VirtualNetworkGatewayConnectionInner>> serviceFuture, final ListOperationCallback<VirtualNetworkGatewayConnectionInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VirtualNetworkGatewayConnectionInner> object
*/
public Observable<Page<VirtualNetworkGatewayConnectionInner>> listByResourceGroupNextAsync(final String nextPageLink) {
return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>, Page<VirtualNetworkGatewayConnectionInner>>() {
@Override
public Page<VirtualNetworkGatewayConnectionInner> call(ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>> response) {
return response.body();
}
});
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VirtualNetworkGatewayConnectionInner> object
*/
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>, Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> call(ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* The List VirtualNetworkGatewayConnections operation retrieves all the virtual network gateways connections created.
*
ServiceResponse<PageImpl<VirtualNetworkGatewayConnectionInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<VirtualNetworkGatewayConnectionInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<VirtualNetworkGatewayConnectionInner>> result = listByResourceGroupNextDelegate(response);
return Observable.just(new ServiceResponse<Page<VirtualNetworkGatewayConnectionInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<VirtualNetworkGatewayConnectionInner>> listByResourceGroupNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<VirtualNetworkGatewayConnectionInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<VirtualNetworkGatewayConnectionInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| mit |
campersau/NuGetPackageExplorer | PackageViewModel/PackageAnalyzer/MisplacedTransformFileRule.cs | 1863 | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using NuGetPackageExplorer.Types;
using NuGetPe;
namespace PackageExplorerViewModel.Rules
{
[Export(typeof(IPackageRule))]
internal class MisplacedTransformFileRule : IPackageRule
{
private const string ContentFolder = "content";
private const string CodeTransformExtension = ".pp";
private const string ConfigTransformExtension = ".transform";
#region IPackageRule Members
public IEnumerable<PackageIssue> Validate(IPackage package, string packagePath)
{
foreach (var file in package.GetFiles())
{
var path = file.Path;
// if not a .transform file, ignore
if (!path.EndsWith(CodeTransformExtension, StringComparison.OrdinalIgnoreCase) &&
!path.EndsWith(ConfigTransformExtension, StringComparison.OrdinalIgnoreCase))
{
continue;
}
// if not inside 'content' folder, warn
if (!path.StartsWith(ContentFolder + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
{
yield return CreatePackageIssueForMisplacedContent(path);
}
}
}
#endregion
private static PackageIssue CreatePackageIssueForMisplacedContent(string path)
{
return new PackageIssue(
PackageIssueLevel.Warning,
"Transform file outside content folder",
"The transform file '" + path +
"' is outside the 'content' folder and hence will not be transformed during installation of this package.",
"Move it into the 'content' folder.");
}
}
}
| mit |
YHTechnology/DocumentManager | DocumentManager/LiteLibrary/Pair.cs | 3905 | using System;
using System.Collections.Generic;
using System.Text;
namespace BIS.Library
{
/// <summary>
/// Pair
/// </summary>
/// <typeparam name="TLeft">The type of the left.</typeparam>
/// <typeparam name="TRight">The type of the right.</typeparam>
public class Pair<TLeft, TRight> : IEquatable<Pair<TLeft, TRight>>
{
/// <summary>
///
/// </summary>
public TLeft Left;
/// <summary>
///
/// </summary>
public TRight Right;
/// <summary>
/// Initializes a new instance of the <see cref="Pair<TLeft, TRight>"/> class.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
public Pair(TLeft left, TRight right)
{
Left = left;
Right = right;
}
/// <summary>
/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </returns>
public override string ToString()
{
return string.Format("({0},{1})", Left, Right);
}
/// <summary>
/// Serves as a hash function for a particular type. <see cref="M:System.Object.GetHashCode"></see> is suitable for use in hashing algorithms and data structures like a hash table.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"></see>.
/// </returns>
public override int GetHashCode()
{
return Left.GetHashCode() + Right.GetHashCode();
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"></see> to compare with the current <see cref="T:System.Object"></see>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
if (obj is Pair<TLeft, TRight>)
{
return this.Equals((Pair<TLeft, TRight>)obj);
}
else
{
return false;
}
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the other parameter; otherwise, false.
/// </returns>
public bool Equals(Pair<TLeft, TRight> other)
{
return this.Left.Equals(other.Left) && this.Right.Equals(other.Right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="one">The one.</param>
/// <param name="other">The other.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(Pair<TLeft, TRight> one, Pair<TLeft, TRight> other)
{
return one.Equals(other);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="one">The one.</param>
/// <param name="other">The other.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(Pair<TLeft, TRight> one, Pair<TLeft, TRight> other)
{
return !(one == other);
}
}
}
| mit |
jendewalt/yumhacker | app/controllers/users_controller.rb | 137 | class UsersController < ApplicationController
def index
@users = User.all.order(:last_name).page(params[:page]).per(1000)
end
end | mit |
beardyunixer/redmatrix | mod/display.php | 7167 | <?php
function display_content(&$a, $update = 0, $load = false) {
// logger("mod-display: update = $update load = $load");
if($load)
$_SESSION['loadtime'] = datetime_convert();
if(intval(get_config('system','block_public')) && (! local_user()) && (! remote_channel())) {
notice( t('Public access denied.') . EOL);
return;
}
require_once("include/bbcode.php");
require_once('include/security.php');
require_once('include/conversation.php');
require_once('include/acl_selectors.php');
require_once('include/items.php');
$a->page['htmlhead'] .= replace_macros(get_markup_template('display-head.tpl'), array());
if(argc() > 1 && argv(1) !== 'load')
$item_hash = argv(1);
if($_REQUEST['mid'])
$item_hash = $_REQUEST['mid'];
if(! $item_hash) {
$a->error = 404;
notice( t('Item not found.') . EOL);
return;
}
$observer_is_owner = false;
if(local_user() && (! $update)) {
$channel = $a->get_channel();
$channel_acl = array(
'allow_cid' => $channel['channel_allow_cid'],
'allow_gid' => $channel['channel_allow_gid'],
'deny_cid' => $channel['channel_deny_cid'],
'deny_gid' => $channel['channel_deny_gid']
);
$x = array(
'is_owner' => true,
'allow_location' => ((intval(get_pconfig($channel['channel_id'],'system','use_browser_location'))) ? '1' : ''),
'default_location' => $channel['channel_location'],
'nickname' => $channel['channel_address'],
'lockstate' => (($group || $cid || $channel['channel_allow_cid'] || $channel['channel_allow_gid'] || $channel['channel_deny_cid'] || $channel['channel_deny_gid']) ? 'lock' : 'unlock'),
'acl' => populate_acl($channel_acl),
'bang' => '',
'visitor' => true,
'profile_uid' => local_user(),
'return_path' => 'channel/' . $channel['channel_address'],
'expanded' => true
);
$o = '<div id="jot-popup">';
$o .= status_editor($a,$x);
$o .= '</div>';
}
// This page can be viewed by anybody so the query could be complicated
// First we'll see if there is a copy of the item which is owned by us - if we're logged in locally.
// If that fails (or we aren't logged in locally),
// query an item in which the observer (if logged in remotely) has cid or gid rights
// and if that fails, look for a copy of the post that has no privacy restrictions.
// If we find the post, but we don't find a copy that we're allowed to look at, this fact needs to be reported.
// find a copy of the item somewhere
$target_item = null;
$r = q("select id, uid, mid, parent_mid, item_restrict from item where mid like '%s' limit 1",
dbesc($item_hash . '%')
);
if($r) {
$target_item = $r[0];
}
$r = null;
if($target_item['item_restrict'] & ITEM_WEBPAGE) {
$x = q("select * from channel where channel_id = %d limit 1",
intval($target_item['uid'])
);
$y = q("select * from item_id where uid = %d and service = 'WEBPAGE' and iid = %d limit 1",
intval($target_item['uid']),
intval($target_item['id'])
);
if($x && $y) {
goaway(z_root() . '/page/' . $x[0]['channel_address'] . '/' . $y[0]['sid']);
}
else {
notice( t('Page not found.') . EOL);
return '';
}
}
$simple_update = (($update) ? " AND item_unseen = 1 " : '');
if($update && $_SESSION['loadtime'])
$simple_update .= " and item.changed > '" . datetime_convert('UTC','UTC',$_SESSION['loadtime']) . "' ";
if($load)
$simple_update = '';
if((! $update) && (! $load)) {
$o .= '<div id="live-display"></div>' . "\r\n";
$o .= "<script> var profile_uid = " . ((intval(local_user())) ? local_user() : (-1))
. "; var netargs = '?f='; var profile_page = " . $a->pager['page'] . "; </script>\r\n";
$a->page['htmlhead'] .= replace_macros(get_markup_template("build_query.tpl"),array(
'$baseurl' => z_root(),
'$pgtype' => 'display',
'$uid' => '0',
'$gid' => '0',
'$cid' => '0',
'$cmin' => '0',
'$cmax' => '99',
'$star' => '0',
'$liked' => '0',
'$conv' => '0',
'$spam' => '0',
'$fh' => '0',
'$nouveau' => '0',
'$wall' => '0',
'$page' => (($a->pager['page'] != 1) ? $a->pager['page'] : 1),
'$list' => ((x($_REQUEST,'list')) ? intval($_REQUEST['list']) : 0),
'$search' => '',
'$order' => '',
'$file' => '',
'$cats' => '',
'$tags' => '',
'$dend' => '',
'$dbegin' => '',
'$verb' => '',
'$mid' => $item_hash
));
}
$observer_hash = get_observer_hash();
$sql_extra = public_permissions_sql($observer_hash);
if(($update && $load) || ($_COOKIE['jsAvailable'] != 1)) {
$updateable = false;
$pager_sql = sprintf(" LIMIT %d OFFSET %d ", intval($a->pager['itemspage']),intval($a->pager['start']));
if($load || ($_COOKIE['jsAvailable'] != 1)) {
$r = null;
require_once('include/identity.php');
$sys = get_sys_channel();
$sysid = $sys['channel_id'];
if(local_user()) {
$r = q("SELECT * from item
WHERE item_restrict = 0
and uid = %d
and mid = '%s'
limit 1",
intval(local_user()),
dbesc($target_item['parent_mid'])
);
if($r) {
$updateable = true;
}
}
if($r === null) {
// in case somebody turned off public access to sys channel content using permissions
// make that content unsearchable by ensuring the owner_xchan can't match
if(! perm_is_allowed($sysid,$observer_hash,'view_stream'))
$sysid = 0;
$r = q("SELECT * from item
WHERE item_restrict = 0
and mid = '%s'
AND (((( `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = ''
AND `item`.`deny_gid` = '' AND item_private = 0 )
and owner_xchan in ( " . stream_perms_xchans(($observer_hash) ? (PERMS_NETWORK|PERMS_PUBLIC) : PERMS_PUBLIC) . " ))
OR uid = %d )
$sql_extra )
limit 1",
dbesc($target_item['parent_mid']),
intval($sysid)
);
}
}
else {
$r = array();
}
}
if($r) {
$parents_str = ids_to_querystr($r,'id');
if($parents_str) {
$items = q("SELECT `item`.*, `item`.`id` AS `item_id`
FROM `item`
WHERE item_restrict = 0 and parent in ( %s ) ",
dbesc($parents_str)
);
xchan_query($items);
$items = fetch_post_tags($items,true);
$items = conv_sort($items,'created');
}
} else {
$items = array();
}
if ($_COOKIE['jsAvailable'] == 1) {
$o .= conversation($a, $items, 'display', $update, 'client');
} else {
$o .= conversation($a, $items, 'display', $update, 'traditional');
if ($items[0]['title'])
$a->page['title'] = $items[0]['title'] . " - " . $a->page['title'];
}
if($updateable) {
$x = q("UPDATE item SET item_unseen = 0 WHERE item_unseen = 1 AND uid = %d and parent = %d ",
intval(local_user()),
intval($r[0]['parent'])
);
}
$o .= '<div id="content-complete"></div>';
return $o;
/*
elseif((! $update) && (! {
$r = q("SELECT `id`, item_flags FROM `item` WHERE `id` = '%s' OR `mid` = '%s' LIMIT 1",
dbesc($item_hash),
dbesc($item_hash)
);
if($r) {
if($r[0]['item_flags'] & ITEM_DELETED) {
notice( t('Item has been removed.') . EOL );
}
else {
notice( t('Permission denied.') . EOL );
}
}
else {
notice( t('Item not found.') . EOL );
}
}
*/
return $o;
}
| mit |
GGAlanSmithee/phaser | v3/src/scene/global/components/CreateSceneFromObject.js | 493 | var Scene = require('../../local/Scene');
var CreateSceneFromObject = function (key, sceneConfig)
{
var newScene = new Scene(sceneConfig);
var configKey = newScene.sys.settings.key;
if (configKey !== '')
{
key = configKey;
}
else
{
newScene.sys.settings.key = key;
}
newScene.sys.init(this.game);
this.createSceneDisplay(newScene);
return this.setupCallbacks(newScene, sceneConfig);
};
module.exports = CreateSceneFromObject;
| mit |
lexor90/node-compiler | node/test/parallel/test-buffer-indexof.js | 23324 | 'use strict';
require('../common');
const assert = require('assert');
const b = Buffer.from('abcdef');
const buf_a = Buffer.from('a');
const buf_bc = Buffer.from('bc');
const buf_f = Buffer.from('f');
const buf_z = Buffer.from('z');
const buf_empty = Buffer.from('');
const s = 'abcdef';
assert.strictEqual(b.indexOf('a'), 0);
assert.strictEqual(b.indexOf('a', 1), -1);
assert.strictEqual(b.indexOf('a', -1), -1);
assert.strictEqual(b.indexOf('a', -4), -1);
assert.strictEqual(b.indexOf('a', -b.length), 0);
assert.strictEqual(b.indexOf('a', NaN), 0);
assert.strictEqual(b.indexOf('a', -Infinity), 0);
assert.strictEqual(b.indexOf('a', Infinity), -1);
assert.strictEqual(b.indexOf('bc'), 1);
assert.strictEqual(b.indexOf('bc', 2), -1);
assert.strictEqual(b.indexOf('bc', -1), -1);
assert.strictEqual(b.indexOf('bc', -3), -1);
assert.strictEqual(b.indexOf('bc', -5), 1);
assert.strictEqual(b.indexOf('bc', NaN), 1);
assert.strictEqual(b.indexOf('bc', -Infinity), 1);
assert.strictEqual(b.indexOf('bc', Infinity), -1);
assert.strictEqual(b.indexOf('f'), b.length - 1);
assert.strictEqual(b.indexOf('z'), -1);
assert.strictEqual(b.indexOf(''), 0);
assert.strictEqual(b.indexOf('', 1), 1);
assert.strictEqual(b.indexOf('', b.length + 1), b.length);
assert.strictEqual(b.indexOf('', Infinity), b.length);
assert.strictEqual(b.indexOf(buf_a), 0);
assert.strictEqual(b.indexOf(buf_a, 1), -1);
assert.strictEqual(b.indexOf(buf_a, -1), -1);
assert.strictEqual(b.indexOf(buf_a, -4), -1);
assert.strictEqual(b.indexOf(buf_a, -b.length), 0);
assert.strictEqual(b.indexOf(buf_a, NaN), 0);
assert.strictEqual(b.indexOf(buf_a, -Infinity), 0);
assert.strictEqual(b.indexOf(buf_a, Infinity), -1);
assert.strictEqual(b.indexOf(buf_bc), 1);
assert.strictEqual(b.indexOf(buf_bc, 2), -1);
assert.strictEqual(b.indexOf(buf_bc, -1), -1);
assert.strictEqual(b.indexOf(buf_bc, -3), -1);
assert.strictEqual(b.indexOf(buf_bc, -5), 1);
assert.strictEqual(b.indexOf(buf_bc, NaN), 1);
assert.strictEqual(b.indexOf(buf_bc, -Infinity), 1);
assert.strictEqual(b.indexOf(buf_bc, Infinity), -1);
assert.strictEqual(b.indexOf(buf_f), b.length - 1);
assert.strictEqual(b.indexOf(buf_z), -1);
assert.strictEqual(b.indexOf(buf_empty), 0);
assert.strictEqual(b.indexOf(buf_empty, 1), 1);
assert.strictEqual(b.indexOf(buf_empty, b.length + 1), b.length);
assert.strictEqual(b.indexOf(buf_empty, Infinity), b.length);
assert.strictEqual(b.indexOf(0x61), 0);
assert.strictEqual(b.indexOf(0x61, 1), -1);
assert.strictEqual(b.indexOf(0x61, -1), -1);
assert.strictEqual(b.indexOf(0x61, -4), -1);
assert.strictEqual(b.indexOf(0x61, -b.length), 0);
assert.strictEqual(b.indexOf(0x61, NaN), 0);
assert.strictEqual(b.indexOf(0x61, -Infinity), 0);
assert.strictEqual(b.indexOf(0x61, Infinity), -1);
assert.strictEqual(b.indexOf(0x0), -1);
// test offsets
assert.strictEqual(b.indexOf('d', 2), 3);
assert.strictEqual(b.indexOf('f', 5), 5);
assert.strictEqual(b.indexOf('f', -1), 5);
assert.strictEqual(b.indexOf('f', 6), -1);
assert.strictEqual(b.indexOf(Buffer.from('d'), 2), 3);
assert.strictEqual(b.indexOf(Buffer.from('f'), 5), 5);
assert.strictEqual(b.indexOf(Buffer.from('f'), -1), 5);
assert.strictEqual(b.indexOf(Buffer.from('f'), 6), -1);
assert.strictEqual(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1);
// test invalid and uppercase encoding
assert.strictEqual(b.indexOf('b', 'utf8'), 1);
assert.strictEqual(b.indexOf('b', 'UTF8'), 1);
assert.strictEqual(b.indexOf('62', 'HEX'), 1);
assert.throws(() => b.indexOf('bad', 'enc'), /Unknown encoding: enc/);
// test hex encoding
assert.strictEqual(
Buffer.from(b.toString('hex'), 'hex')
.indexOf('64', 0, 'hex'),
3
);
assert.strictEqual(
Buffer.from(b.toString('hex'), 'hex')
.indexOf(Buffer.from('64', 'hex'), 0, 'hex'),
3
);
// test base64 encoding
assert.strictEqual(
Buffer.from(b.toString('base64'), 'base64')
.indexOf('ZA==', 0, 'base64'),
3
);
assert.strictEqual(
Buffer.from(b.toString('base64'), 'base64')
.indexOf(Buffer.from('ZA==', 'base64'), 0, 'base64'),
3
);
// test ascii encoding
assert.strictEqual(
Buffer.from(b.toString('ascii'), 'ascii')
.indexOf('d', 0, 'ascii'),
3
);
assert.strictEqual(
Buffer.from(b.toString('ascii'), 'ascii')
.indexOf(Buffer.from('d', 'ascii'), 0, 'ascii'),
3
);
// test latin1 encoding
assert.strictEqual(
Buffer.from(b.toString('latin1'), 'latin1')
.indexOf('d', 0, 'latin1'),
3
);
assert.strictEqual(
Buffer.from(b.toString('latin1'), 'latin1')
.indexOf(Buffer.from('d', 'latin1'), 0, 'latin1'),
3
);
assert.strictEqual(
Buffer.from('aa\u00e8aa', 'latin1')
.indexOf('\u00e8', 'latin1'),
2
);
assert.strictEqual(
Buffer.from('\u00e8', 'latin1')
.indexOf('\u00e8', 'latin1'),
0
);
assert.strictEqual(
Buffer.from('\u00e8', 'latin1')
.indexOf(Buffer.from('\u00e8', 'latin1'), 'latin1'),
0
);
// test binary encoding
assert.strictEqual(
Buffer.from(b.toString('binary'), 'binary')
.indexOf('d', 0, 'binary'),
3
);
assert.strictEqual(
Buffer.from(b.toString('binary'), 'binary')
.indexOf(Buffer.from('d', 'binary'), 0, 'binary'),
3
);
assert.strictEqual(
Buffer.from('aa\u00e8aa', 'binary')
.indexOf('\u00e8', 'binary'),
2
);
assert.strictEqual(
Buffer.from('\u00e8', 'binary')
.indexOf('\u00e8', 'binary'),
0
);
assert.strictEqual(
Buffer.from('\u00e8', 'binary')
.indexOf(Buffer.from('\u00e8', 'binary'), 'binary'),
0
);
// test optional offset with passed encoding
assert.strictEqual(Buffer.from('aaaa0').indexOf('30', 'hex'), 4);
assert.strictEqual(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4);
{
// test usc2 encoding
const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
assert.strictEqual(8, twoByteString.indexOf('\u0395', 4, 'ucs2'));
assert.strictEqual(6, twoByteString.indexOf('\u03a3', -4, 'ucs2'));
assert.strictEqual(4, twoByteString.indexOf('\u03a3', -6, 'ucs2'));
assert.strictEqual(4, twoByteString.indexOf(
Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2'));
assert.strictEqual(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2'));
}
const mixedByteStringUcs2 =
Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2');
assert.strictEqual(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2'));
assert.strictEqual(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2'));
assert.strictEqual(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2'));
assert.strictEqual(
6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2'));
assert.strictEqual(
10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2'));
assert.strictEqual(
-1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2'));
{
const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
// Test single char pattern
assert.strictEqual(0, twoByteString.indexOf('\u039a', 0, 'ucs2'));
assert.strictEqual(2, twoByteString.indexOf('\u0391', 0, 'ucs2'),
'Alpha');
assert.strictEqual(4, twoByteString.indexOf('\u03a3', 0, 'ucs2'),
'First Sigma');
assert.strictEqual(6, twoByteString.indexOf('\u03a3', 6, 'ucs2'),
'Second Sigma');
assert.strictEqual(8, twoByteString.indexOf('\u0395', 0, 'ucs2'),
'Epsilon');
assert.strictEqual(-1, twoByteString.indexOf('\u0392', 0, 'ucs2'),
'Not beta');
// Test multi-char pattern
assert.strictEqual(
0, twoByteString.indexOf('\u039a\u0391', 0, 'ucs2'), 'Lambda Alpha');
assert.strictEqual(
2, twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2'), 'Alpha Sigma');
assert.strictEqual(
4, twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2'), 'Sigma Sigma');
assert.strictEqual(
6, twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2'), 'Sigma Epsilon');
}
const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395');
assert.strictEqual(5, mixedByteStringUtf8.indexOf('bc'));
assert.strictEqual(5, mixedByteStringUtf8.indexOf('bc', 5));
assert.strictEqual(5, mixedByteStringUtf8.indexOf('bc', -8));
assert.strictEqual(7, mixedByteStringUtf8.indexOf('\u03a3'));
assert.strictEqual(-1, mixedByteStringUtf8.indexOf('\u0396'));
// Test complex string indexOf algorithms. Only trigger for long strings.
// Long string that isn't a simple repeat of a shorter string.
let longString = 'A';
for (let i = 66; i < 76; i++) { // from 'B' to 'K'
longString = longString + String.fromCharCode(i) + longString;
}
const longBufferString = Buffer.from(longString);
// pattern of 15 chars, repeated every 16 chars in long
let pattern = 'ABACABADABACABA';
for (let i = 0; i < longBufferString.length - pattern.length; i += 7) {
const index = longBufferString.indexOf(pattern, i);
assert.strictEqual((i + 15) & ~0xf, index,
`Long ABACABA...-string at index ${i}`);
}
assert.strictEqual(510, longBufferString.indexOf('AJABACA'),
'Long AJABACA, First J');
assert.strictEqual(
1534, longBufferString.indexOf('AJABACA', 511), 'Long AJABACA, Second J');
pattern = 'JABACABADABACABA';
assert.strictEqual(
511, longBufferString.indexOf(pattern), 'Long JABACABA..., First J');
assert.strictEqual(
1535, longBufferString.indexOf(pattern, 512), 'Long JABACABA..., Second J');
// Search for a non-ASCII string in a pure ASCII string.
const asciiString = Buffer.from(
'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf');
assert.strictEqual(-1, asciiString.indexOf('\x2061'));
assert.strictEqual(3, asciiString.indexOf('leb', 0));
// Search in string containing many non-ASCII chars.
const allCodePoints = [];
for (let i = 0; i < 65536; i++) allCodePoints[i] = i;
const allCharsString = String.fromCharCode.apply(String, allCodePoints);
const allCharsBufferUtf8 = Buffer.from(allCharsString);
const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2');
// Search for string long enough to trigger complex search with ASCII pattern
// and UC16 subject.
assert.strictEqual(-1, allCharsBufferUtf8.indexOf('notfound'));
assert.strictEqual(-1, allCharsBufferUcs2.indexOf('notfound'));
// Needle is longer than haystack, but only because it's encoded as UTF-16
assert.strictEqual(Buffer.from('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1);
assert.strictEqual(Buffer.from('aaaa').indexOf('a'.repeat(4), 'utf8'), 0);
assert.strictEqual(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1);
// Haystack has odd length, but the needle is UCS2.
assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
{
// Find substrings in Utf8.
const lengths = [1, 3, 15]; // Single char, simple and complex.
const indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b];
for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
for (let i = 0; i < indices.length; i++) {
const index = indices[i];
let length = lengths[lengthIndex];
if (index + length > 0x7F) {
length = 2 * length;
}
if (index + length > 0x7FF) {
length = 3 * length;
}
if (index + length > 0xFFFF) {
length = 4 * length;
}
const patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length);
assert.strictEqual(index, allCharsBufferUtf8.indexOf(patternBufferUtf8));
const patternStringUtf8 = patternBufferUtf8.toString();
assert.strictEqual(index, allCharsBufferUtf8.indexOf(patternStringUtf8));
}
}
}
{
// Find substrings in Usc2.
const lengths = [2, 4, 16]; // Single char, simple and complex.
const indices = [0x5, 0x65, 0x105, 0x205, 0x285, 0x2005, 0x2085, 0xfff0];
for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
for (let i = 0; i < indices.length; i++) {
const index = indices[i] * 2;
const length = lengths[lengthIndex];
const patternBufferUcs2 =
allCharsBufferUcs2.slice(index, index + length);
assert.strictEqual(
index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2'));
const patternStringUcs2 = patternBufferUcs2.toString('ucs2');
assert.strictEqual(
index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2'));
}
}
}
const argumentExpected =
/^TypeError: "val" argument must be string, number, Buffer or Uint8Array$/;
assert.throws(() => {
b.indexOf(() => { });
}, argumentExpected);
assert.throws(() => {
b.indexOf({});
}, argumentExpected);
assert.throws(() => {
b.indexOf([]);
}, argumentExpected);
// Test weird offset arguments.
// The following offsets coerce to NaN or 0, searching the whole Buffer
assert.strictEqual(b.indexOf('b', undefined), 1);
assert.strictEqual(b.indexOf('b', {}), 1);
assert.strictEqual(b.indexOf('b', 0), 1);
assert.strictEqual(b.indexOf('b', null), 1);
assert.strictEqual(b.indexOf('b', []), 1);
// The following offset coerces to 2, in other words +[2] === 2
assert.strictEqual(b.indexOf('b', [2]), -1);
// Behavior should match String.indexOf()
assert.strictEqual(
b.indexOf('b', undefined),
s.indexOf('b', undefined));
assert.strictEqual(
b.indexOf('b', {}),
s.indexOf('b', {}));
assert.strictEqual(
b.indexOf('b', 0),
s.indexOf('b', 0));
assert.strictEqual(
b.indexOf('b', null),
s.indexOf('b', null));
assert.strictEqual(
b.indexOf('b', []),
s.indexOf('b', []));
assert.strictEqual(
b.indexOf('b', [2]),
s.indexOf('b', [2]));
// All code for handling encodings is shared between Buffer.indexOf and
// Buffer.lastIndexOf, so only testing the separate lastIndexOf semantics.
// Test lastIndexOf basic functionality; Buffer b contains 'abcdef'.
// lastIndexOf string:
assert.strictEqual(b.lastIndexOf('a'), 0);
assert.strictEqual(b.lastIndexOf('a', 1), 0);
assert.strictEqual(b.lastIndexOf('b', 1), 1);
assert.strictEqual(b.lastIndexOf('c', 1), -1);
assert.strictEqual(b.lastIndexOf('a', -1), 0);
assert.strictEqual(b.lastIndexOf('a', -4), 0);
assert.strictEqual(b.lastIndexOf('a', -b.length), 0);
assert.strictEqual(b.lastIndexOf('a', -b.length - 1), -1);
assert.strictEqual(b.lastIndexOf('a', NaN), 0);
assert.strictEqual(b.lastIndexOf('a', -Infinity), -1);
assert.strictEqual(b.lastIndexOf('a', Infinity), 0);
// lastIndexOf Buffer:
assert.strictEqual(b.lastIndexOf(buf_a), 0);
assert.strictEqual(b.lastIndexOf(buf_a, 1), 0);
assert.strictEqual(b.lastIndexOf(buf_a, -1), 0);
assert.strictEqual(b.lastIndexOf(buf_a, -4), 0);
assert.strictEqual(b.lastIndexOf(buf_a, -b.length), 0);
assert.strictEqual(b.lastIndexOf(buf_a, -b.length - 1), -1);
assert.strictEqual(b.lastIndexOf(buf_a, NaN), 0);
assert.strictEqual(b.lastIndexOf(buf_a, -Infinity), -1);
assert.strictEqual(b.lastIndexOf(buf_a, Infinity), 0);
assert.strictEqual(b.lastIndexOf(buf_bc), 1);
assert.strictEqual(b.lastIndexOf(buf_bc, 2), 1);
assert.strictEqual(b.lastIndexOf(buf_bc, -1), 1);
assert.strictEqual(b.lastIndexOf(buf_bc, -3), 1);
assert.strictEqual(b.lastIndexOf(buf_bc, -5), 1);
assert.strictEqual(b.lastIndexOf(buf_bc, -6), -1);
assert.strictEqual(b.lastIndexOf(buf_bc, NaN), 1);
assert.strictEqual(b.lastIndexOf(buf_bc, -Infinity), -1);
assert.strictEqual(b.lastIndexOf(buf_bc, Infinity), 1);
assert.strictEqual(b.lastIndexOf(buf_f), b.length - 1);
assert.strictEqual(b.lastIndexOf(buf_z), -1);
assert.strictEqual(b.lastIndexOf(buf_empty), b.length);
assert.strictEqual(b.lastIndexOf(buf_empty, 1), 1);
assert.strictEqual(b.lastIndexOf(buf_empty, b.length + 1), b.length);
assert.strictEqual(b.lastIndexOf(buf_empty, Infinity), b.length);
// lastIndexOf number:
assert.strictEqual(b.lastIndexOf(0x61), 0);
assert.strictEqual(b.lastIndexOf(0x61, 1), 0);
assert.strictEqual(b.lastIndexOf(0x61, -1), 0);
assert.strictEqual(b.lastIndexOf(0x61, -4), 0);
assert.strictEqual(b.lastIndexOf(0x61, -b.length), 0);
assert.strictEqual(b.lastIndexOf(0x61, -b.length - 1), -1);
assert.strictEqual(b.lastIndexOf(0x61, NaN), 0);
assert.strictEqual(b.lastIndexOf(0x61, -Infinity), -1);
assert.strictEqual(b.lastIndexOf(0x61, Infinity), 0);
assert.strictEqual(b.lastIndexOf(0x0), -1);
// Test weird offset arguments.
// The following offsets coerce to NaN, searching the whole Buffer
assert.strictEqual(b.lastIndexOf('b', undefined), 1);
assert.strictEqual(b.lastIndexOf('b', {}), 1);
// The following offsets coerce to 0
assert.strictEqual(b.lastIndexOf('b', 0), -1);
assert.strictEqual(b.lastIndexOf('b', null), -1);
assert.strictEqual(b.lastIndexOf('b', []), -1);
// The following offset coerces to 2, in other words +[2] === 2
assert.strictEqual(b.lastIndexOf('b', [2]), 1);
// Behavior should match String.lastIndexOf()
assert.strictEqual(
b.lastIndexOf('b', undefined),
s.lastIndexOf('b', undefined));
assert.strictEqual(
b.lastIndexOf('b', {}),
s.lastIndexOf('b', {}));
assert.strictEqual(
b.lastIndexOf('b', 0),
s.lastIndexOf('b', 0));
assert.strictEqual(
b.lastIndexOf('b', null),
s.lastIndexOf('b', null));
assert.strictEqual(
b.lastIndexOf('b', []),
s.lastIndexOf('b', []));
assert.strictEqual(
b.lastIndexOf('b', [2]),
s.lastIndexOf('b', [2]));
// Test needles longer than the haystack.
assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'ucs2'), -1);
assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'utf8'), -1);
assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'latin1'), -1);
assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 'binary'), -1);
assert.strictEqual(b.lastIndexOf(Buffer.from('aaaaaaaaaaaaaaa')), -1);
assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 2, 'ucs2'), -1);
assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 3, 'utf8'), -1);
assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 5, 'latin1'), -1);
assert.strictEqual(b.lastIndexOf('aaaaaaaaaaaaaaa', 5, 'binary'), -1);
assert.strictEqual(b.lastIndexOf(Buffer.from('aaaaaaaaaaaaaaa'), 7), -1);
// 你好 expands to a total of 6 bytes using UTF-8 and 4 bytes using UTF-16
assert.strictEqual(buf_bc.lastIndexOf('你好', 'ucs2'), -1);
assert.strictEqual(buf_bc.lastIndexOf('你好', 'utf8'), -1);
assert.strictEqual(buf_bc.lastIndexOf('你好', 'latin1'), -1);
assert.strictEqual(buf_bc.lastIndexOf('你好', 'binary'), -1);
assert.strictEqual(buf_bc.lastIndexOf(Buffer.from('你好')), -1);
assert.strictEqual(buf_bc.lastIndexOf('你好', 2, 'ucs2'), -1);
assert.strictEqual(buf_bc.lastIndexOf('你好', 3, 'utf8'), -1);
assert.strictEqual(buf_bc.lastIndexOf('你好', 5, 'latin1'), -1);
assert.strictEqual(buf_bc.lastIndexOf('你好', 5, 'binary'), -1);
assert.strictEqual(buf_bc.lastIndexOf(Buffer.from('你好'), 7), -1);
// Test lastIndexOf on a longer buffer:
const bufferString = new Buffer('a man a plan a canal panama');
assert.strictEqual(15, bufferString.lastIndexOf('canal'));
assert.strictEqual(21, bufferString.lastIndexOf('panama'));
assert.strictEqual(0, bufferString.lastIndexOf('a man a plan a canal panama'));
assert.strictEqual(-1, bufferString.lastIndexOf('a man a plan a canal mexico'));
assert.strictEqual(-1, bufferString
.lastIndexOf('a man a plan a canal mexico city'));
assert.strictEqual(-1, bufferString.lastIndexOf(Buffer.from('a'.repeat(1000))));
assert.strictEqual(0, bufferString.lastIndexOf('a man a plan', 4));
assert.strictEqual(13, bufferString.lastIndexOf('a '));
assert.strictEqual(13, bufferString.lastIndexOf('a ', 13));
assert.strictEqual(6, bufferString.lastIndexOf('a ', 12));
assert.strictEqual(0, bufferString.lastIndexOf('a ', 5));
assert.strictEqual(13, bufferString.lastIndexOf('a ', -1));
assert.strictEqual(0, bufferString.lastIndexOf('a ', -27));
assert.strictEqual(-1, bufferString.lastIndexOf('a ', -28));
// Test lastIndexOf for the case that the first character can be found,
// but in a part of the buffer that does not make search to search
// due do length constraints.
const abInUCS2 = Buffer.from('ab', 'ucs2');
assert.strictEqual(-1, Buffer.from('µaaaa¶bbbb', 'latin1').lastIndexOf('µ'));
assert.strictEqual(-1, Buffer.from('µaaaa¶bbbb', 'binary').lastIndexOf('µ'));
assert.strictEqual(-1, Buffer.from('bc').lastIndexOf('ab'));
assert.strictEqual(-1, Buffer.from('abc').lastIndexOf('qa'));
assert.strictEqual(-1, Buffer.from('abcdef').lastIndexOf('qabc'));
assert.strictEqual(-1, Buffer.from('bc').lastIndexOf(Buffer.from('ab')));
assert.strictEqual(-1, Buffer.from('bc', 'ucs2').lastIndexOf('ab', 'ucs2'));
assert.strictEqual(-1, Buffer.from('bc', 'ucs2').lastIndexOf(abInUCS2));
assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab'));
assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab', 1));
assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab', 2));
assert.strictEqual(0, Buffer.from('abc').lastIndexOf('ab', 3));
// The above tests test the LINEAR and SINGLE-CHAR strategies.
// Now, we test the BOYER-MOORE-HORSPOOL strategy.
// Test lastIndexOf on a long buffer w multiple matches:
pattern = 'JABACABADABACABA';
assert.strictEqual(1535, longBufferString.lastIndexOf(pattern));
assert.strictEqual(1535, longBufferString.lastIndexOf(pattern, 1535));
assert.strictEqual(511, longBufferString.lastIndexOf(pattern, 1534));
// Finally, give it a really long input to trigger fallback from BMH to
// regular BOYER-MOORE (which has better worst-case complexity).
// Generate a really long Thue-Morse sequence of 'yolo' and 'swag',
// "yolo swag swag yolo swag yolo yolo swag" ..., goes on for about 5MB.
// This is hard to search because it all looks similar, but never repeats.
// countBits returns the number of bits in the binary reprsentation of n.
function countBits(n) {
let count;
for (count = 0; n > 0; count++) {
n = n & (n - 1); // remove top bit
}
return count;
}
const parts = [];
for (let i = 0; i < 1000000; i++) {
parts.push((countBits(i) % 2 === 0) ? 'yolo' : 'swag');
}
const reallyLong = new Buffer(parts.join(' '));
assert.strictEqual('yolo swag swag yolo', reallyLong.slice(0, 19).toString());
// Expensive reverse searches. Stress test lastIndexOf:
pattern = reallyLong.slice(0, 100000); // First 1/50th of the pattern.
assert.strictEqual(4751360, reallyLong.lastIndexOf(pattern));
assert.strictEqual(3932160, reallyLong.lastIndexOf(pattern, 4000000));
assert.strictEqual(2949120, reallyLong.lastIndexOf(pattern, 3000000));
pattern = reallyLong.slice(100000, 200000); // Second 1/50th.
assert.strictEqual(4728480, reallyLong.lastIndexOf(pattern));
pattern = reallyLong.slice(0, 1000000); // First 1/5th.
assert.strictEqual(3932160, reallyLong.lastIndexOf(pattern));
pattern = reallyLong.slice(0, 2000000); // first 2/5ths.
assert.strictEqual(0, reallyLong.lastIndexOf(pattern));
// test truncation of Number arguments to uint8
{
const buf = Buffer.from('this is a test');
assert.strictEqual(buf.indexOf(0x6973), 3);
assert.strictEqual(buf.indexOf(0x697320), 4);
assert.strictEqual(buf.indexOf(0x69732069), 2);
assert.strictEqual(buf.indexOf(0x697374657374), 0);
assert.strictEqual(buf.indexOf(0x69737374), 0);
assert.strictEqual(buf.indexOf(0x69737465), 11);
assert.strictEqual(buf.indexOf(0x69737465), 11);
assert.strictEqual(buf.indexOf(-140), 0);
assert.strictEqual(buf.indexOf(-152), 1);
assert.strictEqual(buf.indexOf(0xff), -1);
assert.strictEqual(buf.indexOf(0xffff), -1);
}
// Test that Uint8Array arguments are okay.
{
const needle = new Uint8Array([ 0x66, 0x6f, 0x6f ]);
const haystack = Buffer.from('a foo b foo');
assert.strictEqual(haystack.indexOf(needle), 2);
assert.strictEqual(haystack.lastIndexOf(needle), haystack.length - 3);
}
| mit |
moomerman/zap | adapter/static/static_test.go | 488 | package static
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func TestStatic(t *testing.T) {
adapter, err := New("./test/static")
if err != nil {
panic(err)
}
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
rr := httptest.NewRecorder()
adapter.ServeHTTP(rr, req)
if status := rr.Code; status != http.StatusOK {
t.Errorf("handler returned wrong status code: got %v want %v",
status, http.StatusOK)
}
fmt.Println(rr)
}
| mit |
lewgun/cloudmusic | vendor/github.com/go-xorm/xorm/engine.go | 39052 | // Copyright 2015 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
import (
"bufio"
"bytes"
"database/sql"
"encoding/gob"
"errors"
"fmt"
"io"
"os"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/go-xorm/core"
)
// Engine is the major struct of xorm, it means a database manager.
// Commonly, an application only need one engine
type Engine struct {
db *core.DB
dialect core.Dialect
ColumnMapper core.IMapper
TableMapper core.IMapper
TagIdentifier string
Tables map[reflect.Type]*core.Table
mutex *sync.RWMutex
Cacher core.Cacher
ShowSQL bool
// !nashtsai! TODO ought to deprecate these but having logger to control its log level
ShowInfo bool
ShowErr bool
ShowDebug bool
ShowWarn bool
// --227
Logger core.ILogger
TZLocation *time.Location
disableGlobalCache bool
}
func (engine *Engine) SetLogger(logger core.ILogger) {
engine.Logger = logger
engine.dialect.SetLogger(logger)
}
func (engine *Engine) SetDisableGlobalCache(disable bool) {
if engine.disableGlobalCache != disable {
engine.disableGlobalCache = disable
}
}
func (engine *Engine) DriverName() string {
return engine.dialect.DriverName()
}
func (engine *Engine) DataSourceName() string {
return engine.dialect.DataSourceName()
}
func (engine *Engine) SetMapper(mapper core.IMapper) {
engine.SetTableMapper(mapper)
engine.SetColumnMapper(mapper)
}
func (engine *Engine) SetTableMapper(mapper core.IMapper) {
engine.TableMapper = mapper
}
func (engine *Engine) SetColumnMapper(mapper core.IMapper) {
engine.ColumnMapper = mapper
}
// If engine's database support batch insert records like
// "insert into user values (name, age), (name, age)".
// When the return is ture, then engine.Insert(&users) will
// generate batch sql and exeute.
func (engine *Engine) SupportInsertMany() bool {
return engine.dialect.SupportInsertMany()
}
// Engine's database use which charactor as quote.
// mysql, sqlite use ` and postgres use "
func (engine *Engine) QuoteStr() string {
return engine.dialect.QuoteStr()
}
// Use QuoteStr quote the string sql
func (engine *Engine) Quote(sql string) string {
if len(sql) == 0 {
return sql
}
if string(sql[0]) == engine.dialect.QuoteStr() || sql[0] == '`' {
return sql
}
return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr()
}
// A simple wrapper to dialect's core.SqlType method
func (engine *Engine) SqlType(c *core.Column) string {
return engine.dialect.SqlType(c)
}
// Database's autoincrement statement
func (engine *Engine) AutoIncrStr() string {
return engine.dialect.AutoIncrStr()
}
// SetMaxOpenConns is only available for go 1.2+
func (engine *Engine) SetMaxOpenConns(conns int) {
engine.db.SetMaxOpenConns(conns)
}
// @Deprecated
func (engine *Engine) SetMaxConns(conns int) {
engine.SetMaxOpenConns(conns)
}
// SetMaxIdleConns
func (engine *Engine) SetMaxIdleConns(conns int) {
engine.db.SetMaxIdleConns(conns)
}
// SetDefaltCacher set the default cacher. Xorm's default not enable cacher.
func (engine *Engine) SetDefaultCacher(cacher core.Cacher) {
engine.Cacher = cacher
}
// If you has set default cacher, and you want temporilly stop use cache,
// you can use NoCache()
func (engine *Engine) NoCache() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCache()
}
func (engine *Engine) NoCascade() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoCascade()
}
// Set a table use a special cacher
func (engine *Engine) MapCacher(bean interface{}, cacher core.Cacher) {
v := rValue(bean)
tb := engine.autoMapType(v)
tb.Cacher = cacher
}
// NewDB provides an interface to operate database directly
func (engine *Engine) NewDB() (*core.DB, error) {
return core.OpenDialect(engine.dialect)
}
func (engine *Engine) DB() *core.DB {
return engine.db
}
func (engine *Engine) Dialect() core.Dialect {
return engine.dialect
}
// New a session
func (engine *Engine) NewSession() *Session {
session := &Session{Engine: engine}
session.Init()
return session
}
// Close the engine
func (engine *Engine) Close() error {
return engine.db.Close()
}
// Ping tests if database is alive
func (engine *Engine) Ping() error {
session := engine.NewSession()
defer session.Close()
engine.LogInfo("PING DATABASE", engine.DriverName)
return session.Ping()
}
// logging sql
func (engine *Engine) logSQL(sqlStr string, sqlArgs ...interface{}) {
if engine.ShowSQL {
engine.overrideLogLevel(core.LOG_INFO)
if len(sqlArgs) > 0 {
engine.Logger.Infof("[sql] %v [args] %v", sqlStr, sqlArgs)
} else {
engine.Logger.Infof("[sql] %v", sqlStr)
}
}
}
func (engine *Engine) LogSQLQueryTime(sqlStr string, args interface{}, executionBlock func() (*core.Stmt, *core.Rows, error)) (*core.Stmt, *core.Rows, error) {
if engine.ShowDebug {
b4ExecTime := time.Now()
stmt, res, err := executionBlock()
execDuration := time.Since(b4ExecTime)
engine.LogDebugf("[time] %s - args %v - query took: %vns", sqlStr, args, execDuration.Nanoseconds())
return stmt, res, err
} else {
return executionBlock()
}
}
func (engine *Engine) LogSQLExecutionTime(sqlStr string, args interface{}, executionBlock func() (sql.Result, error)) (sql.Result, error) {
if engine.ShowDebug {
b4ExecTime := time.Now()
res, err := executionBlock()
execDuration := time.Since(b4ExecTime)
engine.LogDebugf("[time] %s - args %v - execution took: %vns", sqlStr, args, execDuration.Nanoseconds())
return res, err
} else {
return executionBlock()
}
}
// logging error
func (engine *Engine) overrideLogLevel(overrideLevel core.LogLevel) {
logLevel := engine.Logger.Level()
if logLevel == core.LOG_UNKNOWN {
// intend to left empty
} else if logLevel < overrideLevel { // TODO can remove if deprecated engine.ShowErr
engine.Logger.SetLevel(core.LOG_ERR) // try override logger's log level
}
}
func (engine *Engine) LogError(contents ...interface{}) {
if engine.ShowErr {
engine.overrideLogLevel(core.LOG_ERR)
engine.Logger.Err(contents...)
}
}
func (engine *Engine) LogErrorf(format string, contents ...interface{}) {
if engine.ShowErr {
engine.overrideLogLevel(core.LOG_ERR)
engine.Logger.Errf(format, contents...)
}
}
// logging info
func (engine *Engine) LogInfo(contents ...interface{}) {
if engine.ShowInfo {
engine.overrideLogLevel(core.LOG_INFO)
engine.Logger.Info(contents...)
}
}
func (engine *Engine) LogInfof(format string, contents ...interface{}) {
if engine.ShowErr {
engine.overrideLogLevel(core.LOG_INFO)
engine.Logger.Infof(format, contents...)
}
}
// logging debug
func (engine *Engine) LogDebug(contents ...interface{}) {
if engine.ShowDebug {
engine.overrideLogLevel(core.LOG_DEBUG)
engine.Logger.Debug(contents...)
}
}
func (engine *Engine) LogDebugf(format string, contents ...interface{}) {
if engine.ShowDebug {
engine.overrideLogLevel(core.LOG_DEBUG)
engine.Logger.Debugf(format, contents...)
}
}
// logging warn
func (engine *Engine) LogWarn(contents ...interface{}) {
if engine.ShowWarn {
engine.overrideLogLevel(core.LOG_WARNING)
engine.Logger.Warning(contents...)
}
}
func (engine *Engine) LogWarnf(format string, contents ...interface{}) {
if engine.ShowWarn {
engine.overrideLogLevel(core.LOG_WARNING)
engine.Logger.Warningf(format, contents...)
}
}
// Sql method let's you manualy write raw sql and operate
// For example:
//
// engine.Sql("select * from user").Find(&users)
//
// This code will execute "select * from user" and set the records to users
//
func (engine *Engine) Sql(querystring string, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Sql(querystring, args...)
}
// Default if your struct has "created" or "updated" filed tag, the fields
// will automatically be filled with current time when Insert or Update
// invoked. Call NoAutoTime if you dont' want to fill automatically.
func (engine *Engine) NoAutoTime() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.NoAutoTime()
}
// Retrieve all tables, columns, indexes' informations from database.
func (engine *Engine) DBMetas() ([]*core.Table, error) {
tables, err := engine.dialect.GetTables()
if err != nil {
return nil, err
}
for _, table := range tables {
colSeq, cols, err := engine.dialect.GetColumns(table.Name)
if err != nil {
return nil, err
}
for _, name := range colSeq {
table.AddColumn(cols[name])
}
//table.Columns = cols
//table.ColumnsSeq = colSeq
indexes, err := engine.dialect.GetIndexes(table.Name)
if err != nil {
return nil, err
}
table.Indexes = indexes
for _, index := range indexes {
for _, name := range index.Cols {
if col := table.GetColumn(name); col != nil {
col.Indexes[index.Name] = true
} else {
return nil, fmt.Errorf("Unknown col "+name+" in indexes %v of table", index, table.ColumnsSeq())
}
}
}
}
return tables, nil
}
/*
dump database all table structs and data to a file
*/
func (engine *Engine) DumpAllToFile(fp string) error {
f, err := os.Create(fp)
if err != nil {
return err
}
defer f.Close()
return engine.DumpAll(f)
}
/*
dump database all table structs and data to w
*/
func (engine *Engine) DumpAll(w io.Writer) error {
tables, err := engine.DBMetas()
if err != nil {
return err
}
for _, table := range tables {
_, err = io.WriteString(w, engine.dialect.CreateTableSql(table, "", table.StoreEngine, "")+"\n\n")
if err != nil {
return err
}
for _, index := range table.Indexes {
_, err = io.WriteString(w, engine.dialect.CreateIndexSql(table.Name, index)+"\n\n")
if err != nil {
return err
}
}
rows, err := engine.DB().Query("SELECT * FROM " + engine.Quote(table.Name))
if err != nil {
return err
}
cols, err := rows.Columns()
if err != nil {
return err
}
if len(cols) == 0 {
continue
}
for rows.Next() {
dest := make([]interface{}, len(cols))
err = rows.ScanSlice(&dest)
if err != nil {
return err
}
_, err = io.WriteString(w, "INSERT INTO "+engine.Quote(table.Name)+" ("+engine.Quote(strings.Join(cols, engine.Quote(", ")))+") VALUES (")
if err != nil {
return err
}
var temp string
for i, d := range dest {
col := table.GetColumn(cols[i])
if d == nil {
temp += ", NULL"
} else if col.SQLType.IsText() || col.SQLType.IsTime() {
var v = fmt.Sprintf("%s", d)
temp += ", '" + strings.Replace(v, "'", "''", -1) + "'"
} else if col.SQLType.IsBlob() {
if reflect.TypeOf(d).Kind() == reflect.Slice {
temp += fmt.Sprintf(", %s", engine.dialect.FormatBytes(d.([]byte)))
} else if reflect.TypeOf(d).Kind() == reflect.String {
temp += fmt.Sprintf(", '%s'", d.(string))
}
} else if col.SQLType.IsNumeric() {
switch reflect.TypeOf(d).Kind() {
case reflect.Slice:
temp += fmt.Sprintf(", %s", string(d.([]byte)))
default:
temp += fmt.Sprintf(", %v", d)
}
} else {
s := fmt.Sprintf("%v", d)
if strings.Contains(s, ":") || strings.Contains(s, "-") {
temp += fmt.Sprintf(", '%s'", s)
} else {
temp += fmt.Sprintf(", %s", s)
}
}
}
_, err = io.WriteString(w, temp[2:]+");\n\n")
if err != nil {
return err
}
}
}
return nil
}
// use cascade or not
func (engine *Engine) Cascade(trueOrFalse ...bool) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Cascade(trueOrFalse...)
}
// Where method provide a condition query
func (engine *Engine) Where(querystring string, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Where(querystring, args...)
}
// Id mehtod provoide a condition as (id) = ?
func (engine *Engine) Id(id interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Id(id)
}
// Apply before Processor, affected bean is passed to closure arg
func (engine *Engine) Before(closures func(interface{})) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Before(closures)
}
// Apply after insert Processor, affected bean is passed to closure arg
func (engine *Engine) After(closures func(interface{})) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.After(closures)
}
// set charset when create table, only support mysql now
func (engine *Engine) Charset(charset string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Charset(charset)
}
// set store engine when create table, only support mysql now
func (engine *Engine) StoreEngine(storeEngine string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.StoreEngine(storeEngine)
}
// use for distinct columns. Caution: when you are using cache,
// distinct will not be cached because cache system need id,
// but distinct will not provide id
func (engine *Engine) Distinct(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Distinct(columns...)
}
func (engine *Engine) Select(str string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Select(str)
}
// only use the paramters as select or update columns
func (engine *Engine) Cols(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Cols(columns...)
}
func (engine *Engine) AllCols() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.AllCols()
}
func (engine *Engine) MustCols(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.MustCols(columns...)
}
// Xorm automatically retrieve condition according struct, but
// if struct has bool field, it will ignore them. So use UseBool
// to tell system to do not ignore them.
// If no paramters, it will use all the bool field of struct, or
// it will use paramters's columns
func (engine *Engine) UseBool(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.UseBool(columns...)
}
// Only not use the paramters as select or update columns
func (engine *Engine) Omit(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Omit(columns...)
}
// Set null when column is zero-value and nullable for update
func (engine *Engine) Nullable(columns ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Nullable(columns...)
}
// This method will generate "column IN (?, ?)"
func (engine *Engine) In(column string, args ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.In(column, args...)
}
// Method Inc provides a update string like "column = column + ?"
func (engine *Engine) Incr(column string, arg ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Incr(column, arg...)
}
// Method Decr provides a update string like "column = column - ?"
func (engine *Engine) Decr(column string, arg ...interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Decr(column, arg...)
}
// Method SetExpr provides a update string like "column = {expression}"
func (engine *Engine) SetExpr(column string, expression string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.SetExpr(column, expression)
}
// Temporarily change the Get, Find, Update's table
func (engine *Engine) Table(tableNameOrBean interface{}) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Table(tableNameOrBean)
}
// set the table alias
func (engine *Engine) Alias(alias string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Alias(alias)
}
// This method will generate "LIMIT start, limit"
func (engine *Engine) Limit(limit int, start ...int) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Limit(limit, start...)
}
// Method Desc will generate "ORDER BY column1 DESC, column2 DESC"
// This will
func (engine *Engine) Desc(colNames ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Desc(colNames...)
}
// Method Asc will generate "ORDER BY column1,column2 Asc"
// This method can chainable use.
//
// engine.Desc("name").Asc("age").Find(&users)
// // SELECT * FROM user ORDER BY name DESC, age ASC
//
func (engine *Engine) Asc(colNames ...string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Asc(colNames...)
}
// Method OrderBy will generate "ORDER BY order"
func (engine *Engine) OrderBy(order string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.OrderBy(order)
}
// The join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN
func (engine *Engine) Join(join_operator string, tablename interface{}, condition string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Join(join_operator, tablename, condition)
}
// Generate Group By statement
func (engine *Engine) GroupBy(keys string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.GroupBy(keys)
}
// Generate Having statement
func (engine *Engine) Having(conditions string) *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Having(conditions)
}
func (engine *Engine) autoMapType(v reflect.Value) *core.Table {
t := v.Type()
engine.mutex.Lock()
table, ok := engine.Tables[t]
if !ok {
table = engine.mapType(v)
engine.Tables[t] = table
if engine.Cacher != nil {
if v.CanAddr() {
engine.GobRegister(v.Addr().Interface())
} else {
engine.GobRegister(v.Interface())
}
}
}
engine.mutex.Unlock()
return table
}
func (engine *Engine) GobRegister(v interface{}) *Engine {
//fmt.Printf("Type: %[1]T => Data: %[1]#v\n", v)
gob.Register(v)
return engine
}
func (engine *Engine) TableInfo(bean interface{}) *core.Table {
v := rValue(bean)
return engine.autoMapType(v)
}
func addIndex(indexName string, table *core.Table, col *core.Column, indexType int) {
if index, ok := table.Indexes[indexName]; ok {
index.AddColumn(col.Name)
col.Indexes[index.Name] = true
} else {
index := core.NewIndex(indexName, indexType)
index.AddColumn(col.Name)
table.AddIndex(index)
col.Indexes[index.Name] = true
}
}
func (engine *Engine) newTable() *core.Table {
table := core.NewEmptyTable()
if !engine.disableGlobalCache {
table.Cacher = engine.Cacher
}
return table
}
func (engine *Engine) mapType(v reflect.Value) *core.Table {
t := v.Type()
table := engine.newTable()
method := v.MethodByName("TableName")
if !method.IsValid() {
if v.CanAddr() {
method = v.Addr().MethodByName("TableName")
}
}
if method.IsValid() {
params := []reflect.Value{}
results := method.Call(params)
if len(results) == 1 {
table.Name = results[0].Interface().(string)
}
}
if table.Name == "" {
table.Name = engine.TableMapper.Obj2Table(t.Name())
}
table.Type = t
var idFieldColName string
var err error
hasCacheTag := false
hasNoCacheTag := false
for i := 0; i < t.NumField(); i++ {
tag := t.Field(i).Tag
ormTagStr := tag.Get(engine.TagIdentifier)
var col *core.Column
fieldValue := v.Field(i)
fieldType := fieldValue.Type()
if ormTagStr != "" {
col = &core.Column{FieldName: t.Field(i).Name, Nullable: true, IsPrimaryKey: false,
IsAutoIncrement: false, MapType: core.TWOSIDES, Indexes: make(map[string]bool)}
tags := strings.Split(ormTagStr, " ")
if len(tags) > 0 {
if tags[0] == "-" {
continue
}
if strings.ToUpper(tags[0]) == "EXTENDS" {
if fieldValue.Kind() == reflect.Struct {
parentTable := engine.mapType(fieldValue)
for _, col := range parentTable.Columns() {
col.FieldName = fmt.Sprintf("%v.%v", t.Field(i).Name, col.FieldName)
table.AddColumn(col)
}
continue
} else if fieldValue.Kind() == reflect.Ptr {
f := fieldValue.Type().Elem()
if f.Kind() == reflect.Struct {
fieldValue = fieldValue.Elem()
if !fieldValue.IsValid() || fieldValue.IsNil() {
fieldValue = reflect.New(f).Elem()
}
}
parentTable := engine.mapType(fieldValue)
for _, col := range parentTable.Columns() {
col.FieldName = fmt.Sprintf("%v.%v", t.Field(i).Name, col.FieldName)
table.AddColumn(col)
}
continue
}
//TODO: warning
}
indexNames := make(map[string]int)
var isIndex, isUnique bool
var preKey string
for j, key := range tags {
k := strings.ToUpper(key)
switch {
case k == "<-":
col.MapType = core.ONLYFROMDB
case k == "->":
col.MapType = core.ONLYTODB
case k == "PK":
col.IsPrimaryKey = true
col.Nullable = false
case k == "NULL":
if j == 0 {
col.Nullable = true
} else {
col.Nullable = (strings.ToUpper(tags[j-1]) != "NOT")
}
// TODO: for postgres how add autoincr?
/*case strings.HasPrefix(k, "AUTOINCR(") && strings.HasSuffix(k, ")"):
col.IsAutoIncrement = true
autoStart := k[len("AUTOINCR")+1 : len(k)-1]
autoStartInt, err := strconv.Atoi(autoStart)
if err != nil {
engine.LogError(err)
}
col.AutoIncrStart = autoStartInt*/
case k == "AUTOINCR":
col.IsAutoIncrement = true
//col.AutoIncrStart = 1
case k == "DEFAULT":
col.Default = tags[j+1]
case k == "CREATED":
col.IsCreated = true
case k == "VERSION":
col.IsVersion = true
col.Default = "1"
case k == "UPDATED":
col.IsUpdated = true
case k == "DELETED":
col.IsDeleted = true
case strings.HasPrefix(k, "INDEX(") && strings.HasSuffix(k, ")"):
indexName := k[len("INDEX")+1 : len(k)-1]
indexNames[indexName] = core.IndexType
case k == "INDEX":
isIndex = true
case strings.HasPrefix(k, "UNIQUE(") && strings.HasSuffix(k, ")"):
indexName := k[len("UNIQUE")+1 : len(k)-1]
indexNames[indexName] = core.UniqueType
case k == "UNIQUE":
isUnique = true
case k == "NOTNULL":
col.Nullable = false
case k == "CACHE":
if !hasCacheTag {
hasCacheTag = true
}
case k == "NOCACHE":
if !hasNoCacheTag {
hasNoCacheTag = true
}
case k == "NOT":
default:
if strings.HasPrefix(k, "'") && strings.HasSuffix(k, "'") {
if preKey != "DEFAULT" {
col.Name = key[1 : len(key)-1]
}
} else if strings.Contains(k, "(") && strings.HasSuffix(k, ")") {
fs := strings.Split(k, "(")
if _, ok := core.SqlTypes[fs[0]]; !ok {
preKey = k
continue
}
col.SQLType = core.SQLType{fs[0], 0, 0}
if fs[0] == core.Enum && fs[1][0] == '\'' { //enum
options := strings.Split(fs[1][0:len(fs[1])-1], ",")
col.EnumOptions = make(map[string]int)
for k, v := range options {
v = strings.TrimSpace(v)
v = strings.Trim(v, "'")
col.EnumOptions[v] = k
}
} else if fs[0] == core.Set && fs[1][0] == '\'' { //set
options := strings.Split(fs[1][0:len(fs[1])-1], ",")
col.SetOptions = make(map[string]int)
for k, v := range options {
v = strings.TrimSpace(v)
v = strings.Trim(v, "'")
col.SetOptions[v] = k
}
} else {
fs2 := strings.Split(fs[1][0:len(fs[1])-1], ",")
if len(fs2) == 2 {
col.Length, err = strconv.Atoi(fs2[0])
if err != nil {
engine.LogError(err)
}
col.Length2, err = strconv.Atoi(fs2[1])
if err != nil {
engine.LogError(err)
}
} else if len(fs2) == 1 {
col.Length, err = strconv.Atoi(fs2[0])
if err != nil {
engine.LogError(err)
}
}
}
} else {
if _, ok := core.SqlTypes[k]; ok {
col.SQLType = core.SQLType{k, 0, 0}
} else if key != col.Default {
col.Name = key
}
}
engine.dialect.SqlType(col)
}
preKey = k
}
if col.SQLType.Name == "" {
col.SQLType = core.Type2SQLType(fieldType)
}
if col.Length == 0 {
col.Length = col.SQLType.DefaultLength
}
if col.Length2 == 0 {
col.Length2 = col.SQLType.DefaultLength2
}
if col.Name == "" {
col.Name = engine.ColumnMapper.Obj2Table(t.Field(i).Name)
}
if isUnique {
indexNames[col.Name] = core.UniqueType
} else if isIndex {
indexNames[col.Name] = core.IndexType
}
for indexName, indexType := range indexNames {
addIndex(indexName, table, col, indexType)
}
}
} else {
var sqlType core.SQLType
if fieldValue.CanAddr() {
if _, ok := fieldValue.Addr().Interface().(core.Conversion); ok {
sqlType = core.SQLType{core.Text, 0, 0}
}
}
if _, ok := fieldValue.Interface().(core.Conversion); ok {
sqlType = core.SQLType{core.Text, 0, 0}
} else {
sqlType = core.Type2SQLType(fieldType)
}
col = core.NewColumn(engine.ColumnMapper.Obj2Table(t.Field(i).Name),
t.Field(i).Name, sqlType, sqlType.DefaultLength,
sqlType.DefaultLength2, true)
}
if col.IsAutoIncrement {
col.Nullable = false
}
table.AddColumn(col)
if fieldType.Kind() == reflect.Int64 && (strings.ToUpper(col.FieldName) == "ID" || strings.HasSuffix(strings.ToUpper(col.FieldName), ".ID")) {
idFieldColName = col.Name
}
} // end for
if idFieldColName != "" && len(table.PrimaryKeys) == 0 {
col := table.GetColumn(idFieldColName)
col.IsPrimaryKey = true
col.IsAutoIncrement = true
col.Nullable = false
table.PrimaryKeys = append(table.PrimaryKeys, col.Name)
table.AutoIncrement = col.Name
}
if hasCacheTag {
if engine.Cacher != nil { // !nash! use engine's cacher if provided
engine.Logger.Info("enable cache on table:", table.Name)
table.Cacher = engine.Cacher
} else {
engine.Logger.Info("enable LRU cache on table:", table.Name)
table.Cacher = NewLRUCacher2(NewMemoryStore(), time.Hour, 10000) // !nashtsai! HACK use LRU cacher for now
}
}
if hasNoCacheTag {
engine.Logger.Info("no cache on table:", table.Name)
table.Cacher = nil
}
return table
}
// Map a struct to a table
func (engine *Engine) mapping(beans ...interface{}) (e error) {
engine.mutex.Lock()
defer engine.mutex.Unlock()
for _, bean := range beans {
v := rValue(bean)
engine.Tables[v.Type()] = engine.mapType(v)
}
return
}
// If a table has any reocrd
func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) {
session := engine.NewSession()
defer session.Close()
return session.IsTableEmpty(bean)
}
// If a table is exist
func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error) {
session := engine.NewSession()
defer session.Close()
return session.IsTableExist(beanOrTableName)
}
func (engine *Engine) IdOf(bean interface{}) core.PK {
return engine.IdOfV(reflect.ValueOf(bean))
}
func (engine *Engine) IdOfV(rv reflect.Value) core.PK {
v := reflect.Indirect(rv)
table := engine.autoMapType(v)
pk := make([]interface{}, len(table.PrimaryKeys))
for i, col := range table.PKColumns() {
pkField := v.FieldByName(col.FieldName)
switch pkField.Kind() {
case reflect.String:
pk[i] = pkField.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
pk[i] = pkField.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
pk[i] = pkField.Uint()
}
}
return core.PK(pk)
}
// create indexes
func (engine *Engine) CreateIndexes(bean interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.CreateIndexes(bean)
}
// create uniques
func (engine *Engine) CreateUniques(bean interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.CreateUniques(bean)
}
func (engine *Engine) getCacher2(table *core.Table) core.Cacher {
return table.Cacher
}
func (engine *Engine) getCacher(v reflect.Value) core.Cacher {
if table := engine.autoMapType(v); table != nil {
return table.Cacher
}
return engine.Cacher
}
// If enabled cache, clear the cache bean
func (engine *Engine) ClearCacheBean(bean interface{}, id string) error {
t := rType(bean)
if t.Kind() != reflect.Struct {
return errors.New("error params")
}
table := engine.TableInfo(bean)
cacher := table.Cacher
if cacher == nil {
cacher = engine.Cacher
}
if cacher != nil {
cacher.ClearIds(table.Name)
cacher.DelBean(table.Name, id)
}
return nil
}
// If enabled cache, clear some tables' cache
func (engine *Engine) ClearCache(beans ...interface{}) error {
for _, bean := range beans {
t := rType(bean)
if t.Kind() != reflect.Struct {
return errors.New("error params")
}
table := engine.TableInfo(bean)
cacher := table.Cacher
if cacher == nil {
cacher = engine.Cacher
}
if cacher != nil {
cacher.ClearIds(table.Name)
cacher.ClearBeans(table.Name)
}
}
return nil
}
// Sync the new struct changes to database, this method will automatically add
// table, column, index, unique. but will not delete or change anything.
// If you change some field, you should change the database manually.
func (engine *Engine) Sync(beans ...interface{}) error {
for _, bean := range beans {
table := engine.TableInfo(bean)
s := engine.NewSession()
defer s.Close()
isExist, err := s.Table(bean).isTableExist(table.Name)
if err != nil {
return err
}
if !isExist {
err = engine.CreateTables(bean)
if err != nil {
return err
}
}
/*isEmpty, err := engine.IsEmptyTable(bean)
if err != nil {
return err
}*/
var isEmpty bool = false
if isEmpty {
err = engine.DropTables(bean)
if err != nil {
return err
}
err = engine.CreateTables(bean)
if err != nil {
return err
}
} else {
for _, col := range table.Columns() {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
isExist, err := session.Engine.dialect.IsColumnExist(table.Name, col.Name)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addColumn(col.Name)
if err != nil {
return err
}
}
}
for name, index := range table.Indexes {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
if index.Type == core.UniqueType {
//isExist, err := session.isIndexExist(table.Name, name, true)
isExist, err := session.isIndexExist2(table.Name, index.Cols, true)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addUnique(table.Name, name)
if err != nil {
return err
}
}
} else if index.Type == core.IndexType {
isExist, err := session.isIndexExist2(table.Name, index.Cols, false)
if err != nil {
return err
}
if !isExist {
session := engine.NewSession()
session.Statement.RefTable = table
defer session.Close()
err = session.addIndex(table.Name, name)
if err != nil {
return err
}
}
} else {
return errors.New("unknow index type")
}
}
}
}
return nil
}
func (engine *Engine) Sync2(beans ...interface{}) error {
s := engine.NewSession()
defer s.Close()
return s.Sync2(beans...)
}
func (engine *Engine) unMap(beans ...interface{}) (e error) {
engine.mutex.Lock()
defer engine.mutex.Unlock()
for _, bean := range beans {
t := rType(bean)
if _, ok := engine.Tables[t]; ok {
delete(engine.Tables, t)
}
}
return
}
// Drop all mapped table
func (engine *Engine) dropAll() error {
session := engine.NewSession()
defer session.Close()
err := session.Begin()
if err != nil {
return err
}
err = session.dropAll()
if err != nil {
session.Rollback()
return err
}
return session.Commit()
}
// CreateTables create tabls according bean
func (engine *Engine) CreateTables(beans ...interface{}) error {
session := engine.NewSession()
err := session.Begin()
defer session.Close()
if err != nil {
return err
}
for _, bean := range beans {
err = session.CreateTable(bean)
if err != nil {
session.Rollback()
return err
}
}
return session.Commit()
}
func (engine *Engine) DropTables(beans ...interface{}) error {
session := engine.NewSession()
defer session.Close()
err := session.Begin()
if err != nil {
return err
}
for _, bean := range beans {
err = session.DropTable(bean)
if err != nil {
session.Rollback()
return err
}
}
return session.Commit()
}
func (engine *Engine) createAll() error {
session := engine.NewSession()
defer session.Close()
return session.createAll()
}
// Exec raw sql
func (engine *Engine) Exec(sql string, args ...interface{}) (sql.Result, error) {
session := engine.NewSession()
defer session.Close()
return session.Exec(sql, args...)
}
// Exec a raw sql and return records as []map[string][]byte
func (engine *Engine) Query(sql string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) {
session := engine.NewSession()
defer session.Close()
return session.Query(sql, paramStr...)
}
// Insert one or more records
func (engine *Engine) Insert(beans ...interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Insert(beans...)
}
// Insert only one record
func (engine *Engine) InsertOne(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.InsertOne(bean)
}
// Update records, bean's non-empty fields are updated contents,
// condiBean' non-empty filds are conditions
// CAUTION:
// 1.bool will defaultly be updated content nor conditions
// You should call UseBool if you have bool to use.
// 2.float32 & float64 may be not inexact as conditions
func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Update(bean, condiBeans...)
}
// Delete records, bean's non-empty fields are conditions
func (engine *Engine) Delete(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Delete(bean)
}
// Get retrieve one record from table, bean's non-empty fields
// are conditions
func (engine *Engine) Get(bean interface{}) (bool, error) {
session := engine.NewSession()
defer session.Close()
return session.Get(bean)
}
// Find retrieve records from table, condiBeans's non-empty fields
// are conditions. beans could be []Struct, []*Struct, map[int64]Struct
// map[int64]*Struct
func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error {
session := engine.NewSession()
defer session.Close()
return session.Find(beans, condiBeans...)
}
// Iterate record by record handle records from table, bean's non-empty fields
// are conditions.
func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error {
session := engine.NewSession()
defer session.Close()
return session.Iterate(bean, fun)
}
// Return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields
// are conditions.
func (engine *Engine) Rows(bean interface{}) (*Rows, error) {
session := engine.NewSession()
return session.Rows(bean)
}
// Count counts the records. bean's non-empty fields
// are conditions.
func (engine *Engine) Count(bean interface{}) (int64, error) {
session := engine.NewSession()
defer session.Close()
return session.Count(bean)
}
// Import SQL DDL file
func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error) {
file, err := os.Open(ddlPath)
if err != nil {
return nil, err
}
defer file.Close()
return engine.Import(file)
}
// Import SQL DDL file
func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) {
var results []sql.Result
var lastError error
scanner := bufio.NewScanner(r)
semiColSpliter := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, ';'); i >= 0 {
return i + 1, data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
scanner.Split(semiColSpliter)
for scanner.Scan() {
query := scanner.Text()
query = strings.Trim(query, " \t")
if len(query) > 0 {
result, err := engine.DB().Exec(query)
results = append(results, result)
if err != nil {
lastError = err
}
}
}
return results, lastError
}
var (
NULL_TIME time.Time
)
func (engine *Engine) TZTime(t time.Time) time.Time {
if NULL_TIME != t { // if time is not initialized it's not suitable for Time.In()
return t.In(engine.TZLocation)
}
return t
}
func (engine *Engine) NowTime(sqlTypeName string) interface{} {
t := time.Now()
return engine.FormatTime(sqlTypeName, t)
}
func (engine *Engine) NowTime2(sqlTypeName string) (interface{}, time.Time) {
t := time.Now()
return engine.FormatTime(sqlTypeName, t), t
}
func (engine *Engine) FormatTime(sqlTypeName string, t time.Time) (v interface{}) {
if engine.dialect.DBType() == core.ORACLE {
return t
}
switch sqlTypeName {
case core.Time:
s := engine.TZTime(t).Format("2006-01-02 15:04:05") //time.RFC3339
v = s[11:19]
case core.Date:
v = engine.TZTime(t).Format("2006-01-02")
case core.DateTime, core.TimeStamp:
if engine.dialect.DBType() == "ql" {
v = engine.TZTime(t)
} else if engine.dialect.DBType() == "sqlite3" {
v = engine.TZTime(t).UTC().Format("2006-01-02 15:04:05")
} else {
v = engine.TZTime(t).Format("2006-01-02 15:04:05")
}
case core.TimeStampz:
if engine.dialect.DBType() == core.MSSQL {
v = engine.TZTime(t).Format("2006-01-02T15:04:05.9999999Z07:00")
} else if engine.DriverName() == "mssql" {
v = engine.TZTime(t)
} else {
v = engine.TZTime(t).Format(time.RFC3339Nano)
}
case core.BigInt, core.Int:
v = engine.TZTime(t).Unix()
default:
v = engine.TZTime(t)
}
return
}
// Always disable struct tag "deleted"
func (engine *Engine) Unscoped() *Session {
session := engine.NewSession()
session.IsAutoClose = true
return session.Unscoped()
}
| mit |
Nth-iteration-labs/streamingbandit | app/defaults/Lock_In_Feedback/get_context.py | 7 | #EMPTY
| mit |
jenkinsci/jenkins.py | python-wrapper/src/main/java/jenkins/python/expoint/SolutionPW.java | 4451 | package jenkins.python.expoint;
import hudson.model.AdministrativeMonitor;
import jenkins.model.Jenkins;
import hudson.model.AbstractModelObject;
import hudson.Extension;
import hudson.ExtensionPoint;
import hudson.ExtensionList;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import java.io.IOException;
import java.util.List;
import hudson.diagnosis.*;
import hudson.diagnosis.HudsonHomeDiskUsageMonitor.Solution.*;
import hudson.diagnosis.HudsonHomeDiskUsageMonitor.*;
import hudson.search.SearchFactory;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.Stapler;
import javax.servlet.ServletException;
import hudson.search.SearchableModelObject;
import hudson.search.Search;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchIndex;
import org.kohsuke.stapler.interceptor.RequirePOST;
import hudson.model.*;
import hudson.model.AbstractModelObject.*;
import jenkins.python.DataConvertor;
import jenkins.python.PythonExecutor;
/**
* This class was automatically generated by the PWM tool on 2014/03/21.
* @see hudson.diagnosis.HudsonHomeDiskUsageMonitor.Solution
*/
public abstract class SolutionPW extends Solution {
private transient PythonExecutor pexec;
private void initPython() {
if (pexec == null) {
pexec = new PythonExecutor(this);
String[] jMethods = new String[0];
String[] pFuncs = new String[0];
Class[][] argTypes = new Class[0][];
pexec.checkAbstrMethods(jMethods, pFuncs, argTypes);
String[] functions = new String[4];
functions[0] = "get_url";
functions[1] = "make_search_index";
functions[2] = "get_search";
functions[3] = "get_search_name";
int[] argsCount = new int[4];
argsCount[0] = 0;
argsCount[1] = 0;
argsCount[2] = 0;
argsCount[3] = 0;
pexec.registerFunctions(functions, argsCount);
}
}
public SolutionPW(String id) {
super(id);
}
public SolutionPW() {
super();
}
@Override
public String getUrl() {
initPython();
if (pexec.isImplemented(0)) {
return (String) pexec.execPython("get_url");
} else {
return super.getUrl();
}
}
@Override
public SearchIndexBuilder makeSearchIndex() {
initPython();
if (pexec.isImplemented(1)) {
return (SearchIndexBuilder) pexec.execPython("make_search_index");
} else {
return super.makeSearchIndex();
}
}
@Override
public Search getSearch() {
initPython();
if (pexec.isImplemented(2)) {
return (Search) pexec.execPython("get_search");
} else {
return super.getSearch();
}
}
@Override
public String getSearchName() {
initPython();
if (pexec.isImplemented(3)) {
return (String) pexec.execPython("get_search_name");
} else {
return super.getSearchName();
}
}
public String superGetUrl() {
return super.getUrl();
}
public SearchIndexBuilder superMakeSearchIndex() {
return super.makeSearchIndex();
}
public Search superGetSearch() {
return super.getSearch();
}
public String superGetSearchName() {
return super.getSearchName();
}
public Object execPython(String function, Object... params) {
initPython();
return pexec.execPython(function, params);
}
public byte execPythonByte(String function, Object... params) {
initPython();
return pexec.execPythonByte(function, params);
}
public short execPythonShort(String function, Object... params) {
initPython();
return pexec.execPythonShort(function, params);
}
public char execPythonChar(String function, Object... params) {
initPython();
return pexec.execPythonChar(function, params);
}
public int execPythonInt(String function, Object... params) {
initPython();
return pexec.execPythonInt(function, params);
}
public long execPythonLong(String function, Object... params) {
initPython();
return pexec.execPythonLong(function, params);
}
public float execPythonFloat(String function, Object... params) {
initPython();
return pexec.execPythonFloat(function, params);
}
public double execPythonDouble(String function, Object... params) {
initPython();
return pexec.execPythonDouble(function, params);
}
public boolean execPythonBool(String function, Object... params) {
initPython();
return pexec.execPythonBool(function, params);
}
public void execPythonVoid(String function, Object... params) {
initPython();
pexec.execPythonVoid(function, params);
}
}
| mit |
mandino/www.bloggingshakespeare.com | wp-content/plugins/redirection/api/api.php | 5482 | <?php
require_once __DIR__ . '/api-group.php';
require_once __DIR__ . '/api-redirect.php';
require_once __DIR__ . '/api-log.php';
require_once __DIR__ . '/api-404.php';
require_once __DIR__ . '/api-settings.php';
require_once __DIR__ . '/api-plugin.php';
require_once __DIR__ . '/api-import.php';
require_once __DIR__ . '/api-export.php';
define( 'REDIRECTION_API_NAMESPACE', 'redirection/v1' );
/**
* @apiDefine 401Error
*
* @apiError (Error 401) rest_forbidden You are not authorized to access this API endpoint
* @apiErrorExample {json} 401 Error Response:
* HTTP/1.1 401 Bad Request
* {
* "code": "rest_forbidden",
* "message": "Sorry, you are not allowed to do that."
* }
*/
/**
* @apiDefine 404Error
*
* @apiError (Error 404) rest_no_route Endpoint not found
* @apiErrorExample {json} 404 Error Response:
* HTTP/1.1 404 Not Found
* {
* "code": "rest_no_route",
* "message": "No route was found matching the URL and request method"
* }
*/
/**
* @apiDefine 400Error
*
* @apiError rest_forbidden You are not authorized to access this API endpoint
* @apiErrorExample {json} 400 Error Response:
* HTTP/1.1 400 Bad Request
* {
* "error": "invalid",
* "message": "Invalid request"
* }
*/
/**
* @apiDefine 400MissingError
* @apiError (Error 400) rest_missing_callback_param Some required parameters are not present or not in the correct format
* @apiErrorExample {json} 400 Error Response:
* HTTP/1.1 400 Bad Request
* {
* "code": "rest_missing_callback_param",
* "message": "Missing parameter(s): PARAM"
* }
*/
class Redirection_Api_Route {
protected function add_error_details( WP_Error $error, $line, $code = 400 ) {
global $wpdb;
$data = array(
'status' => $code,
'error_code' => $line,
);
if ( isset( $wpdb->last_error ) && $wpdb->last_error ) {
$data['wpdb'] = $wpdb->last_error;
}
$error->add_data( $data );
return $error;
}
public function permission_callback( WP_REST_Request $request ) {
return Redirection_Capabilities::has_access( Redirection_Capabilities::CAP_PLUGIN );
}
public function get_route( $method, $callback, $permissions = false ) {
return [
'methods' => $method,
'callback' => [ $this, $callback ],
'permission_callback' => $permissions ? $permissions : [ $this, 'permission_callback' ],
];
}
}
class Redirection_Api_Filter_Route extends Redirection_Api_Route {
public function validate_filter( $value, $request, $param ) {
$fields = $request->get_attributes()['args']['filterBy']['filter_fields'];
if ( ! is_array( $value ) ) {
return new WP_Error( 'rest_invalid_param', 'Filter is not an array', array( 'status' => 400 ) );
}
if ( ! empty( $fields ) ) {
foreach ( array_keys( $value ) as $key ) {
if ( ! in_array( $key, $fields, true ) ) {
return new WP_Error( 'rest_invalid_param', 'Filter type is not supported: ' . $key, array( 'status' => 400 ) );
}
}
}
return true;
}
protected function get_filter_args( $order_fields, $filters = [] ) {
return [
'filterBy' => [
'description' => 'Field to filter by',
'validate_callback' => [ $this, 'validate_filter' ],
'filter_fields' => $filters,
],
'orderby' => [
'description' => 'Field to order results by',
'type' => 'string',
'enum' => $order_fields,
],
'direction' => [
'description' => 'Direction of ordered results',
'type' => 'string',
'default' => 'desc',
'enum' => [ 'asc', 'desc' ],
],
'per_page' => [
'description' => 'Number of results per page',
'type' => 'integer',
'default' => 25,
'minimum' => 5,
'maximum' => RED_MAX_PER_PAGE,
],
'page' => [
'description' => 'Page offset',
'type' => 'integer',
'minimum' => 0,
'default' => 0,
],
];
}
public function register_bulk( $namespace, $route, $orders, $callback, $permissions = false ) {
register_rest_route( $namespace, $route, array(
$this->get_route( WP_REST_Server::EDITABLE, $callback, $permissions ),
'args' => array_merge( $this->get_filter_args( $orders ), [
'items' => [
'description' => 'Comma separated list of item IDs to perform action on',
'type' => 'string',
'required' => true,
'sanitize_callback' => [ $this, 'sanitize_csv' ],
],
] ),
) );
}
public function sanitize_csv( $param ) {
return array_values( array_filter( array_map( 'intval', explode( ',', $param ) ) ) );
}
}
class Redirection_Api {
private static $instance = null;
private $routes = array();
public static function init() {
if ( is_null( self::$instance ) ) {
self::$instance = new Redirection_Api();
}
return self::$instance;
}
public function __construct() {
global $wpdb;
$wpdb->hide_errors();
$this->routes[] = new Redirection_Api_Redirect( REDIRECTION_API_NAMESPACE );
$this->routes[] = new Redirection_Api_Group( REDIRECTION_API_NAMESPACE );
$this->routes[] = new Redirection_Api_Log( REDIRECTION_API_NAMESPACE );
$this->routes[] = new Redirection_Api_404( REDIRECTION_API_NAMESPACE );
$this->routes[] = new Redirection_Api_Settings( REDIRECTION_API_NAMESPACE );
$this->routes[] = new Redirection_Api_Plugin( REDIRECTION_API_NAMESPACE );
$this->routes[] = new Redirection_Api_Import( REDIRECTION_API_NAMESPACE );
$this->routes[] = new Redirection_Api_Export( REDIRECTION_API_NAMESPACE );
}
}
| mit |
hstarorg/web-dojo | server/src/routes/gist.js | 411 | let router = new Router();
let gistBiz = require('./../bizs/gistBiz');
let authBiz = require('./../bizs/authBiz');
router
// 创建Gist
.post('/', authBiz.validateUser, gistBiz.createGist)
// 获取我的gist
.get('/mygists', authBiz.validateUser, gistBiz.getGists)
// 获取特定的gist
.get('/:gistId', gistBiz.getGist);
module.exports = {
priority: 0,
router: router,
prefix: '/gist'
};
| mit |
phmLabs/Smoke | src/Rules/Http/DurationRule.php | 1412 | <?php
namespace whm\Smoke\Rules\Http;
use phm\HttpWebdriverClient\Http\Response\DurationAwareResponse;
use Psr\Http\Message\ResponseInterface;
use whm\Smoke\Rules\CheckResult;
use whm\Smoke\Rules\Rule;
/**
* This rule can validate if a http request takes longer than a given max duration.
* A website that is slower than one second is considered as slow.
*/
class DurationRule implements Rule
{
private $maxDuration;
/**
* @param int $maxDuration The maximum duration a http call is allowed to take (time to first byte)
*/
public function init($maxDuration = 1000)
{
$this->maxDuration = $maxDuration;
}
public function validate(ResponseInterface $response)
{
if ($response instanceof DurationAwareResponse) {
if ($response->getDuration() > $this->maxDuration) {
return new CheckResult(
CheckResult::STATUS_FAILURE,
'The http request took ' . (int)$response->getDuration() . ' milliseconds (limit was ' . $this->maxDuration . 'ms).',
(int)$response->getDuration());
}
return new CheckResult(
CheckResult::STATUS_SUCCESS,
'The http request took ' . (int)$response->getDuration() . ' milliseconds (limit was ' . $this->maxDuration . 'ms).',
(int)$response->getDuration());
}
}
}
| mit |
gooy/aurelia-ace | demo/src/app/docs.js | 382 | import {EventAggregator} from 'aurelia-event-aggregator';
import {bindable,Animator} from 'aurelia-framework';
export class Docs{
static inject = [Element,EventAggregator,Animator];
constructor(element,ea,animator) {
this.element = element;
this.ea = ea;
this.animator = animator;
}
attached(){
this.ea.publish("page:ready");
}
detached(){
}
}
| mit |
AndreiMisiukevich/FFImageLoading | source/FFImageLoading.Shared.IosMac/Work/BitmapHolder.cs | 904 | using System;
#if __MACOS__
using AppKit;
using PImage = AppKit.NSImage;
#elif __IOS__
using UIKit;
using PImage = UIKit.UIImage;
#endif
namespace FFImageLoading.Work
{
public class BitmapHolder: IBitmap
{
public BitmapHolder(PImage bitmap)
{
NativeBitmap = bitmap;
}
public int Width
{
get
{
return (int)NativeBitmap.Size.Width;
}
}
public int Height
{
get
{
return (int)NativeBitmap.Size.Height;
}
}
internal PImage NativeBitmap
{
get;
private set;
}
}
public static class IBitmapExtensions
{
public static PImage ToNative(this IBitmap bitmap)
{
return ((BitmapHolder)bitmap).NativeBitmap;
}
}
}
| mit |
D1no/meteor | tools/cli/commands-packages-query.js | 63499 | // These commands deal with aggregating local package data with the information
// contained in the Meteor Package Server. They also deal with presenting this
// to the user in various human or machine-readable ways.
var _ = require('underscore');
var archinfo = require('../archinfo.js');
var buildmessage = require('../buildmessage.js');
var catalog = require('../catalog/catalog.js');
var Console = require('../console.js').Console;
var files = require('../fs/files.js');
var isopackets = require('../tool-env/isopackets.js');
var main = require('./main.js');
var packageVersionParser = require('../packaging/package-version-parser.js');
var projectContextModule = require('../project-context.js');
var utils = require('../utils/utils.js');
var catalogUtils = require('../catalog/catalog-utils.js');
var compiler = require('../isobuild/compiler.js');
// We want these queries to be relatively fast, so we will only refresh the
// catalog if it is > 15 minutes old
var DEFAULT_MAX_AGE_MS = 15 * 60 * 1000;
// Maximum number of recent versions of a package or a release that we should
// return to the user, unless a more complete mode is requested.
var MAX_RECENT_VERSIONS = 5;
// XXX: Remove this if/when we do a Troposphere migration to backfill release
// version publication times.
// Estimate the publication date for a release. Since we have failed to keep
// track of publication times of release versions in the past, we will try to
// guess that the release was published at the same time as the tool.
var getReleaseVersionPublishedOn = function (versionRecord) {
if (versionRecord.published) {
return new Date(versionRecord.published);
}
// We don't know when the release was published. Luckily, since there is no
// way to use the tool outside of a release, and we always change the tool
// between releases, it is a good bet that the release was published on the
// same day as the tool.
var toolPackage = versionRecord.tool.split('@');
var toolName = toolPackage[0];
var toolVersion = toolPackage[1];
var toolRecord = catalog.official.getVersion(toolName, toolVersion);
if (! toolRecord || ! toolRecord.published) return null;
return new Date(toolRecord.published);
};
// Processes information about the versions that we hid. Returns a brief
// human-friendly string listing the reasons why some versions of the package
// were not shown.
var formatHiddenVersions = function (hiddenVersions, oldestShownVersion) {
// An array of strings, listing the reasons why some versions were hidden.
var reasons = [];
// Use our information about hidden versions to figure what reasons we
// actually want to return to the user.
if (! oldestShownVersion) {
// We did not show any versions, so presumably all existing versions of
// this package are either unmigrated or pre-release versions.
if (hiddenVersions.lastUnmigrated) {
reasons.push("unmigrated");
}
if (hiddenVersions.lastPreRelease) {
reasons.push("pre-release");
}
} else {
// If the oldest version on record is older than the oldest shown
// version, then it was hidden due to MAX_RECENT_VERSION number. (It
// might also be hidden because it is a pre-release or unmigrated, but
// age takes priority).
if (packageVersionParser.lessThan(
hiddenVersions.oldestVersion, oldestShownVersion)) {
reasons.push("older");
}
// If the latest unmigrated/pre-release version is older than the oldest
// version that we are showing, then we don't care about it. If it is
// younger, we need to tell the user.
//
// It is certainly possible that, even though a pre-release version is older
// than the oldest version that we are showing, but under the limit for the
// MAX_RECENT_VERSIONS. So, in that case, we are eliding that version
// because it is a pre-release, not because of age. It is still,
// technically, an 'older' version though, and that explanation is more
// intuitive.
if (hiddenVersions.lastPreRelease &&
packageVersionParser.lessThan(
oldestShownVersion, hiddenVersions.lastPreRelease)) {
reasons.push("pre-release");
}
if (hiddenVersions.lastUnmigrated &&
packageVersionParser.lessThan(
oldestShownVersion, hiddenVersions.lastUnmigrated)) {
reasons.push("unmigrated");
}
}
// Now, we will aggregate the reasons into a human-readable string.
if (reasons.length === 1) {
return reasons[0];
} else if (reasons.length === 2) {
// There is no oxford comma if only listing two objects
return reasons[0] + " and " + reasons[1];
} else if (reasons.length > 2) {
return reasons.slice(0, -1).join(", ") + ", and " + _.last(reasons);
} else {
// Did we not figure out anything to write? Did something else go wrong?
// This should never happen, but if it does, recover by omitting
// information.
return "Some";
}
};
// Converts an object to an EJSON string with the right spacing.
var formatEJSON = function (data) {
var EJSON = isopackets.load('ejson').ejson.EJSON;
return EJSON.stringify(data, { indent: true }) + "\n";
};
// Takes in a string and pads it with whitespace to the length of the longest
// possible date string.
var padLongformDate = function (dateStr) {
var numSpaces = utils.maxDateLength - dateStr.length;
return dateStr + Array(numSpaces + 1).join(' ');
};
// In order to get access to local package data, we need to create a local
// package catalog. The best way to do that is to create a temporary
// ProjectContext and let it handle catalog initialization. When we do, we need
// to make sure that it is aware of all the local packages that we might care
// about.
//
// This function returns such a ProjectContext, and takes in the following
// options:
// - appDir: If we are running in the context of an app, this will contain the
// root of the app. We want to make sure to grab the data from the app's
// local packages.
// - packageDir: If we are running in a package directory, this will contain
// the source root of that package. If we are running from inside a package,
// we want that package to show up in our results.
var getTempContext = function (options) {
var projectContext;
// If we are running in an app, we will use it to create a
// (mostly immutable) projectContext.
if (options.appDir) {
projectContext = new projectContextModule.ProjectContext({
projectDir: options.appDir
});
} else {
// We're not in an app, so we will create a temporary app and use it to load
// the local catalog. If a local packageDir exists, include it manually.
var currentPackageDir = options.packageDir ? [options.packageDir] : [];
var tempProjectDir = files.mkdtemp('meteor-show');
projectContext = new projectContextModule.ProjectContext({
projectDir: tempProjectDir,
explicitlyAddedLocalPackageDirs: currentPackageDir
});
}
// It is possible that we can't process package.js files in our local packages
// and have to exit early. This is unfortunate, but we can't search local
// packages if we can't read them. If this turns out to be a frequent problem,
// we can give a warning, instead of failing in the future. For now, we want
// to err on the side of consistency.
main.captureAndExit("=> Errors while reading local packages:", function () {
projectContext.initializeCatalog();
});
return projectContext;
};
// Print an error message if the user asks about an unknown item.
var itemNotFound = function (item) {
Console.error(item + ": not found");
catalogUtils.explainIfRefreshFailed();
return 1;
};
// This is a base class for storing package fields that require some processing
// to store and display correctly.
//
// Do NOT initialize this class by itself -- use one of the classes that
// inherits from it.
var BasePkgDatum = function () {
var self = this;
self.data = null;
};
_.extend(BasePkgDatum.prototype, {
// Throws if data has not been initialized.
_checkInitialized: function () {
var self = this;
if (self.data === null) {
throw new Error("do not use the BasePkgDatum class by itself");
}
},
// Returns true if this class does not contain any exports.
isEmpty : function () {
var self = this;
self._checkInitialized();
return _.isEmpty(self.data);
},
// Get exports as a raw object.
getObject : function () {
var self = this;
self._checkInitialized();
return self.data;
},
getConsoleStr : function () {
var self = this;
self._checkInitialized();
return "";
}
});
// This class stores exports from a given package.
//
// Stores exports for a given package and returns them to the caller in a given
// format. Takes in the raw exports from the package.
var PkgExports = function (pkgExports) {
var self = this;
// Process and save the export data.
self.data = _.map(pkgExports, function (exp) {
var arches = exp.architectures;
// Replace 'os' (what we store) with 'server' (what you would put in a
// package.js file). That's more user friendly, and avoids confusing this
// with different OS arches used in binary packages.
if ( _.indexOf(arches, "os") !== -1) {
arches = _.without(arches, "os");
arches.push("server");
}
// Sort architectures alphabetically.
arches.sort();
return { name: exp.name, architectures: arches };
});
// Sort exports alphabetically by name.
self.data = _.sortBy(self.data, "name");
};
// Extend BasePkgDatum.
PkgExports.prototype = new BasePkgDatum();
_.extend(PkgExports.prototype, {
// Convert package exports into a pretty, Console non-wrappable string. If an
// export is only declared for certain architectures, mentions those
// architectures in a user-friendly format.
getConsoleStr: function () {
var self = this;
var strExports = _.map(self.data, function (exp) {
// If this export is valid for all architectures, don't specify
// architectures here.
if (exp.architectures.length === compiler.ALL_ARCHES.length)
return exp.name;
// Don't split descriptions of individual pkgExports between lines.
return Console.noWrap(
exp.name + " (" + exp.architectures.join(", ") + ")");
});
return strExports.join(", ");
}
});
// This class stores implies from a given package.
//
// Stores implies for a given package and returns them to the caller in a given
// format. Takes in the dependencies from the package.
var PkgImplies = function (pkgDeps) {
var self = this;
self.data = [];
// Go through all the package dependencies. If a dependency has any implied
// references, add it to the list.
_.each(pkgDeps, function (ref, name) {
var architectures = [];
// We want to select the references that are implied (instead of just used)
// and save their architectures. Also, we want to replace 'os' with
// 'server', as with exports.
_.each(ref.references, function (r) {
if (! r.implied) return;
var archName = (r.arch === "os") ? "server" : r.arch;
architectures.push(archName);
});
// Sort architecures alphabetically.
architectures.sort();
if (! _.isEmpty(architectures)) {
self.data.push({ name: name, architectures: architectures });
}
});
// Sort by name.
self.data = _.sortBy(self.data, "name");
};
// Extend BasePkgDatum.
PkgImplies.prototype = new BasePkgDatum();
_.extend(PkgImplies.prototype, {
// Convert package exports into a pretty, Console non-wrappable string. If an
// export is only declared for certain architectures, mentions those
// architectures in a user-friendly format.
getConsoleStr: function () {
var self = this;
var strImplies = _.map(self.data, function (ref) {
// If an imply is valid for all architectures, don't specify it here.
if (ref["architectures"].length === compiler.ALL_ARCHES.length)
return ref.name;
// Don't split descriptions of individual implies between lines.
return Console.noWrap(
ref.name + " (" + ref.architectures.join(", ") + ")");
});
return strImplies.join(", ");
}
});
// This class stores dependencies from a given package.
//
// Stores dependencies for a given package and returns them to the caller in a given
// format. Takes in the raw dependencies from the package record.
var PkgDependencies = function (pkgDeps) {
var self = this;
self.data = _.map(
// The dependency on 'meteor' was almost certainly added automatically, by
// Isobuild. Returning this to the user will only cause confusion.
_.omit(pkgDeps, "meteor"),
function (dep, depName) {
// We will only consider this a weak dependency if all of its references
// are marked as weak.
var weak = _.every(dep.references, function (ref) {
return !! ref.weak;
});
return {
name: depName,
constraint: dep.constraint,
weak: weak
};
});
// Sort by name.
self.data = _.sortBy(self.data, "name");
};
// Extend BasePkgDatum.
PkgDependencies.prototype = new BasePkgDatum();
_.extend(PkgDependencies.prototype, {
// Convert package exports into a pretty, Console non-wrappable string. If an
// export is only declared for certain architectures, mentions those
// architectures in a user-friendly format.
getConsoleStr: function () {
var self = this;
var strDeps = _.map(self.data, function (dep) {
var depString = dep.name;
if (dep.constraint && dep.constraint !== null) {
depString += "@" + dep.constraint;
}
if (dep.weak) {
depString += " (weak dependency)";
}
return Console.noWrap(depString);
});
return strDeps.join("\n");
}
});
// The two classes below collect and print relevant information about Meteor
// packages and Meteor releases, respectively. Specifically, they query the
// official catalog and, if applicable, relevant local sources. They also handle
// the details of printing their data to the screen.
//
// A query class has:
// - data: an object representing the data it has collected in response to the
// - query.
// - a print method, that take options as an argument and prints the results to
// the terminal.
// This class deals with information related to packages. To deal with local
// packages, it has to interact with the projectContext.
//
// The constructor takes in the following options:
// - metaRecord: (mandatory) the meta-record for this package from the Packages
// collection.
// - projectContext: (mandatory) a projectContext that we can use to look up
// information on local packages.
// - version: query for a specific version of this package.
// - showArchitecturesOS: collect and process data on OS
// architectures that are available for different versions of this package.
// - showHiddenVersions: return information about all the versions of the
// package, including pre-releases and un-migrate versions.
// - showDependencies: return information information about
// versions' dependencies.
var PackageQuery = function (options) {
var self = this;
// This is the record in the packages collection. It contains things like
// maintainers, and the package homepage.
self.metaRecord = options.metaRecord;
self.name = options.metaRecord.name;
// This argument is required -- we use it to look up data. If it has not been
// passed in, fail early.
if (! options.projectContext) {
throw Error("Missing required argument: projectContext");
}
self.projectContext = options.projectContext;
self.localCatalog = options.projectContext.localCatalog;
// Processing per-version availability architectures & dependencies is
// expensive, so we don't do it unless we are asked to.
self.showArchitecturesOS = options.showArchitecturesOS;
self.showDependencies = options.showDependencies;
// We don't want to show pre-releases and un-migrated versions to the user
// unless they explicitly ask us about it.
self.showHiddenVersions = options.showHiddenVersions;
// Collect the data for this package, including looking up any specific
// package version that we care about.
if (options.version) {
var versionRecord = self._getVersionRecord(options.version);
if (! versionRecord) {
self.data = null;
return;
}
self.data = versionRecord.local ?
self._getLocalVersion(versionRecord) :
self._getOfficialVersion(versionRecord);
} else {
self.data = self._collectPackageData();
}
};
_.extend(PackageQuery.prototype, {
// Find and return a version record for a given version. Mark the version
// record as local, if it is a local version of the package.
_getVersionRecord: function (version) {
var self = this;
// We allow local version to override remote versions in meteor show, so we
// should start by checking if this is a local version first.
var versionRecord = self.localCatalog.getLatestVersion(self.name);
// If we asked for "local" as the version number, and found any local version
// at all, we are done.
if (version === "local") {
return versionRecord && _.extend(versionRecord, { local: true });
}
// We have a local record, and its version matches the version that we asked
// for, so we are done.
if (versionRecord && (versionRecord.version === version)) {
return _.extend(versionRecord, { local: true });
}
// If we haven't found a local record, or if the local record that we found
// doesn't match the version that we asked for, then we have to go look in
// the server catalog.
versionRecord = catalog.official.getVersion(self.name, version);
return versionRecord;
},
// Print the query information to screen.
//
// options:
// - ejson: Don't pretty-print the data. Print a machine-readable ejson
// object.
print: function (options) {
var self = this;
// If we are asking for an EJSON-style output, we will only print out the
// relevant fields.
if (options.ejson) {
Console.rawInfo(formatEJSON(
self.data.version ?
self._generateVersionObject(self.data) :
self._generatePackageObject(self.data)));
return;
}
// Otherwise, display the information that we have. If we were asking about
// a specific version, display that. Otherwise, display package metadata in
// general.
if (self.data.version) {
self._displayVersion(self.data);
return;
}
self._displayPackage(self.data);
},
// Aggregates data about the package as a whole. Returns an object with the
// following keys:
//
// - name: package name
// - maintainers: an array of usernames of maintainers
// - homepage: string homepage
// - totalVersions: total number of versions that this package has, including
// local and hidden versions.
// - defaultVersion: a default version: use this version to look up
// per-version information that is relevant to the package as a whole, such
// as git, description,etc.
// - versions: an array of objects representing versions of this package.
_collectPackageData: function () {
var self = this;
var data = {
name: self.metaRecord.name,
maintainers: _.pluck(self.metaRecord.maintainers, "username"),
homepage: self.metaRecord.homepage
};
// Collect surface information about available versions, starting with the
// versions available on the server.
var serverVersionRecords =
catalog.official.getSortedVersionRecords(self.name);
var totalVersions = serverVersionRecords.length;
// If we are not going to show hidden versions, then we shouldn't waste time
// on them. Trim the serverVersionRecords array to only have the top
// MAX_RECENT_VERSIONS migrated, official versions.
if (! self.showHiddenVersions) {
// We might have to hide some versions from the user. We want to explain
// why we hid them. Here is how we are going to explain things -- any
// versions older than the oldest version that we show, are hidden because
// of age. If, in the covered time period, there are
// unmigrated/pre-release versions, then we will mention those as well.
//
// Specifically, while we filter versions, we are going to memorize the
// most recent version hidden for a specific reason.
var lastUnmigrated = "";
var lastPreRelease = "";
var oldestVersion =
serverVersionRecords[0] && serverVersionRecords[0].version;
var filteredVersionRecords =
_.filter(serverVersionRecords, function (vr) {
if (vr.unmigrated) {
lastUnmigrated = vr.version;
return false;
}
if (vr.version.indexOf("-") !== -1) {
lastPreRelease = vr.version;
return false;
}
return true;
});
serverVersionRecords = _.last(filteredVersionRecords, MAX_RECENT_VERSIONS);
data["hiddenVersions"] = {
oldestVersion: oldestVersion,
lastUnmigrated: lastUnmigrated,
lastPreRelease: lastPreRelease
};
};
// Process the catalog records into our preferred format, and look up any
// other per-version information that we might need.
data["versions"] = _.map(serverVersionRecords, function (versionRecord) {
return self._getOfficialVersion(versionRecord);
});
// The local version doesn't count against the version limit. Look up relevant
// information about the local version.
var localVersion = self.localCatalog.getLatestVersion(self.name);
var local;
if (localVersion) {
local = self._getLocalVersion(localVersion);
data["versions"].push(local);
totalVersions++;
}
// Record the total number of versions, including the ones we hid from the
// user.
data["totalVersions"] = totalVersions;
// Some per-version information gets displayed with the rest of the package
// information. We want to use the right version for that. (We don't want
// to display data from unofficial or un-migrated versions just because they
// are recent.)
if (local) {
data["defaultVersion"] = {
version: "local",
summary: local.summary,
description: local.description,
git: local.git,
implies: local.implies,
exports: local.exports
};
} else {
var mainlineRecord = catalog.official.getLatestMainlineVersion(self.name);
if (mainlineRecord) {
var pkgExports = new PkgExports(mainlineRecord.exports);
var implies = new PkgImplies(mainlineRecord.dependencies);
data["defaultVersion"] = {
version: mainlineRecord.version,
summary: mainlineRecord.description,
description: mainlineRecord.longDescription,
git: mainlineRecord.git,
exports: pkgExports,
implies: implies
};
} else {
data["defaultVersion"] = _.last(data.versions);
}
}
return data;
},
// Takes in a version record from the official catalog and looks up extra
// information that's relevant to this PackageQuery.
//
// - name: package Name
// - version: package version
// - summary: version summary/short description (from Package.describe)
// - description: long-form description (from the README.md)
// - publishedBy: username of the publisher
// - publishedOn: date of publication
// - git: git URL for this version
// - installed: true if the package exists in warehouse, and is therefore
// available for use offline.
// - architectures: (optional) if self.showArchitecturesOS is true, returns an
// array of system architectures for which that package is available.
// - dependencies: (optional) if self.showDependencies is true, return an
// array of objects denoting that package's dependencies. The objects have
// the following keys:
// - packageName: name of the dependency
// - constraint: constraint for that dependency
// - weak: true if this is a weak dependency.
_getOfficialVersion: function (versionRecord) {
var self = this;
var version = versionRecord.version;
var name = self.name;
var data = {
name: name,
version: version,
summary: versionRecord.description,
description: versionRecord.longDescription,
publishedBy:
versionRecord.publishedBy && versionRecord.publishedBy.username,
publishedOn: new Date(versionRecord.published),
git: versionRecord.git,
exports: versionRecord.exports
};
// Get the export and imply data, if the record has any.
data["exports"] = new PkgExports(versionRecord.exports);
data["implies"] = new PkgImplies(versionRecord.dependencies);
// Processing and formatting architectures takes time, so we don't want to
// do this if we don't have to.
if (self.showArchitecturesOS) {
var allBuilds = catalog.official.getAllBuilds(self.name, version);
var architectures = _.map(allBuilds, function (build) {
if (! build['buildArchitectures']) return "unknown";
var archOS =
_.filter(build.buildArchitectures.split('+'), function (arch) {
return ( arch !== "web.browser" ) && ( arch !== "web.cordova" );
});
// At this point, you can only have OS arch at a time per-build.
return archOS[0];
});
data["architecturesOS"] = architectures;
}
// Processing and formatting dependencies also takes time, so we would
// rather not do it if we don't have to.
if (self.showDependencies) {
data["dependencies"] = new PkgDependencies(versionRecord.dependencies);
}
// We want to figure out if we have already downloaded this package, and,
// therefore, can use it offline.
var tropohouse = self.projectContext.tropohouse;
try {
data["installed"] = tropohouse.installed({
packageName: name,
version: version
});
} catch (e) {
// Sometimes, we might be unable to determine if the package is installed
// -- maybe we don't have access to the directory, or there is some sort
// of disk corruption. This might only extend to one version, so it would
// be awkward to fail 'meteor show' altogether. Print an error message (if
// it is a permissions error, for example, that's something the user might
// want to know), but don't throw.
Console.printError(e);
data["installed"] = false;
}
return data;
},
// Takes in a version record from the local catalog and looks up extra
// information that's relevant to this PackageQuery. Returns an object with
// the following keys.
//
// - name: package Name
// - version: package version
// - summary: version summary/short description (from Package.describe)
// - description: long-form description (from the README.md)
// - git: git URL for this version
// - local: always true (denotes that this is a local package).
// - directory: source directory of this package.
// - dependencies: (optional) if self.showDependencies is true, return an
// array of objects denoting that package's dependencies. The objects have
// the following keys:
// - packageName: name of the dependency
// - constraint: constraint for that dependency
// - weak: true if this is a weak dependency.
_getLocalVersion: function (localRecord) {
var self = this;
var data = {
name: self.name,
summary: localRecord.description,
git: localRecord.git,
local: true
};
// Get the source directory.
var packageSource = self.localCatalog.getPackageSource(self.name);
data["directory"] = packageSource.sourceRoot;
// Get the exports.
data["exports"] = new PkgExports(packageSource.getExports());
data["implies"] = new PkgImplies(localRecord.dependencies);
// If the version was not explicitly set by the user, the catalog backfills
// a placeholder version for the constraint solver. We don't want to show
// that version to the user.
data["version"] = packageSource.versionExplicitlyProvided ?
localRecord.version : "local";
// Processing dependencies takes time, and we don't want to do it if we
// don't have to.
if (self.showDependencies) {
data["dependencies"] = new PkgDependencies(localRecord.dependencies);
}
var readmeInfo;
main.captureAndExit(
"=> Errors while reading local packages:",
"reading " + data["directory"],
function () {
readmeInfo = packageSource.processReadme();
});
if (readmeInfo) {
data["description"] = readmeInfo.excerpt;
}
return data;
},
// Displays version information from this PackageQuery to the terminal in a
// human-friendly format. Takes in an object that contains some, but not all,
// of the following keys:
//
// - name: (mandatory) package Name
// - version: (mandatory) package version
// - summary: version summary/short description (from Package.describe)
// - publishedBy: username of the publisher
// - publishedOn: date of publication
// - description: long-form description (from the README.md)
// - git: git URL for this version.
// - local: true for a local version of a package.
// - directory: source directory of this package.
// - installed: true if the package exists in warehouse, and is therefore
// available for use offline.
// - architectures: if self.showArchitecturesOS is true, returns an
// array of system architectures for which that package is available.
// - exports: a PkgExports object, representing package exports.
// - exports: a PkgImplies object, representing package implies.
// - dependencies: a PkgDependencies object, representing dependencies.
_displayVersion: function (data) {
var self = this;
Console.info(
data.name + "@" + data.version,
Console.options({ bulletPoint: "Package: " }));
if (data.directory) {
Console.info("Directory: " + Console.path(data.directory));
}
if (data.exports && ! data.exports.isEmpty()) {
Console.info(
data["exports"].getConsoleStr(),
Console.options({ bulletPoint: "Exports: " }));
}
if (data.implies && ! data.implies.isEmpty()) {
Console.info(
data["implies"].getConsoleStr(),
Console.options({ bulletPoint: "Implies: " }));
}
if (data.git) {
Console.info(
Console.url(data.git),
Console.options({ bulletPoint: "Git: " }));
}
// If we don't have a long-form description, print the summary. (If we don't
// have a summary, print nothing).
if (data.description || data.summary) {
Console.info();
Console.info(data.description || data.summary);
}
// Print dependency information, if the package has any dependencies.
if (data.dependencies && ! data.dependencies.isEmpty()) {
Console.info();
Console.info("Depends on:");
Console.info(
data.dependencies.getConsoleStr(),
Console.options({ indent: 2 }));
}
// Print the 'published by' line at the very bottom.
if (data.publishedBy) {
var publisher = data.publishedBy;
var pubDate = utils.longformDate(data.publishedOn);
Console.info();
Console.info("Published by", publisher, "on", pubDate + ".");
}
// Sometimes, there is a server package and a local package with the same
// version. In this case, we prefer the local package. Explain our choice to
// the user.
if (data.local &&
catalog.official.getVersion(data.name, data.version)) {
Console.info();
Console.info(
"This package version is built locally from source.",
"The same version of this package also exists on the package server.",
"To view its metadata, run",
Console.command("'meteor show " + data.name + "@" + data.version + "'"),
"from outside the project.");
}
},
// Returns a user-friendly object from this PackageQuery to the caller. Takes
// in a data object with the same keys as _displayVersion.
//
// Returns an object with some of the following keys:
// - name: String. Name of the package.
// - version: String. Meteor version number.
// - description: String. Longform description.
// - summary: String. Short summary.
// - git: String. Git URL.
// - publishedBy: String. Username of the publisher.
// - publishedOn: Date. Time of publication.
// - local: Boolean. True if this is a local package.
// - directory: source directory of this package.
// - installed: Boolean. True if the isopack for this package has been
// downloaded, or if the package is local.
// - dependencies: Array of objects representing package dependencies, sorted
// alphabetically by package name.
// - OSarchitectures: Array of OS architectures on for which an isopack of
// this package exists (server packages only).
// - exports: Array of objects representing the package exports, sorted by
// name of export.
_generateVersionObject: function (data) {
var versionFields = [
"name", "version", "description", "summary", "git", "directory",
"publishedBy", "publishedOn", "installed", "local", "architecturesOS",
];
var processedData = {};
_.each(["exports", "implies", "dependencies"], function (key) {
processedData[key] = data[key] ? data[key].getObject() : [];
});
return _.extend(processedData, _.pick(data, versionFields));
},
// Displays general package data from this PackageQuery to the terminal in a
// human-friendly format. Takes in an object that contains some, but not
// always all, of the following keys:
//
// - name: (mandatory) package name
// - maintainers: array of usernames of maintainers
// - homepage: string of the package homepage
// - defaultVersion: the default version of this package to use for looking up
// per-version information that's relevant to the package in general (ex:
// git).
// - totalVersions: the total number of versions that this package has,
// including hidden versions.
// - versions: an ordered array of objects, representing the versions of this
// package that we should return to the user. Each version should contain
// some of the following keys:
// - version: (mandatory) version number, or "local" for a version-less
// local package.
// - publishedOn: the date that the package was published.
// - installed: true if this is a server package that has already been
// downloaded to the warehouse.
// - local: true for a local package.
// - directory: source root directory of a local package.
// - hiddenVersions: an object containing some information about versions that
// have been hidden from the user. Has keys:
// - oldestVersion: the version of this package with the smallest Meteor
// semver number that exists in our records.
// - lastUnmigrated: the most recent (largest Meteor semver) version that
// is marked 'unmigrated'.
// - lastPreRelease: the most recent pre-release version.
_displayPackage: function (data) {
var self = this;
var defaultVersion = data.defaultVersion;
// Every package has a name. Some packages have a homepage.
var displayName = data.defaultVersion ?
data.name + "@" + data.defaultVersion.version : data.name;
Console.info(displayName, Console.options({ bulletPoint: "Package: " }));
if (data.homepage) {
Console.info(Console.url(data.homepage),
Console.options({ bulletPoint: "Homepage: " }));
}
// Local packages might not have any maintainers.
if (! _.isEmpty(data.maintainers)) {
Console.info(data.maintainers.join(", "),
Console.options({ bulletPoint: "Maintainers: " }));
}
// Git is per-version, so we will print the latest one, if one exists.
if (defaultVersion && defaultVersion.git) {
Console.info(Console.url(defaultVersion.git),
Console.options({ bulletPoint: "Git: " }));
}
// Print the exports.
if (defaultVersion && defaultVersion.exports &&
! defaultVersion.exports.isEmpty()) {
Console.info(
defaultVersion["exports"].getConsoleStr(),
Console.options({ bulletPoint: "Exports: " }));
}
if (defaultVersion && defaultVersion.implies &&
! defaultVersion.implies.isEmpty()) {
Console.info(
defaultVersion["implies"].getConsoleStr(),
Console.options({ bulletPoint: "Implies: " }));
}
Console.info();
// If we don't have a long-form description, we will use the summary. For a
// local package, we might not have a summary, in which case we should be
// careful not to print extra lines.
var printDescription = defaultVersion &&
(defaultVersion.description || defaultVersion.summary);
if (printDescription) {
Console.info(printDescription );
Console.info();
}
// If we have any versions to show, print them out now.
var versionRows = [];
if (data.versions && ! _.isEmpty(data.versions)) {
var versionsHeader =
self.showHiddenVersions ? "Versions:" : "Recent versions:";
Console.info(versionsHeader);
_.each(data.versions, function (v) {
// For a local package, we don't have a published date, and we don't
// need to show if it has already been downloaded (it is local, we don't
// need to download it). Instead of showing both of these values, let's
// show the directory.
if (v.local) {
versionRows.push([v.version, v.directory]);
return;
}
// Convert the date into a display-friendly format, or print nothing for
// a local package.
var publishDate = utils.longformDate(v.publishedOn);
// If there is a status that we would like to report for this package,
// figure it out now.
if (v.installed) {
var paddedDate = padLongformDate(publishDate);
versionRows.push([v.version, paddedDate + " " + "installed"]);
} else {
versionRows.push([v.version, publishDate]);
}
});
// The only time that we are going to go over a reasonable character limit
// is with a directory for the local package. We would much rather display
// the full directory than trail it off.
Console.printTwoColumns(versionRows, { indent: 2, ignoreWidth: true });
}
// If we have not shown all the available versions, let the user know.
if (data.totalVersions > versionRows.length) {
var oldestShownVersion =
(data["versions"][0] && data["versions"][0].version) || "";
// A string explaining why those versions have been hidden.
var hiddenVersions =
formatHiddenVersions(data["hiddenVersions"], oldestShownVersion);
// We will word things in the message in different ways, based on whether
// multiple versions exist/have been hidden.
var hiddenVersionsPluralizer =
(data.totalVersions - data.versions.length == 1) ?
"One " + hiddenVersions + " version of " + self.name + " has" :
hiddenVersions[0].toUpperCase() + hiddenVersions.slice(1) +
" versions of " + self.name + " have";
var allVersionsPluralizer =
(data.totalVersions === 1) ?
"the hidden version" :
"all " + data.totalVersions + " versions";
// Display the final message.
Console.info(
hiddenVersionsPluralizer, "been hidden.",
"To see " + allVersionsPluralizer + ", run",
Console.command("'meteor show --show-all " + self.name + "'") + ".");
}
},
// Returns a user-friendly object from this PackageQuery to the caller. Takes
// in a data object with the same keys as _displayPackage.
//
// Returns an object with some of the following keys:
// - name: String. Name of the package.
// - homepage: String. URL of the package homepage.
// - maintainers: Array of strings. Usernames of package maintainers.
// - totalVersions: Number. Total number of versions that exist for this
// package.
// - versions: Array of objects, representing versions of this
// package. Objects have the following keys:
// - name: String. Name of the package.
// - version: String. Meteor version number.
// - description: String. Longform description.
// - summary: String. Short summary.
// - git: String. Git URL.
// - publishedBy: String. Username of the publisher.
// - publishedOn: Date. Time of publication.
// - local: Boolean. True if this is a local package.
// - directory: source directory of this package.
// - installed: Boolean. True if the isopack for this package has been
// downloaded, or if the package is local.
// - exports: Array of objects representing the package exports, sorted by
// name of export.
_generatePackageObject: function (data) {
var packageFields =
[ "name", "homepage", "maintainers", "totalVersions" ];
// Process the versions array. We only want some of the keys, and we want to
// make sure to get the right exports object.
var versions = _.map(data["versions"], function (version) {
var versionFields = [
"name", "version", "description", "summary", "git", "publishedBy",
"publishedOn", "installed", "local", "directory", "architecturesOS"
];
var processedData = {};
_.each(["exports", "implies"], function (key) {
processedData[key] = version[key] ? version[key].getObject() : [];
});
return _.extend(processedData, _.pick(version, versionFields));
});
return _.extend({ versions: versions }, _.pick(data, packageFields));
},
});
// This class looks up release-related information in the official catalog.
//
// The constructor takes in an object with the following keys:
// - metaRecord: (mandatory) the meta-record for this release from the
// Releases collection.
// - version: specific version of a release that we want to query.
// - showHiddenVersions: show experimental, pre-release & otherwise
// non-recommended versions of this release.
var ReleaseQuery = function (options) {
var self = this;
// This is the record in the Releases collection. Contains metadata, such as
// maintainers.
self.metaRecord = options.metaRecord;
self.name = options.metaRecord.name;
// We don't always want to show non-recommended release versions.
self.showHiddenVersions = options.showHiddenVersions;
// Aggregate the query data. If we are asking for a specific version, get data
// for a specific version, otherwise aggregate the data about this release
// track in general.
self.data = options.version ?
self._getVersionDetails(options.version) :
self._getReleaseData();
};
_.extend(ReleaseQuery.prototype, {
// Prints the data from this ReleaseQuery to the terminal. Takes the following
// options:
// - ejson: Don't pretty-print the data. Return a machine-readable ejson
// object.
print: function (options) {
var self = this;
// If we are asking for an EJSON-style output, print out the relevant fields.
if (options.ejson) {
var versionFields = [
"track", "version", "description", "publishedBy", "publishedOn",
"tool", "packages", "recommended"
];
var packageFields = [ "name", "maintainers", "versions" ];
var fields = self.data.version ? versionFields : packageFields;
Console.rawInfo(formatEJSON(_.pick(self.data, fields)));
return;
}
// If we are asking for a specific version, display the information about
// that version.
if (self.data.version) {
self._displayVersion(self.data);
return;
}
// Otherwise, print the data about this release track in general.
self._displayRelease(self.data);
},
// Gets detailed data about a specific version of this release. Returns an
// object with the following keys:
// - track: name of the release track
// - version: release version
// - description: description of the release version
// - recommended: if this is a recommended version.
// - orderKey: the orderKey of this version
// - publishedBy: username of the publisher
// - publishedOn: date this version was published
// - packages: map of packages that go into this version
// - tool: the tool package@version for this release version
_getVersionDetails: function (version) {
var self = this;
var versionRecord =
catalog.official.getReleaseVersion(self.name, version);
if (! versionRecord) {
return null;
}
var publishDate = getReleaseVersionPublishedOn(versionRecord);
return {
track: self.name,
version: version,
description: versionRecord.description,
recommended: versionRecord.recommended,
orderKey: versionRecord.orderKey,
publishedBy: versionRecord.publishedBy["username"],
pubishedOn: publishDate,
packages: versionRecord.packages,
tool: versionRecord.tool
};
},
// Gets aggregate data about this release track in general. Returns an object
// with the following keys:
// - track: name of the release track
// - maintainers: an array of usernames of maintainers
// - defaultVersion: version record for the default version of this release.
// - totalVersions: total number of release versions for this track
// - versions: an array of version objects. If only recommended versions
// are returned, ordered by orderKey, otherwise unordered. Objects have
// the following keys:
// - version: version number
// - description: version description
// - recommended: true for recommended versions
// - orderKey: (only if showHiddenVersions is true) the orderKey of
// this version.
// - publishedBy: username of the publisher
// - publishedOn: date the version was published
_getReleaseData: function () {
var self = this;
var data = {
track: self.metaRecord.name,
maintainers: _.pluck(self.metaRecord.maintainers, "username")
};
data["defaultVersion"] =
catalog.official.getDefaultReleaseVersionRecord(self.name);
// Collect information about versions.
var versions;
if (self.showHiddenVersions) {
// There is no obvious way to get an absolute ranking of all release
// versions, so this is unsorted. If we have to, we will deal with sorting
// this at display time.
versions = catalog.official.getReleaseVersionRecords(self.name);
} else {
versions = catalog.official.getSortedRecommendedReleaseRecords(self.name);
versions.reverse();
}
// We don't want to show the user package or tool data in general release
// mode (it is a lot of data). Select to show the fields that we want to
// return only.
var versionFields =
[ "version", "description", "recommended"];
// orderKey is important for dealing with experimental versions, but it is
// an internal system detail that we would rather not reveal at this level.
if (self.showHiddenVersions) {
versionFields.push("orderKey");
}
data["versions"] = _.map(versions, function (versionRecord) {
var data = _.pick(versionRecord, versionFields);
data.publishedBy = versionRecord.publishedBy["username"];
data.publishedOn = getReleaseVersionPublishedOn(versionRecord);
return data;
});
data["totalVersions"] = catalog.official.getNumReleaseVersions(self.name);
return data;
},
// Displays information about a specific release version in a human-readable
// format. Takes in an object with the following keys:
// - track: release track
// - version: release version
// - publishedBy: username of the publisher
// - publishedOn: date the version was published
// - recommended: true if this is a recommended version
// - description: description of the release version
// - tool: tool package specification for this version
// - packages: map of packages for this release version
_displayVersion: function (data) {
var self = this;
Console.info("Release: " + data.track + "@" + data.version);
var isRecommended = data.recommended ? "yes" : "no";
Console.info("Recommended: " + isRecommended);
Console.info("Tool package: " + data.tool);
Console.info();
Console.info(data.description);
Console.info();
if (!_.isEmpty(data.packages)) {
Console.info("Packages:");
_.each(data.packages, function (version, packageName) {
Console.info(
packageName + ": " + version,
Console.options({ indent: 2 }));
});
Console.info();
}
Console.info(
"Published by " + data.publishedBy + " on " +
utils.longformDate(getReleaseVersionPublishedOn(data)));
},
// Displays information about this release track in general in a
// human-readable format. Takes in an object with the following keys:
// - track: name of the release track
// - maintainers: an array of usernames of maintainers
// - defaultVersion: version record for the default version of this release.
// - totalVersions: total number of release versions for this track
// - versions: an array of version objects. If only recommended versions
// are returned, ordered by orderKey, otherwise unordered. Objects have
// the following keys:
// - version: version number
// - description: version description
// - recommended: true for recommended versions
// - orderKey: (only if showHiddenVersions is true) the orderKey of
// this version.
// - publishedBy: username of the publisher
// - publishedOn: date the version was published
_displayRelease: function (data) {
var self = this;
Console.info("Release:", data.track);
// There is no such thing as a local release, which means all releases have
// a maintainer.
Console.info("Maintainers:", data.maintainers.join(", "));
Console.info();
if (data.defaultVersion) {
Console.info(data.defaultVersion.description);
Console.info();
}
if (self.showHiddenVersions) {
self._displayAllReleaseVersions(data.versions);
return;
}
// Display the recommended versions of this release.
var rows = [];
if (!_.isEmpty(data.versions)) {
Console.info("Recommended versions:");
_.each(data.versions, function (v) {
rows.push([v.version, utils.longformDate(v.publishedOn)]);
});
Console.printTwoColumns(rows, { indent: 2 });
};
// Display a warning about other release versions at the bottom.
if (data.totalVersions > rows.length) {
var versionsPluralizer =
(data.totalVersions > 1) ?
"all " + data.totalVersions + " versions" :
"the hidden version";
// We only hide release versions for one reason -- they are not
// recommended. We would have to parse version numbers to differentiate
// between 'pre-release' and 'deprecated' (and sort-of-experimental, like
// '1.0-weird-trick) and we don't want to rely on version number
// conventions in code.
var versionsHidden =
(data.totalVersions - rows.length > 1) ?
"Non-recommended versions of " + self.name + " have been hidden." :
"One non-recommended version of " + self.name + " has been hidden.";
Console.info(
versionsHidden,
"To see " + versionsPluralizer + ", run",
Console.command("'meteor show --show-all " + self.name + "'") + ".");
}
},
// Displays all the versions of a given release in a human-readable
// format. Includes experimental and otherwise hidden versions. Takes in an
// array of version objects, each of which has the following keys:
// - version: version string
// - orderKey: (optional) orderKey of this version. Not all versions have
// orderKeys.
// - publishedOn: date of publication
// - recommended: true if the version is recommended.
_displayAllReleaseVersions: function (versions) {
var self = this;
var columnOpts = { indent: 2, ignoreWidth: true };
// If we don't have any versions, then there is nothing to display.
if (! versions) { return; }
// We are going to print versions with order key ('versions'), separately
// from versions without an order key ('experimental versions').
var versionsDivided = _.groupBy(versions, function (v) {
return _.has(v, "orderKey");
});
var experimentalVersions = versionsDivided[false];
var versionsWithKey = versionsDivided[true];
if (versionsWithKey) {
// Sort versions that have order keys by order key, so that 1.0 comes
// after 0.9.4.1, etc.
versionsWithKey = _.sortBy(versionsWithKey, function (v) {
return v.orderKey;
});
Console.info("Versions:");
var rows = [];
_.each(versionsWithKey, function (vr) {
var dateStr = utils.longformDate(vr.publishedOn);
if (! vr.recommended) {
rows.push([ vr.version, dateStr ]);
} else {
var paddedDate = padLongformDate(dateStr);
rows.push([ vr.version, paddedDate + " (recommended)" ]);
}
});
Console.printTwoColumns(rows, columnOpts);
}
if (experimentalVersions) {
// We can't sort by order key, so sort by order of publication.
experimentalVersions = _.sortBy(experimentalVersions, function (v) {
return v.publishedOn;
});
Console.info("Experimental versions:");
var rows = [];
_.each(experimentalVersions, function (vr) {
// Experimental versions cannot be recommended.
rows.push([vr.version, utils.longformDate(vr.publishedOn)]);
});
Console.printTwoColumns(rows, columnOpts);
}
}
});
///////////////////////////////////////////////////////////////////////////////
// show
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'show',
pretty: true,
minArgs: 0,
maxArgs: 1,
usesPackage: true,
options: {
"show-all": { type: Boolean },
"ejson": { type: Boolean }
},
catalogRefresh:
new catalog.Refresh.OnceAtStart(
{ maxAge: DEFAULT_MAX_AGE_MS, ignoreErrors: true })
}, function (options) {
var fullName;
var name;
var version;
// Because of the new projectContext interface, we need to initialize the
// project context in order to load the local catalog. This is not ideal.
var projectContext = getTempContext(options);
// If the user specified a query, process it.
if (! _.isEmpty(options.args)) {
// The foo@bar API means that we have to do some string parsing to figure out
// if we want a particular version.
fullName = options.args[0];
var splitArgs = fullName.split('@');
name = splitArgs[0];
version = (splitArgs.length > 1) ? splitArgs[1] : null;
if (splitArgs.length > 2) {
Console.error("Invalid request format: " + fullName);
process.exit(1);
}
} else {
if (! options.packageDir) {
// Letting the user run 'meteor show' without arguments from a package
// directory is a pleasant shortcut, but the default should be specifying
// a query.
Console.error(
"Please specify a package or release name to show information about it."
);
process.exit(1);
}
// Use the projectContext to get the name of the package.
var currentVersion =
projectContext.localCatalog.getVersionBySourceRoot(options.packageDir);
name = currentVersion.packageName;
version = "local";
fullName = name + "@local";
}
var query = null;
// First, we need to figure out if we are dealing with a package, or a
// release. We don't want to rely on capitalization conventions, so we will
// start by checking if a package by that name exists. If it does, then we are
// dealing with a package. (Unlike the normal projectContext, we want to
// prefer the remote record, if one exists, rather than the local record. The
// remote record contains data like 'homepage' and 'maintainers', that the
// local record does not).
var packageRecord =
catalog.official.getPackage(name) ||
projectContext.localCatalog.getPackage(name);
if (packageRecord) {
query = new PackageQuery({
metaRecord: packageRecord,
version: version,
projectContext: projectContext,
showHiddenVersions: options["show-all"],
showArchitecturesOS: options.ejson,
showDependencies: !! version
});
}
// If this is not a package, it might be a release. Let's check if there is
// a release by this name. There are no local releases, so we only need to
// check the official catalog.
if (! query) {
var releaseRecord = catalog.official.getReleaseTrack(name);
if (releaseRecord) {
query = new ReleaseQuery({
metaRecord: releaseRecord,
version: version,
showHiddenVersions: options["show-all"]
});
}
}
// If we have failed to create a query, or if we have created a query and it
// couldn't gather any data about our request, then the item that we are
// looking for does not exist.
if (! query || ! query.data) {
return itemNotFound(fullName);
}
query.print({ ejson: !! options.ejson });
return 0;
});
///////////////////////////////////////////////////////////////////////////////
// search
///////////////////////////////////////////////////////////////////////////////
main.registerCommand({
name: 'search',
pretty: true,
usesPackage: true,
minArgs: 0, // So we can provide specific help
maxArgs: 1,
options: {
maintainer: { type: String },
"show-all": { type: Boolean },
ejson: { type: Boolean },
// Undocumented debug-only option for Velocity.
"debug-only": { type: Boolean }
},
catalogRefresh:
new catalog.Refresh.OnceAtStart(
{ maxAge: DEFAULT_MAX_AGE_MS, ignoreErrors: true })
}, function (options) {
if (options.args.length === 0) {
Console.info(
"To show all packages, do", Console.command("meteor search ."));
return 1;
}
// Because of the new projectContext interface, we need to initialize the
// project context in order to load the local catalog.
var projectContext = getTempContext(options);
// XXX We should push the queries into SQLite!
var allPackages = _.union(
catalog.official.getAllPackageNames(),
projectContext.localCatalog.getAllPackageNames());
var allReleases = catalog.official.getAllReleaseTracks();
var matchingPackages = [];
var matchingReleases = [];
var selector;
var pattern = options.args[0];
var search;
try {
search = new RegExp(pattern);
} catch (err) {
Console.error(err + "");
return 1;
}
// Do not return true on broken packages, unless requested in options.
var filterBroken = function (match, isRelease, name) {
// If the package does not match, or it is not a package at all or if we
// don't want to filter anyway, we do not care.
if (!match || isRelease)
return match;
var vr;
if (!options["show-all"]) {
// If we can't find a version in the local catalog, we want to get the
// latest mainline (ie: non-RC) version from the official catalog.
vr = projectContext.localCatalog.getLatestVersion(name) ||
catalog.official.getLatestMainlineVersion(name);
} else {
// We want the latest version of this package, and we don't care if it is
// a release candidate.
vr = projectContext.projectCatalog.getLatestVersion(name);
}
if (!vr) {
return false;
}
// If we did NOT ask for unmigrated packages and this package is unmigrated,
// we don't care.
if (!options["show-all"] && vr.unmigrated){
return false;
}
// If we asked for debug-only packages and this package is NOT debug only,
// we don't care.
if (options["debug-only"] && !vr.debugOnly) {
return false;
}
return true;
};
if (options.maintainer) {
var username = options.maintainer;
// In the future, we should consider checking this on the server, but I
// suspect the main use of this command will be to deal with the automatic
// migration and uncommon in everyday use. From that perspective, it makes
// little sense to require you to be online to find out what packages you
// own; and the consequence of not mentioning your group packages until
// you update to a new version of meteor is not that dire.
selector = function (name, isRelease) {
var record;
// XXX make sure search works while offline
if (isRelease) {
record = catalog.official.getReleaseTrack(name);
} else {
record = catalog.official.getPackage(name);
}
return filterBroken(
(name.match(search) &&
record && !!_.findWhere(record.maintainers, {username: username})),
isRelease, name);
};
} else {
selector = function (name, isRelease) {
return filterBroken(name.match(search),
isRelease, name);
};
}
buildmessage.enterJob({ title: 'Searching packages' }, function () {
_.each(allPackages, function (pack) {
if (selector(pack, false)) {
var vr;
if (!options['show-all']) {
vr =
projectContext.localCatalog.getLatestVersion(pack) ||
catalog.official.getLatestMainlineVersion(pack);
} else {
vr = projectContext.projectCatalog.getLatestVersion(pack);
}
if (vr) {
matchingPackages.push({
name: pack,
description: vr.description,
latestVersion: vr.version,
lastUpdated: new Date(vr.lastUpdated)
});
}
}
});
_.each(allReleases, function (track) {
if (selector(track, true)) {
var vr = catalog.official.getDefaultReleaseVersionRecord(track);
if (vr) {
matchingReleases.push({
name: track,
description: vr.description,
latestVersion: vr.version,
lastUpdated: new Date(vr.lastUpdated)
});
}
}
});
});
if (options.ejson) {
var ret = {
packages: matchingPackages,
releases: matchingReleases
};
Console.rawInfo(formatEJSON(ret));
return 0;
}
var output = false;
if (!_.isEqual(matchingPackages, [])) {
output = true;
Console.info("Matching packages:");
utils.printPackageList(matchingPackages);
}
if (!_.isEqual(matchingReleases, [])) {
output = true;
Console.info("Matching releases:");
utils.printPackageList(matchingReleases);
}
if (!output) {
Console.error(pattern + ': nothing found');
catalogUtils.explainIfRefreshFailed();
} else {
Console.info(
"You can use", Console.command("'meteor show'"),
"to get more information on a specific item.");
}
});
| mit |
ninnemana/node-battle | client/app/main/main.js | 230 | 'use strict';
angular.module('boomerApp')
.config(function ($stateProvider) {
$stateProvider
.state('main', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainCtrl'
});
}); | mit |
krisjey/netty.book.kor | telnet-server/src/main/java/com/github/nettybook/ch7/junit/TelnetServerV3.java | 1977 | package com.github.nettybook.ch7.junit;
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.net.InetSocketAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public final class TelnetServerV3 {
@Autowired
@Qualifier("tcpSocketAddress")
private InetSocketAddress address;
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new TelnetServerInitializerV3());
ChannelFuture future = b.bind(address).sync();
future.channel().closeFuture().sync();
}
catch (InterruptedException e) {
e.printStackTrace();
}
finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
| mit |
VitSalis/endofcodes | tests/models/round.php | 5647 | <?php
require_once 'models/round.php';
require_once 'models/game.php';
class RoundTest extends UnitTestWithFixtures {
public function testSaveDb() {
$game = $this->buildGame();
$game->rounds[ 0 ] = $round = $this->buildRound();
$round->game = $game;
$round->save();
$caught = false;
try {
$dbRound = new Round( $game, 1 );
}
catch ( ModelNotFoundException $e ) {
$caught = true;
}
$this->assertFalse( $caught, 'A round must be stored in the database' );
$this->assertSame( $round->id, $dbRound->id, "Round's id must be correctly stored in the database" );
$this->assertSame( $round->game->id, $dbRound->game->id, "Round's gameid must be correctly stored in the database" );
foreach ( $dbRound->creatures as $id => $dbCreature ) {
$creature = $round->creatures[ $id ];
$this->assertSame( $creature->id, $dbCreature->id, "Creature's id must be correctly stored in the database" );
$this->assertSame( $creature->locationx, $dbCreature->locationx, "Creature's locationx must be correctly stored in the database" );
$this->assertSame( $creature->locationy, $dbCreature->locationy, "Creature's locationy must be correctly stored in the database" );
$this->assertSame( $creature->hp, $dbCreature->hp, "Creature's hp must be correctly stored in the database" );
$this->assertTrue( isset( $dbCreature->user ), "Creature must have a user" );
$this->assertSame( $creature->user->id, $dbCreature->user->id, "Creature's userid must be correctly stored in the database" );
}
}
public function testError() {
$round = new Round();
$round->error( 1, 'fuck this user', 'actual', 'expected' );
$this->assertEquals( 'fuck this user', $round->errors[ 1 ][ 0 ][ 'description' ], 'description must store the description of the error specfied' );
$this->assertEquals( 'expected', $round->errors[ 1 ][ 0 ][ 'expected' ], 'expected must store the expected of the error specfied' );
$this->assertEquals( 'actual', $round->errors[ 1 ][ 0 ][ 'actual' ], 'actual must store the actual of the error specfied' );
}
protected function buildRoundWithCreatures( $users ) {
$creatureid = 1;
$x = $y = 0;
$creatures = [];
foreach ( $users as $user ) {
$creatures[ $creatureid ] = $this->buildCreature( $creatureid, $x, $y, $user );
++$x;
++$y;
++$creatureid;
}
$round = new Round();
$round->creatures = $creatures;
return $round;
}
public function testIsFinalRoundMultipleCreaturesDifferentUsers() {
$user1 = $this->buildUser( 'vitsalis' );
$user2 = $this->buildUser( 'dionyziz' );
$users = [ $user1->id => $user1, $user2->id => $user2 ];
$round = $this->buildRoundWithCreatures( $users );
$this->assertTrue( method_exists( $round, 'isFinalRound' ), 'Round object must export an isFinalRound function' );
$this->assertFalse( $round->isFinalRound(), "isFinalRound() must be false if the round's creatures belong to multiple users" );
}
public function testIsFinalRound() {
$user1 = $this->buildUser( 'vitsalis' );
$users = [ $user1->id => $user1 ];
$round = $this->buildRoundWithCreatures( $users );
$this->assertTrue( $round->isFinalRound(), "isFinalRound() must be true if the round's creatures belong to only one user" );
}
public function testIsFinalRoundNoCreatures() {
$round = $this->buildRoundWithCreatures( [] );
$this->assertTrue( $round->isFinalRound(), "isFinalRound() must be true if the round has no creatures" );
}
public function testGetWinnerIdOneUser() {
$user1 = $this->buildUser( 'vitsalis' );
$users = [ $user1->id => $user1 ];
$round = $this->buildRoundWithCreatures( $users );
$this->assertEquals( $user1->id, $round->getWinnerId(), 'Get winner id must return the id of the winner' );
}
public function testGetWinnerIdNoUsers() {
$round = $this->buildRoundWithCreatures( [] );
$this->assertFalse( $round->getWinnerId(), 'If there are no players in the round, getWinnerId must return false' );
}
public function testWinnerIdMultipleUsers() {
$user1 = $this->buildUser( 'vitsalis' );
$user2 = $this->buildUser( 'dionyziz' );
$users = [ $user1->id => $user1, $user2->id => $user2 ];
$round = $this->buildRoundWithCreatures( $users );
$this->assertThrows( [ $round, 'getWinnerId' ], 'ModelValidationException', 'A ModelValidationException must be thrown if the round is not the final one' );
}
public function testGenesisOnConstructor() {
$game = $this->buildGameWithRoundAndCreatures();
$genesis = $game->rounds[ 0 ];
$dbRound = new Round( $game, 1, $genesis );
foreach ( $dbRound->creatures as $creatureid => $creature ) {
$this->assertSame( $genesis->creatures[ $creatureid ]->user->id, $creature->user->id, 'Round constructor must copy users from genesis' );
}
}
}
return new RoundTest();
?>
| mit |
adeubank/meteor-demo | lib/game.js | 323 | // add the game over clauses
// this will restart the game if the snake hits something
// add the code for body collision
// if the head of the snake bumps into anything in the array, game over
checkCollision = function (x, y, array) {
return _.any(array, function (elem) {
return elem.x == x && elem.y == y;
});
}; | mit |
wunderg/react-redux-express-mongo-starter | src/actions/login.js | 2556 | import axios from 'axios';
import * as ACTIONS from './constants';
function saveToLocalStorage(token) {
localStorage.setItem('id_token', token);
}
function requestSignup(creds) {
return {
type: ACTIONS.SIGNUP_REQUEST,
isFetching: true,
isAuthenticated: false,
creds
};
}
function recieveSignup(user) {
saveToLocalStorage(user.data.id_token);
return {
type: ACTIONS.SIGNUP_SUCCESS,
isFetching: false,
isAuthenticated: true,
id_token: user.data.id_token
};
}
function signupError(message) {
return {
type: ACTIONS.SIGNUP_FAILURE,
isFetching: false,
isAuthenticated: false,
message
};
}
export function signupUser(creds) {
return dispatch => {
dispatch(requestSignup(creds));
return axios.post('api/signup', creds)
.then(res => dispatch(recieveSignup(res)))
.catch(err => dispatch(signupError(err)));
};
}
function requestLogin(creds) {
return {
type: ACTIONS.LOGIN_REQUEST,
isFetching: true,
isAuthenticated: false,
creds
};
}
function recieveLogin(user) {
if (user.data && user.data.id_token) {
saveToLocalStorage(user.data.id_token);
}
return {
type: ACTIONS.LOGIN_SUCCESS,
isFetching: false,
isAuthenticated: true,
name: user
};
}
function loginError(message) {
return {
type: ACTIONS.LOGIN_FAILURE,
isFetching: false,
isAuthenticated: false,
message
};
}
export function loginUser(creds) {
return dispatch => {
dispatch(requestLogin(creds));
return axios.post('api/login', creds)
.then(res => dispatch(recieveLogin(res)))
.catch(err => dispatch(loginError(err)));
};
}
function requestLoginWithToken() {
return {
type: ACTIONS.TOKEN_LOGIN_REQUEST,
isFetching: true,
isAuthenticated: false,
};
}
function recieveTokenLogin(user) {
return {
type: ACTIONS.TOKEN_LOGIN_SUCCESS,
isFetching: false,
isAuthenticated: true,
name: user
};
}
function tokenLoginError(message) {
return {
type: ACTIONS.TOKEN_LOGIN_FAILURE,
isFetching: false,
isAuthenticated: false,
message
};
}
export function logout() {
localStorage.removeItem('id_token', null);
return {
type: ACTIONS.LOGOUT
};
}
export function loginWithToken(token) {
const config = {
headers: { Authorization: token }
};
return dispatch => {
dispatch(requestLoginWithToken());
return axios.get('api/tokenlogin', config)
.then(res => dispatch(recieveTokenLogin(res)))
.catch(err => dispatch(tokenLoginError(err)));
};
}
| mit |
YoshitsuguFujii/rails_admin_base | lib/rails_admin_base/validators/css_validator.rb | 784 | # Sass::Engineを使った簡易的なチェック
class CssValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
begin
Sass::Engine.new(value, syntax: :scss, style: :expand, cache: false).to_css
rescue Sass::SyntaxError => ex
object.errors[attribute] << (options[:messge] || I18n.t('errors.messages.css_syntax_error'))
rescue Encoding::UndefinedConversionError => ex
object.errors[attribute] << (options[:messge] || I18n.t('errors.messages.css_encoding_utf8_error'))
rescue Encoding::UndefinedConversionError => ex
object.errors[attribute] << (options[:messge] || I18n.t('errors.messages.css_encoding_error'))
rescue => ex
object.errors[attribute] << (options[:messge] || ex.message)
end
end
end
| mit |
P1erreGaultier/FrontPepSII | www/js/services.js | 1579 | angular.module('app.services', [])
.factory('CustomFactory', [function(){
var event;
return {
coucouGlobal : function(name) {
console.log('Coucou ' + name);
return "oui";
},
saveEvent : function(eventToSave) {
event = eventToSave;
},
getEvent : function() {
return event;
}
};
}])
.factory('EventService', [function(){
var event;
var events;
return {
saveEvent : function(eventToSave) {
event = eventToSave;
},
getEvent : function() {
return event;
},
saveEvents : function(eventsToSave) {
events = eventsToSave;
},
getEvents : function() {
return events;
}
};
}])
.service('ConnectedUserService', [function(){
var connectedUser;
var connected = "false";
var googleId;
var responseGoogle;
return {
setConnectedUser: function(user) {
connectedUser = user;
},
getConnectedUser: function() {
return connectedUser;
},
setConnected: function(connect) {
connected = connect;
},
isConnected: function() {
return connected;
},
setGoogleId: function(id) {
googleId = id;
},
getGoogleId: function() {
return googleId;
},
setResponseGoogle: function(google) {
responseGoogle = google;
},
getResponseGoogle: function() {
return responseGoogle;
}
}
}])
.service('GoogleService', [function(){
var gu;
return {
saveGU : function(guToSave) {
gu = guToSave;
},
getGU : function(){
return gu;
}
}
}]);
| mit |
hironapo/pico-tcl | test/if_spec.rb | 1603 | $:.unshift File.dirname(__FILE__) + "../lib"
require 'pico-tcl'
describe PicoTcl::Interp do
it "if0" do
ip = PicoTcl::Interp.new
expect( ip.eval("if { 10 < 20 } {
set a 10
}
") ).to eq "10"
end
it "if1" do
ip = PicoTcl::Interp.new
expect( ip.eval("if { 10 > 20 } {
set a 10
}
") ).to eq ""
end
# TODO: 0 or 1
# it "if2" do
# ip = PicoTcl::Interp.new
# ip.eval("if 1 {
# set a 10
# }
# ").should == "10"
# end
#
# it "if3" do
# ip = PicoTcl::Interp.new
# ip.eval("if 0 {
# set a 10
# }
# ").should == ""
# end
it "if-else2" do
ip = PicoTcl::Interp.new
ip.eval("set a 10")
expect( ip.eval("if { $a < 20 } {
set a 10
} else {
set a 20
}
") ).to eq "10"
end
it "if-else1" do
ip = PicoTcl::Interp.new
ip.eval("set a 10")
expect( ip.eval("if { $a < 5 } {
set a 10
} else {
set a 20
}
") ).to eq "20"
end
it "if-elseif-else" do
ip = PicoTcl::Interp.new
ip.eval("set a 10")
expect( ip.eval("if { $a < 5 } {
set a 10
} elseif { $a > 5} {
set a 50
} else {
set a 20
}
") ).to eq "50"
end
it "if-elseif-else2" do
ip = PicoTcl::Interp.new
ip.eval("set a 10")
expect( ip.eval("if { $a < 5 } {
set a 10
} elseif {$a == 5} {
set a 50
} elseif {$a > 5} {
set a 100
} else {
set a 20
}
") ).to eq "100"
end
end
| mit |
Vulcania/GSB_Symfony | app/cache/de_/twig/78/9f/60fad94cccf3b3c9cebec949f03f9146bc35138ca614a4b2f8c255b0b33b.php | 1598 | <?php
/* FOSUserBundle:Profile:edit_content.html.twig */
class __TwigTemplate_789f60fad94cccf3b3c9cebec949f03f9146bc35138ca614a4b2f8c255b0b33b extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<form action=\"";
echo $this->env->getExtension('routing')->getPath("fos_user_profile_edit");
echo "\" ";
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype');
echo " method=\"POST\" class=\"fos_user_profile_edit\">
";
// line 2
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'widget');
echo "
<div>
<input type=\"submit\" value=\"";
// line 4
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("profile.edit.submit", array(), "FOSUserBundle"), "html", null, true);
echo "\" />
</div>
</form>
";
}
public function getTemplateName()
{
return "FOSUserBundle:Profile:edit_content.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 31 => 4, 26 => 2, 19 => 1,);
}
}
| mit |
phlopsi/access-control | src/Phlopsi/ExceptionTranslator/ExceptionTranslator.php | 1686 | <?php
/**
* @author Patrick Fischer <nbphobos@gmail.com>
*/
declare(strict_types = 1);
namespace Phlopsi\ExceptionTranslator;
use Phlopsi\Reflection\ExceptionReflection;
use Phlopsi\Reflection\ExternalExceptionReflection;
class ExceptionTranslator
{
/**
* @var \Phlopsi\Reflection\ExternalExceptionReflection
*/
private $default_exception_reflection;
/**
* @var string
*/
private $exception_namespace;
/**
* @param \Phlopsi\Reflection\ExternalExceptionReflection $default_exception_reflection
*
* @codeCoverageIgnore
*/
public function __construct(ExternalExceptionReflection $default_exception_reflection)
{
$this->default_exception_reflection = $default_exception_reflection;
$this->exception_namespace = $default_exception_reflection->getNamespaceName();
}
/**
* @param \Phlopsi\Reflection\ExceptionReflection $exception_reflection
*
* @throws \DomainException
*
* @return \Phlopsi\Reflection\ExternalExceptionReflection
*/
public function translate(ExceptionReflection $exception_reflection): ExternalExceptionReflection
{
$current_exception_reflection = $exception_reflection;
do {
$exception_name = $this->exception_namespace . '\\' . $current_exception_reflection->getShortName();
if (\class_exists($exception_name)) {
return new ExternalExceptionReflection($exception_name);
}
} while ($current_exception_reflection = $current_exception_reflection->getParentClass());
return $this->default_exception_reflection;
}
}
| mit |
SocialCentivPublic/cheftacular | lib/cloud_interactor/cloud_interactor.rb | 1187 | class CloudInteractor
ALLOWED_HLMS = ['domain', 'flavor', 'image', 'region', 'server', 'sshkey', 'volume']
def initialize auth_hash, options
@main_obj, @classes = {},{}
@options = options
@main_obj['output'] = {}
@auth_hash = auth_hash
@classes['helper'] = Helper.new(@main_obj, @classes, @options)
@classes['clouds'] = CloudProvider.new(@options)
@classes['domain'] = Domain.new(@main_obj, @auth_hash, @classes, @options)
@classes['flavor'] = Flavor.new(@main_obj, @classes, @options)
@classes['image'] = Image.new(@main_obj, @classes, @options)
@classes['region'] = Region.new(@main_obj, @classes, @options)
@classes['server'] = Server.new(@main_obj, @classes, @options)
@classes['sshkey'] = SSHKey.new(@main_obj, @classes, @options)
@classes['volume'] = Volume.new(@main_obj, @classes, @options)
@classes['auth'] = Authentication.new(@auth_hash, @options)
end
def run args
parse_args(args) unless args.empty?
#clear out the main_obj so repeated runs do not cause strange data
@main_obj = @main_obj.keep_if {|key, value| key == 'output'}
@main_obj['output']
end
end
| mit |
Daisukydayo/icms2 | FrameWork1/RuleClass/Gen/User/UserOrderSendPublicGen.php | 1934 | <?php
/**
* 前台管理 会员订单发货信息 生成类
* @category iCMS
* @package iCMS_FrameWork1_RuleClass_Gen_User
* @author yin
*/
class UserOrderSendPublicGen extends BasePublicGen implements IBasePublicGen{
/**
* @return string
*/
public function GenPublic(){
$method = Control::GetRequest("a","");
$result = "";
switch($method){
case "list":
$result = self::GenList();
break;
}
return $result;
}
private function GenList(){
$userOrderNumber = Control::GetRequest("user_order_number","");
$userOrderId = Control::GetRequest("user_order_id",0);
$templateContent = "";
if($userOrderId > 0 && !empty($userOrderNumber)){
//$templateFileUrl = "user/user_order_send_list.html";
//$templateName = "default";
//$templatePath = "front_template";
//$templateContent = Template::Load($templateFileUrl, $templateName, $templatePath);
$templateContent = parent::GetDynamicTemplateContent("user_register_for_forum");
parent::ReplaceFirst($templateContent);
$userOrderSendPublicData = new UserOrderSendPublicData();
$arrUserOrderSendList = $userOrderSendPublicData->GetList($userOrderId);
$tagId = "user_order_send_list";
if(count($arrUserOrderSendList) > 0){
Template::ReplaceList($templateContent,$arrUserOrderSendList,$tagId);
}else{
Template::ReplaceCustomTag($templateContent,$tagId,Language::Load("user_order_send",1));
}
}
$templateContent = str_ireplace("{UserOrderId}",$userOrderId,$templateContent);
$templateContent = str_ireplace("{UserOrderNumber}",$userOrderNumber,$templateContent);
parent::ReplaceEnd($templateContent);
return $templateContent;
}
} | mit |
sergeyshushlyapin/AutoFixture | Src/AutoFixture.xUnit.net2.UnitTest/Properties/AssemblyInfo.cs | 1480 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AutoFixture.xUnit.net2.UnitTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ploeh")]
[assembly: AssemblyProduct("AutoFixture")]
[assembly: AssemblyCopyright("Copyright © Ploeh 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5a728509-e850-4137-bddc-0cc156a356cb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0.0")]
| mit |