path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/components/cards/card_wild.js
camboio/yooneau
import React from 'react'; export default class CardWild extends React.Component{ render(){ const colour = this.props.card.colour ? this.props.card.colour : 'gray'; return( <svg className="card-wild-component" onClick={this.props.onClick} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 158.7 243.8"> <g id="Layer_3"> <path id="XMLID_5_" className="c0" d="M146.7 243.8H12c-6.6 0-12-5.4-12-12V12C0 5.4 5.4 0 12 0h134.7c6.6 0 12 5.4 12 12v219.8c0 6.6-5.4 12-12 12z"/> </g> <g id="Layer_1"> <path id="XMLID_19_" className={colour} d="M147.5 79.1c0-37.6-30.4-68-68-68h-68v153.2c0 37.6 30.4 68 68 68h68V79.1z"/> </g> <g id="Layer_8"> <g id="XMLID_43_"> <g id="XMLID_38_"> <text id="XMLID_42_" transform="translate(13.747 35.452)" className="wild1 wild2 wild3">W</text> </g> <g id="XMLID_32_"> <text id="XMLID_36_" transform="translate(15.165 34.035)" className="wild4 wild2 wild3">W</text> </g> </g> </g> <g id="Layer_9"> <g id="XMLID_45_"> <g id="XMLID_33_"> <text id="XMLID_35_" transform="rotate(180 72.547 104.114)" className="wild1 wild2 wild3">W</text> </g> <g id="XMLID_29_"> <text id="XMLID_31_" transform="rotate(180 71.84 104.823)" className="wild4 wild2 wild3">W</text> </g> </g> </g> <g id="Layer_13"> <g id="XMLID_53_"> <g id="XMLID_131_"> <path id="XMLID_136_" d="M76.393 67.488l26.94 26.94-26.94 26.94-26.94-26.94z"/> </g> <g id="XMLID_114_"> <path id="XMLID_130_" className="wild5" d="M77.857 66.142l26.94 26.94-26.94 26.94-26.94-26.94z"/> </g> </g> <g id="XMLID_54_"> <g id="XMLID_124_"> <path id="XMLID_132_" d="M105.8 150.9l-26.9-27L105.8 97z"/> </g> <g id="XMLID_113_"> <path id="XMLID_118_" className="wild6" d="M107.2 149.4l-26.9-26.9 26.9-26.9z"/> </g> </g> <g id="XMLID_60_"> <g id="XMLID_116_"> <path id="XMLID_134_" d="M47 97l26.9 26.9-26.9 27z"/> </g> <g id="XMLID_111_"> <path id="XMLID_115_" className="wild7" d="M48.4 95.6l26.9 26.9-26.9 26.9z"/> </g> </g> <g id="XMLID_55_"> <g id="XMLID_125_"> <path id="XMLID_135_" d="M76.358 126.373l26.94 26.94-26.94 26.94-26.94-26.94z"/> </g> <g id="XMLID_108_"> <path id="XMLID_123_" className="wild8" d="M77.822 125.027l26.94 26.94-26.94 26.94-26.94-26.94z"/> </g> </g> </g> </svg> ); } }
src/Containers/ChartContainer/Chart.js
sirjuan/harmonical-oscillation
import React from 'react'; import { Scatter } from 'react-chartjs-2'; const scatterChart = ({color = 'blue', values = [], keys = {}, title = ''}) => { const data = { datasets: [{ label: `${keys.x} / ${keys.y}`, fill: false, pointBackgroundColor: 'rgba(0, 0, 0, 0)', pointBorderColor: 'rgba(0, 0, 0, 0)', borderColor: color, data: values.map(line => ({x: line[keys.x], y: line[keys.y]})) }] } const options = { title: { display: title ? true : false, text: title, fontSize: 24 } } return <Scatter data={data} options={options} /> }; const charts = { scatter: props => scatterChart(props), }; const Chart = ({type, ...props}) => charts[type](props); export default Chart;
es/transitions/Slide.js
uplevel-technology/material-ui-next
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } // @inheritedComponent Transition import React from 'react'; import { findDOMNode } from 'react-dom'; import EventListener from 'react-event-listener'; import debounce from 'lodash/debounce'; import Transition from 'react-transition-group/Transition'; import withTheme from '../styles/withTheme'; import { duration } from '../styles/transitions'; const GUTTER = 24; // Translate the node so he can't be seen on the screen. // Later, we gonna translate back the node to his original location // with `translate3d(0, 0, 0)`.` function getTranslateValue(props, node) { const { direction } = props; const rect = node.getBoundingClientRect(); let transform; if (node.fakeTransform) { transform = node.fakeTransform; } else { const computedStyle = window.getComputedStyle(node); transform = computedStyle.getPropertyValue('-webkit-transform') || computedStyle.getPropertyValue('transform'); } let offsetX = 0; let offsetY = 0; if (transform && transform !== 'none' && typeof transform === 'string') { const transformValues = transform.split('(')[1].split(')')[0].split(','); offsetX = parseInt(transformValues[4], 10); offsetY = parseInt(transformValues[5], 10); } if (direction === 'left') { return `translateX(100vw) translateX(-${rect.left - offsetX}px)`; } else if (direction === 'right') { return `translateX(-${rect.left + rect.width + GUTTER - offsetX}px)`; } else if (direction === 'up') { return `translateY(100vh) translateY(-${rect.top - offsetY}px)`; } // direction === 'down return `translate3d(0, ${0 - (rect.top + rect.height)}px, 0)`; } export function setTranslateValue(props, node) { const transform = getTranslateValue(props, node); if (transform) { node.style.transform = transform; node.style.webkitTransform = transform; } } const reflow = node => node.scrollTop; class Slide extends React.Component { constructor(...args) { var _temp; return _temp = super(...args), this.state = { // We use this state to handle the server-side rendering. firstMount: true }, this.transition = null, this.handleResize = debounce(() => { // Skip configuration where the position is screen size invariant. if (this.props.in || this.props.direction === 'down' || this.props.direction === 'right') { return; } const node = findDOMNode(this.transition); if (node instanceof HTMLElement) { setTranslateValue(this.props, node); } }, 166), this.handleEnter = node => { setTranslateValue(this.props, node); reflow(node); if (this.props.onEnter) { this.props.onEnter(node); } }, this.handleEntering = node => { const { theme, timeout } = this.props; node.style.transition = theme.transitions.create('transform', { duration: typeof timeout === 'number' ? timeout : timeout.enter, easing: theme.transitions.easing.easeOut }); // $FlowFixMe - https://github.com/facebook/flow/pull/5161 node.style.webkitTransition = theme.transitions.create('-webkit-transform', { duration: typeof timeout === 'number' ? timeout : timeout.enter, easing: theme.transitions.easing.easeOut }); node.style.transform = 'translate3d(0, 0, 0)'; node.style.webkitTransform = 'translate3d(0, 0, 0)'; if (this.props.onEntering) { this.props.onEntering(node); } }, this.handleExit = node => { const { theme, timeout } = this.props; node.style.transition = theme.transitions.create('transform', { duration: typeof timeout === 'number' ? timeout : timeout.exit, easing: theme.transitions.easing.sharp }); // $FlowFixMe - https://github.com/facebook/flow/pull/5161 node.style.webkitTransition = theme.transitions.create('-webkit-transform', { duration: typeof timeout === 'number' ? timeout : timeout.exit, easing: theme.transitions.easing.sharp }); setTranslateValue(this.props, node); if (this.props.onExit) { this.props.onExit(node); } }, this.handleExited = node => { // No need for transitions when the component is hidden node.style.transition = ''; // $FlowFixMe - https://github.com/facebook/flow/pull/5161 node.style.webkitTransition = ''; if (this.props.onExited) { this.props.onExited(node); } }, _temp; } componentDidMount() { // state.firstMount handle SSR, once the component is mounted, we need // to properly hide it. if (!this.props.in) { // We need to set initial translate values of transition element // otherwise component will be shown when in=false. this.updatePosition(); } } componentWillReceiveProps() { this.setState({ firstMount: false }); } componentDidUpdate(prevProps) { if (prevProps.direction !== this.props.direction && !this.props.in) { // We need to update the position of the drawer when the direction change and // when it's hidden. this.updatePosition(); } } componentWillUnmount() { this.handleResize.cancel(); } updatePosition() { const element = findDOMNode(this.transition); if (element instanceof HTMLElement) { element.style.visibility = 'inherit'; setTranslateValue(this.props, element); } } render() { const _props = this.props, { children, onEnter, onEntering, onExit, onExited, style: styleProp, theme } = _props, other = _objectWithoutProperties(_props, ['children', 'onEnter', 'onEntering', 'onExit', 'onExited', 'style', 'theme']); const style = _extends({}, styleProp); if (!this.props.in && this.state.firstMount) { style.visibility = 'hidden'; } return React.createElement( EventListener, { target: 'window', onResize: this.handleResize }, React.createElement( Transition, _extends({ onEnter: this.handleEnter, onEntering: this.handleEntering, onExit: this.handleExit, onExited: this.handleExited, appear: true, style: style }, other, { ref: node => { this.transition = node; } }), children ) ); } } Slide.defaultProps = { timeout: { enter: duration.enteringScreen, exit: duration.leavingScreen } }; export default withTheme()(Slide);
app/imports/ui/pages/auth/Signup.js
mondrus/meteor-starter
/** * @Author: philip * @Date: 2017-05-27T16:51:26+00:00 * @Filename: Signup.js * @Last modified by: philip * @Last modified time: 2017-05-27T17:41:50+00:00 */ import React from 'react'; import { Link } from 'react-router-dom'; import { Row, Col, FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap'; import handleSignup from '../../../modules/signup'; export default class Signup extends React.Component { componentDidMount() { handleSignup({ component: this }); } handleSubmit(event) { event.preventDefault(); console.log(this.signupForm); } render() { return ( <div className="middle-box text-center loginscreen animated fadeInDown"> <div> <h1 className="logo-name">IN+</h1> </div> <h3>Register to IN+</h3> <p>Create account to see it in action.</p> <form ref={ form => (this.signupForm = form) } onSubmit={ this.handleSubmit } className="m-t" > <FormGroup> <FormControl type="text" ref="username" name="username" placeholder="Username" /> </FormGroup> <FormGroup> <FormControl type="text" ref="emailAddress" name="emailAddress" placeholder="Email Address" /> </FormGroup> <FormGroup> <FormControl type="password" ref="password" name="password" placeholder="Password" /> </FormGroup> <FormGroup> <ControlLabel><input type="checkbox" /><i></i> Agree the terms and policy</ControlLabel> </FormGroup> <Button type="submit" bsStyle="success" className="btn-primary block full-width m-b">Sign Up</Button> <p className="text-muted text-center"> <small>Already have an account?</small> </p> <Link to="/login" className="btn btn-sm btn-white btn-block">Log In</Link> </form> <p className="m-t"> <small>Inspinia we app framework base on Bootstrap 3 &copy; 2017</small> </p> </div> ); } }
src/routes/logout/Logout.js
AaronHartigan/DudeTruck
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Logout.css'; class Logout extends React.Component { componentDidMount() { setTimeout(() => { window.location.reload(); }, 1250); } render() { return <div className={s.text}>Logging out...</div>; } } export default withStyles(s)(Logout);
src/modules/connect/connectDetail/components/ConnectDetailTagBox.js
Florenz23/sangoo_04
import React, { Component } from 'react'; import { Container,List, Header, Title, Content, Button, Icon, IconNB, Card, CardItem, Text, Left, Right, Body, ListItem } from 'native-base'; import { View } from 'react-native' import styles from '../../styles/socialBox'; import contacts from '../../../../mock/contacts' import realm from '../../db_ini' const _getContact = (contactId) => { const contacts = realm.objects('User') const searchResult = contacts.filtered(`userId = "${contactId}"`) const recent_contact = searchResult[0] return recent_contact } const _getMatchingData = (arr1,arr2) => { arr1.prototype.diff = function(arr2) { var ret = []; for(var i in this) { if(arr2.indexOf( this[i] ) > -1){ ret.push( this[i] ); } } return ret; }; } const renderData = (contactId) => { const datas = contacts const contact = _getContact(contactId) return ( <View> <List dataArray={contact.publicSharedData[0].hashTagData} renderRow={data => <ListItem style={{backgroundColor:'white'}}> <Text>{data.tagDescription}</Text> <Right> <Text>{data.tagText}</Text> </Right> </ListItem> } /> </View> ) } const ConnectDetailTagBox = (props) => { const datas = contacts const {children} = props return ( <View> {renderData(children)} </View> ) } export default ConnectDetailTagBox
src/parser/mage/shared/modules/features/RuneOfPower.js
fyruna/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SPECS from 'game/SPECS'; import SpellLink from 'common/SpellLink'; import { formatNumber, formatPercentage } from 'common/format'; import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import Analyzer from 'parser/core/Analyzer'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import Events from 'parser/core/Events'; import { SELECTED_PLAYER } from 'parser/core/EventFilter'; import SUGGESTION_IMPORTANCE from 'parser/core/ISSUE_IMPORTANCE'; /* * If Rune of Power is substantially better than the rest of the row, enable * ROP talent suggestion. At time of writing, it's a substantial increase over * incanters flow for fire and arcane in all situations. */ const SUGGEST_ROP = { [SPECS.FROST_MAGE.id]: false, [SPECS.ARCANE_MAGE.id]: true, [SPECS.FIRE_MAGE.id]: true }; const DAMAGE_BONUS = 0.4; const RUNE_DURATION = 10; const INCANTERS_FLOW_EXPECTED_BOOST = 0.12; // FIXME due to interactions with Ignite, the damage boost number will be underrated for Fire Mages. Still fine for Arcane and Frost. class RuneOfPower extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, }; hasROP = false; damage = 0; constructor(...args) { super(...args); if (this.selectedCombatant.hasTalent(SPELLS.RUNE_OF_POWER_TALENT.id)) { this.hasROP = true; this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onPlayerDamage); } } onPlayerDamage(event) { if (this.selectedCombatant.hasBuff(SPELLS.RUNE_OF_POWER_BUFF.id)) { this.damage += calculateEffectiveDamage(event, DAMAGE_BONUS); } } get damagePercent() { return this.owner.getPercentageOfTotalDamageDone(this.damage); } get damageIncreasePercent() { return this.damagePercent / (1 - this.damagePercent); } get uptimeMS() { return this.selectedCombatant.getBuffUptime(SPELLS.RUNE_OF_POWER_BUFF.id); } get roundedSecondsPerCast() { return ((this.uptimeMS / this.abilityTracker.getAbility(SPELLS.RUNE_OF_POWER_TALENT.id).casts) / 1000).toFixed(1); } get damageSuggestionThresholds() { return { actual: this.damageIncreasePercent, isLessThan: { minor: INCANTERS_FLOW_EXPECTED_BOOST, average: INCANTERS_FLOW_EXPECTED_BOOST, major: INCANTERS_FLOW_EXPECTED_BOOST - 0.03, }, style: 'percentage', }; } get roundedSecondsSuggestionThresholds() { return { actual: this.roundedSecondsPerCast, isLessThan: { minor: RUNE_DURATION, average: RUNE_DURATION - 1, major: RUNE_DURATION - 2, }, style: 'number', }; } showSuggestion = true; suggestions(when) { if (!this.hasROP) { when(SUGGEST_ROP[this.selectedCombatant.specId]).isTrue() .addSuggestion((suggest) => { return suggest( <> It is highly recommended to talent into <SpellLink id={SPELLS.RUNE_OF_POWER_TALENT.id} /> when playing this spec. While it can take some practice to master, when played correctly it outputs substantially more DPS than <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} /> or <SpellLink id={SPELLS.MIRROR_IMAGE_TALENT.id} />. </>) .icon(SPELLS.RUNE_OF_POWER_TALENT.icon) .staticImportance(SUGGESTION_IMPORTANCE.REGULAR); }); return; } if(!this.showSuggestion) { return; } when(this.damageSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Your <SpellLink id={SPELLS.RUNE_OF_POWER_TALENT.id} /> damage boost is below the expected passive gain from <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />. Either find ways to make better use of the talent, or switch to <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />.</>) .icon(SPELLS.RUNE_OF_POWER_TALENT.icon) .actual(`${formatPercentage(this.damageIncreasePercent)}% damage increase from Rune of Power`) .recommended(`${formatPercentage(recommended)}% is the passive gain from Incanter's Flow`); }); if (this.abilityTracker.getAbility(SPELLS.RUNE_OF_POWER_TALENT.id).casts > 0) { when(this.roundedSecondsSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You sometimes aren't standing in your <SpellLink id={SPELLS.RUNE_OF_POWER_TALENT.id} /> for its full duration. Try to only use it when you know you won't have to move for the duration of the effect.</>) .icon(SPELLS.RUNE_OF_POWER_TALENT.icon) .actual(`Average ${this.roundedSecondsPerCast}s standing in each Rune of Power`) .recommended(`the full duration of ${formatNumber(RUNE_DURATION)}s is recommended`); }); } } showStatistic = true; statistic() { if (!this.hasROP || !this.showStatistic) return null; return ( <TalentStatisticBox talent={SPELLS.RUNE_OF_POWER_TALENT.id} position={STATISTIC_ORDER.CORE(100)} value={`${formatPercentage(this.damagePercent)} %`} label="Rune of Power damage" tooltip={<>This is the portion of your total damage attributable to Rune of Power's boost. Expressed as an increase vs never using Rune of Power, this is a <strong>{formatPercentage(this.damageIncreasePercent)}% damage increase</strong>. Note that this number does <em>not</em> factor in the opportunity cost of casting Rune of Power instead of another damaging spell.</>} /> ); } } export default RuneOfPower;
src/parser/shared/modules/spells/bfa/azeritetraits/BloodRite.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import { calculateAzeriteEffects } from 'common/stats'; import Analyzer from 'parser/core/Analyzer'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; import StatTracker from 'parser/shared/modules/StatTracker'; const bloodRiteStats = traits => Object.values(traits).reduce((obj, rank) => { const [haste] = calculateAzeriteEffects(SPELLS.BLOOD_RITE.id, rank); obj.haste += haste; return obj; }, { haste: 0, }); /** * Blood Rite * Gain x haste while active * * Example report: https://www.warcraftlogs.com/reports/k4bAJZKWVaGt12j9#fight=3&type=auras&source=14 */ class BloodRite extends Analyzer { static dependencies = { statTracker: StatTracker, }; haste = 0; bloodRiteProcs = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.BLOOD_RITE.id); if (!this.active) { return; } const { haste } = bloodRiteStats(this.selectedCombatant.traitsBySpellId[SPELLS.BLOOD_RITE.id]); this.haste = haste; this.statTracker.add(SPELLS.BLOOD_RITE_BUFF.id, { haste, }); } on_byPlayer_applybuff(event) { this.handleBuff(event); } on_byPlayer_refreshbuff(event) { this.handleBuff(event); } handleBuff(event) { if (event.ability.guid !== SPELLS.BLOOD_RITE_BUFF.id) { return; } this.bloodRiteProcs += 1; } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.BLOOD_RITE_BUFF.id) / this.owner.fightDuration; } get averageHaste() { return (this.haste * this.uptime).toFixed(0); } statistic() { return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.BLOOD_RITE.id} value={`${this.averageHaste} average Haste`} tooltip={( <> {SPELLS.BLOOD_RITE.name} grants <strong>{this.haste} Haste</strong> while active.<br /> You had <strong>{this.bloodRiteProcs} {SPELLS.BLOOD_RITE.name} procs</strong> resulting in {formatPercentage(this.uptime)}% uptime. </> )} /> ); } } export default BloodRite;
__tests__/setup.js
brentvatne/react-conf-app
// @flow import React from 'react'; import { View } from 'react-native'; // ------------------------ // Javascript Built-Ins // ------------------------ // Ensure Date.now and new Date() give us the same date for snapshots. import timekeeper from 'timekeeper'; timekeeper.freeze(new Date(2017, 3, 1, 8, 0, 0)); // ------------------------ // React Native Built-Ins // ------------------------ // React Native UI Manager needs a focus function. // $FlowFixMe import { UIManager } from 'NativeModules'; UIManager.focus = jest.fn(); UIManager.createView = jest.fn(() => <View />); UIManager.updateView = jest.fn(); // ------------------------ // NPM Modules // ------------------------ // Provide a manual mock for native modules. jest.mock('react-native-maps');
tests/lib/rules/indent.js
gfxmonk/eslint
/** * @fileoverview This option sets a specific tab width for your code * @author Dmitriy Shekhovtsov * @copyright 2014 Dmitriy Shekhovtsov. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"), ESLintTester = require("eslint-tester"); var fs = require("fs"); var path = require("path"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var fixture = fs.readFileSync(path.join(__dirname, "../../fixtures/rules/indent/indent-invalid-fixture-1.js"), "utf8"); function expectedErrors(errors) { if (!errors[0].length) { errors = [errors]; } return errors.map(function (err) { return { message: "Expected indentation of " + err[1] + " characters.", type: "Program", line: err[0] }; }); } var eslintTester = new ESLintTester(eslint); eslintTester.addRuleTest("lib/rules/indent", { valid: [ { code: "switch (a) {\n" + " case \"foo\":\n" + " a();\n" + " break;\n" + " case \"bar\":\n" + " a(); break;\n" + " case \"baz\":\n" + " a(); break;\n" + "}" }, { code: "switch (0) {\n}" }, { code: "function foo() {\n" + " var a = \"a\";\n" + " switch(a) {\n" + " case \"a\":\n" + " return \"A\";\n" + " case \"b\":\n" + " return \"B\";\n" + " }\n" + "}\n" + "foo();" }, { code: "switch(value){\n" + " case \"1\":\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " a();\n" + " break;\n" + "}\n" + "switch(value){\n" + " case \"1\":\n" + " a();\n" + " break;\n" + " case \"2\":\n" + " break;\n" + " default:\n" + " break;\n" + "}", options: [4] }, { code: "var obj = {foo: 1, bar: 2};\n" + "with (obj) {\n" + " console.log(foo + bar);\n" + "}\n" }, { code: "if (a) {\n" + " (1 + 2 + 3);\n" + // no error on this line "}" }, { code: "switch(value){ default: a(); break; }\n" }, { code: "import {addons} from 'react/addons'\rimport React from 'react'", options: [2], ecmaFeatures: { modules: true } } ], invalid: [ { code: " var a = b;\n" + "if (a) {\n" + " b();\n" + "}\n", options: [2], errors: expectedErrors([[1, 0]]) }, { code: "if (array.some(function(){\n" + " return true;\n" + "})) {\n" + "a++; // ->\n" + " b++;\n" + " c++; // <-\n" + "}\n", options: [2], errors: expectedErrors([[4, 2], [6, 2]]) }, { code: "if (a){\n\tb=c;\n\t\tc=d;\ne=f;\n}", options: ["tab"], errors: expectedErrors([[3, 1], [4, 1]]) }, { code: "if (a){\n b=c;\n c=d;\n e=f;\n}", options: [4], errors: expectedErrors([[3, 4], [4, 4]]) }, { code: fixture, options: [2, {indentSwitchCase: true}], errors: expectedErrors([ [5, 2], [10, 4], [11, 2], [15, 4], [16, 2], [23, 2], [29, 2], [30, 4], [36, 4], [38, 2], [39, 4], [40, 2], [46, 0], [54, 2], [114, 4], [120, 4], [124, 4], [127, 4], [134, 4], [139, 2], [145, 2], [149, 2], [152, 2], [159, 2], [168, 4], [176, 4], [184, 4], [186, 4], [200, 2], [202, 2], [214, 2], [218, 6], [220, 6], [330, 6], [331, 6], [371, 2], [372, 2], [375, 2], [376, 2], [379, 2], [380, 2], [386, 2], [388, 2], [399, 2], [401, 2], [405, 4], [407, 4], [414, 2], [416, 2], [421, 2], [423, 2], [440, 2], [441, 2], [447, 2], [448, 2], [454, 2], [455, 2], [461, 6], [462, 6], [467, 6], [472, 6], [486, 2], [488, 2], [534, 6], [541, 6] ]) }, { code: "switch(value){\n" + " case \"1\":\n" + " a();\n" + " break;\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " a();\n" + " break;\n" + "}", options: [4, {indentSwitchCase: true}], errors: expectedErrors([10, 4]) }, { code: "switch(value){\n" + " case \"1\":\n" + " a();\n" + " break;\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " break;\n" + "}", options: [4, {indentSwitchCase: true}], errors: expectedErrors([9, 8]) }, { code: "switch(value){\n" + " case \"1\":\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " break;\n" + "}\n" + "switch(value){\n" + " case \"1\":\n" + " break;\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " a();\n" + " break;\n" + "}", options: [4, {indentSwitchCase: true}], errors: expectedErrors([[11, 8], [14, 8], [17, 8]]) }, { code: "switch(value){\n" + " case \"1\":\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " a();\n" + " break;\n" + "}\n" + "switch(value){\n" + " case \"1\":\n" + " a();\n" + " break;\n" + " case \"2\":\n" + " break;\n" + " default:\n" + " break;\n" + "}", options: [4, {indentSwitchCase: true}], errors: expectedErrors([[13, 4], [15, 4], [17, 4]]) }, { code: "var obj = {foo: 1, bar: 2};\n" + "with (obj) {\n" + "console.log(foo + bar);\n" + "}\n", args: [2], errors: expectedErrors([3, 4]) } ] });
ui/app/components/layout/index.js
leapcode/bitmask-dev
import React from 'react' import './layout.less' class HorizontalLayout extends React.Component { static get defaultProps() {return{ equalWidths: false, className: '' }} constructor(props) { super(props) } render() { let className = "horizontal-layout " + this.props.className if (this.props.equalWidths) { className = className + " equal" + this.props.children.length } return ( <div className={className}> {this.props.children} </div> ) } } class Column extends React.Component { static get defaultProps() {return{ className: '' }} constructor(props) { super(props) } render() { let className = "layout-column " + this.props.className return ( <div className={className}> {this.props.children} </div> ) } } class VerticalLayout extends React.Component { static get defaultProps() {return{ equalWidths: false, className: '' }} constructor(props) { super(props) } render() { let className = "vertical-layout " + this.props.className if (this.props.equalWidths) { className = className + " equal" + this.props.children.length } return ( <div className={className}> {this.props.children} </div> ) } } class Row extends React.Component { static get defaultProps() {return{ className: '', size: 'expand', gutter: '' }} constructor(props) { super(props) } render() { let style = {} if (this.props.gutter) { style = {marginBottom: this.props.gutter} } let className = ["layout-row", this.props.className, this.props.size].join(" ") return ( <div style={style} className={className}> {this.props.children} </div> ) } } export {HorizontalLayout, VerticalLayout, Column, Row}
src/svg-icons/image/camera-rear.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraRear = (props) => ( <SvgIcon {...props}> <path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zm3-20H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zm-5 6c-1.11 0-2-.9-2-2s.89-2 1.99-2 2 .9 2 2C14 5.1 13.1 6 12 6z"/> </SvgIcon> ); ImageCameraRear = pure(ImageCameraRear); ImageCameraRear.displayName = 'ImageCameraRear'; ImageCameraRear.muiName = 'SvgIcon'; export default ImageCameraRear;
src/DataTable/Selectable.js
react-mdl/react-mdl
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import isEqual from 'lodash.isequal'; import TableHeader from './TableHeader'; import Checkbox from '../Checkbox'; const propTypes = { columns: (props, propName, componentName) => ( props[propName] && new Error(`${componentName}: \`${propName}\` is deprecated, please use the component \`TableHeader\` instead.`) ), data: (props, propName, componentName) => ( props[propName] && new Error(`${componentName}: \`${propName}\` is deprecated, please use \`rows\` instead. \`${propName}\` will be removed in the next major release.`) ), onSelectionChanged: PropTypes.func, rowKeyColumn: PropTypes.string, rows: PropTypes.arrayOf( PropTypes.object ).isRequired, selectable: PropTypes.bool, selectedRows: PropTypes.array }; const defaultProps = { onSelectionChanged: () => { // do nothing } }; export default Component => { class Selectable extends React.Component { constructor(props) { super(props); this.handleChangeHeaderCheckbox = this.handleChangeHeaderCheckbox.bind(this); this.handleChangeRowCheckbox = this.handleChangeRowCheckbox.bind(this); this.builRowCheckbox = this.builRowCheckbox.bind(this); if (props.selectable) { this.state = { headerSelected: false, selectedRows: props.selectedRows || [] }; } } componentWillReceiveProps(nextProps) { if (nextProps.selectable) { const { rows, data, rowKeyColumn } = nextProps; const rrows = rows || data; if (!isEqual(this.props.rows || this.props.data, rrows) || !isEqual(this.props.selectedRows, nextProps.selectedRows)) { // keep only existing rows const selectedRows = (nextProps.selectedRows || this.state.selectedRows) .filter(k => rrows .map((row, i) => row[rowKeyColumn] || row.key || i) .indexOf(k) > -1 ); this.setState({ headerSelected: selectedRows.length === rrows.length, selectedRows }); if (!nextProps.selectedRows) { nextProps.onSelectionChanged(selectedRows); } } } } handleChangeHeaderCheckbox(e) { const { rowKeyColumn, rows, data } = this.props; const selected = e.target.checked; const selectedRows = selected ? (rows || data).map((row, idx) => row[rowKeyColumn] || row.key || idx) : []; this.setState({ headerSelected: selected, selectedRows }); this.props.onSelectionChanged(selectedRows); } handleChangeRowCheckbox(e) { const { rows, data } = this.props; const rowId = JSON.parse(e.target.dataset ? e.target.dataset.reactmdl : e.target.getAttribute('data-reactmdl') ).id; const rowChecked = e.target.checked; const selectedRows = this.state.selectedRows; if (rowChecked) { selectedRows.push(rowId); } else { const idx = selectedRows.indexOf(rowId); selectedRows.splice(idx, 1); } this.setState({ headerSelected: (rows || data).length === selectedRows.length, selectedRows }); this.props.onSelectionChanged(selectedRows); } builRowCheckbox(content, row, idx) { const rowKey = row[this.props.rowKeyColumn] || row.key || idx; const isSelected = this.state.selectedRows.indexOf(rowKey) > -1; return ( <Checkbox className="mdl-data-table__select" data-reactmdl={JSON.stringify({ id: rowKey })} checked={isSelected} onChange={this.handleChangeRowCheckbox} /> ); } render() { const { rows, data, selectable, children, rowKeyColumn, ...otherProps } = this.props; // remove unwatned props // see https://github.com/Hacker0x01/react-datepicker/issues/517#issuecomment-230171426 delete otherProps.onSelectionChanged; delete otherProps.selectedRows; const realRows = selectable ? (rows || data).map((row, idx) => { const rowKey = row[rowKeyColumn] || row.key || idx; return { ...row, className: classNames({ 'is-selected': this.state.selectedRows.indexOf(rowKey) > -1 }, row.className) }; }) : (rows || data); return ( <Component rows={realRows} {...otherProps}> {selectable && ( <TableHeader name="mdl-header-select" cellFormatter={this.builRowCheckbox}> <Checkbox className="mdl-data-table__select" checked={this.state.headerSelected} onChange={this.handleChangeHeaderCheckbox} /> </TableHeader> )} {children} </Component> ); } } Selectable.propTypes = propTypes; Selectable.defaultProps = defaultProps; return Selectable; };
dashboard/src/index.js
lsumedia/lcr-web
import React from 'react'; import ReactDOM from 'react-dom'; import { createBrowserHistory } from 'history'; import { HashRouter, Route, Switch } from 'react-router-dom'; import App from './containers/App/App.jsx'; import './assets/css/bootstrap.min.css'; import './assets/css/animate.min.css'; import './assets/sass/light-bootstrap-dashboard.css'; import './assets/css/demo.css'; import './assets/css/pe-icon-7-stroke.css'; const history = createBrowserHistory(); ReactDOM.render(( <HashRouter history={history}> <Switch> <Route path="/" name="Home" component={App}/> </Switch> </HashRouter> ),document.getElementById('root'));
docs/app/Examples/addons/TextArea/Usage/TextAreaExampleAutoHeightMinHeight.js
aabustamante/Semantic-UI-React
import React from 'react' import { Form, TextArea } from 'semantic-ui-react' const TextAreaExampleAutoHeightMinHeight = () => ( <Form> <TextArea autoHeight placeholder='Try adding multiple lines' style={{ minHeight: 100 }} /> </Form> ) export default TextAreaExampleAutoHeightMinHeight
loc8-react-redux-front-end/src/components/Home/MainView.js
uberslackin/django-redux-loc8-ARweb
import ArticleList from '../ArticleList'; import React from 'react'; import agent from '../../agent'; import { connect } from 'react-redux'; const YourFeedTab = props => { if (props.token) { const clickHandler = ev => { ev.preventDefault(); props.onTabClick('feed', agent.Articles.feed()); } return ( <li className="nav-item"> <a href="" className={ props.tab === 'feed' ? 'nav-link active' : 'nav-link' } onClick={clickHandler}> Your Feed </a> </li> ); } return null; }; const GlobalFeedTab = props => { const clickHandler = ev => { ev.preventDefault(); props.onTabClick('all', agent.Articles.all()); }; return ( <li className="nav-item"> <a href="" className={ props.tab === 'all' ? 'nav-link active' : 'nav-link' } onClick={clickHandler}> Global Feed </a> </li> ); }; const TagFilterTab = props => { if (!props.tag) { return null; } return ( <li className="nav-item"> <a href="" className="nav-link active"> <i className="ion-pound"></i> {props.tag} </a> </li> ); }; const mapStateToProps = state => ({ ...state.articleList, tags: state.home.tags, token: state.common.token }); const mapDispatchToProps = dispatch => ({ onTabClick: (tab, payload) => dispatch({ type: 'CHANGE_TAB', tab, payload }) }); const MainView = props => { return ( <div className="col-md-9"> <div className="feed-toggle"> <ul className="nav nav-pills outline-active"> <YourFeedTab token={props.token} tab={props.tab} onTabClick={props.onTabClick} /> <GlobalFeedTab tab={props.tab} onTabClick={props.onTabClick} /> <TagFilterTab tag={props.tag} /> </ul> </div> <ArticleList articles={props.articles} loading={props.loading} articlesCount={props.articlesCount} currentPage={props.currentPage} /> </div> ); }; export default connect(mapStateToProps, mapDispatchToProps)(MainView);
app/routes.js
jbarabander/game-site
import { Route, IndexRoute } from 'react-router'; import App from 'containers/App'; import Home from 'containers/HomePage'; import React from 'react'; const routes = ( <Route path="/" component={App}> <IndexRoute component={Home} /> </Route> ); export default routes;
docs/src/app/components/pages/components/List/ExampleSettings.js
ArcanisCz/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import Divider from 'material-ui/Divider'; import Checkbox from 'material-ui/Checkbox'; import Toggle from 'material-ui/Toggle'; const styles = { root: { display: 'flex', flexWrap: 'wrap', }, }; const ListExampleSettings = () => ( <div style={styles.root}> <MobileTearSheet> <List> <Subheader>General</Subheader> <ListItem primaryText="Profile photo" secondaryText="Change your Google+ profile photo" /> <ListItem primaryText="Show your status" secondaryText="Your status is visible to everyone you use with" /> </List> <Divider /> <List> <Subheader>Hangout Notifications</Subheader> <ListItem leftCheckbox={<Checkbox />} primaryText="Notifications" secondaryText="Allow notifications" /> <ListItem leftCheckbox={<Checkbox />} primaryText="Sounds" secondaryText="Hangouts message" /> <ListItem leftCheckbox={<Checkbox />} primaryText="Video sounds" secondaryText="Hangouts video call" /> </List> </MobileTearSheet> <MobileTearSheet> <List> <ListItem primaryText="When calls and notifications arrive" secondaryText="Always interrupt" /> </List> <Divider /> <List> <Subheader>Priority Interruptions</Subheader> <ListItem primaryText="Events and reminders" rightToggle={<Toggle />} /> <ListItem primaryText="Calls" rightToggle={<Toggle />} /> <ListItem primaryText="Messages" rightToggle={<Toggle />} /> </List> <Divider /> <List> <Subheader>Hangout Notifications</Subheader> <ListItem primaryText="Notifications" leftCheckbox={<Checkbox />} /> <ListItem primaryText="Sounds" leftCheckbox={<Checkbox />} /> <ListItem primaryText="Video sounds" leftCheckbox={<Checkbox />} /> </List> </MobileTearSheet> </div> ); export default ListExampleSettings;
src/browser/ui/EmptyArticle.react.js
syroegkin/mikora.eu
import Component from 'react-pure-render/component'; import React from 'react'; import { FormattedMessage, defineMessages } from 'react-intl'; import EditorFormatAlignLeft from 'material-ui/svg-icons/editor/format-align-left'; import { grey200 } from 'material-ui/styles/colors'; const _messages = defineMessages({ emptyArticle: { defaultMessage: 'No data so far', id: 'ui.emptyArticle.empty' } }); export default class EmptyList extends Component { render() { const emptyListContainerStyle = { width: '100%', height: '70vh', verticalAlign: 'middle', textAlign: 'center', color: grey200 }; const emptyListContentStyle = { position: 'relative', top: '50%', transform: 'translateY(-50%)' }; const iconStyle = { width: 300, height: 300 }; return ( <div style={emptyListContainerStyle}> <div style={emptyListContentStyle}> <EditorFormatAlignLeft color={grey200} style={iconStyle} /> <p> <FormattedMessage {..._messages.emptyArticle} /> </p> </div> </div> ); } }
src/svg-icons/device/bluetooth-searching.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBluetoothSearching = (props) => ( <SvgIcon {...props}> <path d="M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33 0-.82-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z"/> </SvgIcon> ); DeviceBluetoothSearching = pure(DeviceBluetoothSearching); DeviceBluetoothSearching.displayName = 'DeviceBluetoothSearching'; DeviceBluetoothSearching.muiName = 'SvgIcon'; export default DeviceBluetoothSearching;
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
ketoo/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import AvatarItem from 'components/common/AvatarItem.react'; var ContactItem = React.createClass({ displayName: 'ContactItem', propTypes: { contact: React.PropTypes.object, onSelect: React.PropTypes.func }, mixins: [PureRenderMixin], _onSelect() { this.props.onSelect(this.props.contact); }, render() { let contact = this.props.contact; return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this._onSelect}>add</a> </div> </li> ); } }); export default ContactItem;
admin/client/App/shared/Popout/index.js
Adam14Four/keystone
/** * A Popout component. * One can also add a Header (Popout/Header), a Footer * (Popout/Footer), a Body (Popout/Body) and a Pan (Popout/Pane). */ import React from 'react'; import Portal from '../Portal'; import Transition from 'react-addons-css-transition-group'; const SIZES = { arrowHeight: 12, arrowWidth: 16, horizontalMargin: 20, }; var Popout = React.createClass({ displayName: 'Popout', propTypes: { isOpen: React.PropTypes.bool, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, relativeToID: React.PropTypes.string.isRequired, width: React.PropTypes.number, }, getDefaultProps () { return { width: 320, }; }, getInitialState () { return {}; }, componentWillReceiveProps (nextProps) { if (!this.props.isOpen && nextProps.isOpen) { window.addEventListener('resize', this.calculatePosition); this.calculatePosition(nextProps.isOpen); } else if (this.props.isOpen && !nextProps.isOpen) { window.removeEventListener('resize', this.calculatePosition); } }, getPortalDOMNode () { return this.refs.portal.getPortalDOMNode(); }, calculatePosition (isOpen) { if (!isOpen) return; let posNode = document.getElementById(this.props.relativeToID); const pos = { top: 0, left: 0, width: posNode.offsetWidth, height: posNode.offsetHeight, }; while (posNode.offsetParent) { pos.top += posNode.offsetTop; pos.left += posNode.offsetLeft; posNode = posNode.offsetParent; } let leftOffset = Math.max(pos.left + (pos.width / 2) - (this.props.width / 2), SIZES.horizontalMargin); let topOffset = pos.top + pos.height + SIZES.arrowHeight; var spaceOnRight = window.innerWidth - (leftOffset + this.props.width + SIZES.horizontalMargin); if (spaceOnRight < 0) { leftOffset = leftOffset + spaceOnRight; } const arrowLeftOffset = leftOffset === SIZES.horizontalMargin ? pos.left + (pos.width / 2) - (SIZES.arrowWidth / 2) - SIZES.horizontalMargin : null; const newStateAvaliable = this.state.leftOffset !== leftOffset || this.state.topOffset !== topOffset || this.state.arrowLeftOffset !== arrowLeftOffset; if (newStateAvaliable) { this.setState({ leftOffset: leftOffset, topOffset: topOffset, arrowLeftOffset: arrowLeftOffset, }); } }, renderPopout () { if (!this.props.isOpen) return; const { arrowLeftOffset, leftOffset, topOffset } = this.state; const arrowStyles = arrowLeftOffset ? { left: 0, marginLeft: arrowLeftOffset } : null; return ( <div className="Popout" style={{ left: leftOffset, top: topOffset, width: this.props.width, }} > <span className="Popout__arrow" style={arrowStyles} /> <div className="Popout__inner"> {this.props.children} </div> </div> ); }, renderBlockout () { if (!this.props.isOpen) return; return <div className="blockout" onClick={this.props.onCancel} />; }, render () { return ( <Portal className="Popout-wrapper" ref="portal"> <Transition className="Popout-animation" transitionEnterTimeout={190} transitionLeaveTimeout={190} transitionName="Popout" component="div" > {this.renderPopout()} </Transition> {this.renderBlockout()} </Portal> ); }, }); module.exports = Popout; // expose the child to the top level export module.exports.Header = require('./PopoutHeader'); module.exports.Body = require('./PopoutBody'); module.exports.Footer = require('./PopoutFooter'); module.exports.Pane = require('./PopoutPane');
admin/client/App/index.js
joerter/keystone
/** * The App component is the component that is rendered around all views, and * contains common things like navigation, footer, etc. */ import React from 'react'; import Lists from '../utils/ListsByKey'; import MobileNavigation from './components/Navigation/Mobile'; import PrimaryNavigation from './components/Navigation/Primary'; import SecondaryNavigation from './components/Navigation/Secondary'; import Footer from './components/Footer'; const App = (props) => { // If we're on either a list or an item view let currentList, currentSection; if (props.params.listId) { currentList = Lists[props.params.listId]; // Get the current section we're in for the navigation currentSection = Keystone.nav.by.list[currentList.key]; } // Default current section key to dashboard const currentSectionKey = (currentSection && currentSection.key) || 'dashboard'; return ( <div className="keystone-wrapper"> <header className="keystone-header"> <MobileNavigation brand={Keystone.brand} currentListKey={props.params.listId} currentSectionKey={currentSectionKey} sections={Keystone.nav.sections} signoutUrl={Keystone.signoutUrl} /> <PrimaryNavigation currentSectionKey={currentSectionKey} brand={Keystone.brand} sections={Keystone.nav.sections} signoutUrl={Keystone.signoutUrl} /> {/* If a section is open currently, show the secondary nav */} {(currentSection) ? ( <SecondaryNavigation currentListKey={props.params.listId} lists={currentSection.lists} /> ) : null} </header> <div className="keystone-body"> {props.children} </div> <Footer appversion={Keystone.appversion} backUrl={Keystone.backUrl} brand={Keystone.brand} User={Keystone.User} user={Keystone.user} version={Keystone.version} /> </div> ); }; module.exports = App;
src/docs/Components.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Paragraph from 'grommet/components/Paragraph'; import DocsArticle from '../components/DocsArticle'; export default class Components extends Component { render () { return ( <DocsArticle title="Components"> <Paragraph> Whether it's structuring content, controlling interaction, or visualizing data, Grommet provides a wide range of components for a variety of situations. And, all components are fully responsive and accessible. </Paragraph> </DocsArticle> ); } };
test/common/components/App-test.js
LandyCandy/beHeard
import test from 'ava'; import React from 'react'; import { shallow } from 'enzyme'; import App from '../../../src/common/components/App'; test('render with container div', t => { const wrapper = shallow(React.createElement(App)); t.is(wrapper.find('#container').length, 1); });
client/src/components/dashboard/profile/edit-info.js
mikelearning91/seeme-starter
import React, { Component } from 'react'; import Female from '../../../icons/female'; import Male from '../../../icons/male'; import FaBicycle from 'react-icons/lib/fa/bicycle'; import FaBed from 'react-icons/lib/fa/bed'; import FaNewspaperO from 'react-icons/lib/fa/newspaper-o'; import FaMotorcycle from 'react-icons/lib/fa/motorcycle'; import FaBank from 'react-icons/lib/fa/bank'; import FaAutomobile from 'react-icons/lib/fa/automobile'; import FaBriefcase from 'react-icons/lib/fa/briefcase'; import FaPlane from 'react-icons/lib/fa/plane'; import FaLightbulbO from 'react-icons/lib/fa/lightbulb-o'; import FaGavel from 'react-icons/lib/fa/gavel'; import FaPaintBrush from 'react-icons/lib/fa/paint-brush'; import FaCalculator from 'react-icons/lib/fa/calculator'; import FaGraduationCap from 'react-icons/lib/fa/graduation-cap'; import FaCamera from 'react-icons/lib/fa/camera'; import FaMusic from 'react-icons/lib/fa/music'; import FaSpoon from 'react-icons/lib/fa/spoon'; import FaTree from 'react-icons/lib/fa/tree'; import { RadioGroup, Radio } from 'react-radio-group'; const axios = require('axios'), cookie = require('react-cookie'); class EditInfo extends React.Component { constructor (props) { super(props); let user = cookie.load('user'); console.log(user.interests); this.state = { firstName: user.firstName, is_male: user.is_male, seeking_male: user.seeking_male, age: user.age, age_pref_min: user.age_pref_min, age_pref_max: user.age_pref_max, cycling: user.interests.cycling, news: user.interests.news, sleeping: user.interests.sleeping, motorcycles: user.interests.motorcycles, cars: user.interests.cars, photography: user.interests.photography, learning: user.interests.learning, traveling: user.interests.traveling, innovating: user.interests.innovating, art: user.interests.art, music: user.interests.music, cooking: user.interests.cooking, outdoors: user.interests.outdoors } this.handleChange = this.handleChange.bind(this) this.handleRadioIsChange = this.handleRadioIsChange.bind(this); this.handleRadioSeekingChange = this.handleRadioSeekingChange.bind(this); this.handleFormSubmit = this.handleFormSubmit.bind(this); } handleFormSubmit (e) { e.preventDefault(); const user = cookie.load('user'); const emailQuery = user.email; axios.put('https://seemedate.herokuapp.com/api/see/update', { emailQuery: emailQuery, firstName: this.state.firstName, is_male: this.state.is_male, seeking_male: this.state.seeking_male, age: this.state.age, age_pref_min: this.state.age_pref_min, age_pref_max: this.state.age_pref_max, cycling: this.state.cycling, news: this.state.news, sleeping: this.state.sleeping, politics: this.state.politics, motorcycles: this.state.motorcycles, cars: this.state.cars, working: this.state.working, photography: this.state.photography, learning: this.state.learning, traveling: this.state.traveling, innovating: this.state.innovating, law: this.state.law, art: this.state.art, math: this.state.math, school: this.state.school, music: this.state.music, cooking: this.state.cooking, outdoors: this.state.outdoors }, { headers: { Authorization: cookie.load('token') } }) .then((response) => { cookie.save('token', response.data.token, { path: '/' }); cookie.save('user', response.data.user, { path: '/' }); window.location.href = 'https://seemedate.herokuapp.com/my-profile'; }) .catch((error) => { console.log(error); }); } handleRadioIsChange(value) { this.setState({ is_male: value }); } handleRadioSeekingChange(value) { this.setState({ seeking_male: value }); } render () { return ( <div className="edit-info"> <form id="edit-info" onSubmit={this.handleFormSubmit}> <div className="app-section"> <div className="form-section-row"> <span className="form-section-title">The Basics</span> </div> <div className="form-row"> <span className="form-label">Name</span> <input className="form-text" onChange={this.handleChange} name="firstName" type="text" placeholder={this.state.firstName} defaultValue={this.state.firstName} /> </div> <div className="form-row"> <span className="form-label">Age</span> <input className="form-text" onChange={this.handleChange} name="age" type="number" placeholder={this.state.age} defaultValue={this.state.age} /> </div> <div className="form-row"> <span className="form-label">Gender</span> <RadioGroup className="radio-group" name="is_male" is_male={this.state.is_male} onChange={this.handleRadioIsChange}> <Radio id="imale" value="true" defaultChecked={this.state.is_male === true} /><label htmlFor="imale" className="radio-label"><i><Male /></i>Guy</label> <Radio id="ifemale" value="false" defaultChecked={this.state.is_male === false} /><label htmlFor="ifemale" className="radio-label"><i><Female /></i>Girl</label> </RadioGroup> </div> </div> <div className="app-section"> <div className="form-section-row"> <span className="form-section-title">Match Preferences</span> </div> <div className="form-row"> <span className="form-label">Interested In</span> <RadioGroup className="radio-group" name="seeking_male" seeking_male={this.state.seeking_male} onChange={this.handleRadioSeekingChange}> <Radio id="smale" value="true" defaultChecked={this.state.seeking_male === true} /><label htmlFor="smale" className="radio-label"><i><Male /></i>Guy</label> <Radio id="sfemale" value="false" defaultChecked={this.state.seeking_male === false} /><label htmlFor="sfemale" className="radio-label"><i><Female /></i>Girl</label> </RadioGroup> </div> <div className="form-row"> <span className="form-label">Age Range</span> <input onChange={this.handleChange} name="age_pref_min" id="min" className="inline" type="number" placeholder={this.state.age_pref_min} defaultValue={this.state.age_pref_min} /> <span className="inline-label">to</span> <input onChange={this.handleChange} name="age_pref_max" id="max" className="inline" type="number" placeholder={this.state.age_pref_max} defaultValue={this.state.age_pref_max} /> </div> </div> <div className="app-section interests"> <div className="form-section-row"> <span className="form-section-title">The Things I Love</span> </div> <div className="form-col"> <div> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="cycling" name="cycling" defaultChecked={this.state.cycling === true} /><label htmlFor="cycling" className="radio-label"><i><FaBicycle /></i>Cycling</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="sleeping" name="sleeping" defaultChecked={this.state.sleeping === true} /><label htmlFor="sleeping" className="radio-label"><i><FaBed /></i>Sleeping</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="motorcycles" name="motorcycles" defaultChecked={this.state.motorcycles === true} /><label htmlFor="motorcycles" className="radio-label"><i><FaMotorcycle /></i>Motorcycles</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="learning" name="learning" defaultChecked={this.state.learning === true} /><label htmlFor="learning" className="radio-label"><i><FaGraduationCap /></i>Learning</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="traveling" name="traveling" defaultChecked={this.state.traveling === true} /><label htmlFor="traveling" className="radio-label"><i><FaPlane /></i>Traveling</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="innovating" name="innovating" defaultChecked={this.state.innovating === true} /><label htmlFor="innovating" className="radio-label"><i><FaLightbulbO /></i>Innovating</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="photography" name="photography" defaultChecked={this.state.photography === true} /><label htmlFor="photography" className="radio-label"><i><FaCamera /></i>Photography</label> </span> </div> <div> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="cars" name="cars" defaultChecked={this.state.cars === true} /><label htmlFor="cars" className="radio-label"><i><FaAutomobile /></i>Cars</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="news" name="news" defaultChecked={this.state.news === true} /><label htmlFor="news" className="radio-label"><i><FaNewspaperO /></i>News</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="art" name="art" defaultChecked={this.state.art === true} /><label htmlFor="art" className="radio-label"><i><FaPaintBrush /></i>Art</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="music" name="music" defaultChecked={this.state.music === true} /><label htmlFor="music" className="radio-label"><i><FaMusic /></i>Music</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="cooking" name="cooking" defaultChecked={this.state.cooking === true} /><label htmlFor="cooking" className="radio-label"><i><FaSpoon /></i>Cooking</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="outdoors" name="outdoors" defaultChecked={this.state.outdoors === true} /><label htmlFor="outdoors" className="radio-label"><i><FaTree /></i>Outdoors</label> </span> </div> </div> </div> <div className="form-row"> <button id="save-profile" type="submit" className="btn btn-lg btn-success">Save Profile Info</button> </div> </form> </div> ); } handleChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; console.log(name, value); this.setState({ [name]: value }); } }; export default EditInfo;
src/icons/LabelIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class LabelIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M35.27 11.69C34.54 10.67 33.35 10 32 10l-22 .02c-2.21 0-4 1.77-4 3.98v20c0 2.21 1.79 3.98 4 3.98L32 38c1.35 0 2.54-.67 3.27-1.69L44 24l-8.73-12.31z"/></svg>;} };
docs/app/Examples/collections/Grid/Types/GridExampleCelledInternally.js
clemensw/stardust
import React from 'react' import { Grid, Image } from 'semantic-ui-react' const GridExampleCelledInternally = () => ( <Grid celled='internally'> <Grid.Row> <Grid.Column width={3}> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column width={10}> <Image src='http://semantic-ui.com/images/wireframe/centered-paragraph.png' /> </Grid.Column> <Grid.Column width={3}> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={3}> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column width={10}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column width={3}> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> </Grid> ) export default GridExampleCelledInternally
client/extensions/woocommerce/app/order/order-customer/dialog.js
Automattic/woocommerce-connect-client
/** @format */ /** * External dependencies */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import emailValidator from 'email-validator'; import { find, get, isEmpty, noop } from 'lodash'; import { localize } from 'i18n-calypso'; /** * Internal dependencies */ import AddressView from 'woocommerce/components/address-view'; import { areLocationsLoaded, getAllCountries, } from 'woocommerce/state/sites/data/locations/selectors'; import { areSettingsGeneralLoaded, getStoreLocation, } from 'woocommerce/state/sites/settings/general/selectors'; import Button from 'components/button'; import Dialog from 'components/dialog'; import { fetchLocations } from 'woocommerce/state/sites/data/locations/actions'; import { fetchSettingsGeneral } from 'woocommerce/state/sites/settings/general/actions'; import FormCheckbox from 'components/forms/form-checkbox'; import FormFieldset from 'components/forms/form-fieldset'; import FormInputValidation from 'components/forms/form-input-validation'; import FormLabel from 'components/forms/form-label'; import FormLegend from 'components/forms/form-legend'; import FormPhoneMediaInput from 'components/forms/form-phone-media-input'; import FormTextInput from 'components/forms/form-text-input'; import getAddressViewFormat from 'woocommerce/lib/get-address-view-format'; import getCountries from 'state/selectors/get-countries'; import QueryPaymentCountries from 'components/data/query-countries/payments'; const defaultAddress = { street: '', street2: '', city: '', postcode: '', email: '', first_name: '', last_name: '', phone: '', }; class CustomerAddressDialog extends Component { static propTypes = { address: PropTypes.shape( { address_1: PropTypes.string, address_2: PropTypes.string, city: PropTypes.string, state: PropTypes.string, country: PropTypes.string, postcode: PropTypes.string, email: PropTypes.string, first_name: PropTypes.string, last_name: PropTypes.string, phone: PropTypes.string, } ), areLocationsLoaded: PropTypes.bool, closeDialog: PropTypes.func, countries: PropTypes.arrayOf( PropTypes.shape( { code: PropTypes.string.isRequired, name: PropTypes.string.isRequired, states: PropTypes.arrayOf( PropTypes.shape( { code: PropTypes.string.isRequired, name: PropTypes.string.isRequired, } ) ), } ) ), countriesList: PropTypes.array.isRequired, isBilling: PropTypes.bool, isVisible: PropTypes.bool, siteId: PropTypes.number, updateAddress: PropTypes.func.isRequired, }; static defaultProps = { address: defaultAddress, closeDialog: noop, isBilling: false, isVisible: false, updateAddress: noop, }; state = {}; maybeFetchLocations() { const { siteId } = this.props; if ( siteId && ! this.props.areLocationsLoaded ) { this.props.fetchLocations( siteId ); } } componentDidMount() { this.initializeState(); this.maybeFetchLocations(); } UNSAFE_componentWillMount() { this.fetchData( this.props ); } UNSAFE_componentWillReceiveProps( newProps ) { if ( newProps.siteId !== this.props.siteId ) { this.fetchData( newProps ); } } componentDidUpdate( prevProps ) { // Modal was just opened if ( this.props.isVisible && ! prevProps.isVisible ) { this.initializeState(); } this.maybeFetchLocations(); } initializeState = () => { const { defaultCountry, defaultState } = this.props; const address = { ...defaultAddress, country: defaultCountry, state: defaultState, ...this.props.address, }; this.setState( { address, phoneCountry: address.country || defaultCountry, emailValidMessage: false, } ); }; fetchData = ( { siteId, areSettingsLoaded } ) => { if ( ! siteId ) { return; } if ( ! areSettingsLoaded ) { this.props.fetchSettingsGeneral( siteId ); } }; updateAddress = () => { this.props.updateAddress( this.state.address ); this.props.closeDialog(); }; closeDialog = () => { this.props.closeDialog(); }; onPhoneChange = phone => { this.setState( prevState => { const { address } = prevState; const newState = { ...address, phone: phone.value }; return { address: newState, phoneCountry: phone.countryCode }; } ); }; onChange = event => { const value = event.target.value; let name = event.target.name; if ( 'street' === name ) { name = 'address_1'; } else if ( 'street2' === name ) { name = 'address_2'; } this.setState( prevState => { const { address } = prevState; const newState = { address: { ...address, [ name ]: value } }; // Users of AddressView isEditable must always update the state prop // passed to AddressView in the event of country changes if ( 'country' === name ) { const countryData = find( this.props.countries, { code: value } ); if ( ! isEmpty( countryData.states ) ) { newState.address.state = countryData.states[ 0 ].code; } else { newState.address.state = ''; } } return newState; } ); }; validateEmail = event => { const { translate } = this.props; if ( ! emailValidator.validate( event.target.value ) ) { this.setState( { emailValidMessage: translate( 'Please enter a valid email address.' ), } ); } else { this.setState( { emailValidMessage: false, } ); } }; toggleShipping = () => { this.setState( prevState => { const { address } = prevState; const newState = { ...address, copyToShipping: ! prevState.address.copyToShipping }; return { address: newState }; } ); }; renderBillingFields = () => { const { isBilling, translate } = this.props; const { address, emailValidMessage } = this.state; if ( ! isBilling ) { return null; } return ( <div className="order-customer__billing-fields"> <FormFieldset> <QueryPaymentCountries /> <FormPhoneMediaInput label={ translate( 'Phone Number' ) } onChange={ this.onPhoneChange } countryCode={ this.state.phoneCountry } countriesList={ this.props.countriesList } value={ get( address, 'phone', '' ) } /> </FormFieldset> <FormFieldset> <FormLabel htmlFor="email">{ translate( 'Email address' ) }</FormLabel> <FormTextInput id="email" name="email" value={ get( address, 'email', '' ) } onChange={ this.onChange } onBlur={ this.validateEmail } /> { emailValidMessage && <FormInputValidation text={ emailValidMessage } isError /> } </FormFieldset> <FormFieldset> <FormLabel> <FormCheckbox checked={ get( address, 'copyToShipping', false ) } onChange={ this.toggleShipping } /> <span>{ translate( 'Copy changes to shipping' ) }</span> </FormLabel> </FormFieldset> </div> ); }; render() { const { countries, isBilling, isVisible, translate } = this.props; const { address, emailValidMessage } = this.state; if ( ! address || isEmpty( countries ) ) { return null; } const dialogButtons = [ <Button onClick={ this.closeDialog }>{ translate( 'Close' ) }</Button>, <Button primary onClick={ this.updateAddress } disabled={ !! emailValidMessage }> { translate( 'Save' ) } </Button>, ]; return ( <Dialog isVisible={ isVisible } onClose={ this.closeDialog } className="order-customer__dialog woocommerce" buttons={ dialogButtons } > <FormFieldset> <FormLegend className="order-customer__billing-details"> { isBilling ? translate( 'Billing Details' ) : translate( 'Shipping Details' ) } </FormLegend> <div className="order-customer__fieldset"> <div className="order-customer__field"> <FormLabel htmlFor="first_name">{ translate( 'First Name' ) }</FormLabel> <FormTextInput id="first_name" name="first_name" value={ get( address, 'first_name', '' ) } onChange={ this.onChange } /> </div> <div className="order-customer__field"> <FormLabel htmlFor="last_name">{ translate( 'Last Name' ) }</FormLabel> <FormTextInput id="last_name" name="last_name" value={ get( address, 'last_name', '' ) } onChange={ this.onChange } /> </div> </div> <AddressView address={ getAddressViewFormat( address ) } countries={ countries } isEditable onChange={ this.onChange } /> { this.renderBillingFields() } </FormFieldset> </Dialog> ); } } export default connect( state => { const address = getStoreLocation( state ); const locationsLoaded = areLocationsLoaded( state ); const areSettingsLoaded = areSettingsGeneralLoaded( state ); const countries = getAllCountries( state ); return { areLocationsLoaded: locationsLoaded, areSettingsLoaded, countries, countriesList: getCountries( state, 'payments' ), defaultCountry: address.country, defaultState: address.state, }; }, dispatch => bindActionCreators( { fetchLocations, fetchSettingsGeneral }, dispatch ) )( localize( CustomerAddressDialog ) );
examples/embeds/video.js
ashutoshrishi/slate
import React from 'react' /** * An video embed component. * * @type {Component} */ class Video extends React.Component { /** * When the input text changes, update the `video` data on the node. * * @param {Event} e */ onChange = e => { const video = e.target.value const { node, editor } = this.props editor.change(c => c.setNodeByKey(node.key, { data: { video } })) } /** * When clicks happen in the input, stop propagation so that the void node * itself isn't focused, since that would unfocus the input. * * @type {Event} e */ onClick = e => { e.stopPropagation() } /** * Render. * * @return {Element} */ render() { return ( <div {...this.props.attributes}> {this.renderVideo()} {this.renderInput()} </div> ) } /** * Render the Youtube iframe, responsively. * * @return {Element} */ renderVideo = () => { const { node, isSelected } = this.props const video = node.data.get('video') const wrapperStyle = { position: 'relative', outline: isSelected ? '2px solid blue' : 'none', } const maskStyle = { display: isSelected ? 'none' : 'block', position: 'absolute', top: '0', left: '0', height: '100%', width: '100%', cursor: 'cell', zIndex: 1, } const iframeStyle = { display: 'block', } return ( <div style={wrapperStyle}> <div style={maskStyle} /> <iframe id="ytplayer" type="text/html" width="640" height="476" src={video} frameBorder="0" style={iframeStyle} /> </div> ) } /** * Render the video URL input. * * @return {Element} */ renderInput = () => { const { node } = this.props const video = node.data.get('video') const style = { marginTop: '5px', boxSizing: 'border-box', } return ( <input value={video} onChange={this.onChange} onClick={this.onClick} style={style} /> ) } } /** * Export. */ export default Video
fields/types/color/ColorField.js
snowkeeper/keystone
import { SketchPicker } from 'react-color'; import { css, StyleSheet } from 'aphrodite/no-important'; import Field from '../Field'; import React from 'react'; import { Button, FormInput, InputGroup } from 'elemental'; import transparentSwatch from './transparent-swatch'; import theme from '../../../admin/client/theme'; const ColorField = Field.create({ displayName: 'ColorField', statics: { type: 'Color', }, propTypes: { onChange: React.PropTypes.func, path: React.PropTypes.string, value: React.PropTypes.string, }, getInitialState () { return { displayColorPicker: false, }; }, updateValue (value) { this.props.onChange({ path: this.props.path, value: value, }); }, handleInputChange (event) { var newValue = event.target.value; if (/^([0-9A-F]{3}){1,2}$/.test(newValue)) { newValue = '#' + newValue; } if (newValue === this.props.value) return; this.updateValue(newValue); }, handleClick () { this.setState({ displayColorPicker: !this.state.displayColorPicker }); }, handleClose () { this.setState({ displayColorPicker: false }); }, handlePickerChange (color) { var newValue = color.hex; if (newValue === this.props.value) return; this.updateValue(newValue); }, renderSwatch () { const className = `${css(classes.swatch)} e2e-type-color__swatch`; return (this.props.value) ? ( <span className={className} style={{ backgroundColor: this.props.value }} /> ) : ( <span className={className} dangerouslySetInnerHTML={{ __html: transparentSwatch }} /> ); }, renderField () { const { displayColorPicker } = this.state; const blockoutClassName = `${css(classes.blockout)} e2e-type-color__blockout`; const popoverClassName = `${css(classes.popover)} e2e-type-color__popover`; return ( <div className="e2e-type-color__wrapper" style={{ position: 'relative' }}> <InputGroup> <InputGroup.Section grow> <FormInput autoComplete="off" name={this.getInputName(this.props.path)} onChange={this.valueChanged} ref="field" value={this.props.value} /> </InputGroup.Section> <InputGroup.Section> <Button onClick={this.handleClick} className={`${css(classes.button)} e2e-type-color__button`}> {this.renderSwatch()} </Button> </InputGroup.Section> </InputGroup> {displayColorPicker && ( <div> <div className={blockoutClassName} onClick={this.handleClose} /> <div className={popoverClassName} onClick={e => e.stopPropagation()}> <SketchPicker color={this.props.value} onChangeComplete={this.handlePickerChange} onClose={this.handleClose} /> </div> </div> )} </div> ); }, }); /* eslint quote-props: ["error", "as-needed"] */ const classes = StyleSheet.create({ button: { background: 'white', padding: 4, width: theme.component.height, ':hover': { background: 'white', }, }, blockout: { bottom: 0, left: 0, position: 'fixed', right: 0, top: 0, zIndex: 1, }, popover: { marginTop: 10, position: 'absolute', right: 0, zIndex: 2, }, swatch: { borderRadius: 1, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.1)', display: 'block', height: '100%', width: '100%', }, }); module.exports = ColorField;
src/interface/icons/Haste.js
ronaldpereira/WoWAnalyzer
import React from 'react'; const icon = props => ( <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="16 16 32 32" className="icon" {...props}> <path d="M33.446,23.135c-0.89,0-1.612,0.722-1.612,1.612v8.049l-4.079,4.078c-0.63,0.629-0.63,1.65,0,2.28 c0.315,0.314,0.728,0.472,1.14,0.472c0.413,0,0.825-0.157,1.14-0.472l4.551-4.55c0.302-0.302,0.472-0.712,0.472-1.14v-8.716 C35.059,23.856,34.337,23.135,33.446,23.135z M32.111,16.668c-8.509,0-15.431,6.92-15.431,15.427 c0,8.506,6.922,15.426,15.431,15.426c8.509,0,15.431-6.92,15.431-15.426C47.542,23.588,40.62,16.668,32.111,16.668z M19.179,38.606c-1.025-2.031-1.545-4.222-1.545-6.511c0-7.981,6.495-14.473,14.477-14.473v2.097 c-6.826,0-12.379,5.552-12.379,12.376c0,1.959,0.444,3.831,1.32,5.566L19.179,38.606z M32.111,43.516 c-6.3,0-11.426-5.124-11.426-11.422c0-6.298,5.126-11.422,11.426-11.422s11.426,5.124,11.426,11.422 C43.537,38.392,38.411,43.516,32.111,43.516z" /> </svg> ); export default icon;
src/components/Main.js
surce2010/react-webpack-gallery
require('normalize.css/normalize.css'); require('styles/App.css'); require('styles/main.less'); import React from 'react'; import _ from 'lodash'; import classNames from 'classnames'; let CONSTANT = { centerPos: { //中间取值范围 left: 0, top: 0 }, hPosRange: { //水平方向取值范围 leftSecX: [0, 0], rightSecX: [0, 0], y: [0, 0] }, vPosRange: { //垂直方向取值范围 x: [0, 0], topY: [0, 0] } }; // 获取图片相关的数组 var imagesData = require('../data/imagesData.json'); // 利用自执行函数, 将图片名信息转成图片URL路径信息 imagesData = ((imagesDataArr) => { for (let i = 0, j = imagesDataArr.length; i < j; i++) { let singleImageData = imagesDataArr[i]; singleImageData.imageURL = require('../images/' + singleImageData.fileName); imagesDataArr[i] = singleImageData; } return imagesDataArr; })(imagesData); //图片组件 class ImageFigure extends React.Component { render() { let me = this, props = me.props, imgArrange = _.get(props, 'imgArrange'), styleObj = {}; _.set(styleObj, 'left', _.get(imgArrange, 'pos.left')); _.set(styleObj, 'top', _.get(imgArrange, 'pos.top')); _.get(imgArrange, 'rotate') && _.map(['Webkit', 'O', 'ms', 'Moz', 'Khtml'], (item) => { return styleObj[item + 'Transform'] = 'rotate(' + _.get(imgArrange, 'rotate') + 'deg)'; }); _.get(imgArrange, 'isCenter') && _.set(styleObj, 'zIndex', '101'); return ( <figure className={classNames('img-figure', {'is-inverse': _.get(imgArrange, 'isInverse')})} onClick={me.props.changeCenterIndex} ref={(c) => {this.figure = c}} style={styleObj} > <img src={_.get(props, 'imagesData.imageURL')} /> <figcaption className="img-title">{_.get(props, 'imagesData.fileName')}</figcaption> <div className='text'>{_.get(props, 'imagesData.desc')}</div> </figure> ); } } //控制组件 class ControllerUnit extends React.Component { constructor(props) { super(props); } render() { let me = this, props = me.props, imgArrange = _.get(props, 'imgArrange'); return ( <span className={classNames('controller-unit', {'is-center': _.get(imgArrange, 'isCenter')}, {'is-inverse': _.get(imgArrange, 'isInverse')})} onClick={me.props.changeCenterIndex} > </span> ); } } //舞台 class AppComponent extends React.Component { constructor(props) { super(props); this.state = { imgsArrangeArr: [{ pos: { //位置 left: '', top: '' }, rotate: '', //旋转角度 isInverse: false, //是否正面 isCenter: false //是否居中 }] }; } render() { let me = this, state = me.state, imgFiguresJSX = [], controllerUnits = []; _.map(imagesData, function (item, index) { if (!_.get(state, ['imgsArrangeArr', index])) { _.set(state, ['imgsArrangeArr', index], { pos: { left:0, top:0 }, rotate: 0, isInverse: false, isCenter: false }); } imgFiguresJSX.push( <ImageFigure key={'imgFigure'+index} imagesData={item} ref={'imgFigure' + index} changeCenterIndex={me.handleChangeCenterIndex.bind(me, index)} imgArrange={_.get(state, ['imgsArrangeArr', index])} /> ); controllerUnits.push( <ControllerUnit key={'controllerUnit'+index} imagesData={item} ref={'controllerUnit' + index} changeCenterIndex={me.handleChangeCenterIndex.bind(me, index)} imgArrange={_.get(state, ['imgsArrangeArr', index])} /> ); }.bind(me)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFiguresJSX} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } //组件加载以后,为每一个图片计算位置取值区间 componentDidMount() { let me = this; //舞台大小 let stageDOM = me.refs.stage, stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); //单个图片组件大小 let imgFigureDOM = me.refs.imgFigure0.figure, imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); //计算中心图片的位置点 _.set(CONSTANT, 'centerPos.left', halfStageW - halfImgW); _.set(CONSTANT, 'centerPos.top', halfStageH - halfImgH); //计算左侧,右侧图片位置取值区间 _.set(CONSTANT, 'hPosRange.leftSecX', [-halfImgW, halfStageW - halfImgW * 3]); _.set(CONSTANT, 'hPosRange.rightSecX', [halfStageW + halfImgW, stageW - halfImgW]); _.set(CONSTANT, 'hPosRange.y', [-halfImgH, halfStageH - halfImgH]); //计算上侧图片位置取值区间 _.set(CONSTANT, 'vPosRange.x', [halfStageW - halfImgW, halfStageW]); _.set(CONSTANT, 'vPosRange.topY', [-halfImgH, halfStageH - halfImgH * 3]); me.hanlderLayoutPicture(2); } /** * 计算随机数 * @param low, high取值区间的端点值 */ calcRandomNumber (low, high) { return Math.floor(Math.random() * (high - low) + low); } /** * 旋转随机角度 * return 随机输出正负30Deg */ rotateRandomDeg () { return (Math.random() > 0.5 ? '-' : '') + Math.ceil(Math.random() * 30); } /** * 切换居中图片 * @param index 居中图片索引值 * 如果点击的图片不为居中图片,则居中;反之,则翻转; */ handleChangeCenterIndex (index) { let me = this, { state } = me, imgsArrangeArr = _.get(state, 'imgsArrangeArr'); let centerIndex = _.findIndex(imgsArrangeArr, (item) => { return item.isCenter === true; }); if (centerIndex === index) { if (_.get(imgsArrangeArr, [index, 'isInverse'])) { _.set(imgsArrangeArr, [index, 'isInverse'], false); } else { _.set(imgsArrangeArr, [index, 'isInverse'], true); } me.setState({ imgsArrangeArr: imgsArrangeArr }); } else { me.hanlderLayoutPicture(index); } } /** * 重新布局图片 * @param centerIndex 居中图片索引 */ hanlderLayoutPicture (centerIndex) { let me = this, state = me.state, imgsArrangeArr = _.get(state, 'imgsArrangeArr'); imgsArrangeArr.splice(centerIndex, 1); if (imgsArrangeArr.length > 0) { let topIndex = Math.floor(Math.random() * (imgsArrangeArr.length - 1)); imgsArrangeArr.splice(topIndex, 1); //重绘左,右侧图片 if (imgsArrangeArr.length) { let l = imgsArrangeArr.length; for (let i = 0, j = Math.floor(l / 2); i < j, j < l; i++, j++) { imgsArrangeArr[i] = { pos: { left: me.calcRandomNumber(_.get(CONSTANT, ['hPosRange', 'leftSecX', 0]), _.get(CONSTANT, ['hPosRange', 'leftSecX', 1])), top: me.calcRandomNumber(_.get(CONSTANT, ['hPosRange', 'y', 0]), _.get(CONSTANT, ['hPosRange', 'y', 1])) }, rotate: me.rotateRandomDeg() }; imgsArrangeArr[j] = { pos:{ left: me.calcRandomNumber(_.get(CONSTANT, ['hPosRange', 'rightSecX', 0]), _.get(CONSTANT, ['hPosRange', 'rightSecX', 1])), top: me.calcRandomNumber(_.get(CONSTANT, ['hPosRange', 'y', 0]), _.get(CONSTANT, ['hPosRange', 'y', 1])) }, rotate: me.rotateRandomDeg() }; } } imgsArrangeArr.splice(topIndex, 0, { pos: { left: me.calcRandomNumber(_.get(CONSTANT, ['vPosRange', 'x', 0]), _.get(CONSTANT, ['vPosRange', 'x', 1])), top: me.calcRandomNumber(_.get(CONSTANT, ['vPosRange', 'topY', 0]), _.get(CONSTANT, ['vPosRange', 'topY', 1])) }, rotate: me.rotateRandomDeg() }); } imgsArrangeArr.splice(centerIndex, 0, { pos: _.get(CONSTANT, 'centerPos'), isCenter: true }); me.setState({ imgsArrangeArr: imgsArrangeArr }, () => { console.log(state, 'imgsArrangeArr'); }); } } AppComponent.defaultProps = { }; export default AppComponent;
src/modules/pages/Header.js
lenxeon/react
require('../../css/header.less') import React from 'react'; import SearchBox from './SearchBox'; import {Link} from 'react-router'; var {createActiveRouteComponent} = require('./NavLink'); var NavLink = createActiveRouteComponent('li'); class Header extends React.Component { constructor(props, context){ super(props); context.router // will work } // contextTypes: { // router: React.PropTypes.object, // } state: { focus: false, value: '智能搜索...', } render(){ // console.log(this.context); return( <div id="header" className="fadeInDown"> <div className="home-menu pure-menu pure-menu-horizontal pure-menu-fixed clear"> <a className="pure-menu-heading" href="#"><i className="fa fa-xing"></i>workin.me</a> <ul className="pure-menu-list left-menus"> <NavLink to="/feeds" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-commenting-o mr-5"></i>动态 </NavLink> <NavLink to="/tasks" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-list mr-5"></i>任务 </NavLink> <NavLink to="/calendar" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-calendar mr-5"></i>日程 </NavLink> <NavLink to="/portals" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-coffee mr-5"></i>知识 </NavLink> <NavLink to="/org" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-sitemap mr-5"></i>组织 </NavLink> <li className="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <span className="pure-menu-link more">更多</span> <ul className="pure-menu-children"> <NavLink to="/hr" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-calendar-check-o mr-5"></i>考勤 </NavLink> <NavLink to="/skydrive" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-cloud-upload mr-5"></i>网盘 </NavLink> <NavLink to="/crm" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa fa-user-secret mr-5"></i>客户 </NavLink> </ul> </li> </ul> <ul className="pure-menu-list right-menus rgt"> <li className="pure-menu-item pure-menu-has-children pure-menu-allow-hover user"> <span className="avatar"> <img src="https://dn-mdpic.qbox.me/UserAvatar/default.gif?imageView2/1/w/48/h/48/q/90" alt="头像" /> </span> <span className="name">冷馨</span> <ul className="pure-menu-children"> <li className="pure-menu-item"><a href="#" className="pure-menu-link">考勤</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">网盘</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">客户</a></li> </ul> </li> <li className="pure-menu-item pure-menu-has-children pure-menu-allow-hover message"> <i className="fa fa-bell"></i> <ul className="pure-menu-children"> <li className="pure-menu-item"><a href="#" className="pure-menu-link">考勤</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">网盘</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">客户</a></li> </ul> </li> <li className="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <span className="pure-menu-link more">新建</span> <ul className="pure-menu-children"> <li className="pure-menu-item"><a href="#" className="pure-menu-link">考勤</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">网盘</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">客户</a></li> </ul> </li> <li className="pure-menu-item search-box"> <SearchBox/> </li> </ul> </div> </div> ) } }; // Header.contextTypes = { // router: React.PropTypes.object.isRequired // }; export default Header;
src/modules/editor/components/popovers/tooltip/TooltipLIMC/TooltipLIMC.js
CtrHellenicStudies/Commentary
import React from 'react' import autoBind from 'react-autobind'; import { connect } from 'react-redux'; // redux import editorActions from '../../../../actions'; // component import TooltipItemButton from '../TooltipItemButton'; class TooltipLIMC extends React.Component { constructor(props) { super(props); autoBind(this); } async promptForLIMC(e) { e.preventDefault(); const { setTooltip, tooltip } = this.props; await setTooltip({ ...tooltip, mode: 'limc' }); } isActive() { const { editorState } = this.props; if (!editorState) { return null; } let selection = editorState.getSelection(); let activeBlockType = editorState .getCurrentContent() .getBlockForKey(selection.getStartKey()) .getType(); return 'LIMC' === activeBlockType; } render() { return ( <TooltipItemButton className={`${this.isActive() ? 'active' : ''}`} onClick={this.promptForLIMC} > LIMC </TooltipItemButton> ); } } const mapStateToProps = state => ({ ...state.editor, }); const mapDispatchToProps = dispatch => ({ setTooltip: (tooltip) => { dispatch(editorActions.setTooltip(tooltip)); }, }); export default connect( mapStateToProps, mapDispatchToProps, )(TooltipLIMC);
app/components/Store/Routes/CategoriesRoute/index.js
VineRelay/VineRelayStore
import React from 'react'; import PropTypes from 'prop-types'; import { QueryRenderer, graphql } from 'react-relay'; import relayEnvironment from 'app/config/relay'; import PageError from 'app/components/Common/PageError'; import PageLoader from 'app/components/Common/PageLoader'; import StoreLayout from 'app/components/Store/Main/StoreLayout'; import CategoriesGrid from 'app/components/Store/Category/CategoriesGrid'; import Paper from 'app/components/Store/Main/Paper'; const CategoriesRoute = ({ categories, history, notifier, viewer, }) => ( <StoreLayout notifier={notifier} viewer={viewer} > <Paper paddings={['top', 'bottom', 'left', 'right']}> <h1>Shop By Categories</h1> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.</p> </Paper> <Paper paddings={['bottom', 'left', 'right']}> <CategoriesGrid categories={categories} onCategoryClick={(id) => history.push(`category/${id}`)} /> </Paper> </StoreLayout> ); CategoriesRoute.propTypes = { viewer: PropTypes.object.isRequired, notifier: PropTypes.object.isRequired, history: PropTypes.object.isRequired, categories: PropTypes.object.isRequired, }; export default (props) => ( <QueryRenderer environment={relayEnvironment} query={graphql` query CategoriesRouteQuery { categories { ...CategoriesGrid_categories } notifier { ...StoreLayout_notifier } viewer { ...StoreLayout_viewer } } `} render={({ error, props: relayProps }) => { if (error) { return <PageError error={error} />; } if (relayProps) { return <CategoriesRoute {...relayProps} {...props} />; } return <PageLoader />; }} /> );
src/RootCloseWrapper.js
AlexKVal/react-overlays
import React from 'react'; import addEventListener from './utils/addEventListener'; import createChainedFunction from './utils/createChainedFunction'; import ownerDocument from './utils/ownerDocument'; // TODO: Consider using an ES6 symbol here, once we use babel-runtime. const CLICK_WAS_INSIDE = '__click_was_inside'; function suppressRootClose(event) { // Tag the native event to prevent the root close logic on document click. // This seems safer than using event.nativeEvent.stopImmediatePropagation(), // which is only supported in IE >= 9. event.nativeEvent[CLICK_WAS_INSIDE] = true; } export default class RootCloseWrapper extends React.Component { constructor(props) { super(props); this.handleDocumentClick = this.handleDocumentClick.bind(this); this.handleDocumentKeyUp = this.handleDocumentKeyUp.bind(this); } bindRootCloseHandlers() { const doc = ownerDocument(this); this._onDocumentClickListener = addEventListener(doc, 'click', this.handleDocumentClick); this._onDocumentKeyupListener = addEventListener(doc, 'keyup', this.handleDocumentKeyUp); } handleDocumentClick(e) { // This is now the native event. if (e[CLICK_WAS_INSIDE]) { return; } this.props.onRootClose(); } handleDocumentKeyUp(e) { if (e.keyCode === 27) { this.props.onRootClose(); } } unbindRootCloseHandlers() { if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } if (this._onDocumentKeyupListener) { this._onDocumentKeyupListener.remove(); } } componentDidMount() { this.bindRootCloseHandlers(); } render() { const {noWrap, children} = this.props; const child = React.Children.only(children); if (noWrap) { return React.cloneElement(child, { onClick: createChainedFunction(suppressRootClose, child.props.onClick) }); } // Wrap the child in a new element, so the child won't have to handle // potentially combining multiple onClick listeners. return ( <div onClick={suppressRootClose}> {child} </div> ); } getWrappedDOMNode() { // We can't use a ref to identify the wrapped child, since we might be // stealing the ref from the owner, but we know exactly the DOM structure // that will be rendered, so we can just do this to get the child's DOM // node for doing size calculations in OverlayMixin. const node = React.findDOMNode(this); return this.props.noWrap ? node : node.firstChild; } componentWillUnmount() { this.unbindRootCloseHandlers(); } } RootCloseWrapper.displayName = 'RootCloseWrapper'; RootCloseWrapper.propTypes = { onRootClose: React.PropTypes.func.isRequired, /** * Passes the suppress click handler directly to the child component instead * of placing it on a wrapping div. Only use when you can be sure the child * properly handle the click event. */ noWrap: React.PropTypes.bool };
src/pages/conference/people/userProfile/changeAvatar/userAvatar.js
sunway-official/acm-admin
import React from 'react'; import { images } from '../../../../../theme'; import './style.css'; const UserAvatar = () => ( <div className="user-profile-img other-user-avatar"> <img src={images.defaultAvatar} alt="avatar" id="avatar" /> </div> ); export default UserAvatar;
app/components/app-layout.js
KleeGroup/focus-starter-kit
import React from 'react'; import Layout from 'focus-components/components/layout'; import MenuLeft from '../views/menu/menu-left'; import Footer from '../views/footer'; import DevTools from './dev-tools'; const CustomLayout = (props) => ( <div> <Layout Footer={Footer} MenuLeft={MenuLeft} > {props.children} </Layout> {__DEV__ && <DevTools />} </div > ); CustomLayout.displayName = 'CustomAppLayout'; export default CustomLayout;
src/Jumbotron.js
egauci/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import elementType from 'react-prop-types/lib/elementType'; const Jumbotron = React.createClass({ propTypes: { /** * You can use a custom element for this component */ componentClass: elementType }, getDefaultProps() { return { componentClass: 'div' }; }, render() { const ComponentClass = this.props.componentClass; return ( <ComponentClass {...this.props} className={classNames(this.props.className, 'jumbotron')}> {this.props.children} </ComponentClass> ); } }); export default Jumbotron;
frontend/src/Components/Table/TableOptions/TableOptionsColumnDragPreview.js
lidarr/Lidarr
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { DragLayer } from 'react-dnd'; import DragPreviewLayer from 'Components/DragPreviewLayer'; import { TABLE_COLUMN } from 'Helpers/dragTypes'; import dimensions from 'Styles/Variables/dimensions.js'; import TableOptionsColumn from './TableOptionsColumn'; import styles from './TableOptionsColumnDragPreview.css'; const formGroupSmallWidth = parseInt(dimensions.formGroupSmallWidth); const formLabelLargeWidth = parseInt(dimensions.formLabelLargeWidth); const formLabelRightMarginWidth = parseInt(dimensions.formLabelRightMarginWidth); const dragHandleWidth = parseInt(dimensions.dragHandleWidth); function collectDragLayer(monitor) { return { item: monitor.getItem(), itemType: monitor.getItemType(), currentOffset: monitor.getSourceClientOffset() }; } class TableOptionsColumnDragPreview extends Component { // // Render render() { const { item, itemType, currentOffset } = this.props; if (!currentOffset || itemType !== TABLE_COLUMN) { return null; } // The offset is shifted because the drag handle is on the right edge of the // list item and the preview is wider than the drag handle. const { x, y } = currentOffset; const handleOffset = formGroupSmallWidth - formLabelLargeWidth - formLabelRightMarginWidth - dragHandleWidth; const transform = `translate3d(${x - handleOffset}px, ${y}px, 0)`; const style = { position: 'absolute', WebkitTransform: transform, msTransform: transform, transform }; return ( <DragPreviewLayer> <div className={styles.dragPreview} style={style} > <TableOptionsColumn isDragging={false} {...item} /> </div> </DragPreviewLayer> ); } } TableOptionsColumnDragPreview.propTypes = { item: PropTypes.object, itemType: PropTypes.string, currentOffset: PropTypes.shape({ x: PropTypes.number.isRequired, y: PropTypes.number.isRequired }) }; export default DragLayer(collectDragLayer)(TableOptionsColumnDragPreview);
src/components/AppBox.js
leanix/leanix-app-launchpad
import React from 'react' // eslint-disable-next-line no-unused-vars import { Avatar, Card, CardActions, CardExpandable, CardHeader, CardMedia, CardText, CardTitle } from 'material-ui' // eslint-disable-next-line no-unused-vars import Tag from './Tag' import store from '../services/Store' export default class AppBox extends React.Component { constructor (props, context) { super(props, context) this.state = { expanded: this.props.app.expanded } } clicked () { this.props.app.expanded = !this.props.app.expanded this.setState({ expanded: this.props.app.expanded }) } componentDidMount () { this.unsubscribe = store.subscribe(() => { this.setState({ expanded: false }) }) } componentWillUnmount () { this.unsubscribe() } render () { const app = this.props.app let avatar if (app.logo) avatar = app.logo else { const words = app.name.split(' ') const letters = words.length > 1 ? words[0][0] + words[1][0] : words[0][0] avatar = <Avatar>{letters}</Avatar> } const cardStyle = { cursor: 'pointer', height: '75px' } // const cardHeight = '75px' if (this.state.expanded) { cardStyle.minHeight = '150px'; cardStyle.height = '' } let stateColor let stateIcon switch (app.approvalStatus) { case 'approved': stateColor = 'green' stateIcon = 'fa fa-check-circle-o' break case 'pending': stateColor = '#FCDF00' stateIcon = 'fa fa-spinner' break case 'onrequest': stateColor = 'green' stateIcon = 'fa fa-question-circle' break case 'rejected': stateColor = 'red' stateIcon = 'fa fa-times-circle-o' break } const headerDescription = this.state.expanded ? '' : app.description const bodyDescription = this.state.expanded ? app.description : '' const link = app.applink ? <a href={app.applink}>{app.applink}</a> : '' let tags let footer if (this.state.expanded) { tags = (<div style={{ display: 'flex', flexFlow: 'row wrap', alignItems: 'center', justifyContent: 'flex-start', padding: '8px 0' }}> {app.tags.map((t, idx) => <Tag key={idx} tag={t}></Tag>)} </div>) const buttonMapper = function buttonMapper (button) { const clickHandler = evt => { if (button.click) { button.click(app) } evt.stopPropagation() } return ( <a className={button.classes} style={{ marginLeft: '4px', marginBottom: '4px' }} onClick={clickHandler} href={button.link} target='_blank' key={button.label}> {button.label} </a>) } let firstRow let secondRow firstRow = app.buttonsFirstRow.map(buttonMapper) secondRow = <div>{app.buttons.map(buttonMapper)}</div> footer = ( <div className="AppBox-bodyFooter" style={{ padding: '0px 8px 8px 0px', textAlign: 'right' }}> <div style={{ padding: '4px 0' }}>{firstRow}</div> {secondRow} </div> ) } return ( <div className="col-sm-6 col-md-4 col-lg-4 AppLaunchpad-AppBox" style={{ marginBottom: '20px' }}> <Card style={cardStyle} onClick={e => this.clicked(e)}> <CardHeader title={app.name} subtitle={headerDescription} textStyle={{ height: '40px', overflow: 'hidden', width: 'calc(100% - 70px)' }} subtitleStyle={{ overflow: 'hidden' }} avatar={avatar}> <div className="pull-right data-tip-left data-tip-rounded" data-tip={app.tooltip} style={{ position: 'relative', top: '-50px', left: '8px' }}> <i className={stateIcon} style={{ color: stateColor, fontSize: '24px' }}></i> </div> {tags} </CardHeader> <div className="AppBox-body" style={{ padding: '0px 16px 5px 16px', minHeight: '40px', fontSize: '0.8rem' }}> <span>{link}</span> <span className="AppBox-bodyDescription"> {bodyDescription} </span> </div> {footer} </Card> </div> ) } }
js/common/VideoComponent.js
FurtherMyFuture/FutureMobile
/** * @flow * @providesModule VideoComponent */ import React from 'react' import { AppState, StyleSheet, View } from 'react-native' import Video from 'react-native-video' type Props = { source: { uri: string } | number, children?: React.Element<any>, muted: boolean } type State = { paused: boolean, muted: boolean } export class VideoComponent extends React.Component { props: Props state: State = { paused: false, muted: this.props.muted, } componentDidMount() { AppState.addEventListener('change', this._handleAppStateChange) } componentWillUnmount() { AppState.removeEventListener('change', this._handleAppStateChange) } render(): React.Element<any> { const { source, children } = this.props return ( <View style={styles.container}> <Video paused={this.state.paused} muted={this.props.muted} repeat resizeMode="cover" source={source} disableFocus style={StyleSheet.absoluteFill} /> <View style={StyleSheet.absoluteFill}> {React.Children.only(children)} </View> </View> ) } _handleAppStateChange = (currentAppState: 'active' | 'background' | 'inactive') => { this.setState({ paused: currentAppState !== 'active' }) } } const styles = StyleSheet.create({ container: { flex: 1, }, })
docs/app/Examples/elements/Button/Types/ButtonExampleLabeledBasic.js
koenvg/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleLabeledBasic = () => ( <div> <Button color='red' content='Like' icon='heart' label={{ basic: true, color: 'red', pointing: 'left', content: '2,048' }} /> <Button basic color='blue' content='Fork' icon='fork' label={{ as: 'a', basic: true, color: 'blue', pointing: 'left', content: '1,048' }} /> </div> ) export default ButtonExampleLabeledBasic
packages/wix-style-react/src/SidePanel/SidePanelAPI.js
wix/wix-style-react
import React from 'react'; export const SidePanelContext = React.createContext();
src/svg-icons/device/signal-wifi-3-bar.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalWifi3Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/><path d="M3.53 10.95l8.46 10.54.01.01.01-.01 8.46-10.54C20.04 10.62 16.81 8 12 8c-4.81 0-8.04 2.62-8.47 2.95z"/> </SvgIcon> ); DeviceSignalWifi3Bar = pure(DeviceSignalWifi3Bar); DeviceSignalWifi3Bar.displayName = 'DeviceSignalWifi3Bar'; DeviceSignalWifi3Bar.muiName = 'SvgIcon'; export default DeviceSignalWifi3Bar;
app/components/SelectWbtStatement.js
rick-maclean/wbt-canada-stmts-electron-react-simmering
// @flow import React, { Component } from 'react'; import electron from 'electron'; import jquery from 'jquery'; // import PropTypes from 'prop-types'; // import { Link } from 'react-router-dom'; // import styles from './LoginForm.css'; const app = electron.remote; const dialog = app.dialog; const fs = require('fs'); const fsOutput = require('fs'); class SelectWbtStatement extends Component { props: { onTransactionDate: () => void }; state: { wbtStatementFile: string, wbtDonorFile: string, wbtGiftsFile: string, transactionDate: string, singleTransaction: string, transactionAmount: string, transDescription: string, tntUserIdSt: string, stFirstName: string, stLastName: string, stStreetAddress: string, stCity: string, stProv: string, stPostalCode: string, stCountry: string, transMethod: string, transAccount: string, transReference: string } constructor() { super(); this.state = { wbtStatementFile: 'wbtStatementFile', wbtDonorFile: 'wbtDonorFile', wbtGiftsFile: 'wbtGiftsFile', transactionDate: 'transactionDate', singleTransaction: 'singleTransaction', transactionAmount: 'transactionAmount', transDescription: 'transDescr', tntUserIdSt: 'tntUserId', stFirstName: 'stFirstName', stLastName: 'stLastName', stStreetAddress: 'stStreetAddress', stCity: 'string', stProv: 'string', stPostalCode: 'string', stCountry: 'country', transMethod: 'transMethod', transAccount: 'transAccount', transReference: 'transReference' }; } readWbtStatementIntojQuery = () => { console.log('entering readWbtStatementIntojQuery'); const filename = this.state.wbtStatementFile; const subfileName = filename.replace(/^.*[\\\/]/, '').substring(16, 34); console.log('subfileName is'); console.log(subfileName); const donorfile = `${subfileName}DonorList.csv`; console.log('donorfile is'); console.log(donorfile); const giftfile = `${subfileName}Gifts.csv`; console.log('giftfile is'); console.log(giftfile); console.log('filename is==> ' + filename); fs.readFile(filename, (err, html) => { let jqueryHtml; if (err) { // handle error console.log('inside readWbtStatementIntojQuery fs.readFile has an error'); } else { console.log('entering else of fs.readFile readWbtStatementIntojQuery'); // console.log(html); jqueryHtml = jquery(html.toString()); console.log('jqueryHtml.className===>'); console.log(jqueryHtml.className); console.log('jqueryHtml is set to ===> \n'); console.log(jqueryHtml); // const evenElements = jqueryHtml.find('odd'); // console.log('evenElements is set to ==> \n'); // console.log(evenElements); const tableData = jqueryHtml[12]; console.log('tableData.className===>'); console.log(tableData.className); console.log('tableData is set to ==> \n'); console.log(tableData); const evenTableEntries = tableData.getElementsByClassName('even'); console.log('evenTableEntries are --> '); console.log(evenTableEntries); console.log('oddTableEntries are --> '); const oddTableEntries = tableData.getElementsByClassName('odd'); console.log(oddTableEntries); const firstOddEntry = oddTableEntries[0]; console.log('firstOddEntry is: '); console.log(firstOddEntry); this.setState({ singleTransaction: firstOddEntry }); const dateDt = firstOddEntry.getElementsByClassName('date')[0]; console.log('dateDt is: '); console.log(dateDt); const dateText = dateDt.innerText; console.log('dateText is: '); console.log(dateText); this.setState({ transactionDate: dateText }); let amountDt = firstOddEntry.getElementsByClassName('currency')[0].innerText; amountDt = Number(amountDt.replace(/[^0-9\.-]+/g,"")); this.setState({ transactionAmount: amountDt }); const transDescr = firstOddEntry.getElementsByClassName('description')[0].innerHTML; this.setState({ transDescription: transDescr }); const decscriptionSplit = transDescr.split('<br>'); for (let i = 0, len = decscriptionSplit.length; i < len; i++) { console.log(decscriptionSplit[i]); } // tntUserId let tntUserId = decscriptionSplit[0]; console.log(tntUserId); let indx = tntUserId.indexOf(')'); tntUserId = tntUserId.substring(1, indx); console.log(tntUserId); this.setState({ tntUserIdSt: tntUserId }); // tntName const tntName = decscriptionSplit[1]; console.log(tntName); indx = tntName.lastIndexOf(' '); const tntFirstName = tntName.substring(0, indx); this.setState({ stFirstName: tntFirstName }); console.log('#' + tntFirstName +'#'); const tntLastName = tntName.substring(indx+1, tntName.length); this.setState({ stLastName: tntLastName }); console.log('#' + tntLastName +'#'); // tntStreet const tntStreet = decscriptionSplit[2]; console.log(tntStreet); this.setState({ stStreetAddress: tntStreet }); // tntCityStZip const tntCityStZip = decscriptionSplit[3]; console.log(tntCityStZip); const tntCityStZipSplit = tntCityStZip.split(' '); const cityStZpLength = tntCityStZipSplit.length; const postalCode = tntCityStZipSplit[cityStZpLength-2] + ' ' + tntCityStZipSplit[cityStZpLength-1]; console.log(postalCode); this.setState({ stPostalCode: postalCode }); const province = tntCityStZipSplit[cityStZpLength-3]; console.log(province); this.setState({ stProv: province }); const otherLength = postalCode.length + province.length + 1; const diffLeng = tntCityStZip.length - otherLength; const city = tntCityStZip.substring(0, diffLeng) console.log(city); this.setState({ stCity: city }); // tntCountry const tntCountry = decscriptionSplit[4]; console.log(tntCountry); this.setState({ stCountry: tntCountry }); const methodDt = firstOddEntry.getElementsByClassName('method')[0].innerHTML; this.setState({ transMethod: methodDt }); const accountDt = firstOddEntry.getElementsByClassName('account')[0].innerHTML; this.setState({ transAccount: accountDt }); const referenceDt = firstOddEntry.getElementsByClassName('reference')[0].innerHTML; this.setState({ transReference: referenceDt }); //---------------------------------------------------------------------------- //------------Open Files and Write to them------------------------------------- //---------------------------------------------------------------------------- const donorFileName = `./app/components/output/${donorfile}`; this.setState({ wbtDonorFile: donorFileName }); const outputFileDonors = fs.createWriteStream(donorFileName, { flags: 'a' // }); outputFileDonors.write('\n'); outputFileDonors.write('[ORGANIZATION]\n'); outputFileDonors.write('Name=Wycliffe Canada\n'); outputFileDonors.write('\n'); outputFileDonors.write('Abbreviation=WBTC\n'); outputFileDonors.write('Code=WBT-CAD\n'); outputFileDonors.write('DefaultCurrencyCode=CAD\n'); outputFileDonors.write('[DONORS]\n'); outputFileDonors.write('"DISPLAY_DATE","PEOPLE_ID","ACCT_NAME","PERSON_TYPE","LAST_NAME_ORG","FIRST_NAME","MIDDLE_NAME","TITLE","SUFFIX",'); outputFileDonors.write('"SP_LAST_NAME","SP_FIRST_NAME","SP_MIDDLE_NAME","SP_TITLE","SP_SUFFIX",'); outputFileDonors.write('"ADDR1","ADDR2","ADDR3","ADDR4","CITY","STATE","ZIP","COUNTRY","CNTRY_DESCR",'); outputFileDonors.write('"ADDR_CHANGED","PHONE","PHONE_CHANGED"\n'); const giftsFileName = `./app/components/output/${giftfile}`; this.setState({ wbtGiftsFile: giftsFileName }); const outputFileGifts = fs.createWriteStream(giftsFileName, { flags: 'a' // }); outputFileGifts.write('[GIFTS]\n'); outputFileGifts.write('"PEOPLE_ID","ACCT_NAME","DISPLAY_DATE","AMOUNT","DONATION_ID","DESIGNATION","MEMO","MOTIVATION","PAYMENT_METHOD"\n'); let accountRecord = ''; let giftFromSupporter = ''; // For loop for processing all the even entries for (let i = 0; i < evenTableEntries.length; i++) { console.log('next entry is ==============================================>'); console.log(evenTableEntries[i]); let entryToProcess = evenTableEntries[i]; // DATE let dateDtlp = entryToProcess.getElementsByClassName('date')[0]; let displayDate = dateDtlp.innerText; console.log('displayDate before is: '); console.log(displayDate); let date = new Date(displayDate); //console.log('date before is: '); //console.log(date); //console.log('date.getMonth() is: '); //console.log(date.getMonth()); //console.log('date.getDate() is: '); //console.log(date.getDate()); //console.log('date.getFullYear() is: '); //console.log(date.getFullYear()); displayDate = (date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear(); console.log('displayDate after is: '); console.log(displayDate); // DESCRIPTION Section================================================================ // ==================================================================================== // ==================================================================================== const transDescrLp = entryToProcess.getElementsByClassName('description')[0].innerHTML; const decscriptionSplitLp = transDescrLp.split('<br>'); if (decscriptionSplitLp.length < 2) { console.log('skipping EVEN record since it is not a Canada donation'); } else { // tntUserId let tntUserIdLp = decscriptionSplitLp[0]; let indx = tntUserIdLp.indexOf(')'); tntUserIdLp = tntUserIdLp.substring(1, indx); console.log('UserId is: '); console.log(tntUserIdLp); // tntName const tntAcctName = decscriptionSplitLp[1]; accountRecord = `"${tntUserIdLp}","${tntAcctName}","","",`; //caclulate donation_id let donationId = ''; donationId = displayDate.replace(/\//g, ''); donationId += tntUserIdLp + "ZZ"; console.log('donationId is: '); console.log(donationId); indx = tntAcctName.lastIndexOf(' '); const tntFirstNameLp = tntAcctName.substring(0, indx); console.log(`#${tntFirstNameLp}#`); const tntLastNameLp = tntAcctName.substring(indx + 1, tntAcctName.length); console.log(`#${tntLastNameLp}#`); // "PEOPLE_ID","ACCT_NAME","PERSON_TYPE","LAST_NAME_ORG","FIRST_NAME","MIDDLE_NAME","TITLE","SUFFIX", // "SP_LAST_NAME","SP_FIRST_NAME","SP_MIDDLE_NAME","SP_TITLE","SP_SUFFIX", accountRecord = `"${displayDate}","${tntUserIdLp}","${tntAcctName}","","${tntLastNameLp}","${tntFirstNameLp}","","","","","","","","",`; // tntStreet let tntStreet1 = decscriptionSplitLp[2]; console.log('Street is : '); console.log(tntStreet1); let tntStreet2 = '""'; let iExtra = 0; if (decscriptionSplitLp.length === 6) { iExtra = 1; tntStreet2 = decscriptionSplitLp[3]; console.log('Street 2 is : '); console.log(tntStreet2); } let addressToOutput = ''; // "ADDR1","ADDR2", "ADDR3","ADDR4", addressToOutput = `"${tntStreet1}","${tntStreet2}","","",`; // tntCityStZip const tntCityStZipLp = decscriptionSplitLp[3+iExtra]; console.log('CityStZip is : '); console.log(tntCityStZipLp); const tntCityStZipSplitLp = tntCityStZipLp.split(' '); const cityStZpLengthLp = tntCityStZipSplitLp.length; const postalCodeLp = tntCityStZipSplitLp[cityStZpLengthLp-2] + ' ' + tntCityStZipSplitLp[cityStZpLengthLp-1]; console.log('PostalCode is : '); console.log(postalCodeLp); const provinceLp = tntCityStZipSplitLp[cityStZpLengthLp-3]; console.log('Province is : '); console.log(provinceLp); const otherLengthLp = postalCodeLp.length + provinceLp.length + 1; const diffLengLp = tntCityStZipLp.length - otherLengthLp; const cityLp = tntCityStZipLp.substring(0, diffLengLp) console.log('City is : '); console.log(cityLp); // tntCountry const tntCountryLp = decscriptionSplitLp[4+iExtra]; console.log('Country is : '); console.log(tntCountryLp); //"CITY","STATE","ZIP","COUNTRY","CNTRY_DESCR","ADDR_CHANGED","PHONE","PHONE_CHANGED" addressToOutput += `"${cityLp}","${provinceLp}","${postalCodeLp}","${tntCountryLp}","${tntCountryLp}","","",""`; // end of DESCRIPTION Section================================================================ // ==================================================================================== // ==================================================================================== // AMOUNT let amountDtlp = entryToProcess.getElementsByClassName('currency')[0].innerText; amountDtlp = Number(amountDtlp.replace(/[^0-9\.-]+/g,"")); amountDtlp = amountDtlp.toFixed(2); console.log('currency is: '); console.log(amountDtlp); const methodDtLp = entryToProcess.getElementsByClassName('method')[0].innerHTML; console.log(" method is ===>"); console.log(methodDtLp); const accountDtLp = entryToProcess.getElementsByClassName('account')[0].innerHTML; console.log(" account is ===>"); console.log(accountDtLp); const referenceDtLp = entryToProcess.getElementsByClassName('reference')[0].innerHTML; console.log(" reference is ===>"); console.log(referenceDtLp); giftFromSupporter = `"${tntUserIdLp}","${tntAcctName}","${displayDate}","${amountDtlp}","${donationId}","51361","","Unknown","${methodDtLp}"`; outputFileGifts.write(giftFromSupporter); outputFileGifts.write('\n'); outputFileDonors.write(accountRecord); outputFileDonors.write(addressToOutput); outputFileDonors.write('\n'); } } // ============================================================ // ================================================================ for (let i = 0; i < oddTableEntries.length; i++) { console.log('next entry is ==============================================>'); console.log(oddTableEntries[i]); let entryToProcess = oddTableEntries[i]; // DATE let dateDtlp = entryToProcess.getElementsByClassName('date')[0]; let displayDate = dateDtlp.innerText; console.log('displayDate before is: '); console.log(displayDate); let date = new Date(displayDate); //console.log('date before is: '); //console.log(date); //console.log('date.getMonth() is: '); //console.log(date.getMonth()); //console.log('date.getDate() is: '); //console.log(date.getDate()); //console.log('date.getFullYear() is: '); //console.log(date.getFullYear()); displayDate = (date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear(); console.log('displayDate after is: '); console.log(displayDate); // DESCRIPTION Section================================================================ // ==================================================================================== // ==================================================================================== const transDescrLp = entryToProcess.getElementsByClassName('description')[0].innerHTML; const decscriptionSplitLp = transDescrLp.split('<br>'); if (decscriptionSplitLp.length < 2) { console.log('skipping record since it is not a Canada donation'); } else { // tntUserId let tntUserIdLp = decscriptionSplitLp[0]; let indx = tntUserIdLp.indexOf(')'); tntUserIdLp = tntUserIdLp.substring(1, indx); console.log('UserId is: '); console.log(tntUserIdLp); // tntName const tntAcctName = decscriptionSplitLp[1]; accountRecord = `"${tntUserIdLp}","${tntAcctName}","","",`; //caclulate donation_id let donationId = ''; donationId = displayDate.replace(/\//g, ''); donationId += tntUserIdLp + "ZZ"; console.log('donationId is: '); console.log(donationId); indx = tntAcctName.lastIndexOf(' '); const tntFirstNameLp = tntAcctName.substring(0, indx); console.log(`#${tntFirstNameLp}#`); const tntLastNameLp = tntAcctName.substring(indx + 1, tntAcctName.length); console.log(`#${tntLastNameLp}#`); // "PEOPLE_ID","ACCT_NAME","PERSON_TYPE","LAST_NAME_ORG","FIRST_NAME","MIDDLE_NAME","TITLE","SUFFIX", // "SP_LAST_NAME","SP_FIRST_NAME","SP_MIDDLE_NAME","SP_TITLE","SP_SUFFIX", accountRecord = `"${displayDate}","${tntUserIdLp}","${tntAcctName}","","${tntLastNameLp}","${tntFirstNameLp}","","","","","","","","",`; // tntStreet let tntStreet1 = decscriptionSplitLp[2]; console.log('Street is : '); console.log(tntStreet1); let tntStreet2 = '""'; let iExtra = 0; if (decscriptionSplitLp.length === 6) { iExtra = 1; tntStreet2 = decscriptionSplitLp[3]; console.log('Street 2 is : '); console.log(tntStreet2); } let addressToOutput = ''; // "ADDR1","ADDR2", "ADDR3","ADDR4", addressToOutput = `"${tntStreet1}","${tntStreet2}","","",`; // tntCityStZip const tntCityStZipLp = decscriptionSplitLp[3+iExtra]; console.log('CityStZip is : '); console.log(tntCityStZipLp); const tntCityStZipSplitLp = tntCityStZipLp.split(' '); const cityStZpLengthLp = tntCityStZipSplitLp.length; const postalCodeLp = tntCityStZipSplitLp[cityStZpLengthLp-2] + ' ' + tntCityStZipSplitLp[cityStZpLengthLp-1]; console.log('PostalCode is : '); console.log(postalCodeLp); const provinceLp = tntCityStZipSplitLp[cityStZpLengthLp-3]; console.log('Province is : '); console.log(provinceLp); const otherLengthLp = postalCodeLp.length + provinceLp.length + 1; const diffLengLp = tntCityStZipLp.length - otherLengthLp; const cityLp = tntCityStZipLp.substring(0, diffLengLp) console.log('City is : '); console.log(cityLp); // tntCountry const tntCountryLp = decscriptionSplitLp[4+iExtra]; console.log('Country is : '); console.log(tntCountryLp); //"CITY","STATE","ZIP","COUNTRY","CNTRY_DESCR","ADDR_CHANGED","PHONE","PHONE_CHANGED" addressToOutput += `"${cityLp}","${provinceLp}","${postalCodeLp}","${tntCountryLp}","${tntCountryLp}","","","",`; // end of DESCRIPTION Section================================================================ // ==================================================================================== // ==================================================================================== // AMOUNT let amountDtlp = entryToProcess.getElementsByClassName('currency')[0].innerText; amountDtlp = Number(amountDtlp.replace(/[^0-9\.-]+/g,"")); amountDtlp = amountDtlp.toFixed(2); console.log('currency is: '); console.log(amountDtlp); const methodDtLp = entryToProcess.getElementsByClassName('method')[0].innerHTML; console.log(" method is ===>"); console.log(methodDtLp); const accountDtLp = entryToProcess.getElementsByClassName('account')[0].innerHTML; console.log(" account is ===>"); console.log(accountDtLp); const referenceDtLp = entryToProcess.getElementsByClassName('reference')[0].innerHTML; console.log(" reference is ===>"); console.log(referenceDtLp); giftFromSupporter = `"${tntUserIdLp}","${tntAcctName}","${displayDate}","${amountDtlp}","${donationId}","51361","","Unknown","${methodDtLp}"`; outputFileGifts.write(giftFromSupporter); outputFileGifts.write('\n'); outputFileDonors.write(accountRecord); outputFileDonors.write(addressToOutput); outputFileDonors.write('\n'); } } // ============================================================ // ================================================================ outputFileDonors.end(); // close string outputFileGifts.end(); // close file //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- } }); console.log('leaving readWbtStatementIntojQuery'); } selectWbtStatementFile = () => { console.log('called selectWbtStatementFile'); const fileNames = dialog.showOpenDialog(); if (fileNames === undefined) { console.log('inside selectWbtStatementFile No file selected'); this.setState({ wbtStatementFile: '' }); } else { // console.log('going to set the filename and boolean' + fileNames); this.setState({ wbtStatementFile: fileNames[0] }); } console.log('end of selectWbtStatementFile'); } handleTransactionDate = (event) => { const target = event.target; console.log(target.name); console.log(target.value); if (target.name === 'transactionDateTextBox') { this.setState({ transactionDate: target.value }); } this.props.onTransactionDate(this.state.transactionDate); } render() { /* if (this.state.jobFilepathSelected && this.state.metaDataFolderSelected) { $('#sendButton').removeAttr('disabled'); } else { $('#sendButton').attr('disabled', 'true'); } */ let transDate; let transactionAmount; let transDescr; let transMethod = 'blah'; let transAccount = 'blah'; let transReference = 'blah'; let tntUserId = 'blah'; let tntFirstName = 'blah'; let tntLastName = 'blah'; let tntStreet = 'blahla'; let tntCity = 'blahla'; let tntProv = 'blahla'; let tntPostalCode = 'blahla'; let tntCountry ='blalaCountry' if (this.state.wbtStatementFile === 'wbtStatementFile') { transDate = 'No file selected Gumbo.'; transactionAmount = 'No amount yet'; } else { transDate = this.state.transactionDate; transactionAmount = this.state.transactionAmount; transDescr = this.state.transDescription; transMethod = this.state.transMethod; transAccount = this.state.transAccount; transReference = this.state.transReference; tntUserId = this.state.tntUserIdSt; tntFirstName = this.state.stFirstName; tntLastName = this.state.stLastName; tntStreet = this.state.stStreetAddress; tntCity = this.state.stCity; tntProv = this.state.stProv; tntPostalCode = this.state.stPostalCode; tntCountry = this.state.stCountry; } return ( <div className="panel panel-primary"> <div className="panel-heading apt-addheading">Select WBT Statement</div> <div className="panel-body"> <form className="form" onSubmit={this.localHandleSend}> <div className="form-group"> <label htmlFor="wbtStatementFile">WBT Statement</label> <div className="form-text" id="wbtStatementFileId" >{this.state.wbtStatementFile}</div> <div className="col-sm-offset-3 col-sm-9"> <div className="pull-right"> <button type="button" className="btn btn-primary" onClick={this.selectWbtStatementFile} >Select WBT Statement</button>&nbsp; </div> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" htmlFor="transactionDate">transactionDate</label> <div className="form-text" id="transactionDate" placeholder="transactionDate" >{transDate}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="transactionAmount">Amount</label> <div className="form-text" id="transactionAmount" placeholder="transactionAmount" >{transactionAmount}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="transDescr">Description</label> <div className="form-text" id="transDescr" placeholder="transDescr" >{transDescr}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="tntUserId">tntUserId</label> <div className="form-text" id="tntUserId" placeholder="tntUserId" >{tntUserId}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="tntFirstName">tntFirstName</label> <div className="form-text" id="tntFirstName" placeholder="tntFirstName" >{tntFirstName}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="tntLastName">tntLastName</label> <div className="form-text" id="tntLastName" placeholder="tntLastName" >{tntLastName}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="tntStreet">tntStreet</label> <div className="form-text" id="tntStreet" placeholder="tntStreet" >{tntStreet}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="tntCity">tntCity</label> <div className="form-text" id="tntCity" placeholder="tntCity" >{tntCity}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="tntProv">tntProv</label> <div className="form-text" id="tntProv" placeholder="tntProv" >{tntProv}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="tntPostalCode">tntPostalCode</label> <div className="form-text" id="tntPostalCode" placeholder="tntPostalCode" >{tntPostalCode}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="tntCountry">tntCountry</label> <div className="form-text" id="tntCountry" placeholder="tntCountry" >{tntCountry}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="transMethod">method</label> <div className="form-text" id="transMethod" placeholder="transMethod" >{transMethod}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="transAccount">account Member</label> <div className="form-text" id="transAccount" placeholder="transAccount" >{transAccount}</div> <br></br> <label className="col-sm-3 control-label" htmlFor="transReference">reference</label> <div className="form-text" id="transReference" placeholder="transReference" >{transReference}</div> <div className="col-sm-offset-3 col-sm-9"> <div className="pull-right"> <button type="button" className="btn btn-primary" onClick={this.readWbtStatementIntojQuery} >Process WBT Statement</button>&nbsp; </div> </div> </div> <div className="form-group"> <label htmlFor="wbtDonorFile">output DonorFile</label> <div className="form-text" id="wbtDonorFileId" >{this.state.wbtDonorFile}</div> <label htmlFor="wbtGiftsFile">output GiftsFile</label> <div className="form-text" id="wbtGiftsFileId" >{this.state.wbtGiftsFile}</div> </div> </form> </div> </div> ); } } export default SelectWbtStatement;
src/components/App/App.js
ihenvyr/react-app
import React from 'react'; import { Router } from 'react-router'; import routes from '../../routes'; import { browserHistory } from 'react-router'; import './App.scss'; const store = window.store = {}; const createElement = (Component, props) => { return <Component {...props} store={store} /> }; const App = () => { return ( <Router history={browserHistory} children={routes} createElement={createElement} /> ) }; export default App;
src/containers/pages/create-deck/after-class-selection/left-container/sidebar/details/deck-mechanics.js
vFujin/HearthLounge
import React from 'react'; import PropTypes from 'prop-types'; import _ from 'lodash'; import Loader from "../../../../../../../components/loaders/diamond/loader"; const DeckMechanics = ({deck, cards}) => { const {loading} = cards; let deckMechanics = [].concat.apply([], _.map(deck, (value)=>value.hasOwnProperty('mechanics') ? value.mechanics : null)); let countMechanics = _.countBy(deckMechanics, 'name'); const listMechanics = () =>{ const {mechanics} = cards; return _.sortBy(mechanics).map(mechanic=> <tr className={`${countMechanics[mechanic] > 0 ? 'has-mechanic' : ''}`} key={mechanic}> <td>{_.startCase(mechanic)}</td> <td>{countMechanics[mechanic] || 0}</td> </tr> ) }; return ( <div className="list mechanics-list"> <div className="table-scroll"> <table> <thead> <tr> <td>Mechanic</td> <td>Amount</td> </tr> </thead> <tbody> {loading ? <Loader theme="light"/> : listMechanics()} </tbody> </table> </div> </div> ); }; export default DeckMechanics; DeckMechanics.propTypes = { deck: PropTypes.array, cards: PropTypes.object };
frontend/src/containers/CollectionManagement/CollectionManagement.js
webrecorder/webrecorder
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { asyncConnect } from 'redux-connect'; import { load as loadColl } from 'store/modules/collection'; import { getOrderedRecordings } from 'store/selectors'; import { AccessContext } from 'store/contexts'; import CollectionManagementUI from 'components/collection/CollectionManagementUI'; class CollectionManagement extends Component { static propTypes = { auth: PropTypes.object, match: PropTypes.object, history: PropTypes.object }; render() { const { auth, match: { params: { user } } } = this.props; const canAdmin = auth.getIn(['user', 'username']) === user; return ( <AccessContext.Provider value={{ canAdmin }}> <CollectionManagementUI {...this.props} /> </AccessContext.Provider> ); } } const initialData = [ { promise: ({ match: { params: { coll, user } }, store: { dispatch } }) => { return dispatch(loadColl(user, coll)); } } ]; const mapStateToProps = (outerState) => { const { app, reduxAsyncConnect } = outerState; const isLoaded = app.getIn(['collection', 'loaded']); return { auth: app.get('auth'), collection: app.get('collection'), recordingEdited: app.getIn(['recordings', 'edited']), recordings: isLoaded ? getOrderedRecordings(app, true) : null }; }; export default asyncConnect( initialData, mapStateToProps )(CollectionManagement);
frontend/node_modules/react-router/es/Prompt.js
justdotJS/rowboat
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import invariant from 'invariant'; /** * The public API for prompting the user before navigating away * from a screen with a component. */ var Prompt = function (_React$Component) { _inherits(Prompt, _React$Component); function Prompt() { _classCallCheck(this, Prompt); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Prompt.prototype.enable = function enable(message) { if (this.unblock) this.unblock(); this.unblock = this.context.router.history.block(message); }; Prompt.prototype.disable = function disable() { if (this.unblock) { this.unblock(); this.unblock = null; } }; Prompt.prototype.componentWillMount = function componentWillMount() { invariant(this.context.router, 'You should not use <Prompt> outside a <Router>'); if (this.props.when) this.enable(this.props.message); }; Prompt.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (nextProps.when) { if (!this.props.when || this.props.message !== nextProps.message) this.enable(nextProps.message); } else { this.disable(); } }; Prompt.prototype.componentWillUnmount = function componentWillUnmount() { this.disable(); }; Prompt.prototype.render = function render() { return null; }; return Prompt; }(React.Component); Prompt.propTypes = { when: PropTypes.bool, message: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired }; Prompt.defaultProps = { when: true }; Prompt.contextTypes = { router: PropTypes.shape({ history: PropTypes.shape({ block: PropTypes.func.isRequired }).isRequired }).isRequired }; export default Prompt;
fixtures/fiber-debugger/src/Fibers.js
prometheansacrifice/react
import React from 'react'; import {Motion, spring} from 'react-motion'; import dagre from 'dagre'; // import prettyFormat from 'pretty-format'; // import reactElement from 'pretty-format/plugins/ReactElement'; function getFiberColor(fibers, id) { if (fibers.currentIDs.indexOf(id) > -1) { return 'lightgreen'; } if (id === fibers.workInProgressID) { return 'yellow'; } return 'lightyellow'; } function Graph(props) { const {rankdir, trackActive} = props.settings; var g = new dagre.graphlib.Graph(); g.setGraph({ width: 1000, height: 1000, nodesep: 50, edgesep: 150, ranksep: 100, marginx: 100, marginy: 100, rankdir, }); var edgeLabels = {}; React.Children.forEach(props.children, function(child) { if (!child) { return; } if (child.type.isVertex) { g.setNode(child.key, { label: child, width: child.props.width, height: child.props.height, }); } else if (child.type.isEdge) { const relationshipKey = child.props.source + ':' + child.props.target; if (!edgeLabels[relationshipKey]) { edgeLabels[relationshipKey] = []; } edgeLabels[relationshipKey].push(child); } }); Object.keys(edgeLabels).forEach(key => { const children = edgeLabels[key]; const child = children[0]; g.setEdge(child.props.source, child.props.target, { label: child, allChildren: children.map(c => c.props.children), weight: child.props.weight, }); }); dagre.layout(g); var activeNode = g .nodes() .map(v => g.node(v)) .find(node => node.label.props.isActive); const [winX, winY] = [window.innerWidth / 2, window.innerHeight / 2]; var focusDx = trackActive && activeNode ? winX - activeNode.x : 0; var focusDy = trackActive && activeNode ? winY - activeNode.y : 0; var nodes = g.nodes().map(v => { var node = g.node(v); return ( <Motion style={{ x: props.isDragging ? node.x + focusDx : spring(node.x + focusDx), y: props.isDragging ? node.y + focusDy : spring(node.y + focusDy), }} key={node.label.key}> {interpolatingStyle => React.cloneElement(node.label, { x: interpolatingStyle.x + props.dx, y: interpolatingStyle.y + props.dy, vanillaX: node.x, vanillaY: node.y, }) } </Motion> ); }); var edges = g.edges().map(e => { var edge = g.edge(e); let idx = 0; return ( <Motion style={edge.points.reduce((bag, point) => { bag[idx + ':x'] = props.isDragging ? point.x + focusDx : spring(point.x + focusDx); bag[idx + ':y'] = props.isDragging ? point.y + focusDy : spring(point.y + focusDy); idx++; return bag; }, {})} key={edge.label.key}> {interpolatedStyle => { let points = []; Object.keys(interpolatedStyle).forEach(key => { const [idx, prop] = key.split(':'); if (!points[idx]) { points[idx] = {x: props.dx, y: props.dy}; } points[idx][prop] += interpolatedStyle[key]; }); return React.cloneElement(edge.label, { points, id: edge.label.key, children: edge.allChildren.join(', '), }); }} </Motion> ); }); return ( <div style={{ position: 'relative', height: '100%', }}> {edges} {nodes} </div> ); } function Vertex(props) { if (Number.isNaN(props.x) || Number.isNaN(props.y)) { return null; } return ( <div style={{ position: 'absolute', border: '1px solid black', left: props.x - props.width / 2, top: props.y - props.height / 2, width: props.width, height: props.height, overflow: 'hidden', padding: '4px', wordWrap: 'break-word', }}> {props.children} </div> ); } Vertex.isVertex = true; const strokes = { alt: 'blue', child: 'green', sibling: 'darkgreen', return: 'red', fx: 'purple', }; function Edge(props) { var points = props.points; var path = 'M' + points[0].x + ' ' + points[0].y + ' '; if (!points[0].x || !points[0].y) { return null; } for (var i = 1; i < points.length; i++) { path += 'L' + points[i].x + ' ' + points[i].y + ' '; if (!points[i].x || !points[i].y) { return null; } } var lineID = props.id; return ( <svg width="100%" height="100%" style={{ position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, }}> <defs> <path d={path} id={lineID} /> <marker id="markerCircle" markerWidth="8" markerHeight="8" refX="5" refY="5"> <circle cx="5" cy="5" r="3" style={{stroke: 'none', fill: 'black'}} /> </marker> <marker id="markerArrow" markerWidth="13" markerHeight="13" refX="2" refY="6" orient="auto"> <path d="M2,2 L2,11 L10,6 L2,2" style={{fill: 'black'}} /> </marker> </defs> <use xlinkHref={`#${lineID}`} fill="none" stroke={strokes[props.kind]} style={{ markerStart: 'url(#markerCircle)', markerEnd: 'url(#markerArrow)', }} /> <text> <textPath xlinkHref={`#${lineID}`}> {'     '} {props.children} </textPath> </text> </svg> ); } Edge.isEdge = true; function formatPriority(priority) { switch (priority) { case 1: return 'synchronous'; case 2: return 'task'; case 3: return 'hi-pri work'; case 4: return 'lo-pri work'; case 5: return 'offscreen work'; default: throw new Error('Unknown priority.'); } } export default function Fibers({fibers, show, graphSettings, ...rest}) { const items = Object.keys(fibers.descriptions).map( id => fibers.descriptions[id] ); const isDragging = rest.className.indexOf('dragging') > -1; const [_, sdx, sdy] = rest.style.transform.match(/translate\((-?\d+)px,(-?\d+)px\)/) || []; const dx = Number(sdx); const dy = Number(sdy); return ( <div {...rest} style={{ width: '100%', height: '100%', position: 'absolute', top: 0, left: 0, ...rest.style, transform: null, }}> <Graph className="graph" dx={dx} dy={dy} isDragging={isDragging} settings={graphSettings}> {items.map(fiber => [ <Vertex key={fiber.id} width={150} height={100} isActive={fiber.id === fibers.workInProgressID}> <div style={{ width: '100%', height: '100%', backgroundColor: getFiberColor(fibers, fiber.id), }} title={ /*prettyFormat(fiber, { plugins: [reactElement ]})*/ 'todo: this was hanging last time I tried to pretty print' }> <small> {fiber.tag} #{fiber.id} </small> <br /> {fiber.type} <br /> {fibers.currentIDs.indexOf(fiber.id) === -1 ? ( <small> {fiber.pendingWorkPriority !== 0 && [ <span key="span"> Needs: {formatPriority(fiber.pendingWorkPriority)} </span>, <br key="br" />, ]} {fiber.memoizedProps !== null && fiber.pendingProps !== null && [ fiber.memoizedProps === fiber.pendingProps ? 'Can reuse memoized.' : 'Cannot reuse memoized.', <br key="br" />, ]} </small> ) : ( <small>Committed</small> )} {fiber.effectTag && [ <br key="br" />, <small key="small">Effect: {fiber.effectTag}</small>, ]} </div> </Vertex>, fiber.child && show.child && ( <Edge source={fiber.id} target={fiber.child} kind="child" weight={1000} key={`${fiber.id}-${fiber.child}-child`}> child </Edge> ), fiber.sibling && show.sibling && ( <Edge source={fiber.id} target={fiber.sibling} kind="sibling" weight={2000} key={`${fiber.id}-${fiber.sibling}-sibling`}> sibling </Edge> ), fiber.return && show.return && ( <Edge source={fiber.id} target={fiber.return} kind="return" weight={1000} key={`${fiber.id}-${fiber.return}-return`}> return </Edge> ), fiber.nextEffect && show.fx && ( <Edge source={fiber.id} target={fiber.nextEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.nextEffect}-nextEffect`}> nextFx </Edge> ), fiber.firstEffect && show.fx && ( <Edge source={fiber.id} target={fiber.firstEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.firstEffect}-firstEffect`}> firstFx </Edge> ), fiber.lastEffect && show.fx && ( <Edge source={fiber.id} target={fiber.lastEffect} kind="fx" weight={100} key={`${fiber.id}-${fiber.lastEffect}-lastEffect`}> lastFx </Edge> ), fiber.alternate && show.alt && ( <Edge source={fiber.id} target={fiber.alternate} kind="alt" weight={10} key={`${fiber.id}-${fiber.alternate}-alt`}> alt </Edge> ), ])} </Graph> </div> ); }
src/svg-icons/notification/sync.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSync = (props) => ( <SvgIcon {...props}> <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/> </SvgIcon> ); NotificationSync = pure(NotificationSync); NotificationSync.displayName = 'NotificationSync'; export default NotificationSync;
node_modules/react-router/modules/Router.js
SlateRobotics/slate-website
import createHashHistory from 'history/lib/createHashHistory' import useQueries from 'history/lib/useQueries' import React from 'react' import createTransitionManager from './createTransitionManager' import { routes } from './PropTypes' import RouterContext from './RouterContext' import { createRoutes } from './RouteUtils' import { createRouterObject, createRoutingHistory } from './RouterUtils' import warning from './routerWarning' function isDeprecatedHistory(history) { return !history || !history.__v2_compatible__ } const { func, object } = React.PropTypes /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RouterContext> with all the props * it needs each time the URL changes. */ const Router = React.createClass({ propTypes: { history: object, children: routes, routes, // alias for children render: func, createElement: func, onError: func, onUpdate: func, // PRIVATE: For client-side rehydration of server match. matchContext: object }, getDefaultProps() { return { render(props) { return <RouterContext {...props} /> } } }, getInitialState() { return { location: null, routes: null, params: null, components: null } }, handleError(error) { if (this.props.onError) { this.props.onError.call(this, error) } else { // Throw errors by default so we don't silently swallow them! throw error // This error probably occurred in getChildRoutes or getComponents. } }, componentWillMount() { const { parseQueryString, stringifyQuery } = this.props warning( !(parseQueryString || stringifyQuery), '`parseQueryString` and `stringifyQuery` are deprecated. Please create a custom history. http://tiny.cc/router-customquerystring' ) const { history, transitionManager, router } = this.createRouterObjects() this._unlisten = transitionManager.listen((error, state) => { if (error) { this.handleError(error) } else { this.setState(state, this.props.onUpdate) } }) this.history = history this.router = router }, createRouterObjects() { const { matchContext } = this.props if (matchContext) { return matchContext } let { history } = this.props const { routes, children } = this.props if (isDeprecatedHistory(history)) { history = this.wrapDeprecatedHistory(history) } const transitionManager = createTransitionManager( history, createRoutes(routes || children) ) const router = createRouterObject(history, transitionManager) const routingHistory = createRoutingHistory(history, transitionManager) return { history: routingHistory, transitionManager, router } }, wrapDeprecatedHistory(history) { const { parseQueryString, stringifyQuery } = this.props let createHistory if (history) { warning(false, 'It appears you have provided a deprecated history object to `<Router/>`, please use a history provided by ' + 'React Router with `import { browserHistory } from \'react-router\'` or `import { hashHistory } from \'react-router\'`. ' + 'If you are using a custom history please create it with `useRouterHistory`, see http://tiny.cc/router-usinghistory for details.') createHistory = () => history } else { warning(false, '`Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead. http://tiny.cc/router-defaulthistory') createHistory = createHashHistory } return useQueries(createHistory)({ parseQueryString, stringifyQuery }) }, /* istanbul ignore next: sanity check */ componentWillReceiveProps(nextProps) { warning( nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored' ) warning( (nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored' ) }, componentWillUnmount() { if (this._unlisten) this._unlisten() }, render() { const { location, routes, params, components } = this.state const { createElement, render, ...props } = this.props if (location == null) return null // Async match // Only forward non-Router-specific props to routing context, as those are // the only ones that might be custom routing context props. Object.keys(Router.propTypes).forEach(propType => delete props[propType]) return render({ ...props, history: this.history, router: this.router, location, routes, params, components, createElement }) } }) export default Router
src/TabPane.js
xiaoking/react-bootstrap
import React from 'react'; import deprecationWarning from './utils/deprecationWarning'; import Tab from './Tab'; const TabPane = React.createClass({ componentWillMount() { deprecationWarning( 'TabPane', 'Tab', 'https://github.com/react-bootstrap/react-bootstrap/pull/1091' ); }, render() { return ( <Tab {...this.props} /> ); } }); export default TabPane;
src/components/calculationmonitor.js
OpenChemistry/mongochemclient
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Avatar from '@material-ui/core/Avatar'; import Chip from '@material-ui/core/Chip'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import AccessTime from '@material-ui/icons/AccessTime'; import AutoRenew from '@material-ui/icons/Autorenew'; import Backup from '@material-ui/icons/Backup'; import Done from '@material-ui/icons/Done'; import Help from '@material-ui/icons/Help'; import Launch from '@material-ui/icons/Launch'; import ReportProblem from '@material-ui/icons/ReportProblem'; import blue from '@material-ui/core/colors/blue'; import grey from '@material-ui/core/colors/grey'; import indigo from '@material-ui/core/colors/indigo'; import lightGreen from '@material-ui/core/colors/lightGreen'; import red from '@material-ui/core/colors/red'; import { CalculationState } from '../utils/constants'; const blue200 = blue['200']; const blue500 = blue['500']; const red500 = red['500']; const lightGreen200 = lightGreen['200']; const lightGreenA700 = lightGreen['A700']; const grey300 = grey['300']; const indigoA200 = indigo['A200']; const statusToStyle = (status) => { const iconMap = { [CalculationState.initializing.name]: { icon: <Launch/>, color: indigoA200, }, [CalculationState.queued.name]: { icon: <AccessTime/>, color: lightGreen200, }, [CalculationState.running.name]: { icon: <AutoRenew/>, color: lightGreenA700 }, [CalculationState.error.name]: { icon: <ReportProblem/>, color: red500, }, [CalculationState.complete.name]: { icon: <Done/>, color: blue500, }, [CalculationState.uploading.name]: { icon: <Backup/>, color: blue200, } }; if (status in iconMap) { return iconMap[status] } else { return { icon: <Help/>, color: grey300 } } } class CalculationMonitorTable extends Component { render() { return ( <div> <h2 style={{textAlign: 'center'}}>{this.props.title}</h2> <Table> <TableHead> <TableRow> <TableCell tooltip="ID">ID</TableCell> <TableCell tooltip="Code">Code</TableCell> <TableCell tooltip="Type">Type</TableCell> <TableCell tooltip="The Status">Status</TableCell> </TableRow> </TableHead> <TableBody> {this.props.calculations.map( (calculation, index) => ( <TableRow key={index}> <TableCell>{calculation.name}</TableCell> <TableCell>{calculation.code ? calculation.code : 'N/A'}</TableCell> <TableCell>{calculation.type ? calculation.type : 'N/A'}</TableCell> <TableCell> <Chip avatar={ <Avatar style={{backgroundColor: statusToStyle(calculation.status).color}}> {statusToStyle(calculation.status).icon} </Avatar> } label={calculation.status ? calculation.status.toUpperCase() : ''} /> </TableCell> </TableRow> ))} </TableBody> </Table> </div> ); } } CalculationMonitorTable.propTypes = { calculations: PropTypes.array, title: PropTypes.string, } CalculationMonitorTable.defaultProps = { calculations: [], title: 'Pending Calculations' } export default CalculationMonitorTable
ui/src/js/statistics/TreesPerOrgType.js
Dica-Developer/weplantaforest
import axios from 'axios'; import counterpart from 'counterpart'; import React, { Component } from 'react'; import { Pie } from 'react-chartjs'; export default class TreesPerOrgType extends Component { constructor() { super(); this.state = { chartData: [], amountOfTrees: [1, 1, 1, 1], labels: [counterpart.translate('PRIVATEPERSON'), counterpart.translate('COMPANY'), counterpart.translate('NGO'), counterpart.translate('SCHOOL')], options: { scaleShowGridLines: true, scaleOverride: false, tooltipTemplate: '<%= value %>' } }; } componentDidMount() { this.updateChartForYear(); this.state.chartData.push({ color: 'rgb(50, 171, 31)', label: this.state.labels[0], value: this.state.amountOfTrees[0] }); this.state.chartData.push({ color: 'rgb(70, 100, 31)', label: this.state.labels[1], value: this.state.amountOfTrees[1] }); this.state.chartData.push({ color: 'rgb(10, 50, 31)', label: this.state.labels[2], value: this.state.amountOfTrees[2] }); this.state.chartData.push({ color: 'rgb(130, 171, 100)', label: this.state.labels[3], value: this.state.amountOfTrees[3] }); this.refs['barChart'].update(); } updateChartForYear() { var that = this; axios .get('http://localhost:8081/statistic/treesPerOrgType') .then(function(response) { var result = response.data; for (var year in result) { that.state.chartData[year].value = result[year].amount; } that.forceUpdate(); that.refs['barChart'].update(); }) .catch(function(response) { if (response instanceof Error) { console.error('Error', response.message); } else { console.error(response.data); console.error(response.status); console.error(response.headers); console.error(response.config); } }); } render() { var that = this; return ( <div className="row pie-chart"> <div className="col-md-3"> <ul className="pie-legend"> <li> <span></span> {this.state.labels[0]} </li> <li> <span></span> {this.state.labels[1]} </li> <li> <span></span> {this.state.labels[2]} </li> <li> <span></span> {this.state.labels[3]} </li> </ul> </div> <div className="col-md-9"> <Pie ref="barChart" data={this.state.chartData} options={this.state.options} /> </div> </div> ); } } /* vim: set softtabstop=2:shiftwidth=2:expandtab */
webclient/src/components/Navbar.js
jadiego/bloom
import React, { Component } from 'react'; import { Menu, Container, Image } from 'semantic-ui-react' import { Link, withRouter } from 'react-router-dom'; import image from '../img/lotus.svg'; import { isEmpty } from 'lodash'; import './navbar.css' import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { signOut } from '../redux/actions'; class TopNavBar extends Component { render() { const { signOut, currentUser } = this.props if (!isEmpty(currentUser) && localStorage.getItem("auth")) { return ( <Menu fixed='top' className='navbar'> <Container> <Menu.Item header as={Link} to='/' className='nav-main-item'> <Image size='mini' src={image} id='nav-logo'></Image> Bloom </Menu.Item> <Menu.Menu position='right'> <Menu.Item name='about' as={Link} to='/about'> About </Menu.Item> <Menu.Item name='account' as={Link} to='/account'> Account </Menu.Item> <Menu.Item name='signout' as='a' onClick={signOut}> Sign out </Menu.Item> </Menu.Menu> </Container> </Menu> ) } else { return ( <Menu fixed='top' className='navbar'> <Container> <Menu.Item header as={Link} to='/' className='nav-main-item'> <Image size='mini' src={image} id='nav-logo'></Image> Bloom </Menu.Item> <Menu.Menu position='right'> <Menu.Item name='about' as={Link} to='/about'> About </Menu.Item> <Menu.Item name='login' as={Link} to='/login'> Sign in </Menu.Item> </Menu.Menu> </Container> </Menu> ) } } } const mapStateToProps = (state) => { return { currentUser: state.currentUser, } } const mapDispatchToProps = (dispatch) => { return bindActionCreators({ signOut, }, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(TopNavBar);
examples/suggest.js
eternalsky/select
/* eslint no-console: 0 */ import React from 'react'; import Select, { Option } from 'rc-select'; import 'rc-select/assets/index.less'; import { fetch } from './common/tbFetchSuggest'; import ReactDOM from 'react-dom'; const Input = (props) => <input {...props} />; class Search extends React.Component { state = { data: [], value: '', }; onKeyDown = (e) => { if (e.keyCode === 13) { console.log('onEnter', this.state.value); this.jump(this.state.value); } }; onSelect = (value) => { console.log('select ', value); this.jump(value); }; jump = (v) => { console.log('jump ', v); // location.href = 'https://s.taobao.com/search?q=' + encodeURIComponent(v); }; fetchData = (value) => { this.setState({ value, }); fetch(value, (data) => { this.setState({ data, }); }); }; render() { const data = this.state.data; const options = data.map((d) => { return <Option key={d.value}>{d.text}</Option>; }); return (<div> <h2>suggest</h2> <div onKeyDown={this.onKeyDown}> <Select style={{ width: 500 }} combobox value={this.state.value} placeholder="placeholder" defaultActiveFirstOption={false} getInputElement={() => <Input />} showArrow={false} notFoundContent="" onChange={this.fetchData} onSelect={this.onSelect} filterOption={false} > {options} </Select> </div> </div>); } } ReactDOM.render(<Search />, document.getElementById('__react-content'));
src/svg-icons/image/looks-3.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLooks3 = (props) => ( <SvgIcon {...props}> <path d="M19.01 3h-14c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 7.5c0 .83-.67 1.5-1.5 1.5.83 0 1.5.67 1.5 1.5V15c0 1.11-.9 2-2 2h-4v-2h4v-2h-2v-2h2V9h-4V7h4c1.1 0 2 .89 2 2v1.5z"/> </SvgIcon> ); ImageLooks3 = pure(ImageLooks3); ImageLooks3.displayName = 'ImageLooks3'; export default ImageLooks3;
src/svg-icons/editor/vertical-align-top.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorVerticalAlignTop = (props) => ( <SvgIcon {...props}> <path d="M8 11h3v10h2V11h3l-4-4-4 4zM4 3v2h16V3H4z"/> </SvgIcon> ); EditorVerticalAlignTop = pure(EditorVerticalAlignTop); EditorVerticalAlignTop.displayName = 'EditorVerticalAlignTop'; EditorVerticalAlignTop.muiName = 'SvgIcon'; export default EditorVerticalAlignTop;
src/js/components/icons/base/Integration.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-integration`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'integration'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#231F1F" strokeWidth="2" d="M5,21 L23,21 L23,9 L5,9 M19,15 L1,15 L1,3 L19,3"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Integration'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/components/thunderbird/footer.js
mozilla/donate.mozilla.org
import React from 'react'; import Footer from '../footer.js'; import { FormattedHTMLMessage } from 'react-intl'; var ThunderbirdFooter = React.createClass({ contextTypes: { intl: React.PropTypes.object }, render: function() { // We can customize the thunderbird message here if we want. return ( <Footer {...this.props}> <FormattedHTMLMessage id='footer_updates' /> </Footer> ); } }); module.exports = ThunderbirdFooter;
src/containers/NotFound/NotFound.js
huangc28/palestine-2
import React from 'react'; export default function NotFound() { return ( <div className="container"> <h1>Doh! 404!</h1> <p>These are <em>not</em> the droids you are looking for!</p> </div> ); }
app/javascript/mastodon/features/account_timeline/components/moved_note.js
salvadorpla/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import AvatarOverlay from '../../../components/avatar_overlay'; import DisplayName from '../../../components/display_name'; import Icon from 'mastodon/components/icon'; export default class MovedNote extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { from: ImmutablePropTypes.map.isRequired, to: ImmutablePropTypes.map.isRequired, }; handleAccountClick = e => { if (e.button === 0) { e.preventDefault(); this.context.router.history.push(`/accounts/${this.props.to.get('id')}`); } e.stopPropagation(); } render () { const { from, to } = this.props; const displayNameHtml = { __html: from.get('display_name_html') }; return ( <div className='account__moved-note'> <div className='account__moved-note__message'> <div className='account__moved-note__icon-wrapper'><Icon id='suitcase' className='account__moved-note__icon' fixedWidth /></div> <FormattedMessage id='account.moved_to' defaultMessage='{name} has moved to:' values={{ name: <bdi><strong dangerouslySetInnerHTML={displayNameHtml} /></bdi> }} /> </div> <a href={to.get('url')} onClick={this.handleAccountClick} className='detailed-status__display-name'> <div className='detailed-status__display-avatar'><AvatarOverlay account={to} friend={from} /></div> <DisplayName account={to} /> </a> </div> ); } }
client/components/shared/SearchBar.js
AnatolyBelobrovik/itechartlabs
import React from 'react'; import PropTypes from 'prop-types'; const SearchBar = ({ term, data, update, userSearch }) => { const dataSearch = (e) => { const value = e.target.value.toLowerCase(); let filter = []; if (userSearch) { filter = data.filter(data => { return data.name.toLowerCase().includes(value); }); } else { filter = data.filter(data => { return data.title.toLowerCase().includes(value); }); } update({ data: filter, term: value }); }; return ( <div className="input-group"> <span className="input-group-addon"> <i className="fa fa-search" aria-hidden="true"></i> </span> <input value={term} onChange={dataSearch} type="text" className="form-control" placeholder="Search" /> </div> ); }; SearchBar.propTypes = { term: PropTypes.string, data: PropTypes.array, update: PropTypes.func.isRequired, userSearch: PropTypes.bool.isRequired }; export default SearchBar;
src/svg-icons/action/zoom-in.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionZoomIn = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/> </SvgIcon> ); ActionZoomIn = pure(ActionZoomIn); ActionZoomIn.displayName = 'ActionZoomIn'; ActionZoomIn.muiName = 'SvgIcon'; export default ActionZoomIn;
ui-lib/ModuleExport/Hint.js
nikgraf/future-react-ui
import React from 'react'; export const defaultTheme = { base: undefined, questionMark: undefined, visibleContent: undefined, hiddenContent: undefined, }; const Hint = ({ children, isOpen = false, theme = defaultTheme }) => { // eslint-disable-line no-shadow return ( <div className={theme.base}> <div className={theme.questionMark}>?</div> <div className={isOpen ? theme.visibleContent : theme.hiddenContent}> {children} </div> </div> ); }; export default Hint;
src/components/CheckBoxes/Component.js
nickorsk2020/agave-react-UI
/* * This file is part of the "Agave react UI" package * * Copyright (c) 2016 Stepanov Nickolay <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ import React from 'react'; import ReactDOM from 'react-dom' import Component from '../classes/Component' import PrivateSettings from './PrivateSettings' import { deepClone } from '../../Helper' class CheckBoxes extends Component { binding(){ this.sendValue = this.sendValue.bind(this); this.clickParentDiv = this.clickParentDiv.bind(this); this.changeRadio = this.changeRadio.bind(this); this.clickRadio = this.clickRadio.bind(this); this.setValueFromSchema = this.setValueFromSchema.bind(this); } constructor(props){ super(props); this.binding(); } // set value from schema setValueFromSchema(){ let value = this.getValueElement(); if(value.length>0){ let settings = deepClone(this.getSettings()); let array_values = value.split(';'); settings.array_values = array_values; this.setSettings(settings); } } componentWillMount(){ this.initSettingsElement(PrivateSettings); this.setValueFromSchema(); } // send value to dispatcher sendValue(Value){ let parent = ReactDOM.findDOMNode(this.refs['parent-container']); let settings = deepClone(this.getSettings()); let array_values = settings.array_values; let isCheked = false; for(let a=array_values.length-1;a>=0;a--){ if(Value==array_values[a]){ isCheked = true; array_values.splice(a,1); } } if(!isCheked){ array_values.push(Value) } // settings.array_values = array_values; this.setSettings(settings); // отправляем событие через диспетчер в форму c ID елемента, его схемой и значением this.props.handle.onChange({ElementID:this.props.ElementID,Value:array_values.join(';')}); } clickParentDiv(event){ //event.stopPropagation(); let el = event.target; let radio = el.getElementsByClassName('checkbox-element')[0]; if(radio!=null){ this.sendValue(radio.value); } } clickRadio(event){ event.stopPropagation(); } changeRadio(event){ event.stopPropagation(); let radio = event.target; !radio.checked ? this.sendValue(radio.value,true): this.sendValue(radio.value); } render() { let style = ` .checkbox-element-parent{ cursor:pointer; display:inline-block; } `; let valuesSchema = this.getSchemaElement().values; let _this = this; let settings = this.getSettings(); let array_values = settings.array_values; return( <div ref="parent-container"> <style> {style} </style> {valuesSchema.map(function (Value) { let checked = false; for(let a=0;a<array_values.length;a++){ if(Value.value==array_values[a]){ checked =true; break; } } return( <div key={Value.value} > <div onClick={_this.clickParentDiv} className="checkbox-element-parent"> <input className="checkbox-element" checked={checked} type="checkbox" name={_this.props.ElementID} value={Value.value} onChange={_this.changeRadio} onClick={_this.clickRadio}/> &nbsp;{Value.text} </div><br/> </div>) })} </div> ); } } export default CheckBoxes;
src/svg-icons/image/filter-7.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilter7 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zm-8-2l4-8V5h-6v2h4l-4 8h2z"/> </SvgIcon> ); ImageFilter7 = pure(ImageFilter7); ImageFilter7.displayName = 'ImageFilter7'; ImageFilter7.muiName = 'SvgIcon'; export default ImageFilter7;
lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/export-names.input.js
kadirahq/react-storybook
/* eslint-disable import/no-extraneous-dependencies */ import React from 'react'; import { storiesOf } from '@storybook/react'; import FlexCenter from './FlexCenter'; import { specs, urls } from './LiveView.stories'; import { ignoredRegions } from './IgnoredRegions.stories'; export { specs, urls, ignoredRegions }; storiesOf('FlexCenter', module).add('2:1', () => ( <FlexCenter width={200} height={100} style={{ background: 'papayawhip' }}> <div style={{ padding: 30, background: 'hotpink' }}>2:1</div> </FlexCenter> ));
src/contexts/PlayContext.js
Xvakin/quiz
import React from 'react' const PlayContext = React.createContext( { play: {}, playKey: '', }, ) export default PlayContext
src/client.js
nobleach/react-redux-example
import React from 'react'; import Router from 'react-router'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import routes from './views/routes'; import createRedux from './redux/create'; import { Provider } from 'redux/react'; import ApiClient from './ApiClient'; const history = new BrowserHistory(); const client = new ApiClient(); const dest = document.getElementById('content'); const redux = createRedux(client, window.__data); const element = (<Provider redux={redux}> {() => <Router history={history} children={routes}/> } </Provider>); React.render(element, dest); if (process.env.NODE_ENV !== 'production') { window.React = React; // enable debugger const reactRoot = window.document.getElementById('content'); if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) { console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.'); } }
generators/component/templates/_main-hooks.js
prescottprue/generator-react-firebase
import React from 'react'<% if (addStyle) { %> import { makeStyles } from '@material-ui/core/styles'<% } %> // import use<%= startCaseName %> from './use<%= startCaseName %>'<% if (addStyle) { %> import styles from './<%= name %>.styles' const useStyles = makeStyles(styles)<% } %> function <%= name %>() { <% if (addStyle) { %>const classes = useStyles()<% } %> // const {} = use<%= startCaseName %>() return ( <% if (addStyle) { %><div className={classes.root}><% } else { %><div><% } %> <span><%= name %> Component</span> </div> ) } export default <%= name %>
client/node_modules/uu5g03/dist-node/bricks/table-col.js
UnicornCollege/ucl.itkpd.configurator
import React from 'react'; import {BaseMixin, ElementaryMixin, ColorSchemaMixin} from './../common/common.js'; import './table-col.less'; export default React.createClass({ //@@viewOn:mixins mixins: [ BaseMixin, ElementaryMixin, ColorSchemaMixin ], //@@viewOff:mixins //@@viewOn:statics statics: { tagName: 'UU5.Bricks.Table.Col', classNames: { main: 'uu5-bricks-table-col', bg: 'uu5-common-bg' }, defaults: { parentTagName: 'UU5.Bricks.Table.ColGroup' } }, //@@viewOff:statics //@@viewOn:propTypes propTypes: { span: React.PropTypes.number }, //@@viewOff:propTypes //@@viewOn:getDefaultProps getDefaultProps: function () { return { span: null }; }, //@@viewOff:getDefaultProps //@@viewOn:standardComponentLifeCycle componentWillMount: function () { this.checkParentTagName(this.getDefault().parentTagName); }, //@@viewOff:standardComponentLifeCycle //@@viewOn:interface //@@viewOff:interface //@@viewOn:overridingMethods //@@viewOff:overridingMethods //@@viewOn:componentSpecificHelpers _getMainProps: function () { var props = this.buildMainAttrs(); this.getColorSchema() && (props.className += ' ' + this.getClassName().bg); this.props.span && (props.span = this.props.span); return props; }, //@@viewOff:componentSpecificHelpers //@@viewOn:render render: function () { return <col {...this._getMainProps()} />; } //@@viewOff:render });
src/svg-icons/device/signal-cellular-null.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularNull = (props) => ( <SvgIcon {...props}> <path d="M20 6.83V20H6.83L20 6.83M22 2L2 22h20V2z"/> </SvgIcon> ); DeviceSignalCellularNull = pure(DeviceSignalCellularNull); DeviceSignalCellularNull.displayName = 'DeviceSignalCellularNull'; export default DeviceSignalCellularNull;
src/pages/data/CBA/playerdata/PlayerData.js
HeliumLau/Hoop-react
import React from 'react'; import PropTypes from 'prop-types'; import './PlayerData.less'; import DataAside from 'components/DataAside.js'; import EastRank from 'pages/data/NBA/NBADraft/EastRank.js'; import WestRank from 'pages/data/NBA/NBADraft/WestRank.js'; export default class PlayerData extends React.Component { constructor(props, context) { super(props); } render() { const list = [ { name: '得分', url: '' }, { name: '篮板', url: '' }, { name: '助攻', url: '' }, { name: '抢断', url: '' }, { name: '盖帽', url: '' }, { name: '两分球进球数', url: '' }, { name: '两分球命中率', url: '' }, { name: '三分球进球数', url: '' }, { name: '三分球命中率', url: '' }, { name: '有效命中率', url: '' }, { name: '真实命中率', url: '' }, { name: '罚球进球数', url: '' }, { name: '罚球命中率', url: '' }, { name: '失误', url: '' }, { name: '失误率', url: '' }, { name: '两双', url: '' }, { name: '三双', url: '' }, { name: '犯规', url: '' }, { name: '出场时间', url: '' } ]; return ( <div className="CBA-content-container"> <DataAside list={list} /> <div id="data-list-container"> <EastRank /> <WestRank /> </div> </div> ) } } PlayerData.contextTypes = { router: PropTypes.object }
templates/src/routes/index.js
chenym1992/create-react-frame
/** * react routes模块 * @description:定义路由跳转组件 */ import React from 'react' import { BrowserRouter as Router, Switch, Route } from 'react-router-dom' /** * App:base component * @description:Entry component, first entered the rendering page */ import App from '../containers/AppContainer' /** * NotFound:404 component * @description:route not match */ import NotFound from '../components/NotFound' /** * route config */ const routes = ( <Router> <Switch> {/*base route*/} <Route exact path="/" component={App}/> {/*404页面*/} <Route component={NotFound}/> </Switch> </Router> ) export default routes
ui/src/components/domain/ManageDomains.js
yahoo/athenz
/* * Copyright 2020 Verizon Media * * 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. */ import React from 'react'; import styled from '@emotion/styled'; import Switch from '../denali/Switch'; import Icon from '../denali/icons/Icon'; import { colors } from '../denali/styles'; import DeleteModal from '../modal/DeleteModal'; import Color from '../denali/Color'; import DateUtils from '../utils/DateUtils'; import RequestUtils from '../utils/RequestUtils'; const ManageDomainSectionDiv = styled.div` margin: 20px; `; const AddContainerDiv = styled.div` padding-bottom: 20px; `; const RoleTable = styled.table` width: 100%; border-spacing: 0; display: table; border-collapse: separate; border-color: grey; `; const TableHeadStyled = styled.th` text-align: ${(props) => props.align}; border-bottom: 2px solid #d5d5d5; color: #9a9a9a; font-weight: 600; font-size: 0.8rem; padding-bottom: 5px; vertical-align: top; text-transform: uppercase; padding: 5px 0 5px 15px; word-break: break-all; `; const TDStyled = styled.td` background-color: ${(props) => props.color}; text-align: ${(props) => props.align}; padding: 5px 0 5px 15px; vertical-align: middle; word-break: break-all; `; export default class ManageDomains extends React.Component { constructor(props) { super(props); this.api = props.api; this.state = { showDelete: false, auditEnabled: false, auditRef: '', }; this.saveJustification = this.saveJustification.bind(this); this.domainNameProvided = this.domainNameProvided.bind(this); this.dateUtils = new DateUtils(); } onClickDelete(name, auditEnabled) { this.setState({ showDelete: true, deleteName: name, auditEnabled: auditEnabled, }); } onClickDeleteCancel() { this.setState({ showDelete: false, deleteName: '', auditEnabled: false, auditRef: '', errorMessage: null, }); } saveJustification(val) { this.setState({ auditRef: val, }); } domainNameProvided(val) { this.setState({ domainNameProvided: val, }); } ascertainDomainType(domain) { if (domain) { var splits = domain.split('.'); if (splits.length === 2 && domain.indexOf('home.') === 0) { return 'Personal'; } if (splits.length >= 2) { return 'Sub domain'; } return 'Top Level'; } return ''; } onSubmitDelete() { let domainName = this.state.deleteName; if (domainName !== this.state.domainNameProvided) { this.setState({ errorMessageForModal: 'Domain names do not match', }); return; } const splittedDomain = domainName.split('.'); const domain = splittedDomain.pop(); const parent = splittedDomain.join('.'); this.api .deleteSubDomain( parent, domain, this.state.auditRef, this.props._csrf ) .then(() => { this.setState({ showDelete: false, deleteName: null, auditEnabled: false, auditRef: '', errorMessage: null, }); this.props.loadDomains( `Successfully deleted domain ${domainName}` ); }) .catch((err) => { this.setState({ errorMessage: RequestUtils.xhrErrorCheckHelper(err), showDelete: false, deleteName: null, auditEnabled: false, auditRef: '', }); }); } render() { const left = 'left'; const center = 'center'; const rows = this.props.domains ? this.props.domains.map((item, i) => { const domainType = this.ascertainDomainType(item.domain.name); let deletable = false; let auditEnabled = !!item.domain.auditEnabled; let deleteItem = this.onClickDelete.bind( this, item.domain.name, auditEnabled ); let color = ''; if (i % 2 === 0) { color = colors.row; } if (domainType === 'Sub domain') { deletable = true; } return ( <tr key={item.domain.name}> <TDStyled color={color} align={left}> {item.domain.name} </TDStyled> <TDStyled color={color} align={left}> {domainType} </TDStyled> <TDStyled color={color} align={left}> {this.dateUtils.getLocalDate( item.domain.modified, 'UTC', 'UTC' )} </TDStyled> <TDStyled color={color} align={center}> {item.domain.ypmId ? item.domain.ypmId : ''} </TDStyled> <TDStyled color={color} align={center}> <Switch name={'selfServe-' + i} value={auditEnabled} checked={auditEnabled} disabled /> </TDStyled> <TDStyled color={color} align={center}> {item.domain.account ? item.domain.account : ''} </TDStyled> <TDStyled color={color} align={center}> {deletable ? ( <Icon icon={'trash'} onClick={deleteItem} color={colors.icons} isLink size={'1.25em'} verticalAlign={'text-bottom'} /> ) : null} </TDStyled> </tr> ); }) : ''; if (this.state.showDelete) { let clickDeleteCancel = this.onClickDeleteCancel.bind(this); let clickDeleteSubmit = this.onSubmitDelete.bind(this); rows.push( <DeleteModal isOpen={this.state.showDelete} cancel={clickDeleteCancel} message={ 'Are you sure you want to permanently delete the Domain ' } name={this.state.deleteName} submit={clickDeleteSubmit} showJustification={this.state.auditEnabled} showDomainInput={true} onJustification={this.saveJustification} key={'delete-modal'} errorMessage={this.state.errorMessageForModal} domainNameProvided={this.domainNameProvided} /> ); } return ( <ManageDomainSectionDiv data-testid='manage-domains'> <AddContainerDiv /> {this.state.errorMessage && ( <Color name={'red600'}>{this.state.errorMessage}</Color> )} <RoleTable> <thead> <tr> <TableHeadStyled align={left}>Name</TableHeadStyled> <TableHeadStyled align={left}>Type</TableHeadStyled> <TableHeadStyled align={left}> Modified Date </TableHeadStyled> <TableHeadStyled align={center}> Product Master Id </TableHeadStyled> <TableHeadStyled align={center}> Audit </TableHeadStyled> <TableHeadStyled align={center}> AWS Account # </TableHeadStyled> <TableHeadStyled align={center}> Delete </TableHeadStyled> </tr> </thead> <tbody>{rows}</tbody> </RoleTable> </ManageDomainSectionDiv> ); } }
src/views/Comment/CommentAvatar.js
Semantic-Org/Semantic-UI-React
import cx from 'clsx' import PropTypes from 'prop-types' import React from 'react' import { createHTMLImage, getElementType, getUnhandledProps, htmlImageProps, partitionHTMLProps, } from '../../lib' /** * A comment can contain an image or avatar. */ function CommentAvatar(props) { const { className, src } = props const classes = cx('avatar', className) const rest = getUnhandledProps(CommentAvatar, props) const [imageProps, rootProps] = partitionHTMLProps(rest, { htmlProps: htmlImageProps }) const ElementType = getElementType(CommentAvatar, props) return ( <ElementType {...rootProps} className={classes}> {createHTMLImage(src, { autoGenerateKey: false, defaultProps: imageProps })} </ElementType> ) } CommentAvatar.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.elementType, /** Additional classes. */ className: PropTypes.string, /** Specifies the URL of the image. */ src: PropTypes.string, } export default CommentAvatar
src/routes/error/index.js
langpavel/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ErrorPage from './ErrorPage'; function action() { return { title: 'Demo Error', component: <ErrorPage />, }; } export default action;
app/javascript/mastodon/features/ui/components/upload_area.js
tri-star/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { FormattedMessage } from 'react-intl'; export default class UploadArea extends React.PureComponent { static propTypes = { active: PropTypes.bool, onClose: PropTypes.func, }; handleKeyUp = (e) => { const keyCode = e.keyCode; if (this.props.active) { switch(keyCode) { case 27: e.preventDefault(); e.stopPropagation(); this.props.onClose(); break; } } } componentDidMount () { window.addEventListener('keyup', this.handleKeyUp, false); } componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp); } render () { const { active } = this.props; return ( <Motion defaultStyle={{ backgroundOpacity: 0, backgroundScale: 0.95 }} style={{ backgroundOpacity: spring(active ? 1 : 0, { stiffness: 150, damping: 15 }), backgroundScale: spring(active ? 1 : 0.95, { stiffness: 200, damping: 3 }) }}> {({ backgroundOpacity, backgroundScale }) => ( <div className='upload-area' style={{ visibility: active ? 'visible' : 'hidden', opacity: backgroundOpacity }}> <div className='upload-area__drop'> <div className='upload-area__background' style={{ transform: `scale(${backgroundScale})` }} /> <div className='upload-area__content'><FormattedMessage id='upload_area.title' defaultMessage='Drag & drop to upload' /></div> </div> </div> )} </Motion> ); } }
docs/src/app/components/pages/components/Stepper/CustomIcon.js
w01fgang/material-ui
import React from 'react'; import { Step, Stepper, StepLabel, } from 'material-ui/Stepper'; import WarningIcon from 'material-ui/svg-icons/alert/warning'; import {red500} from 'material-ui/styles/colors'; /** * Custom icons can be used to create different visual states. */ class CustomIcon extends React.Component { state = { stepIndex: 0, }; handleNext = () => { const {stepIndex} = this.state; if (stepIndex < 2) { this.setState({stepIndex: stepIndex + 1}); } }; handlePrev = () => { const {stepIndex} = this.state; if (stepIndex > 0) { this.setState({stepIndex: stepIndex - 1}); } }; getStepContent(stepIndex) { switch (stepIndex) { case 0: return 'Select campaign settings...'; case 1: return 'What is an ad group anyways?'; case 2: return 'This is the bit I really care about!'; default: return 'You\'re a long way from home sonny jim!'; } } render() { return ( <div style={{width: '100%', maxWidth: 700, margin: 'auto'}}> <Stepper linear={false}> <Step completed={false}> <StepLabel> Select campaign settings </StepLabel> </Step> <Step completed={false}> <StepLabel icon={<WarningIcon color={red500} />} style={{color: red500}} > Create an ad group </StepLabel> </Step> <Step completed={false}> <StepLabel> Create an ad </StepLabel> </Step> </Stepper> </div> ); } } export default CustomIcon;
js/controls/KendoDatePicker.js
wingspan/wingspan-forms
import React from 'react' import DateWidgetMixin from '../mixins/DateWidgetMixin' const KendoDatePicker = React.createClass({ mixins: [DateWidgetMixin('kendoDatePicker')], statics: { fieldClass: function () { return 'formFieldDatepicker'; } }, getDefaultProps: function () { return { format: 'dd-MMM-yyyy' }; }, /*jshint ignore:start */ render: function () { return (this.props.noControl ? (<span>{this.renderValue()}</span>) : (<input type="text" />)); } /*jshint ignore:end */ }); export default KendoDatePicker;
src/svg-icons/image/movie-creation.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageMovieCreation = (props) => ( <SvgIcon {...props}> <path d="M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z"/> </SvgIcon> ); ImageMovieCreation = pure(ImageMovieCreation); ImageMovieCreation.displayName = 'ImageMovieCreation'; export default ImageMovieCreation;
src/svg-icons/image/crop-square.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropSquare = (props) => ( <SvgIcon {...props}> <path d="M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H6V6h12v12z"/> </SvgIcon> ); ImageCropSquare = pure(ImageCropSquare); ImageCropSquare.displayName = 'ImageCropSquare'; ImageCropSquare.muiName = 'SvgIcon'; export default ImageCropSquare;
src/svg-icons/action/gavel.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGavel = (props) => ( <SvgIcon {...props}> <path d="M1 21h12v2H1zM5.245 8.07l2.83-2.827 14.14 14.142-2.828 2.828zM12.317 1l5.657 5.656-2.83 2.83-5.654-5.66zM3.825 9.485l5.657 5.657-2.828 2.828-5.657-5.657z"/> </SvgIcon> ); ActionGavel = pure(ActionGavel); ActionGavel.displayName = 'ActionGavel'; export default ActionGavel;
components/plugins/js-features-table.js
ccheever/expo-docs
import React from 'react' // TODO: Make this not look terrible // We probably need some CSS stuff to be done here function createMarkup() { return { __html: ` <!-- Generated with gatsby/src/data/javascript-features.js --> <table> <thead> <tr> <th>Feature</th> <th>Works with Expo</th> <th>Links</th> <th>Spec</th> <th>Implementation</th> </tr> </thead> <tbody> <tr> <td>Object rest/spread</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">MDN</a> <br /> <a href="http://2ality.com/2016/10/rest-spread-properties.html">2ality</a></td> <td>Proposal</td> <td>Babel <hr class="vertical-divider" /> No JSC support</td> </tr> <tr> <td>Class properties</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://tc39.github.io/proposal-class-public-fields/">TC39 Proposal</a></td> <td>Proposal</td> <td>Babel <hr class="vertical-divider" /> No JSC support</td> </tr> <tr> <td>Revised template literals (lenient escape sequences)</td> <td><span class="centered-text-cell"> ❌ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">MDN</a> <br /> <a href="http://2ality.com/2016/09/template-literal-revision.html">2ality</a></td> <td>ES2018</td> <td>JSC support: iOS 11</td> </tr> <tr> <td>Async functions ( <code>async</code> / <code>await</code> )</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">MDN</a> <br /> <a href="http://exploringjs.com/es2016-es2017/ch_async-functions.html">Exploring ES2017</a></td> <td>ES2017</td> <td>Babel with Regenerator <hr class="vertical-divider" /> JSC support: Android, iOS 10.3+</td> </tr> <tr> <td>Trailing commas in function calls and signatures</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Trailing_commas">MDN</a> <br /> <a href="http://exploringjs.com/es2016-es2017/ch_trailing-comma-parameters.html">Exploring ES2017</a></td> <td>ES2017</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 10.3+</td> </tr> <tr> <td>Shared memory (SharedArrayBuffer, Atomics)</td> <td><span class="centered-text-cell"> ⚠️ <br /> (Android and iOS 10.3+, iOS 10.3 doesn’t implement byteLength) </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer">MDN (SharedArrayBuffer)</a> <br /> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics">MDN (Atomics)</a> <br /> <a href="http://exploringjs.com/es2016-es2017/ch_shared-array-buffer.html">Exploring ES2017</a></td> <td>ES2017</td> <td>JSC support: Android, iOS 10.3+</td> </tr> <tr> <td>Object static methods (entries, values, getOwnPropertyDescriptors)</td> <td><span class="centered-text-cell"> ⚠️ <br /> (Android and iOS 10+, and only Object.entries and Object.values on iOS 9) </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">MDN</a> <br /> <a href="http://exploringjs.com/es2016-es2017/ch_object-entries-object-values.html">Exploring ES2017 (entries, values)</a> <br /> <a href="http://exploringjs.com/es2016-es2017/ch_object-getownpropertydescriptors.html">Exploring ES2017 (getOwnPropertyDescriptors)</a></td> <td>ES2017</td> <td>Polyfills for Object.entries and Object.values <hr class="vertical-divider" /> JSC support: Android, iOS 10.3+</td> </tr> <tr> <td>String instance methods (padStart, padEnd)</td> <td><span class="centered-text-cell"> ⚠️ <br /> (Android and iOS 10+) </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String">MDN</a> <br /> <a href="http://exploringjs.com/es2016-es2017/ch_string-padding.html">Exploring ES2017</a></td> <td>ES2017</td> <td>JSC support: Android, iOS 10+</td> </tr> <tr> <td>Proxy <code>ownKeys</code> handler</td> <td><span class="centered-text-cell"> ⚠️ <br /> (Android and iOS 10+) </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/ownKeys">MDN</a></td> <td>ES2017</td> <td>JSC support: Android, iOS 10+</td> </tr> <tr> <td>Exponentiation operator ( <code>**</code> )</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation_(**)">MDN</a> <br /> <a href="http://exploringjs.com/es2016-es2017/ch_exponentiation-operator.html">Exploring ES2017</a></td> <td>ES2016</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 10.3+</td> </tr> <tr> <td>Destructuring nested rest declarations</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring">MDN</a></td> <td>ES2016</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 10.3+</td> </tr> <tr> <td>Array.prototype.includes</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes">MDN</a> <br /> <a href="http://exploringjs.com/es2016-es2017/ch_array-prototype-includes.html">Exploring ES2016</a></td> <td>ES2016</td> <td>Polyfilled <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td><code>for</code> … <code>of</code> loops</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_for-of.html">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Array instance methods (entries, keys, values, find, findIndex, copyWithin, fill)</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_arrays.html#sec_new-array-prototype-methods">Exploring ES6</a></td> <td>ES2015</td> <td>Some methods have polyfills <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Octal and binary literals</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="http://exploringjs.com/es6/ch_numbers.html#sec_new-integer-literals">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Number static properties and methods (EPSILON, MIN <em>SAFE</em> INTEGER, MAX <em>SAFE</em> INTEGER, isInteger, isSafeInteger, isNaN, isFinite, parseInt, parseFloat)</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_numbers.html#sec_new-static-number-props">Exploring ES6</a></td> <td>ES2015</td> <td>Some properties and methods have polyfills <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Math static methods (sign, trunc, cbrt, expm1, log1p, log2, log10, fround, imul, clz32, sinh, cosh, tanh, asinh, acosh, atanh, hypot)</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_numbers.html#sec_new-math">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 9+</td> </tr> <tr> <td>Unicode code point escapes</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="http://exploringjs.com/es6/ch_unicode.html#sec_escape-sequences">Exploring ES6</a></td> <td>ES2015</td> <td>Babel, in string literals <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>String instance methods (codePointAt, normalize, startsWith, endsWith, includes, repeat)</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_strings.html#sec_reference-strings">Exploring ES6</a></td> <td>ES2015</td> <td>Some methods have polyfills <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>String static methods (raw, fromCodePoint)</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_strings.html#sec_reference-strings">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 9+</td> </tr> <tr> <td>Symbols</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_symbols.html">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 9+</td> </tr> <tr> <td>Template literals (including tags)</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_template-literals.html">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Block scoping ( <code>let</code> , <code>const</code> )</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block">MDN</a> <br /> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">MDN (let)</a> <br /> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">MDN (const)</a> <br /> <a href="http://www.2ality.com/2015/02/es6-scoping.html">2ality</a> <br /> <a href="http://exploringjs.com/es6/ch_variables.html">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Destructuring syntax</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_destructuring.html">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9 (partially), iOS 10+</td> </tr> <tr> <td>Default parameter values</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_parameter-handling.html#sec_parameter-default-values">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 10+</td> </tr> <tr> <td>Rest parameters ( <code>...</code> )</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_parameter-handling.html#sec_rest-parameters">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 10+</td> </tr> <tr> <td>Spread syntax ( <code>...</code> )</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_parameter-handling.html#sec_spread-operator">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9 (partially), iOS 10+</td> </tr> <tr> <td>Function <code>name</code> property</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_callables.html#sec_function-names">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9 (partially), iOS 10+</td> </tr> <tr> <td><code>new.target</code></td> <td><span class="centered-text-cell"> ⚠️ <br /> (Android and iOS 10+) </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_callables.html#_how-do-i-determine-whether-a-function-was-invoked-via-new">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 10+</td> </tr> <tr> <td>Arrow functions</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_arrow-functions.html">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 10+</td> </tr> <tr> <td>Object static methods (assign, is, setPrototypeOf, getOwnPropertySymbols)</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_oop-besides-classes.html#sec_new-methods-object">Exploring ES6</a></td> <td>ES2015</td> <td>Polyfill for Object.assign (overrides native implementation with stricter one) <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Shorthand for object methods</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_oop-besides-classes.html#object-literal-method-definitions">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Shorthand for object properties</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_oop-besides-classes.html#_property-value-shorthands-1">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Computed properties and methods</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_oop-besides-classes.html#_computed-property-keys-1">Exploring ES6 (properties)</a> <br /> <a href="http://exploringjs.com/es6/ch_classes.html#_computed-method-names">Exploring ES6 (methods)</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9 (partially), iOS 10+</td> </tr> <tr> <td>Classes</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_classes.html">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 9 (partially), iOS 10+</td> </tr> <tr> <td>Modules ( <code>import</code> , <code>export</code> )</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">MDN (import)</a> <br /> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export">MDN (export)</a> <br /> <a href="http://exploringjs.com/es6/ch_modules.html">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> Natively supported on Android and iOS 10+ but we always use Babel’s implementation</td> </tr> <tr> <td>Map</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_maps-sets.html#sec_map">Exploring ES6</a></td> <td>ES2015</td> <td>Polyfilled <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Set</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_maps-sets.html#sec_set">Exploring ES6</a></td> <td>ES2015</td> <td>Polyfilled <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>WeakMap</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_maps-sets.html#sec_weakmap">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 9+</td> </tr> <tr> <td>WeakSet</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_maps-sets.html#sec_weakset">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 9+</td> </tr> <tr> <td>Typed arrays (ArrayBuffers, DataViews)</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_typed-arrays.html">Exploring ES6</a></td> <td>ES2015</td> <td>Polyfilled on iOS 9 <hr class="vertical-divider" /> JSC support: Android, iOS 9 (partially), iOS 10+</td> </tr> <tr> <td>Generators ( <code>function*</code> )</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_generators.html">Exploring ES6</a></td> <td>ES2015</td> <td>Babel <hr class="vertical-divider" /> JSC support: Android, iOS 10+</td> </tr> <tr> <td>RegExp <code>y</code> and <code>u</code> flags</td> <td><span class="centered-text-cell"> ⚠️ <br /> (Android and iOS 10+) </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_regexp.html#sec_regexp-flag-y">Exploring ES6 (sticky “y”)</a> <br /> <a href="http://exploringjs.com/es6/ch_regexp.html#sec_regexp-flag-u">Exploring ES6 (unicode “u”)</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 10+</td> </tr> <tr> <td>RegExp.prototype.flags</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/flags">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_regexp.html#sec_regexp-data-property-flags">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 9+</td> </tr> <tr> <td>Promises</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_promises.html">Exploring ES6</a></td> <td>ES2015</td> <td>Polyfill overrides native implementation <hr class="vertical-divider" /> JSC support: Android, iOS 9+</td> </tr> <tr> <td>Proxy</td> <td><span class="centered-text-cell"> ⚠️ <br /> (Android and iOS 10+) </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_proxies.html">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 10+</td> </tr> <tr> <td>Reflect (object introspection)</td> <td><span class="centered-text-cell"> ⚠️ <br /> (Android and iOS 10+) </span></td> <td><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflex">MDN</a> <br /> <a href="http://exploringjs.com/es6/ch_proxies.html#_reflect">Exploring ES6</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 10+</td> </tr> <tr> <td>Tail call optimization</td> <td><span class="centered-text-cell"> ✅ </span></td> <td><a href="http://exploringjs.com/es6/ch_tail-calls.html">Exploring ES6</a> <br /> <a href="http://www.2ality.com/2015/06/tail-call-optimization.html">2ality</a></td> <td>ES2015</td> <td>JSC support: Android, iOS 9+</td> </tr> </tbody> </table> ` } } export default class JSFeaturesTable extends React.Component { render() { return <div dangerouslySetInnerHTML={createMarkup()} /> } }
examples/dest/src/index.js
pure-ui/styleguide
import React from 'react'; import ReactDOM from 'react-dom'; import Button from './components/Button'; import Card from './components/Card'; ReactDOM.render( <div> Hello World <Button /> <Card /> </div>, document.getElementById('root') );
app/components/shared/Chooser/option.js
buildkite/frontend
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; class Option extends React.Component { static displayName = "Chooser.Option"; static propTypes = { tag: PropTypes.string.isRequired, children: PropTypes.node.isRequired, className: PropTypes.string, unselectedClassName: PropTypes.string, selectedClassName: PropTypes.string, value: PropTypes.any.isRequired, data: PropTypes.any }; static contextTypes = { chooser: PropTypes.object.isRequired }; static defaultProps = { tag: 'div' }; render() { const selectionClasses = this.context.chooser.isSelected(this.props.value) ? this.props.selectedClassName : this.props.unselectedClassName; const classes = classNames(this.props.className, selectionClasses); return React.createElement(this.props.tag, { className: classes, onClick: this.handleClick }, this.props.children); } handleClick = (evt) => { evt.preventDefault(); this.context.chooser.handleChoiceClick(this.props.value, this.props.data); } } export default Option;
client/containers/messages.js
nearform/vidi-dashboard
'use strict' import React from 'react' import {connect} from 'react-redux' import {Link} from 'react-router' import {Panel, PageHeader, HealthPanel, InfoCell} from '../components/index' import ChartistGraph from 'react-chartist' import {subscribe, unsubscribe} from '../actions/vidi' import _ from 'lodash' export const Overview = React.createClass({ componentDidMount () { this.props.dispatch(subscribe('messages')) }, componentWillUnmount () { this.props.dispatch(unsubscribe('messages')) }, render () { var sections = [] var groups = _.groupBy(this.props.messages, 'pattern') var sortedKeys = _.keys(groups).sort() _.each(sortedKeys, (theKey) => { var group = groups[theKey] if (group) { var proc_sections = [] var data = _.orderBy(group, ['pid'], ['desc']) var count = data.length var tag = '' var key _.each(data, (message) => { if (message) { key = message.pattern.replace(/:/, '_').replace(/,/, '_ ') tag = message.pattern proc_sections.push(makeMessageSections(message)) } }) sections.push( <div key={key} className="process-group panel"> <div className="panel-heading cf"> <h3 className="m0 fl-left"><strong>{tag}</strong></h3> <a href="" className="fl-right icon icon-collapse"></a> </div> <div className="panel-body"> <HealthPanel count={count}/> {proc_sections} </div> </div> ) } }) return ( <div className="page page-processes"> <div className="container-fluid"> <PageHeader title={'Messages'} /> </div> <div className="container-fluid"> {sections} </div> </div> ) } }) export default connect((state) => { var vidi = state.vidi var messages = vidi.messages || {data: [null]} return { messages: messages.data } })(Overview) function makeMessageSections (messages) { var section = [] var now = messages.latest var link = `/process/${now.pid}` return ( <div key={now.pid} className="process-card"> <div className="process-heading has-icon"> <span className="status status-healthy status-small" title="Status: healthy"></span> <Link to={link}>{`${now.pid} - ${now.tag}`}</Link> </div> <div className="row middle-xs"> <div className="col-xs-12 mtb"> <ChartistGraph type={'Line'} data={{labels: messages.series.time, series: [messages.series.rate]}} options={{ fullWidth: true, showArea: false, showLine: true, showPoint: false, chartPadding: {right: 30}, axisY: {onlyInteger: true}, axisX: {labelOffset: {x: -15}, labelInterpolationFnc: (val) => { if (_.last(val) == '0') return val else return null }}, }}/> </div> </div> </div> ) }
components/svg/Settings.js
jkling38/carbon
import React from 'react' export default () => ( <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 18 18"> <path fill="#fff" fillRule="evenodd" d="M206.532032,366.702224 L208.523318,368.142728 C208.69279,368.3122 208.721035,368.509915 208.608053,368.735877 L206.786238,371.74399 C206.673257,371.969953 206.503788,372.040565 206.277825,371.955829 L203.989964,371.066106 C203.283831,371.546276 202.775423,371.842848 202.464724,371.955829 L202.125782,374.286058 C202.069291,374.51202 201.913944,374.625 201.659736,374.625 L198.058474,374.625 C197.804266,374.625 197.648919,374.51202 197.592428,374.286058 L197.253486,371.955829 C196.829806,371.786357 196.321398,371.489786 195.728246,371.066106 L193.440385,371.955829 C193.214422,372.068811 193.044953,371.998198 192.931972,371.74399 L191.110157,368.735877 C190.96893,368.481669 190.997175,368.283955 191.194892,368.142728 L193.101443,366.702224 C193.101443,366.617488 193.094382,366.476263 193.080259,366.278546 C193.066136,366.080828 193.059075,365.925481 193.059075,365.8125 C193.059075,365.699519 193.066136,365.544172 193.080259,365.346454 C193.094382,365.148737 193.101443,365.007512 193.101443,364.922776 L191.152525,363.482272 C190.983053,363.3128 190.954808,363.115085 191.067789,362.889123 L192.889604,359.88101 C193.002585,359.655047 193.172055,359.584435 193.398017,359.669171 L195.685878,360.558894 C196.392011,360.078724 196.90042,359.782152 197.211118,359.669171 L197.550061,357.338942 C197.606551,357.11298 197.761898,357 198.016106,357 L201.617368,357 C201.871576,357 202.026923,357.11298 202.083414,357.338942 L202.379988,359.669171 C202.803668,359.838643 203.312077,360.135214 203.905229,360.558894 L206.150722,359.669171 C206.376684,359.556189 206.560276,359.626802 206.701503,359.88101 L208.523318,362.889123 C208.664544,363.143331 208.6363,363.341045 208.438582,363.482272 L206.532032,364.922776 C206.532032,365.007512 206.539093,365.148737 206.553216,365.346454 C206.567338,365.544172 206.5744,365.699519 206.5744,365.8125 C206.5744,366.23618 206.560277,366.532752 206.532032,366.702224 Z M199.795553,368.905349 C200.671159,368.905349 201.419649,368.608777 202.041046,368.015625 C202.662443,367.422473 202.973138,366.688105 202.973138,365.8125 C202.973138,364.936895 202.662443,364.202527 202.041046,363.609375 C201.419649,363.016223 200.671159,362.719651 199.795553,362.719651 C198.919948,362.719651 198.178519,363.016223 197.571244,363.609375 C196.96397,364.202527 196.660337,364.936895 196.660337,365.8125 C196.660337,366.688105 196.96397,367.422473 197.571244,368.015625 C198.178519,368.608777 198.919948,368.905349 199.795553,368.905349 Z" transform="translate(-191 -357)" /> </svg> )
src/containers/DevToolsWindow.js
dfalling/todo
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; export default createDevTools( <LogMonitor /> );
fixtures/nesting/src/modern/HomePage.js
ArunTesco/react
import React from 'react'; import {useContext} from 'react'; import {Link} from 'react-router-dom'; import ThemeContext from './shared/ThemeContext'; import Clock from './shared/Clock'; export default function HomePage({counter, dispatch}) { const theme = useContext(ThemeContext); return ( <> <h2>src/modern/HomePage.js</h2> <h3 style={{color: theme}}> This component is rendered by the outer React ({React.version}). </h3> <Clock /> <b> <Link to="/about">Go to About</Link> </b> </> ); }
src/components/videoDetail.js
TheeSweeney/ReactReview
import React from 'react'; const VideoDetail = ({video}) => { if(!video){ return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://youtube.com/embed/${videoId}` return ( <div className='video-detail col-md-8'> <div className='embed-responsive embed-responsive-16by9'> <iframe className='embed-responsive-item' src={url}></iframe> </div> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> ) } export default VideoDetail
tests/react_instance/class.js
ylu1317/flow
// @flow import React from 'react'; declare var any: any; class Foo extends React.Component<{}, void> {yep1: boolean} class Bar extends React.Component<{}, void> {yep2: boolean} (any: React$ElementRef<Class<Foo>>).yep1; // OK (any: React$ElementRef<Class<Foo>>).yep2; // Error (any: React$ElementRef<Class<Foo>>).nope; // Error (any: React$ElementRef<Class<Bar>>).yep1; // Error (any: React$ElementRef<Class<Bar>>).yep2; // OK (any: React$ElementRef<Class<Bar>>).nope; // Error
src/svg-icons/editor/border-outer.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorBorderOuter = (props) => ( <SvgIcon {...props}> <path d="M13 7h-2v2h2V7zm0 4h-2v2h2v-2zm4 0h-2v2h2v-2zM3 3v18h18V3H3zm16 16H5V5h14v14zm-6-4h-2v2h2v-2zm-4-4H7v2h2v-2z"/> </SvgIcon> ); EditorBorderOuter = pure(EditorBorderOuter); EditorBorderOuter.displayName = 'EditorBorderOuter'; EditorBorderOuter.muiName = 'SvgIcon'; export default EditorBorderOuter;
packages/@lyra/components/src/lists/grid/GridItem.js
VegaPublish/vega-studio
import React from 'react' import cx from 'classnames' import styles from './styles/GridItem.css' export default function GridItem(props: {className: string}) { const {className, ...rest} = props return <li {...rest} className={cx(styles.root, className)} /> }
src/parser/mage/frost/modules/features/ThermalVoid.js
FaideWW/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatDuration, formatNumber } from 'common/format'; import TalentStatisticBox from 'interface/others/TalentStatisticBox'; import Analyzer from 'parser/core/Analyzer'; import SpellIcon from 'common/SpellIcon'; const BASE_DUR = 20; // The standard duration of IV /* * Icy Veins' duration is increased by 10 sec. * Your Ice Lances against frozen targets extend your Icy Veins by an additional 1 sec. */ class ThermalVoid extends Analyzer { constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.THERMAL_VOID_TALENT.id); } statistic() { const hist = this.selectedCombatant.getBuffHistory(SPELLS.ICY_VEINS.id); if(!hist || hist.length === 0) { return null; } let totalIncrease = 0; let totalDuration = 0; // We could use getBuffUptime but we are doing the math anyway const castRows = hist.map((buff, idx) => { const end = buff.end || this.owner.currentTimestamp; const castTime = (buff.start - this.owner.fight.start_time) / 1000; const duration = (end - buff.start) / 1000; totalDuration += duration; // If the buff ended early because of death or fight end, don't blame the talent const increase = Math.max(0, duration - BASE_DUR); totalIncrease += increase; return ( <tr key={idx}> <td>{formatDuration(castTime)}</td> <td>{formatDuration(duration)}</td> <td>{formatDuration(increase)}</td> </tr> ); }); return ( <TalentStatisticBox talent={SPELLS.THERMAL_VOID_TALENT.id} value={<><SpellIcon id={SPELLS.ICY_VEINS.id} /> +{formatNumber(totalIncrease)} seconds</>} tooltip="Extension times include the base 10 second increase from the talent." > <table className="table table-condensed"> <thead> <tr> <th>Cast</th> <th>Duration</th> <th>Extension</th> </tr> </thead> <tbody> {castRows} <tr key="avg"> <th>Average</th> <th>{formatDuration(totalDuration / hist.length)}</th> <th>{formatDuration(totalIncrease / hist.length)}</th> </tr> </tbody> </table> </TalentStatisticBox> ); } } export default ThermalVoid;
src/Quickstart/Quickstart.js
halhenke/example-with-react-router
import React from 'react'; import {ComponentRouter} from 'component-router'; import styles from './Quickstart.css'; import Filter from './Filter'; import Content from './Content'; const FilterWrapper = React.createClass({ propTypes: { componentRouter: React.PropTypes.object }, shouldComponentUpdate({componentRouter: {value}}) { return value !== this.props.componentRouter.value; }, render() { const {value} = this.props.componentRouter; return <Filter isOpened={value === 'opened'} />; } }); const ContentWrapper = React.createClass({ propTypes: { componentRouter: React.PropTypes.object }, shouldComponentUpdate({componentRouter: {value}}) { return value !== this.props.componentRouter.value; }, render() { const {value = 'chart'} = this.props.componentRouter; return <Content expanded={value} />; } }); const Quickstart = React.createClass({ shouldComponentUpdate() { return false; }, render() { return ( <div className={styles.quickstart}> <ComponentRouter config={FilterWrapper} namespace="filter" /> <div className={styles.content}> <ComponentRouter config={ContentWrapper} namespace="expanded" /> </div> </div> ); } }); export default Quickstart;