path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/svg-icons/communication/stay-primary-landscape.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationStayPrimaryLandscape = (props) => ( <SvgIcon {...props}> <path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/> </SvgIcon> ); CommunicationStayPrimaryLandscape = pure(CommunicationStayPrimaryLandscape); CommunicationStayPrimaryLandscape.displayName = 'CommunicationStayPrimaryLandscape'; CommunicationStayPrimaryLandscape.muiName = 'SvgIcon'; export default CommunicationStayPrimaryLandscape;
webpack/ForemanTasks/Components/TasksDashboard/Components/TasksCardsGrid/Components/TasksDonutCard/TasksDonutCard.js
adamruzicka/foreman-tasks
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Card } from 'patternfly-react'; import { noop } from 'foremanReact/common/helpers'; import { TASKS_DASHBOARD_AVAILABLE_QUERY_MODES, TASKS_DASHBOARD_AVAILABLE_TIMES, TASKS_DASHBOARD_CURRENT_TIME, } from '../../../../TasksDashboardConstants'; import { getQueryValueText } from '../../../../TasksDashboardHelper'; import { timePropType, queryPropType, } from '../../../../TasksDashboardPropTypes'; import { TASKS_DONUT_CHART_FOCUSED_ON_OPTIONS } from '../TasksDonutChart/TasksDonutChartConstants'; import { getFocusedOn } from '../TasksDonutChart/TasksDonutChartHelper'; import TasksDonutChart from '../TasksDonutChart/TasksDonutChart'; import './TasksDonutCard.scss'; const TasksDonutCard = ({ title, data, query, wantedQueryState, className, time, updateQuery, ...props }) => { const { LAST, OLDER } = TASKS_DASHBOARD_AVAILABLE_QUERY_MODES; const focusedOn = getFocusedOn(query, wantedQueryState, time); const onTotalClick = () => updateQuery({ state: wantedQueryState }); return ( <Card className={classNames('tasks-donut-card', className, { 'selected-tasks-card': focusedOn !== TASKS_DONUT_CHART_FOCUSED_ON_OPTIONS.NORMAL && focusedOn !== TASKS_DONUT_CHART_FOCUSED_ON_OPTIONS.NONE, 'not-focused': focusedOn === TASKS_DONUT_CHART_FOCUSED_ON_OPTIONS.NONE, })} {...props} > <Card.Title onClick={onTotalClick}>{title}</Card.Title> <Card.Body> <TasksDonutChart last={data.last} older={data.older} time={getQueryValueText(time)} focusedOn={focusedOn} onTotalClick={onTotalClick} onLastClick={() => updateQuery({ state: wantedQueryState, mode: LAST, time: TASKS_DASHBOARD_CURRENT_TIME, }) } onOlderClick={() => updateQuery({ state: wantedQueryState, mode: OLDER, time: TASKS_DASHBOARD_CURRENT_TIME, }) } /> </Card.Body> </Card> ); }; TasksDonutCard.propTypes = { title: PropTypes.string, data: PropTypes.shape({ last: PropTypes.number.isRequired, older: PropTypes.number.isRequired, }), time: timePropType, query: queryPropType, wantedQueryState: PropTypes.string, className: PropTypes.string, updateQuery: PropTypes.func, }; TasksDonutCard.defaultProps = { title: '', data: { last: 0, older: 0 }, query: {}, wantedQueryState: '', time: TASKS_DASHBOARD_AVAILABLE_TIMES.H24, className: '', updateQuery: noop, }; export default TasksDonutCard;
src/components/ProgressBar/ProgressBar.stories.js
guilhermecvm/react-dribbble-components
// import React from 'react' // // import { storiesOf } from '@storybook/react' // import { ProgressBar } from './ProgressBar' // // class ProgressBarWrapper extends React.Component { // constructor(props) { // super(props) // this.state = { pct: 0 } // } // // componentDidMount() { // setTimeout(() => this.setState({ pct: 100 })) // } // // render() { // return <ProgressBar pct={this.state.pct} color="#24425E" /> // } // } // // storiesOf('ProgressBar', module) // .add('normal', () => <ProgressBarWrapper />)
src/Parser/AfflictionWarlock/Modules/Talents/MaleficGrasp.js
mwwscott0/WoWAnalyzer
import React from 'react'; import Module from 'Parser/Core/Module'; import Enemies from 'Parser/Core/Modules/Enemies'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatNumber, formatPercentage } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; import { UNSTABLE_AFFLICTION_DEBUFF_IDS } from '../../Constants'; import getDamageBonus from '../WarlockCore/getDamageBonus'; const AFFECTED_ABILITIES = new Set([ SPELLS.AGONY.id, SPELLS.CORRUPTION_DEBUFF.id, SPELLS.SIPHON_LIFE.id, ...UNSTABLE_AFFLICTION_DEBUFF_IDS, ]); const MALEFIC_GRASP_DAMAGE_BONUS = 0.25; class MaleficGrasp extends Module { static dependencies = { enemies: Enemies, combatants: Combatants, }; totalBonusDmg = 0; agonyBonusDmg = 0; corruptionBonusDmg = 0; siphonLifeBonusDmg = 0; unstableAfflictionBonusDmg = 0; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.MALEFIC_GRASP_TALENT.id); } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (!AFFECTED_ABILITIES.has(spellId)) { return; } const target = this.enemies.getEntity(event); const buffedByDrain = target.hasBuff(SPELLS.DRAIN_SOUL.id, event.timestamp); if (!buffedByDrain) { return; } const bonus = getDamageBonus(event, MALEFIC_GRASP_DAMAGE_BONUS); this.totalBonusDmg += bonus; switch (spellId) { case SPELLS.AGONY.id: this.agonyBonusDmg += bonus; break; case SPELLS.CORRUPTION_DEBUFF.id: this.corruptionBonusDmg += bonus; break; case SPELLS.SIPHON_LIFE.id: this.siphonLifeBonusDmg += bonus; break; case SPELLS.UNSTABLE_AFFLICTION_DEBUFF_1.id: case SPELLS.UNSTABLE_AFFLICTION_DEBUFF_2.id: case SPELLS.UNSTABLE_AFFLICTION_DEBUFF_3.id: case SPELLS.UNSTABLE_AFFLICTION_DEBUFF_4.id: case SPELLS.UNSTABLE_AFFLICTION_DEBUFF_5.id: this.unstableAfflictionBonusDmg += bonus; break; default: break; } } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.MALEFIC_GRASP_TALENT.id} />} value={`${formatNumber(this.totalBonusDmg / this.owner.fightDuration * 1000)} DPS`} label="Damage contributed" tooltip={`Your Malefic Grasp talent contributed ${formatNumber(this.totalBonusDmg)} total damage (${formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.totalBonusDmg))} %). <ul> ${this.agonyBonusDmg > 0 ? ` <li>${formatNumber(this.agonyBonusDmg)} bonus Agony damage.</li> ` : ''} ${this.corruptionBonusDmg > 0 ? ` <li>${formatNumber(this.corruptionBonusDmg)} bonus Corruption damage.</li> ` : ''} ${this.siphonLifeBonusDmg > 0 ? ` <li>${formatNumber(this.siphonLifeBonusDmg)} bonus Siphon Life damage.</li> ` : ''} ${this.unstableAfflictionBonusDmg > 0 ? ` <li>${formatNumber(this.unstableAfflictionBonusDmg)} bonus Unstable Affliction damage.</li> ` : ''} </ul> `} /> ); } statisticOrder = STATISTIC_ORDER.OPTIONAL(0); } export default MaleficGrasp;
app/components/ProductTable.js
pacmessica/hackathon-frontend
import PropTypes from 'prop-types'; import React from 'react'; import ProductRow from './ProductRow'; const products = [ { category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football' }, { category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball' }, { category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball' }, { category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch' }, { category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5' }, { category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7' } ]; const ProductTable = ({ filter }) => { let rows = []; products.forEach(p => { const nameLC = p.name.toLowerCase(); const filterLC = filter.toLowerCase(); if (nameLC.indexOf(filterLC) !== -1) { rows.push( <ProductRow key={p.name} data={p} /> ); } }); return <div> {rows} </div>; }; ProductTable.propTypes = { filter: PropTypes.string }; export default ProductTable;
docs/src/components/header.js
FormidableLabs/spectacle
import React from 'react'; import styled from 'styled-components'; import Hero from '../screens/home/hero'; import bgImg from '../static/bg_hero_feather.jpg'; import headerTriangle from '../static/svgs/header-triangle.svg'; import logoFormidableWhite from '../assets/logo_formidable_white.png'; const Container = styled.header` padding: 0px 0px 14rem; color: ${p => p.theme.colors.textLight}; background-size: cover; background: ${p => p.theme.colors.textDark}; background-image: linear-gradient(14deg, #404a5f, #7f526a); @media ${p => p.theme.media.sm} { background-image: url(${bgImg}), linear-gradient( 194deg, #77414b, #564c60 18%, #0d4a5d 73%, #023340, #023340, #023340 ); } `; const Triangle = styled.img` position: absolute; left: -0.7rem; top: -0.3rem; width: 20rem; @media ${p => p.theme.media.sm} { width: 26rem; } @media ${p => p.theme.media.md} { width: 30rem; } `; const HeaderContainer = styled.a` display: flex; flex-direction: column; position: absolute; left: 2rem; top: 1.5rem; font-size: 0.8rem; color: ${p => p.theme.colors.textLight}; @media ${p => p.theme.media.sm} { left: 3.5rem; top: 2rem; font-size: 1.2rem; } @media ${p => p.theme.media.md} { left: 4rem; top: 3rem; } > * { margin-top: 0; margin-bottom: 0; } > * + * { margin-top: 1rem; } `; const HeaderText = styled.p` text-transform: uppercase; margin: 0; font-family: inherit; font-size: inherit; line-height: 1.5; letter-spacing: 0.86px; max-width: 10rem; `; const HeaderLogo = styled.img` width: 4rem; @media ${p => p.theme.media.sm} { width: 6rem; } `; export const Header = () => ( <Container> <Triangle src={headerTriangle} /> <HeaderContainer href="https://formidable.com" title="Formidable" target="_blank" rel="noopener noreferrer" > <HeaderText>Another oss project by</HeaderText> <HeaderLogo src={logoFormidableWhite} alt="Formidable Logo" /> </HeaderContainer> <Hero /> </Container> );
frontend/src/screens/camera-log/camera-log.js
linea-it/qlf
import React from 'react'; import PropTypes from 'prop-types'; import Terminal from '../../components/terminal/terminal'; import Paper from '@material-ui/core/Paper'; const styles = { close: { float: 'right', cursor: 'pointer', }, main: { width: 'calc(100vw - 64px)', margin: '16px', padding: '16px', }, }; export default class CameraLog extends React.Component { static propTypes = { cameraIndex: PropTypes.string, arm: PropTypes.string, lines: PropTypes.array.isRequired, getLines: PropTypes.func.isRequired, online: PropTypes.bool, }; componentDidMount() { setTimeout(this.props.getLines, 2000); } renderTitle = () => { return ( <div> <span>{`Camera ${this.props.arm}${this.props.cameraIndex}`}</span> </div> ); }; render() { return ( <Paper elevation={4} style={styles.main}> {this.renderTitle()} <Terminal height={'calc(100vh - 150px)'} lines={this.props.lines.reverse()} /> </Paper> ); } }
stories/Typography.js
abouthiroppy/scuba
import React from 'react'; import { storiesOf } from '@kadira/storybook'; import { Container } from '../src'; storiesOf('Typography', module).add('list', () => ( <Container> <h1>h1 Hello!</h1> <h2>h2 Hello!</h2> <h3>h3 Hello!</h3> <h4>h4 Hello!</h4> <h5>h5 Hello!</h5> <h6>h6 Hello!</h6> </Container> ));
node_modules/react-bootstrap/es/MenuItem.js
yeshdev1/Everydays-project
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import all from 'react-prop-types/lib/all'; import SafeAnchor from './SafeAnchor'; import { bsClass, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; var propTypes = { /** * Highlight the menu item as active. */ active: PropTypes.bool, /** * Disable the menu item, making it unselectable. */ disabled: PropTypes.bool, /** * Styles the menu item as a horizontal rule, providing visual separation between * groups of menu items. */ divider: all(PropTypes.bool, function (_ref) { var divider = _ref.divider, children = _ref.children; return divider && children ? new Error('Children will not be rendered for dividers') : null; }), /** * Value passed to the `onSelect` handler, useful for identifying the selected menu item. */ eventKey: PropTypes.any, /** * Styles the menu item as a header label, useful for describing a group of menu items. */ header: PropTypes.bool, /** * HTML `href` attribute corresponding to `a.href`. */ href: PropTypes.string, /** * Callback fired when the menu item is clicked. */ onClick: PropTypes.func, /** * Callback fired when the menu item is selected. * * ```js * (eventKey: any, event: Object) => any * ``` */ onSelect: PropTypes.func }; var defaultProps = { divider: false, disabled: false, header: false }; var MenuItem = function (_React$Component) { _inherits(MenuItem, _React$Component); function MenuItem(props, context) { _classCallCheck(this, MenuItem); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleClick = _this.handleClick.bind(_this); return _this; } MenuItem.prototype.handleClick = function handleClick(event) { var _props = this.props, href = _props.href, disabled = _props.disabled, onSelect = _props.onSelect, eventKey = _props.eventKey; if (!href || disabled) { event.preventDefault(); } if (disabled) { return; } if (onSelect) { onSelect(eventKey, event); } }; MenuItem.prototype.render = function render() { var _props2 = this.props, active = _props2.active, disabled = _props2.disabled, divider = _props2.divider, header = _props2.header, onClick = _props2.onClick, className = _props2.className, style = _props2.style, props = _objectWithoutProperties(_props2, ['active', 'disabled', 'divider', 'header', 'onClick', 'className', 'style']); var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['eventKey', 'onSelect']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; if (divider) { // Forcibly blank out the children; separators shouldn't render any. elementProps.children = undefined; return React.createElement('li', _extends({}, elementProps, { role: 'separator', className: classNames(className, 'divider'), style: style })); } if (header) { return React.createElement('li', _extends({}, elementProps, { role: 'heading', className: classNames(className, prefix(bsProps, 'header')), style: style })); } return React.createElement( 'li', { role: 'presentation', className: classNames(className, { active: active, disabled: disabled }), style: style }, React.createElement(SafeAnchor, _extends({}, elementProps, { role: 'menuitem', tabIndex: '-1', onClick: createChainedFunction(onClick, this.handleClick) })) ); }; return MenuItem; }(React.Component); MenuItem.propTypes = propTypes; MenuItem.defaultProps = defaultProps; export default bsClass('dropdown', MenuItem);
packages/material-ui-icons/src/DesktopMac.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7l-2 3v1h8v-1l-2-3h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 12H3V4h18v10z" /></g> , 'DesktopMac');
src/components/pages/NotFoundPage.js
annamaz/pokedex
import React from 'react'; import {Link} from 'react-router'; const NotFoundPage = () => { return ( <div className="not-found-page"> <h4> 404 Page Not Found </h4> <Link to="/">Go back to homepage</Link> </div> ); }; export default NotFoundPage;
src/app/routes.js
Drathal/redux-playground
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from '../containers/App' import LayoutDashboard from '../components/LayoutDashboard' import LayoutMain from '../components/LayoutMain' import NotFound from '../components/NotFound' import ProductListContainer from '../containers/ProductListContainer' export default ( <Route component={ App }> { /* LayoutMain */ } <Route path="/" component={ LayoutMain }> <IndexRoute component={ ProductListContainer } /> <Route path="products" component={ ProductListContainer } /> </Route> { /* LayoutDashboard */ } <Route path="/dashboard" component={ LayoutDashboard }> <IndexRoute component={ ProductListContainer } /> <Route path="products" component={ ProductListContainer } /> </Route> { /* not found */ } <Route path="*" component={ NotFound } /> </Route> );
src/App.js
rbtpzk/react-redux-currency-xchange
import React, { Component } from 'react'; import './App.css'; import NumberInput from './Components/NumberInput' import { fetchData, swapThem, updateSettings } from "./Actions/dataActions" import { connect } from 'react-redux' import Button from './Components/Button'; import Dropdown from './Components/Dropdown'; import AllBalances from './Components/AllBalances' function mapStateToProps(state) { return { async: state.async, settings: state.settings, rates: state.rates, inputs: state.inputs, balances: state.balances, currencies: [ {label: "Euro", shortcode: "EUR"}, {label: "US Dollar", shortcode: "USD"}, {label: "British Pound", shortcode: "GBP"}, {label: "Polish Zloty", shortcode: "PLN"}, ], } } export function roundMe(num) { if (num === "") { return num } return Math.round(num * 100) / 100; } class App extends Component { constructor(props) { super(props) this.state = { inputs: { baseValue: '', resultValue: '' }, balances: props.balances, submitDisabled: false } this.isDisabled = this.props.isFetching === false && this.props.isError === false ? true : false } updateInput(event) { if (/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/.test(event.target.value) || event.target.value === "" || event.target.value.isNaN() !== true) { // console.log(event.target.value.replace(/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/)) this.setState({ inputs: { baseValue: parseFloat(event.target.value), resultValue: parseFloat(event.target.value * this.props.rates) } },() => { this.balanceValidation(this.state.balances, this.state.inputs.baseValue) }) } } updateResultInput(event) { if (/(?=.)^\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/.test(event.target.value) || event.target.value === "" || event.target.value.isNaN() !== true) { this.setState({ inputs: { baseValue: parseFloat(event.target.value / this.props.rates), resultValue: parseFloat(event.target.value) } },this.balanceValidation(this.state.balances, this.state.inputs.baseValue)) } } updateAppSettings(baseShortcode, resultShortcode) { this.props.dispatch(updateSettings(baseShortcode, resultShortcode)) } getRates() { this.props.dispatch(fetchData(this.props.settings.baseCurrency, this.props.settings.convertTo)) } // Fetch Data Method componentDidMount() { this.getRates(); setInterval(() => { this.getRates() },10000); // Fetch Data from API every 10s and refresh state. // this.props.subscribe((event) => { // console.log(event) // this.balanceValidation(this.state.balances); // }) } swapCurrencies() { this.props.dispatch( swapThem({...this.props.settings}) ) this.setState({ inputs: { baseValue: this.state.inputs.resultValue, resultValue: this.state.inputs.baseValue }},() => { this.props.dispatch(fetchData(this.props.settings.baseCurrency, this.props.settings.convertTo)) }) } refreshInputs() { this.setState({ inputs: { baseValue: this.state.inputs.baseValue, resultValue: this.state.inputs.baseValue * this.props.rates } },this.balanceValidation(this.state.balances, this.state.inputs.baseValue)) } // Balances balanceError(balances, base) { let current = balances.filter((item) => item.shortcode === this.props.settings.baseCurrency); console.log(current); const baseVal = base === "" || base === null || isNaN(base) ? 0 : Number(this.state.inputs.baseValue) // returns 0 if base is empty or baseValue[input] let check = Number(current[0].balance) - Number(baseVal) if (check < 0) { // console.log('disabled button') return true; } else { // console.log('enabled button') return false; } } balanceValidation(balances, base) { this.setState({ submitDisabled: this.balanceError(balances, base) }) } exChangeIt(inputs, settings) { // the final exchange method let postObj = this.state.balances this.props.dispatch({type: "UPDATE_WALLETS", payload: { balances: postObj, inputs, settings} }, // Dispatch Store change setTimeout(() => { this.setState({balances: [...this.props.balances]}) // Update local state from Store this.setState({inputs: { baseValue: '', resultValue: ''}}) // Reset Inputs },300) ) } render() { return ( <div className="App text-center"> <header> <div className="container"> <h5 className="main-title"> <i className="im im-coin"></i><span>Currency Exchange App</span> </h5> <h3 className="lead"> 1 {this.props.settings.baseCurrency} = {this.props.rates} {this.props.settings.convertTo} </h3> </div> </header> <AllBalances balances={this.state.balances} settings={this.props.settings} {...this.state.inputs} /> <br /> <div className="container"> <div className="col-sm-5"> <p className="small">From</p> <div className="col-xs-5 col-sm-4"> <Dropdown type="base" items={this.props.currencies} inputs={this.props.inputs} rates={this.props.rates} {...this.props.settings} updateAppSettings={this.updateAppSettings.bind(this)} refreshInputs={this.refreshInputs.bind(this)} /> </div> <div className="col-xs-7 col-sm-8"> <NumberInput type="base" rates={roundMe(this.props.rates)} value={roundMe(this.state.inputs.baseValue)} onChange={this.updateInput.bind(this)} /> </div> </div> <div className="col-sm-2"> <p><button onClick={this.swapCurrencies.bind(this)} title="Swap currencies" className="swap-them"><i className="fa fa-exchange" aria-hidden="true"></i></button></p> </div> <div className="col-sm-5"> <p className="small">To</p> <div className="col-xs-5 col-sm-4"> <Dropdown type="result" items={this.props.currencies} inputs={this.props.inputs} rates={this.props.rates} {...this.props.settings} updateAppSettings={this.updateAppSettings.bind(this)} refreshInputs={this.refreshInputs.bind(this)} /> </div> <div className="col-xs-7 col-sm-8"> <NumberInput type="result" rates={roundMe(this.props.rates)} value={roundMe(this.state.inputs.resultValue)} onChange={this.updateResultInput.bind(this)} /> </div> </div> <div className="col-sm-12"> <Button onClick={() => this.exChangeIt(this.state.inputs, this.props.settings)} className="exchange-btn" disabled={this.state.submitDisabled} label="Exchange" /> </div> <footer className="text-center"> <p className="small">icons by: <a href="http://iconmonstr.com">iconmonstr</a> — built with react/redux by <a href="http://github.com/rbtpzk">@rbtpzk</a></p> </footer> </div> </div> ); } } export default connect(mapStateToProps)(App)
packages/web/examples/mongo-examples/DataSearch/src/index.js
appbaseio/reactivesearch
import React from 'react'; import ReactDOM from 'react-dom'; import { ReactiveBase, DataSearch, ReactiveList, ResultCard, SelectedFilters, } from '@appbaseio/reactivesearch'; import './index.css'; const Main = () => ( <ReactiveBase enableAppbase app="default" url="https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/public-demo-skxjb/service/http_endpoint/incoming_webhook/reactivesearch" mongodb={{ db: 'sample_airbnb', collection: 'listingsAndReviews', }} > <div> <div> <DataSearch title="DataSearch" dataField={[ { field: 'name', weight: 3, }, { field: 'description', weight: 1, }, ]} componentId="search-component" URLParams size={5} /> </div> <div> <SelectedFilters /> <ReactiveList componentId="SearchResult" dataField="property_type" size={10} className="result-list-container" pagination react={{ and: 'search-component', }} render={({ data }) => ( <ReactiveList.ResultCardsWrapper> {data.map(item => ( <ResultCard id={item._id} key={item._id}> <ResultCard.Image src={item.images.picture_url} /> <ResultCard.Title> <div className="title" dangerouslySetInnerHTML={{ __html: item.name, }} /> </ResultCard.Title> <ResultCard.Description> <div className="flex column justify-space-between"> <div title={item.description} className="description"> ({item.description} ) </div> <div className="tag"> Accomodates <span>{item.accommodates}</span> </div> </div> </ResultCard.Description> </ResultCard> ))} </ReactiveList.ResultCardsWrapper> )} /> </div> </div> </ReactiveBase> ); export default Main; ReactDOM.render(<Main />, document.getElementById('root'));
src/components/Preview.js
rsamec/react-designer
import React from 'react'; import Binder from 'react-binding'; import _ from 'lodash'; import {HtmlPagesRenderer} from 'react-html-pages-renderer'; export default class Preview extends React.Component { constructor(props) { super(props); this.state = {data: _.cloneDeep(this.props.schema.props && this.props.schema.props.defaultData) || {}} } render() { var schema = _.cloneDeep(this.props.schema); var dataContext = Binder.bindToState(this, 'data'); var pageOptions = schema.props && schema.props.pageOptions || {width:794,height:1123}; return ( <div> <HtmlPagesRenderer widgets={this.props.widgets} schema={schema} dataContext={dataContext} pageOptions={pageOptions}/> </div> ); } }
packages/example-phone/src/scripts/containers/page-sections/call-page-header.js
good-joe/spark-js-sdk
import React from 'react'; import {connect} from 'react-redux'; import {PageHeader} from 'react-bootstrap'; function CallPageHeader({callStatus}) { return ( <PageHeader>Call Status: <small className="call-status">{callStatus}</small></PageHeader> ); } CallPageHeader.propTypes = { callStatus: React.PropTypes.string.isRequired }; export default connect( (state) => ({ callStatus: state.activeCall.status }) )(CallPageHeader);
src/containers/referrals/index.js
dylanlott/bridge-gui
import React, { Component } from 'react'; import { connect } from 'react-apollo'; import { hashHistory } from 'react-router'; import client from 'utils/api-client'; import gql from 'graphql-tag'; import { ReferralInfo, ReferralLink, SendReferralEmail } from '../../components'; import { isValidEmail } from '../../utils/validation'; import axios from 'axios'; const BILLING_URL = process.env.APOLLO_CLIENT_URL; const mapQueriesToProps = () => { return { marketingQuery: { query: gql`query { marketing { id, user, referralLink } }` } } }; const mapStateToProps = (state) => { return { user: state.localStorage.email } }; @connect({ mapQueriesToProps, mapStateToProps }) export default class Referrals extends Component { constructor(props) { super(props); this.state = { value: '', copied: false, valid: true, emailFailures: [], emailSuccesses: [] }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleCopy = this.handleCopy.bind(this); this.handleValidation = this.handleValidation.bind(this); } componentWillMount() { const props = this.props; const privkey = window.localStorage.getItem('privkey'); if (privkey) { client.api.getPublicKeys() .then(function success() { // TODO: Don't make unnecessary request (would be mo'bettah) props.marketingQuery.refetch(); return true; }, function fail() { hashHistory.push('/'); }); } else { hashHistory.push('/'); } } handleChange(event) { this.setState({ value: event.target.value }); this.handleValidation(event.target.value); } handleValidation(emails) { const list = emails.split(','); list.forEach((email) => { isValidEmail(email.trim()) ? this.setState({valid: true}) : this.setState({valid: false}) }); } handleSubmit(event) { event.preventDefault(); if (this.state.value) { const emailList = this.state.value .split(',').map((email) => email.trim()); axios.post(`${BILLING_URL}/referrals/sendReferralEmail`, { marketing: this.props.marketingQuery.marketing, emailList }).then((response) => { const failures = response.data.failures.map((failure, index) => { return <p key={index}>{failure.email} ({failure.message})</p>; }); const successes = response.data.successes.map((success, index) => { return <p key={index}>{success.email}</p>; }); this.setState({ value: '', emailSuccesses: successes, emailFailures: failures }); setTimeout(() => { this.setState({ emailSuccesses: [], emailFailures: [] }); }, 5000); }); } } handleCopy() { this.setState({ copied: true }) setTimeout(() => { this.setState({ copied: false }) }, 2000); } render () { let referralLink; const { marketing, loading } = this.props.marketingQuery; if (loading || !(marketing && marketing.referralLink)) { referralLink = 'Loading ...'; } else { referralLink = 'https://app.storj.io/#/signup?referralLink=' + marketing.referralLink; } return ( <section> <div className="container"> <ReferralInfo></ReferralInfo> <div className="row"> <SendReferralEmail handleSubmit={this.handleSubmit} handleChange={this.handleChange} value={this.state.value} valid={this.state.valid} emailFailures={this.state.emailFailures} emailSuccesses={this.state.emailSuccesses} > </SendReferralEmail> <ReferralLink referralLink={referralLink} handleCopy={this.handleCopy} copied={this.state.copied} > </ReferralLink> </div> </div> </section> ); } }
src/scripts/views/form/index.js
JanKuukkanen/Oauth-client-react
import page from 'page'; import React from 'react'; import Broadcaster from '../../components/broadcaster'; import FormData from '../../views/form/form-map'; import BroadcastAction from '../../actions/broadcast'; /** * */ export default React.createClass({ mixins: [ React.addons.LinkedStateMixin ], propTypes: { formProfile: React.PropTypes.string.isRequired, boardID: React.PropTypes.string, accessCode: React.PropTypes.string }, getInitialState() { return FormData.fieldNames.reduce((state, field) => { state[field] = ''; return state; }, {}); }, checkPasswords(){ if(this.props.formProfile === 'registerForm' && this.state.passwordAgain !== '') { return this.state.passwordAgain !== this.state.passwordRegister ? <span className="fa fa-times mismatch">Password mismatch!</span> : <span className="fa fa-check match">Passwords match!</span>; } }, renderFields(fields) { return fields.map((field, index) => { let controlattrs = { title: field.title, pattern: field.pattern, required: field.required } return ( <section key={field.name} className="input"> <label htmlFor={field.name}>{field.label}</label> <input autoFocus={index === 0} name={field.name} type={field.type} {...controlattrs} valueLink={this.linkState(field.name)} /> </section> ); }); }, //submit will execute in all cases other than when //passwords given in registration do not match. submitPrimary(currentForm, ...rest) { if(this.props.formProfile !== 'registerForm' || this.state.passwordAgain === this.state.passwordRegister) { let fields = currentForm.fields.reduce((fields, field) => { fields[field.name] = this.state[field.name]; return fields; }, {}); return (event) => { if(this.props.formProfile === 'registerForm') fields.password = fields.passwordRegister; let submitParams = [ fields ].concat(rest); currentForm.submit.apply(null, submitParams); return event.preventDefault(); } } else return (event) => { BroadcastAction.add({ type: 'Error', content: 'Passwords entered do not match!' }); return event.preventDefault(); } }, submitSecondary(currentForm) { return (event) => { currentForm.secondary.submit(this.state); return event.preventDefault(); } }, renderForm(formType) { let secondaryContent = !formType.secondary ? null : ( <section className="secondary"> <p>{formType.secondary.description}</p> <button className="btn-secondary" onClick={this.submitSecondary(formType)}> {formType.secondary.action} </button> </section> ); return ( <div className="view view-form"> <Broadcaster /> <div className="content"> <form className="form" onSubmit={this.submitPrimary(formType, this.props.boardID, this.props.accessCode)}> <div className="logo"> <img src="/dist/assets/img/logo.svg" /> <h1>Contriboard</h1> </div> {this.renderFields(formType.fields)} {this.checkPasswords()} <input type="submit" className="btn-primary" value={formType.action} /> <article className="help">{formType.help}</article> <section className="secondary-content"> {secondaryContent} </section> </form> </div> </div> ); }, render() { return this.renderForm(FormData[this.props.formProfile]); } });
renderer/components/Icon/Plus.js
LN-Zap/zap-desktop
import React from 'react' const SvgPlus = props => ( <svg className="plus_svg__feather plus_svg__feather-plus" fill="none" height="1em" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} viewBox="0 0 24 24" width="1em" {...props} > <path d="M12 5v14M5 12h14" /> </svg> ) export default SvgPlus
website/src/PhoneGraphic.js
half-shell/react-navigation
import React, { Component } from 'react'; export default class PhoneGraphic extends Component { props: { sources: { android: string, iphone: string } }; state = { activeExample: this.props.alt ? 'android' : 'iphone' }; render() { const {activeExample} = this.state; return ( <div className="example-section"> <div className="buttonbar"> <a className={activeExample === 'android'} onClick={() => this.setState({ activeExample: 'android' })}> Android </a> <a className={activeExample === 'iphone'} onClick={() => this.setState({ activeExample: 'iphone' })}> iPhone </a> </div> <div className="phone"> <div className={`android ${activeExample === 'android'}`}> <img src={this.props.sources.android} role="presentation" /> </div> <div className="phone-example-spacer" /> <div className={`iphone ${activeExample === 'iphone'}`}> <img src={this.props.sources.iphone} role="presentation" /> </div> </div> </div> ); } }
client/node_modules/react-error-overlay/lib/index.js
bourdakos1/Visual-Recognition-Tool
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import ReactDOM from 'react-dom'; import CompileErrorContainer from './containers/CompileErrorContainer'; import RuntimeErrorContainer from './containers/RuntimeErrorContainer'; import { listenToRuntimeErrors } from './listenToRuntimeErrors'; import { iframeStyle, overlayStyle } from './styles'; import { applyStyles } from './utils/dom/css'; var iframe = null; var isLoadingIframe = false; var renderedElement = null; var currentBuildError = null; var currentRuntimeErrorRecords = []; var currentRuntimeErrorOptions = null; var stopListeningToRuntimeErrors = null; export function reportBuildError(error) { currentBuildError = error; update(); } export function dismissBuildError() { currentBuildError = null; update(); } export function startReportingRuntimeErrors(options) { if (stopListeningToRuntimeErrors !== null) { throw new Error('Already listening'); } currentRuntimeErrorOptions = options; listenToRuntimeErrors(function (errorRecord) { try { if (typeof options.onError === 'function') { options.onError.call(null); } } finally { handleRuntimeError(errorRecord); } }, options.filename); } function handleRuntimeError(errorRecord) { if (currentRuntimeErrorRecords.some(function (_ref) { var error = _ref.error; return error === errorRecord.error; })) { // Deduplicate identical errors. // This fixes https://github.com/facebookincubator/create-react-app/issues/3011. return; } currentRuntimeErrorRecords = currentRuntimeErrorRecords.concat([errorRecord]); update(); } function dismissRuntimeErrors() { currentRuntimeErrorRecords = []; update(); } export function stopReportingRuntimeErrors() { if (stopListeningToRuntimeErrors === null) { throw new Error('Not currently listening'); } currentRuntimeErrorOptions = null; try { stopListeningToRuntimeErrors(); } finally { stopListeningToRuntimeErrors = null; } } function update() { renderedElement = render(); // Loading iframe can be either sync or async depending on the browser. if (isLoadingIframe) { // Iframe is loading. // First render will happen soon--don't need to do anything. return; } if (iframe) { // Iframe has already loaded. // Just update it. updateIframeContent(); return; } // We need to schedule the first render. isLoadingIframe = true; var loadingIframe = window.document.createElement('iframe'); applyStyles(loadingIframe, iframeStyle); loadingIframe.onload = function () { var iframeDocument = loadingIframe.contentDocument; if (iframeDocument != null && iframeDocument.body != null) { iframeDocument.body.style.margin = '0'; // Keep popup within body boundaries for iOS Safari iframeDocument.body.style['max-width'] = '100vw'; var iframeRoot = iframeDocument.createElement('div'); applyStyles(iframeRoot, overlayStyle); iframeDocument.body.appendChild(iframeRoot); // Ready! Now we can update the UI. iframe = loadingIframe; isLoadingIframe = false; updateIframeContent(); } }; var appDocument = window.document; appDocument.body.appendChild(loadingIframe); } function render() { if (currentBuildError) { return React.createElement(CompileErrorContainer, { error: currentBuildError }); } if (currentRuntimeErrorRecords.length > 0) { if (!currentRuntimeErrorOptions) { throw new Error('Expected options to be injected.'); } return React.createElement(RuntimeErrorContainer, { errorRecords: currentRuntimeErrorRecords, close: dismissRuntimeErrors, launchEditorEndpoint: currentRuntimeErrorOptions.launchEditorEndpoint }); } return null; } function updateIframeContent() { if (iframe === null) { throw new Error('Iframe has not been created yet.'); } var iframeBody = iframe.contentDocument.body; if (!iframeBody) { throw new Error('Expected iframe to have a body.'); } var iframeRoot = iframeBody.firstChild; if (renderedElement === null) { // Destroy iframe and force it to be recreated on next error window.document.body.removeChild(iframe); ReactDOM.unmountComponentAtNode(iframeRoot); iframe = null; return; } // Update the overlay ReactDOM.render(renderedElement, iframeRoot); }
blueocean-material-icons/src/js/components/svg-icons/maps/local-phone.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const MapsLocalPhone = (props) => ( <SvgIcon {...props}> <path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/> </SvgIcon> ); MapsLocalPhone.displayName = 'MapsLocalPhone'; MapsLocalPhone.muiName = 'SvgIcon'; export default MapsLocalPhone;
src/components/Feedback/Feedback.js
bmatthews/haze-lea
/** * 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 withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Feedback.css'; const facebook = require('react-icons/lib/fa/facebook'); const instagram = require('react-icons/lib/fa/instagram'); class Feedback extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <h4 className={s.contactMe}>Contact me:</h4> <div className={s.contactDetailsWrapper}> <dl className={s.contactDetails}> <dt>e.</dt> <dd> <a className={s.link} href="mailto:hello@hazelea.co.uk"> hello@hazelea.co.uk </a> </dd> <dt>t.</dt> <dd> <a className={s.link} href="tel:+447598 835 544"> 07598 835 544 </a> </dd> </dl> <hr /> <h4 className={s.contactMe}>Lets be friends</h4> <a href="https://www.facebook.com/hazeleafloraldesign/"> {React.createElement(facebook, null)} </a> <a href="https://www.instagram.com/hazelea_designs/"> {React.createElement(instagram, null)} </a> </div> </div> </div> ); } } export default withStyles(s)(Feedback);
app/javascript/mastodon/features/account_timeline/index.js
hyuki0000/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { fetchAccount } from '../../actions/accounts'; import { refreshAccountTimeline, expandAccountTimeline } from '../../actions/timelines'; import StatusList from '../../components/status_list'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import HeaderContainer from './containers/header_container'; import ColumnBackButton from '../../components/column_back_button'; import { List as ImmutableList } from 'immutable'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ statusIds: state.getIn(['timelines', `account:${Number(props.params.accountId)}`, 'items'], ImmutableList()), isLoading: state.getIn(['timelines', `account:${Number(props.params.accountId)}`, 'isLoading']), hasMore: !!state.getIn(['timelines', `account:${Number(props.params.accountId)}`, 'next']), me: state.getIn(['meta', 'me']), }); @connect(mapStateToProps) export default class AccountTimeline extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, statusIds: ImmutablePropTypes.list, isLoading: PropTypes.bool, hasMore: PropTypes.bool, me: PropTypes.number.isRequired, }; componentWillMount () { this.props.dispatch(fetchAccount(Number(this.props.params.accountId))); this.props.dispatch(refreshAccountTimeline(Number(this.props.params.accountId))); } componentWillReceiveProps (nextProps) { if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) { this.props.dispatch(fetchAccount(Number(nextProps.params.accountId))); this.props.dispatch(refreshAccountTimeline(Number(nextProps.params.accountId))); } } handleScrollToBottom = () => { if (!this.props.isLoading && this.props.hasMore) { this.props.dispatch(expandAccountTimeline(Number(this.props.params.accountId))); } } render () { const { statusIds, isLoading, hasMore, me } = this.props; if (!statusIds && isLoading) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column> <ColumnBackButton /> <StatusList prepend={<HeaderContainer accountId={this.props.params.accountId} />} scrollKey='account_timeline' statusIds={statusIds} isLoading={isLoading} hasMore={hasMore} me={me} onScrollToBottom={this.handleScrollToBottom} /> </Column> ); } }
Realization/frontend/czechidm-core/src/components/advanced/Form/EavForm.js
bcvsolutions/CzechIdMng
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import _ from 'lodash'; // import * as Basic from '../../basic'; import * as Utils from '../../../utils'; import { FormAttributeManager } from '../../../redux'; import FormInstance from '../../../domain/FormInstance'; // const attributeManager = new FormAttributeManager(); /** * Content of eav form by given form instance (= form definition + form values). * * @author Radek Tomiška */ export default class EavForm extends Basic.AbstractContextComponent { /** * Return component identifier, with can be used in localization etc. * * @return {string} component identifier */ getComponentKey() { return 'component.advanced.EavForm'; } /** * Returns true, when form is valid, otherwise false * * @return {Boolean} [description] */ isValid() { const { formInstance } = this.props; let isAllValid = true; let firstInvalidComponent = null; formInstance.getAttributes().forEach(attribute => { const formComponent = this.refs[attribute.code]; if (!formComponent) { // unsupported persistentType return true; } // we need to call validate method on all component (break is not needed) if (!formComponent.isValid()) { isAllValid = false; if (!firstInvalidComponent) { firstInvalidComponent = formComponent; } return false; } return true; }); // if (firstInvalidComponent) { firstInvalidComponent.focus(); // all eav renderers supports focus } // return isAllValid; } /** * Focus form. * * @param {string} [attributeCode=null] attribute by given code ~ ref is focused or the first form attribute by default * @since 10.7.0 */ focus(attributeCode = null) { const { formInstance } = this.props; let formComponent = null; // if (attributeCode) { formComponent = this.refs[attributeCode]; } else { for (const attribute of formInstance.getAttributes()) { formComponent = this.refs[attribute.code]; if (formComponent) { break; } } } // if (formComponent) { formComponent.focus(); return true; } // component not found return false; } /** * Return form definition used for form instance * * @return {formDefinition} */ getFormDefinition() { const { formInstance } = this.props; // if (!formInstance) { return null; } return formInstance.getDefinition(); } /** * Returns array of filled form values (form value object) * * @return {arrayOf(formValue)} */ getValues() { const { formInstance } = this.props; let filledFormValues = []; // formInstance.getAttributes().forEach(attribute => { if (attribute.readonly) { // readOnly (~ disabled from our point of view) attributes are not sent to BE return true; } const formComponent = this.refs[attribute.code]; if (!formComponent) { // unsupported persistentType return true; } const values = formComponent.getValues(); if (values === undefined) { // values are not controlled return true; } filledFormValues = filledFormValues.concat(values); return true; }); return filledFormValues; } /** * Returns filled values as properties object (ConfigurationMap on BE is preferred) * * TODO: multiple properties * * @return {object} [description] */ getProperties() { const formInstance = new FormInstance(this.props.formInstance.getDefinition(), this.getValues()); // return formInstance.getProperties(); } getInvalidFormAttributes(validationErrors, code, formInstance) { if (!validationErrors) { return []; } // return validationErrors .filter(attribute => { // by attribute code return attribute.attributeCode === code; }) .filter(attribute => { // by owner id if (!formInstance || !formInstance.getOwnerId() || !attribute.ownerId) { // backward compatible return true; } // return formInstance.getOwnerId() === attribute.ownerId; }); } render() { const { formInstance, rendered, showLoading, readOnly, useDefaultValue, validationErrors, formableManager, showAttributes, formValidations, condensed, className } = this.props; // if (!rendered || !formInstance) { return null; } // if (showLoading) { return ( <Basic.Loading isStatic showLoading/> ); } if (formInstance.getAttributes().size === 0) { return ( <Basic.Alert level="info" text={ this.i18n('attributes.empty') } className="no-margin" rendered={ !showAttributes && !condensed }/> ); } // return ( <span className={ classnames( { 'eav-form': true, condensed }, className ) }> { [...formInstance.getAttributes().map(attribute => { if (showAttributes && showAttributes.size > 0 && !showAttributes.has(attribute.code) && !showAttributes.has(attribute.id)) { return null; } // const values = formInstance.getValues(attribute.code); const filledValues = !values ? [] : values.filter(value => !Utils.Ui.isEmpty(value.value)); if (filledValues.length === 0 && condensed) { return null; } const component = attributeManager.getFormComponent(attribute); if (!component) { if (condensed) { return ( <Basic.LabelWrapper label={ attribute.code } > { filledValues.map(value => Utils.Ui.toStringValue(value.value)).join(', ') } </Basic.LabelWrapper> ); } return ( <Basic.LabelWrapper label={attribute.name}> <Basic.Alert level="warning" text={ this.i18n('persistentType.unsupported.title', { name: attribute.persistentType, face: attribute.faceType }) } className="no-margin"/> </Basic.LabelWrapper> ); } // // apply overridden form Validations and setting const _finalAttribute = _.merge({}, attribute); if (formValidations) { try { const _overridenAttribute = JSON .parse(formValidations) .find(a => a.id === attribute.id); if (_overridenAttribute) { _finalAttribute.readonly = _overridenAttribute.readonly; _finalAttribute.required = _overridenAttribute.required; if (_overridenAttribute.placeholder) { _finalAttribute.placeholder = _overridenAttribute.placeholder; } if (_overridenAttribute.label) { _finalAttribute.name = _overridenAttribute.label; } if (_overridenAttribute.min) { _finalAttribute.min = _overridenAttribute.min; } if (_overridenAttribute.max) { _finalAttribute.max = _overridenAttribute.max; } if (_overridenAttribute.regex) { _finalAttribute.regex = _overridenAttribute.regex; } if (_overridenAttribute.validationMessage) { _finalAttribute.validationMessage = _overridenAttribute.validationMessage; } // // set overridden attribute back into form instance definition => used in validations formInstance.setAttribute(_finalAttribute); } } catch (syntaxError) { // nothing - attribute will not be overriden } } // const FormValueComponent = component.component; const ManagerType = component.manager; // return ( <FormValueComponent ref={ attribute.code } uiKey={ `form-attribute-${ attribute.code }` } formDefinition={ this.getFormDefinition() } attribute={ _finalAttribute } values={ values } readOnly={ readOnly } useDefaultValue={ useDefaultValue } manager={ ManagerType ? new ManagerType() : null } validationErrors={ this.getInvalidFormAttributes(validationErrors || formInstance.validationErrors, attribute.code, formInstance) } className={ !showAttributes && formInstance.getAttributes().last().id === attribute.id ? 'last' : '' } formableManager={ formableManager } component={ component }/> ); }).values()] } </span> ); } } EavForm.propTypes = { ...Basic.AbstractContextComponent.propTypes, /** * FormInstance (definition + values) */ formInstance: PropTypes.object, /** * Manager controlls owners extended attributes, e.g. identityManager, roleManager. * Enable additional features, which depends on concrete manager (e.g. download attachment). * When manager is not given, features are disabled. */ formableManager: PropTypes.object, /** * ReadOnly form */ readOnly: PropTypes.bool, /** * Use default value as filled value */ useDefaultValue: PropTypes.bool, /** * List of InvalidFormAttributeDto */ validationErrors: PropTypes.arrayOf(PropTypes.object), /** * Render given attributes only. Render all atributes otherwise. */ showAttributes: PropTypes.arrayOf(PropTypes.string), /** * Overriden attributes validations and settings * * @since 12.0.0 */ formValidations: PropTypes.arrayOf(PropTypes.object), /** * Condensed (shorten) form properties - usable in tables. Just filled values without help will be shown. */ condensed: PropTypes.bool }; EavForm.defaultProps = { ...Basic.AbstractContextComponent.defaultProps, formInstance: null, readOnly: false, useDefaultValue: false, condensed: false };
src/main.js
Mrancois/barduino
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-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 'babel-polyfill'; import 'whatwg-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import FastClick from 'fastclick'; import { Provider } from 'react-redux'; import store from './store'; import router from './router'; import history from './history'; let routes = require('./routes.json').default; // Loaded with utils/routes-loader.js const container = document.getElementById('container'); function renderComponent(component) { ReactDOM.render(<Provider store={store}>{component}</Provider>, container); } // Find and render a web page matching the current URL path, // if such page is not found then render an error page (see routes.json, core/router.js) function render(location) { router.resolve(routes, location) .then(renderComponent) .catch(error => router.resolve(routes, { ...location, error }).then(renderComponent)); } // Handle client-side navigation by using HTML5 History API // For more information visit https://github.com/ReactJSTraining/history/tree/master/docs#readme history.listen(render); render(history.location); // Eliminates the 300ms delay between a physical tap // and the firing of a click event on mobile browsers // https://github.com/ftlabs/fastclick FastClick.attach(document.body); // Enable Hot Module Replacement (HMR) if (module.hot) { module.hot.accept('./routes.json', () => { routes = require('./routes.json').default; // eslint-disable-line global-require render(history.location); }); }
app/components/NewRecipeDialog.js
tempestaddepvc/proyecto-electron
import React from 'react'; import axios from "axios"; import Dialog from 'material-ui/Dialog'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; import AppBar from 'material-ui/AppBar'; import IconButton from 'material-ui/IconButton'; import Divider from 'material-ui/Divider' import Steps from './Steps' import FavoriteIcon from './FavoriteIcon' import getMuiTheme from 'material-ui/styles/getMuiTheme'; import TextField from 'material-ui/TextField'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import InputQuantity from "./InputQuantity" import FloatingActionButton from 'material-ui/FloatingActionButton'; import ContentAdd from 'material-ui/svg-icons/content/add'; import InputSteps from './InputSteps' import FlatButton from 'material-ui/FlatButton'; import RaisedButton from 'material-ui/RaisedButton'; import querystring from 'querystring'; import UserStore from '../stores/UserStore'; const muiTheme = getMuiTheme(); /** * A modal dialog can only be closed by selecting one of the actions. */ export default class NewRecipeDialog extends React.Component { constructor(props) { super(props); this.state = { file: 'a', imagePreviewUrl: '', value: 1, allIngredients: [], quantities: [0], steps: [0], }; }; updateAllIngredients = (ingredients) => { for (let ingredient of ingredients) { this.state.allIngredients.push(ingredient.name) } console.log(this.state.allIngredients); }; componentWillMount(){ var self=this; axios.get('http://52.31.144.145/api/v1/ingredients').then(function (response){ console.log("Ingredientes"); console.log(response.data.message); self.updateAllIngredients(response.data.message); }).catch(function (response) { console.log('problemitas con los ingredientes'); }); } _handleSubmit(e) { e.preventDefault(); // TODO: do something with -> this.state.file console.log('handle uploading-', this.state.file); } _handleImageChange(e) { e.preventDefault(); let reader = new FileReader(); let file = e.target.files[0]; reader.onloadend = () => { this.setState({ file: file, imagePreviewUrl: reader.result }); } reader.readAsDataURL(file) } handleChange = (event, index, value) => this.setState({value}); appendQuantityInput() { this.setState({ quantities: this.state.quantities.concat([Date.now()]) }); } deleteQuantityInput(number){ var index=this.state.quantities.indexOf(number); this.state.quantities.splice(index,1); this.setState({ quantities:this.state.quantities }) console.log("Quantities despues de eliminar"); console.log(this.state.quantities); } appendStepInput() { this.setState({ steps: this.state.steps.concat([Date.now()]) }); } deleteStepInput(number){ var index=this.state.steps.indexOf(number); this.state.steps.splice(index,1); this.setState({ steps:this.state.steps }) console.log("Steps despues de eliminar"); console.log(this.state.steps); } uploadRecipe(){ var json = {}; json.name=this.refs.name.getValue(); json.details=this.refs.details.getValue(); json.time=Number(this.refs.time.getValue()); json.diners=Number(this.refs.diners.getValue()); json.difficulty=this.state.value; json.quantities=[]; json.steps=[]; console.log(this.refs) if (this.state.file=='a') { json.picture=""; }else{ var data = new FormData(); data.append('image',this.state.file) axios.post('https://api.imgur.com/3/image',data,{ headers:{ authorization:"Client-ID 78af42f7d86086c" } } ).then(function(response){ json.picture=(response.data.data.link); }).catch(function(response){ console.log(response); }) } for (let component of Object.keys(this.refs).map(key => this.refs[key])) { if(Object.getPrototypeOf(component) == InputQuantity.prototype){ json.quantities.push({ name:component.refs.name.getValue(), cant:component.refs.cant.getValue(), measure:component.refs.measure.getValue(), }) } else if(Object.getPrototypeOf(component) == InputSteps.prototype){ json.steps.push({ step: component.refs.step.getValue(), picture:"" }) } } var self=this; setTimeout(function(){ console.log(JSON.stringify(json)); axios.post('http://52.31.144.145/api/v1/recipes',querystring.stringify( { recipe: JSON.stringify(json), }),{ headers:{ authorization:UserStore.getApiKey() } } ).then(function(response){ console.log('FUNSIONA WEON') self.handleClose(); }).catch(function(response){ console.log('Casi funciona el createRecipe,pero no'); console.log(json); console.log(response); }) }, 3000); } sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } } handleClose(){ this.props.handleClose(); this.state = { file: 'a', imagePreviewUrl: '', value: 1, allIngredients: [], quantities: "", steps: "", } this.state = { file: 'a', imagePreviewUrl: '', value: 1, allIngredients: [], quantities: [0], steps: [0], } } render() { const inputsQuantities=this.state.quantities.map(quantity => <InputQuantity key={quantity} id={quantity} ref={'quantity'+quantity} deleteQuantityInput={this.deleteQuantityInput.bind(this)} allIngredients={this.state.allIngredients}/>) const inputsSteps=this.state.steps.map(step => <InputSteps key={step} id={step} ref={'step'+ step} deleteStepInput={this.deleteStepInput.bind(this)}/>) let { imagePreviewUrl } = this.state; let $imagePreview = null; if (imagePreviewUrl) { $imagePreview = (<img src={imagePreviewUrl} style={{ maxWidth:'100%', maxHeight:'100%', margin: 'auto', display: 'block', }}/>); } else { $imagePreview = (<div >Please select an image for the recipe</div>); } const styleDiv = { textAlign: 'center', marginTop: '10px', display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px' } return ( <Dialog modal={true} open={this.props.isOpen} autoScrollBodyContent={true} > <AppBar style={{ position:'absolute', top: 0, left: 0, }} title={'New Recipe'} iconElementLeft={<a></a>} iconElementRight={ <IconButton onTouchTap={this.handleClose.bind(this)}><NavigationClose /></IconButton> } /> <div style={{ textAlign:'center', }}> <TextField style={{ marginTop: '40px', }} ref='name' maxLength="45" hintText="Recipe name" floatingLabelText="Recipe Name" /> <div style={{ marginTop:'20px' }}> <form onSubmit={(e)=>this._handleSubmit(e)}> <input className="fileInput" type="file" onChange={(e)=>this._handleImageChange(e)} /> </form> <div className="imgPreview"> {$imagePreview} </div> </div> </div> <div style={{ textAlign:'center', }}> <TextField style={{ marginTop: '10px', }} ref='details' maxLength="45" hintText="Recipe description" floatingLabelText="Recipe description" /> </div> <div style={styleDiv}> <TextField ref='time' type='number' maxLength="10" hintText="Time(in minutes)" floatingLabelText="Time(in minutes)" inputStyle={{ textAlign: 'right' }} style={{ width: '125px', }} /> <SelectField ref='difficulty' value={this.state.value} onChange={this.handleChange} floatingLabelText='Difficulty' style={{ width: '125px', }}> <MenuItem value={0} primaryText="Easy" /> <MenuItem value={1} primaryText="Medium" /> <MenuItem value={2} primaryText="Hard" /> </SelectField> <TextField ref='diners' type='number' maxLength="10" hintText="Diners number" floatingLabelText="Diners number" inputStyle={{ textAlign: 'right' }} style={{ width: '125px', }} /> </div> <h4 style={{textAlign:'center',marginTop:'50px'}}>Ingredients</h4> {inputsQuantities} <FloatingActionButton mini={true} onTouchTap={this.appendQuantityInput.bind(this)} style={{ marginTop:'10px', marginBottom:'10px', marginLeft:'10px' }}> <ContentAdd /> </FloatingActionButton> <h4 style={{textAlign:'center'}}>Directions</h4> {inputsSteps} <FloatingActionButton mini={true} onTouchTap={this.appendStepInput.bind(this)} style={{ marginTop:'10px', marginBottom:'10px', marginLeft:'10px' }}><ContentAdd /> </FloatingActionButton> <br/> <div style={{textAlign:"center"}}> <FlatButton label="Submit" primary={true} keyboardFocused={true} onTouchTap={this.uploadRecipe.bind(this)} /> </div> </Dialog> ); } }
public/js/components/chat/tabs1.react.js
MadushikaPerera/Coupley
import React from 'react'; import List from 'material-ui/lib/lists/list'; import ListItem from 'material-ui/lib/lists/list-item'; import TextField from 'material-ui/lib/text-field'; import Divider from 'material-ui/lib/divider'; import IconButton from 'material-ui/lib/icon-button'; import Tabs from 'material-ui/lib/tabs/tabs'; import Tab from 'material-ui/lib/tabs/tab'; import Slider from 'material-ui/lib/slider'; import Dialog from 'material-ui/lib/dialog'; import FlatButton from 'material-ui/lib/flat-button'; import RaisedButton from 'material-ui/lib/raised-button'; import PreviousChat from './ChatPrevious.react'; import ThreadActions from '../../actions/Thread/ThreadActions'; import ThreadStore from '../../stores/ThreadStore'; import LoginStore from '../../stores/LoginStore'; var SearchCeck = true; const ListStyle = { width: 300, height:635, }; const searchconvo = { marginTop:'-18', paddingLeft:20, }; const initMessagges = { user1:LoginStore.getUsername(), }; function validateStatusText(textStatus) { if (textStatus.length > 250) { return { error: '*search is too long', }; } else if (textStatus.length == 0) { console.log('empty'); return { error: '*search cannot be empty', }; } else { return true; } }; const PreviousChatContainer = React.createClass({ handleOpen: function () { this.setState({ open: true }); }, handleClose: function () { this.setState({ open: false }); }, getInitialState: function () { return { results:ThreadStore.getpreviousmessage(initMessagges), statusText: '', value: 'a', open: false, }; }, componentDidMount: function () { ThreadStore.addChangeListener(this._onChange); ThreadActions.getpreviousmessage(initMessagges); }, handleChange:function (event, index, value) { this.setState({ value: event, }); }, _onChange: function () { if (SearchCeck) { this.setState({ results:ThreadStore.getpreviousmessage(initMessagges) }); } else if (!SearchCeck) { this.setState({ results:ThreadStore.getsearchconv() }); } }, previousMList: function () { return this.state.results.map((result) => { return (<PreviousChat key={result.id} id={result.thread_id} firstname={result.firstname} message={result.message} created_at={result.created_at}/>); }); }, SearchConv:function () { let ThisUser = this.refs.SearchM.getValue(); let ToSearch = { user1:LoginStore.getUsername(), user2:ThisUser, }; if (validateStatusText(ThisUser).error) { console.log('menna error'); this.setState({ statusText: validateStatusText(ThisUser).error, }); val = false; } else { console.log('error na'); ThreadActions.getseachconv(ToSearch); SearchCeck = false; this.setState({ statusText: '', }); } {this.SearchResult();} {this.clearText();} }, clearText:function () { document.getElementById('SearchField').value = ''; }, EnterKey(e) { if (e.key === 'Enter') { console.log('enter una'); {this.SearchConv();} } }, SearchResult:function () { this.setState({ results:ThreadStore.getsearchconv() }); return this.state.results.map((result) => { return (<PreviousChat key={result.id} id={result.id} firstname={result.firstname} message={result.message} created_at={result.created_at}/>); }); }, render: function () { const actions = [ <FlatButton label="Cancel" secondary={true} onTouchTap={this.handleClose} />, <FlatButton label="Submit" primary={true} keyboardFocused={true} onTouchTap={this.handleClose} />, ]; return ( <List style={ListStyle} zDepth={1}> <Tabs> <Tab label="Conversations" > <div> <Divider inset={false} /> <TextField hintText="Username" floatingLabelText="Search Conversation" style={searchconvo} ref="SearchM" errorText={this.state.statusText} onKeyPress={this.EnterKey} id="SearchField"/> <Divider inset={false} /> <div> {this.previousMList()} </div> </div> </Tab> <Tab label="Message Request" > <div> <Divider inset={false} /> <TextField hintText="Username" floatingLabelText="Search Conversation" style={searchconvo} ref="SearchM" errorText={this.state.statusText} onKeyPress={this.EnterKey} id="SearchField"/> <Divider inset={false} /> <div> <div> <RaisedButton label="Dialog" onTouchTap={this.handleOpen} /> <Dialog title="Dialog With Actions" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose} > The actions in this window were passed in as an array of React objects. </Dialog> </div> </div> </div> </Tab> </Tabs> </List> ); }, }); export default PreviousChatContainer;
src/components/common/svg-icons/device/airplanemode-inactive.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAirplanemodeInactive = (props) => ( <SvgIcon {...props}> <path d="M13 9V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5v3.68l7.83 7.83L21 16v-2l-8-5zM3 5.27l4.99 4.99L2 14v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-3.73L18.73 21 20 19.73 4.27 4 3 5.27z"/> </SvgIcon> ); DeviceAirplanemodeInactive = pure(DeviceAirplanemodeInactive); DeviceAirplanemodeInactive.displayName = 'DeviceAirplanemodeInactive'; DeviceAirplanemodeInactive.muiName = 'SvgIcon'; export default DeviceAirplanemodeInactive;
docs/src/app/components/pages/get-started/Usage.js
pancho111203/material-ui
import React from 'react'; import Title from 'react-title-component'; import MarkdownElement from '../../MarkdownElement'; import usageText from './usage.md'; const Usage = () => ( <div> <Title render={(previousTitle) => `Usage - ${previousTitle}`} /> <MarkdownElement text={usageText} /> </div> ); export default Usage;
le-react-app/src/Components/Footer.js
TS000/react-app
import React, { Component } from 'react'; class Footer extends Component { render() { return ( <footer className="App-footer"> <h1 className="FooterText">I am the Footer!</h1> </footer> ); } } export default Footer;
geonode/monitoring/frontend/monitoring/src/components/cels/errors/index.js
tomkralidis/geonode
/* ######################################################################### # # Copyright (C) 2019 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import HoverPaper from '../../atoms/hover-paper'; import actions from '../../organisms/error-list/actions'; import styles from './styles'; import {withRouter} from 'react-router-dom'; const mapStateToProps = (state) => ({ errorList: state.errorList.response, interval: state.interval.interval, timestamp: state.interval.timestamp, }); @connect(mapStateToProps, actions) class Errors extends React.Component { static propTypes = { errorList: PropTypes.object, get: PropTypes.func.isRequired, interval: PropTypes.number, style: PropTypes.object, timestamp: PropTypes.instanceOf(Date), } constructor(props) { super(props); this.handleClick = () => { this.props.history.push('/errors'); }; this.get = (interval = this.props.interval) => { this.props.get(interval); }; } componentWillMount() { this.get(); } componentWillReceiveProps(nextProps) { if (nextProps) { if (nextProps.timestamp && nextProps.timestamp !== this.props.timestamp) { this.get(nextProps.interval); } } } render() { const errorNumber = this.props.errorList ? this.props.errorList.exceptions.length : 0; const extraStyle = errorNumber > 0 ? { backgroundColor: '#d12b2b', color: '#fff' } : {}; const style = { ...styles.content, ...this.props.style, ...extraStyle, }; return ( <HoverPaper style={style}> <div onClick={this.handleClick} style={styles.clickable}> <h3>Errors</h3> <span style={styles.stat}>{errorNumber} Errors occured</span> </div> </HoverPaper> ); } } export default withRouter(Errors);
app/react-icons/fa/circle-thin.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaCircleThin extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m20.1 5.7q-2.9 0-5.5 1.2t-4.6 3-3 4.6-1.1 5.5 1.1 5.5 3 4.6 4.6 3 5.5 1.2 5.6-1.2 4.5-3 3.1-4.6 1.1-5.5-1.1-5.5-3.1-4.6-4.5-3.1-5.6-1.1z m17.2 14.3q0 4.7-2.3 8.6t-6.3 6.2-8.6 2.3-8.6-2.3-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3 8.6 2.3 6.3 6.2 2.3 8.6z"/></g> </IconBase> ); } }
examples/huge-apps/components/GlobalNav.js
hgezim/react-router
import React from 'react'; import { Link } from 'react-router'; const styles = {}; class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } }; constructor (props, context) { super(props, context); this.logOut = this.logOut.bind(this); } logOut () { alert('log out'); } render () { var { user } = this.props; return ( <div style={styles.wrapper}> <div style={{float: 'left'}}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{float: 'right'}}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ); } } var dark = 'hsl(200, 20%, 20%)'; var light = '#fff'; styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light }; styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = Object.assign({}, styles.link, { background: light, color: dark }); export default GlobalNav;
examples/react-native-counter/index.js
6061960/react_native
import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; var Counter = React.createClass({ getInitialState: function() { return {counter: 0}; }, componentWillMount: function() { setInterval(this.minus, 1000, this); }, add: function() { let counter = this.state.counter; this.setState({counter: counter + 1}); }, minus: function() { let counter = this.state.counter; this.setState({counter: counter - 1}); }, render: function() { return ( <Text onPress={this.add}>{this.state.counter}</Text> ); } }); AppRegistry.registerComponent('Counter', () => Counter);
src/wallet/Transfer.js
ryanbaer/busy
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { injectIntl, FormattedMessage } from 'react-intl'; import steem from 'steem'; import steemConnect from 'sc2-sdk'; import { Form, Input, Radio, Modal } from 'antd'; import { closeTransfer } from './walletActions'; import { getIsAuthenticated, getAuthenticatedUser, getIsTransferVisible, getTransferTo } from '../reducers'; import './Transfer.less'; @injectIntl @connect(state => ({ visible: getIsTransferVisible(state), to: getTransferTo(state), authenticated: getIsAuthenticated(state), user: getAuthenticatedUser(state), }), { closeTransfer, }) @Form.create() export default class Transfer extends React.Component { static propTypes = { intl: PropTypes.shape().isRequired, visible: PropTypes.bool, to: PropTypes.string, authenticated: PropTypes.bool.isRequired, user: PropTypes.shape().isRequired, form: PropTypes.shape().isRequired, closeTransfer: PropTypes.func, }; static defaultProps = { to: '', visible: false, closeTransfer: () => {}, }; static amountRegex = /^[0-9]*\.?[0-9]{0,3}$/; state = { currency: 'STEEM', oldAmount: undefined, }; componentWillReceiveProps(nextProps) { const { form, to } = nextProps; if (this.props.to !== to) { form.setFieldsValue({ to, amount: undefined, currency: 'STEEM', memo: undefined, }); this.setState({ currency: 'STEEM', }); } } handleBalanceClick = (event) => { this.props.form.setFieldsValue({ amount: parseFloat(event.currentTarget.innerText), }); } handleCurrencyChange = (event) => { const { form } = this.props; this.setState({ currency: event.target.value }, () => form.validateFields(['amount'], { force: true })); }; handleContinueClick = () => { const { form } = this.props; form.validateFields({ force: true }, (errors, values) => { if (!errors) { const transferQuery = { to: values.to, amount: `${values.amount} ${values.currency}`, }; if (values.memo) transferQuery.memo = values.memo; const win = window.open(steemConnect.sign('transfer', transferQuery), '_blank'); win.focus(); this.props.closeTransfer(); } }); } handleCancelClick = () => this.props.closeTransfer(); handleAmountChange = (event) => { const { value } = event.target; const { oldAmount } = this.state; this.setState({ oldAmount: Transfer.amountRegex.test(value) ? value : oldAmount, }); this.props.form.setFieldsValue({ amount: Transfer.amountRegex.test(value) ? value : oldAmount, }); this.props.form.validateFields(['amount']); } validateUsername = (rule, value, callback) => { const { intl } = this.props; if (!value) { callback(); return; } steem.api.getAccounts([value], (err, result) => { if (result[0]) { callback(); } else { callback([ new Error(intl.formatMessage({ id: 'to_error_not_found_username', defaultMessage: "Couldn't find user with name {username}." }, { username: value, })), ]); } }); } validateBalance = (rule, value, callback) => { const { intl, authenticated, user } = this.props; const currentValue = parseFloat(value); if (value && currentValue <= 0) { callback([ new Error(intl.formatMessage({ id: 'amount_error_zero', defaultMessage: 'Amount has to be higher than 0.' })), ]); return; } const selectedBalance = this.state.currency === 'STEEM' ? user.balance : user.sbd_balance; if (authenticated && currentValue !== 0 && currentValue > parseFloat(selectedBalance)) { callback([ new Error(intl.formatMessage({ id: 'amount_error_funds', defaultMessage: 'Insufficient funds.' })), ]); } else { callback(); } } render() { const { intl, visible, authenticated, user } = this.props; const { getFieldDecorator } = this.props.form; const balance = this.state.currency === 'STEEM' ? user.balance : user.sbd_balance; const currencyPrefix = getFieldDecorator('currency', { initialValue: this.state.currency, })( <Radio.Group onChange={this.handleCurrencyChange}> <Radio.Button value="STEEM">STEEM</Radio.Button> <Radio.Button value="SBD">SBD</Radio.Button> </Radio.Group>, ); return ( <Modal visible={visible} title={intl.formatMessage({ id: 'transfer_modal_title', defaultMessage: 'Transfer funds' })} okText={intl.formatMessage({ id: 'continue', defaultMessage: 'Continue' })} cancelText={intl.formatMessage({ id: 'cancel', defaultMessage: 'Cancel' })} onOk={this.handleContinueClick} onCancel={this.handleCancelClick} > <Form className="Transfer container" hideRequiredMark> <Form.Item label={<FormattedMessage id="to" defaultMessage="To" />}> {getFieldDecorator('to', { rules: [ { required: true, message: intl.formatMessage({ id: 'to_error_empty', defaultMessage: 'Recipient is required.' }) }, { validator: this.validateUsername }, ], })(<Input type="text" placeholder={intl.formatMessage({ id: 'to_placeholder', defaultMessage: 'Payment recipient' })} />)} </Form.Item> <Form.Item label={<FormattedMessage id="amount" defaultMessage="Amount" />}> {getFieldDecorator('amount', { trigger: '', rules: [ { required: true, message: intl.formatMessage({ id: 'amount_error_empty', defaultMessage: 'Amount is required.' }) }, { pattern: Transfer.amountRegex, message: intl.formatMessage({ id: 'amount_error_format', defaultMessage: 'Incorrect format. Use comma or dot as decimal separator. Use at most 3 decimal places.', }), }, { validator: this.validateBalance }, ], })(<Input addonAfter={currencyPrefix} onChange={this.handleAmountChange} placeholder={intl.formatMessage({ id: 'amount_placeholder', defaultMessage: 'How much do you want to send' })} style={{ width: '100%' }} />)} {authenticated && <FormattedMessage id="balance_amount" defaultMessage="Your balance: {amount}" values={{ amount: <span role="presentation" onClick={this.handleBalanceClick} className="balance">{balance}</span>, }} />} </Form.Item> <Form.Item label={<FormattedMessage id="memo" defaultMessage="Memo" />}> {getFieldDecorator('memo')(<Input.TextArea autosize={{ minRows: 2, maxRows: 6 }} placeholder={intl.formatMessage({ id: 'memo_placeholder', defaultMessage: 'Additional message to include in this payment (optional)' })} />)} </Form.Item> </Form> <FormattedMessage id="transfer_modal_info" defaultMessage="Click the button below to be redirected to SteemConnect to complete your transaction." /> </Modal> ); } }
src/frontend/index.js
Tjorriemorrie/pokeraide
import React from 'react'; import ReactDOM from 'react-dom'; import {Router, Route, IndexRoute, browserHistory} from 'react-router'; import rootRoute from './views' ReactDOM.render( <Router routes={rootRoute} history={browserHistory} />, document.getElementById('app') );
Libraries/Components/MapView/MapView.js
mrspeaker/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule MapView * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const EdgeInsetsPropType = require('EdgeInsetsPropType'); const Image = require('Image'); const NativeMethodsMixin = require('react/lib/NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const StyleSheet = require('StyleSheet'); const View = require('View'); const deprecatedPropType = require('deprecatedPropType'); const processColor = require('processColor'); const resolveAssetSource = require('resolveAssetSource'); const requireNativeComponent = require('requireNativeComponent'); type Event = Object; /** * State an annotation on the map. */ export type AnnotationDragState = $Enum<{ /** * Annotation is not being touched. */ idle: string; /** * Annotation dragging has began. */ starting: string; /** * Annotation is being dragged. */ dragging: string; /** * Annotation dragging is being canceled. */ canceling: string; /** * Annotation dragging has ended. */ ending: string; }>; /** * **This component is only supported on iOS.** * * `MapView` is used to display embeddable maps and annotations using * `MKMapView`. * * For a cross-platform solution, check out * [react-native-maps](https://github.com/lelandrichardson/react-native-maps) * by Leland Richardson. * * ``` * import React, { Component } from 'react'; * import { MapView } from 'react-native'; * * class MapMyRide extends Component { * render() { * return ( * <MapView * style={{height: 200, margin: 40}} * showsUserLocation={true} * /> * ); * } * } * ``` * */ const MapView = React.createClass({ mixins: [NativeMethodsMixin], propTypes: { ...View.propTypes, /** * Used to style and layout the `MapView`. */ style: View.propTypes.style, /** * If `true` the app will ask for the user's location and display it on * the map. Default value is `false`. * * **NOTE**: You'll need to add the `NSLocationWhenInUseUsageDescription` * key in Info.plist to enable geolocation, otherwise it will fail silently. */ showsUserLocation: React.PropTypes.bool, /** * If `true` the map will follow the user's location whenever it changes. * Note that this has no effect unless `showsUserLocation` is enabled. * Default value is `true`. */ followUserLocation: React.PropTypes.bool, /** * If `false` points of interest won't be displayed on the map. * Default value is `true`. */ showsPointsOfInterest: React.PropTypes.bool, /** * If `false`, compass won't be displayed on the map. * Default value is `true`. */ showsCompass: React.PropTypes.bool, /** * If `false` the user won't be able to pinch/zoom the map. * Default value is `true`. */ zoomEnabled: React.PropTypes.bool, /** * When this property is set to `true` and a valid camera is associated with * the map, the camera's heading angle is used to rotate the plane of the * map around its center point. * * When this property is set to `false`, the * camera's heading angle is ignored and the map is always oriented so * that true north is situated at the top of the map view */ rotateEnabled: React.PropTypes.bool, /** * When this property is set to `true` and a valid camera is associated * with the map, the camera's pitch angle is used to tilt the plane * of the map. * * When this property is set to `false`, the camera's pitch * angle is ignored and the map is always displayed as if the user * is looking straight down onto it. */ pitchEnabled: React.PropTypes.bool, /** * If `false` the user won't be able to change the map region being displayed. * Default value is `true`. */ scrollEnabled: React.PropTypes.bool, /** * The map type to be displayed. * * - `standard`: Standard road map (default). * - `satellite`: Satellite view. * - `hybrid`: Satellite view with roads and points of interest overlaid. */ mapType: React.PropTypes.oneOf([ 'standard', 'satellite', 'hybrid', ]), /** * The region to be displayed by the map. * * The region is defined by the center coordinates and the span of * coordinates to display. */ region: React.PropTypes.shape({ /** * Coordinates for the center of the map. */ latitude: React.PropTypes.number.isRequired, longitude: React.PropTypes.number.isRequired, /** * Distance between the minimum and the maximum latitude/longitude * to be displayed. */ latitudeDelta: React.PropTypes.number, longitudeDelta: React.PropTypes.number, }), /** * Map annotations with title and subtitle. */ annotations: React.PropTypes.arrayOf(React.PropTypes.shape({ /** * The location of the annotation. */ latitude: React.PropTypes.number.isRequired, longitude: React.PropTypes.number.isRequired, /** * Whether the pin drop should be animated or not */ animateDrop: React.PropTypes.bool, /** * Whether the pin should be draggable or not */ draggable: React.PropTypes.bool, /** * Event that fires when the annotation drag state changes. */ onDragStateChange: React.PropTypes.func, /** * Event that fires when the annotation gets was tapped by the user * and the callout view was displayed. */ onFocus: React.PropTypes.func, /** * Event that fires when another annotation or the mapview itself * was tapped and a previously shown annotation will be closed. */ onBlur: React.PropTypes.func, /** * Annotation title and subtile. */ title: React.PropTypes.string, subtitle: React.PropTypes.string, /** * Callout views. */ leftCalloutView: React.PropTypes.element, rightCalloutView: React.PropTypes.element, detailCalloutView: React.PropTypes.element, /** * The pin color. This can be any valid color string, or you can use one * of the predefined PinColors constants. Applies to both standard pins * and custom pin images. * * Note that on iOS 8 and earlier, only the standard PinColor constants * are supported for regular pins. For custom pin images, any tintColor * value is supported on all iOS versions. */ tintColor: ColorPropType, /** * Custom pin image. This must be a static image resource inside the app. */ image: Image.propTypes.source, /** * Custom pin view. If set, this replaces the pin or custom pin image. */ view: React.PropTypes.element, /** * annotation id */ id: React.PropTypes.string, /** * Deprecated. Use the left/right/detailsCalloutView props instead. */ hasLeftCallout: deprecatedPropType( React.PropTypes.bool, 'Use `leftCalloutView` instead.' ), hasRightCallout: deprecatedPropType( React.PropTypes.bool, 'Use `rightCalloutView` instead.' ), onLeftCalloutPress: deprecatedPropType( React.PropTypes.func, 'Use `leftCalloutView` instead.' ), onRightCalloutPress: deprecatedPropType( React.PropTypes.func, 'Use `rightCalloutView` instead.' ), })), /** * Map overlays */ overlays: React.PropTypes.arrayOf(React.PropTypes.shape({ /** * Polyline coordinates */ coordinates: React.PropTypes.arrayOf(React.PropTypes.shape({ latitude: React.PropTypes.number.isRequired, longitude: React.PropTypes.number.isRequired })), /** * Line attributes */ lineWidth: React.PropTypes.number, strokeColor: ColorPropType, fillColor: ColorPropType, /** * Overlay id */ id: React.PropTypes.string })), /** * Maximum size of the area that can be displayed. */ maxDelta: React.PropTypes.number, /** * Minimum size of the area that can be displayed. */ minDelta: React.PropTypes.number, /** * Insets for the map's legal label, originally at bottom left of the map. */ legalLabelInsets: EdgeInsetsPropType, /** * Callback that is called continuously when the user is dragging the map. */ onRegionChange: React.PropTypes.func, /** * Callback that is called once, when the user is done moving the map. */ onRegionChangeComplete: React.PropTypes.func, /** * Deprecated. Use annotation `onFocus` and `onBlur` instead. */ onAnnotationPress: React.PropTypes.func, /** * @platform android */ active: React.PropTypes.bool, }, statics: { /** * Standard iOS MapView pin color constants, to be used with the * `annotation.tintColor` property. On iOS 8 and earlier these are the * only supported values when using regular pins. On iOS 9 and later * you are not obliged to use these, but they are useful for matching * the standard iOS look and feel. */ PinColors: { RED: '#ff3b30', GREEN: '#4cd964', PURPLE: '#c969e0', }, }, render: function() { let children = [], {annotations, overlays, followUserLocation} = this.props; annotations = annotations && annotations.map((annotation: Object) => { let { id, image, tintColor, view, leftCalloutView, rightCalloutView, detailCalloutView, } = annotation; if (!view && image && tintColor) { view = <Image style={{ tintColor: processColor(tintColor), }} source={image} />; image = undefined; } if (view) { if (image) { console.warn('`image` and `view` both set on annotation. Image will be ignored.'); } var viewIndex = children.length; children.push(React.cloneElement(view, { // $FlowFixMe - An array of styles should be fine style: [styles.annotationView, view.props.style || {}] })); } if (leftCalloutView) { var leftCalloutViewIndex = children.length; children.push(React.cloneElement(leftCalloutView, { style: [styles.calloutView, leftCalloutView.props.style || {}] })); } if (rightCalloutView) { var rightCalloutViewIndex = children.length; children.push(React.cloneElement(rightCalloutView, { style: [styles.calloutView, rightCalloutView.props.style || {}] })); } if (detailCalloutView) { var detailCalloutViewIndex = children.length; children.push(React.cloneElement(detailCalloutView, { style: [styles.calloutView, detailCalloutView.props.style || {}] })); } let result = { ...annotation, tintColor: tintColor && processColor(tintColor), image, viewIndex, leftCalloutViewIndex, rightCalloutViewIndex, detailCalloutViewIndex, view: undefined, leftCalloutView: undefined, rightCalloutView: undefined, detailCalloutView: undefined, }; result.id = id || encodeURIComponent(JSON.stringify(result)); result.image = image && resolveAssetSource(image); return result; }); overlays = overlays && overlays.map((overlay: Object) => { let {id, fillColor, strokeColor} = overlay; let result = { ...overlay, strokeColor: strokeColor && processColor(strokeColor), fillColor: fillColor && processColor(fillColor), }; result.id = id || encodeURIComponent(JSON.stringify(result)); return result; }); const findByAnnotationId = (annotationId: string) => { if (!annotations) { return null; } for (let i = 0, l = annotations.length; i < l; i++) { if (annotations[i].id === annotationId) { return annotations[i]; } } return null; }; // TODO: these should be separate events, to reduce bridge traffic let onPress, onAnnotationDragStateChange, onAnnotationFocus, onAnnotationBlur; if (annotations) { onPress = (event: Event) => { if (event.nativeEvent.action === 'annotation-click') { // TODO: Remove deprecated onAnnotationPress API call later. this.props.onAnnotationPress && this.props.onAnnotationPress(event.nativeEvent.annotation); } else if (event.nativeEvent.action === 'callout-click') { const annotation = findByAnnotationId(event.nativeEvent.annotationId); if (annotation) { // Pass the right function if (event.nativeEvent.side === 'left' && annotation.onLeftCalloutPress) { annotation.onLeftCalloutPress(event.nativeEvent); } else if (event.nativeEvent.side === 'right' && annotation.onRightCalloutPress) { annotation.onRightCalloutPress(event.nativeEvent); } } } }; onAnnotationDragStateChange = (event: Event) => { const annotation = findByAnnotationId(event.nativeEvent.annotationId); if (annotation) { // Call callback annotation.onDragStateChange && annotation.onDragStateChange(event.nativeEvent); } }; onAnnotationFocus = (event: Event) => { const annotation = findByAnnotationId(event.nativeEvent.annotationId); if (annotation && annotation.onFocus) { annotation.onFocus(event.nativeEvent); } }; onAnnotationBlur = (event: Event) => { const annotation = findByAnnotationId(event.nativeEvent.annotationId); if (annotation && annotation.onBlur) { annotation.onBlur(event.nativeEvent); } }; } // TODO: these should be separate events, to reduce bridge traffic if (this.props.onRegionChange || this.props.onRegionChangeComplete) { var onChange = (event: Event) => { if (event.nativeEvent.continuous) { this.props.onRegionChange && this.props.onRegionChange(event.nativeEvent.region); } else { this.props.onRegionChangeComplete && this.props.onRegionChangeComplete(event.nativeEvent.region); } }; } // followUserLocation defaults to true if showUserLocation is set if (followUserLocation === undefined) { followUserLocation = this.props.showUserLocation; } return ( <RCTMap {...this.props} annotations={annotations} children={children} followUserLocation={followUserLocation} overlays={overlays} onPress={onPress} onChange={onChange} onAnnotationDragStateChange={onAnnotationDragStateChange} onAnnotationFocus={onAnnotationFocus} onAnnotationBlur={onAnnotationBlur} /> ); }, }); const styles = StyleSheet.create({ annotationView: { position: 'absolute', backgroundColor: 'transparent', }, calloutView: { position: 'absolute', backgroundColor: 'white', }, }); const RCTMap = requireNativeComponent('RCTMap', MapView, { nativeOnly: { onAnnotationDragStateChange: true, onAnnotationFocus: true, onAnnotationBlur: true, onChange: true, onPress: true } }); module.exports = MapView;
src/svg-icons/image/filter-none.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterNone = (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 16H7V3h14v14z"/> </SvgIcon> ); ImageFilterNone = pure(ImageFilterNone); ImageFilterNone.displayName = 'ImageFilterNone'; ImageFilterNone.muiName = 'SvgIcon'; export default ImageFilterNone;
src/components/ListPicker.js
pixel-glyph/better-reads
import React from 'react'; import PropTypes from 'prop-types'; import BookList from './BookList'; import Plus from './svg/Plus'; class ListPicker extends React.Component { componentDidMount() { if(this.props.newListInputActive) { this.newListName.focus(); } } getNumbooks = (list, i) => { const { lists } = this.props; const numBooks = lists[list] && lists[list].books ? Object.keys(lists[list].books).length : 0; return <BookList key={i} listName={list} listDisplayName={list} numBooks={numBooks} toggleSideList={this.props.toggleSideList} switchList={this.props.switchList} onMobile={this.props.onMobile} removeListHandler={this.props.removeListHandler} lists={this.props.lists} />; }; newListSubmit = (e) => { e.preventDefault(); if(!this.props.newListInputActive) { this.props.toggleNewListInput(); } this.newListName.focus(); if(!this.newListName.value) return; if(this.props.doesListExist(this.props.lists, this.newListName.value)) { return alert('list already exists'); } const currList = this.props.getCurrentList(); this.props.createList(this.newListName.value.trim()); this.props.toggleSelected(currList.listName); this.props.toggleNewListInput(); }; render() { const { showList, newListInputActive, fixList } = this.props; const showClass = showList.isActive ? " show-list" : ""; const activeClass = newListInputActive ? "active" : ""; const posClass = fixList ? " list-picker-fixed" : ""; let lists = Object.keys(this.props.lists); lists.forEach((list, i) => { if(list === "Read" || list === "Want to Read") { lists.splice(i, 1); lists.unshift(list); } }); return ( <div className={`app-list-picker-wrapper${posClass}`}> <div className={`app-list-picker${showClass}`}> <ul className="book-lists list-names"> <li className="list-title">Shelves</li> { lists.map((list, i) => this.getNumbooks(list, i)) } </ul> </div> <div className="add-list-wrapper"> <form ref={(input) => this.newListForm = input} onSubmit={(e) => this.newListSubmit(e)}> <button className={activeClass} type="submit" title="create a new shelf"> <Plus onDesktop={true}/> </button> <input className={activeClass} ref={(input) => this.newListName = input} type="text" placeholder="Shelf Title" maxLength="30"/> </form> </div> </div> ) } } ListPicker.propTypes = { lists: PropTypes.object.isRequired, toggleSideList: PropTypes.func.isRequired, showList: PropTypes.object.isRequired, switchList: PropTypes.func.isRequired, removeListHandler: PropTypes.func, doesListExist: PropTypes.func, toggleSelected: PropTypes.func, getCurrentList: PropTypes.func, createList: PropTypes.func, onMobile: PropTypes.bool, fixList: PropTypes.bool, newListInputActive: PropTypes.bool, toggleNewListInput: PropTypes.func }; export default ListPicker;
app/javascript/mastodon/features/ui/components/report_modal.js
anon5r/mastonon
import React from 'react'; import { connect } from 'react-redux'; import { changeReportComment, changeReportForward, submitReport } from '../../../actions/reports'; import { expandAccountTimeline } from '../../../actions/timelines'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { makeGetAccount } from '../../../selectors'; import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; import StatusCheckBox from '../../report/containers/status_check_box_container'; import { OrderedSet } from 'immutable'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Button from '../../../components/button'; import Toggle from 'react-toggle'; import IconButton from '../../../components/icon_button'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, placeholder: { id: 'report.placeholder', defaultMessage: 'Additional comments' }, submit: { id: 'report.submit', defaultMessage: 'Submit' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = state => { const accountId = state.getIn(['reports', 'new', 'account_id']); return { isSubmitting: state.getIn(['reports', 'new', 'isSubmitting']), account: getAccount(state, accountId), comment: state.getIn(['reports', 'new', 'comment']), forward: state.getIn(['reports', 'new', 'forward']), statusIds: OrderedSet(state.getIn(['timelines', `account:${accountId}:with_replies`, 'items'])).union(state.getIn(['reports', 'new', 'status_ids'])), }; }; return mapStateToProps; }; @connect(makeMapStateToProps) @injectIntl export default class ReportModal extends ImmutablePureComponent { static propTypes = { isSubmitting: PropTypes.bool, account: ImmutablePropTypes.map, statusIds: ImmutablePropTypes.orderedSet.isRequired, comment: PropTypes.string.isRequired, forward: PropTypes.bool, dispatch: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; handleCommentChange = e => { this.props.dispatch(changeReportComment(e.target.value)); } handleForwardChange = e => { this.props.dispatch(changeReportForward(e.target.checked)); } handleSubmit = () => { this.props.dispatch(submitReport()); } componentDidMount () { this.props.dispatch(expandAccountTimeline(this.props.account.get('id'), { withReplies: true })); } componentWillReceiveProps (nextProps) { if (this.props.account !== nextProps.account && nextProps.account) { this.props.dispatch(expandAccountTimeline(nextProps.account.get('id'), { withReplies: true })); } } render () { const { account, comment, intl, statusIds, isSubmitting, forward, onClose } = this.props; if (!account) { return null; } const domain = account.get('acct').split('@')[1]; return ( <div className='modal-root__modal report-modal'> <div className='report-modal__target'> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} /> <FormattedMessage id='report.target' defaultMessage='Report {target}' values={{ target: <strong>{account.get('acct')}</strong> }} /> </div> <div className='report-modal__container'> <div className='report-modal__comment'> <p><FormattedMessage id='report.hint' defaultMessage='The report will be sent to your instance moderators. You can provide an explanation of why you are reporting this account below:' /></p> <textarea className='setting-text light' placeholder={intl.formatMessage(messages.placeholder)} value={comment} onChange={this.handleCommentChange} disabled={isSubmitting} /> {domain && ( <div> <p><FormattedMessage id='report.forward_hint' defaultMessage='The account is from another server. Send an anonymized copy of the report there as well?' /></p> <div className='setting-toggle'> <Toggle id='report-forward' checked={forward} disabled={isSubmitting} onChange={this.handleForwardChange} /> <label htmlFor='report-forward' className='setting-toggle__label'><FormattedMessage id='report.forward' defaultMessage='Forward to {target}' values={{ target: domain }} /></label> </div> </div> )} <Button disabled={isSubmitting} text={intl.formatMessage(messages.submit)} onClick={this.handleSubmit} /> </div> <div className='report-modal__statuses'> <div> {statusIds.map(statusId => <StatusCheckBox id={statusId} key={statusId} disabled={isSubmitting} />)} </div> </div> </div> </div> ); } }
docs/src/app/components/pages/components/List/ExampleContacts.js
ngbrown/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import ActionGrade from 'material-ui/svg-icons/action/grade'; import Divider from 'material-ui/Divider'; import Avatar from 'material-ui/Avatar'; import {pinkA200, transparent} from 'material-ui/styles/colors'; const ListExampleContacts = () => ( <MobileTearSheet> <List> <ListItem primaryText="Chelsea Otakan" leftIcon={<ActionGrade color={pinkA200} />} rightAvatar={<Avatar src="images/chexee-128.jpg" />} /> <ListItem primaryText="Eric Hoffman" insetChildren={true} rightAvatar={<Avatar src="images/kolage-128.jpg" />} /> <ListItem primaryText="James Anderson" insetChildren={true} rightAvatar={<Avatar src="images/jsa-128.jpg" />} /> <ListItem primaryText="Kerem Suer" insetChildren={true} rightAvatar={<Avatar src="images/kerem-128.jpg" />} /> </List> <Divider inset={true} /> <List> <ListItem primaryText="Adelle Charles" leftAvatar={ <Avatar color={pinkA200} backgroundColor={transparent} style={{left: 8}} > A </Avatar> } rightAvatar={<Avatar src="images/adellecharles-128.jpg" />} /> <ListItem primaryText="Adham Dannaway" insetChildren={true} rightAvatar={<Avatar src="images/adhamdannaway-128.jpg" />} /> <ListItem primaryText="Allison Grayce" insetChildren={true} rightAvatar={<Avatar src="images/allisongrayce-128.jpg" />} /> <ListItem primaryText="Angel Ceballos" insetChildren={true} rightAvatar={<Avatar src="images/angelceballos-128.jpg" />} /> </List> </MobileTearSheet> ); export default ListExampleContacts;
app/javascript/mastodon/components/error_boundary.js
gol-cha/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { version, source_url } from 'mastodon/initial_state'; import StackTrace from 'stacktrace-js'; export default class ErrorBoundary extends React.PureComponent { static propTypes = { children: PropTypes.node, }; state = { hasError: false, errorMessage: undefined, stackTrace: undefined, mappedStackTrace: undefined, componentStack: undefined, }; componentDidCatch (error, info) { this.setState({ hasError: true, errorMessage: error.toString(), stackTrace: error.stack, componentStack: info && info.componentStack, mappedStackTrace: undefined, }); StackTrace.fromError(error).then((stackframes) => { this.setState({ mappedStackTrace: stackframes.map((sf) => sf.toString()).join('\n'), }); }).catch(() => { this.setState({ mappedStackTrace: undefined, }); }); } handleCopyStackTrace = () => { const { errorMessage, stackTrace, mappedStackTrace } = this.state; const textarea = document.createElement('textarea'); let contents = [errorMessage, stackTrace]; if (mappedStackTrace) { contents.push(mappedStackTrace); } textarea.textContent = contents.join('\n\n\n'); textarea.style.position = 'fixed'; document.body.appendChild(textarea); try { textarea.select(); document.execCommand('copy'); } catch (e) { } finally { document.body.removeChild(textarea); } this.setState({ copied: true }); setTimeout(() => this.setState({ copied: false }), 700); } render() { const { hasError, copied, errorMessage } = this.state; if (!hasError) { return this.props.children; } const likelyBrowserAddonIssue = errorMessage && errorMessage.includes('NotFoundError'); return ( <div className='error-boundary'> <div> <p className='error-boundary__error'> { likelyBrowserAddonIssue ? ( <FormattedMessage id='error.unexpected_crash.explanation_addons' defaultMessage='This page could not be displayed correctly. This error is likely caused by a browser add-on or automatic translation tools.' /> ) : ( <FormattedMessage id='error.unexpected_crash.explanation' defaultMessage='Due to a bug in our code or a browser compatibility issue, this page could not be displayed correctly.' /> )} </p> <p> { likelyBrowserAddonIssue ? ( <FormattedMessage id='error.unexpected_crash.next_steps_addons' defaultMessage='Try disabling them and refreshing the page. If that does not help, you may still be able to use Mastodon through a different browser or native app.' /> ) : ( <FormattedMessage id='error.unexpected_crash.next_steps' defaultMessage='Try refreshing the page. If that does not help, you may still be able to use Mastodon through a different browser or native app.' /> )} </p> <p className='error-boundary__footer'>Mastodon v{version} · <a href={source_url} rel='noopener noreferrer' target='_blank'><FormattedMessage id='errors.unexpected_crash.report_issue' defaultMessage='Report issue' /></a> · <button onClick={this.handleCopyStackTrace} className={copied ? 'copied' : ''}><FormattedMessage id='errors.unexpected_crash.copy_stacktrace' defaultMessage='Copy stacktrace to clipboard' /></button></p> </div> </div> ); } }
packages/ringcentral-widgets-docs/src/app/pages/Components/ActiveCallActionMenu/index.js
ringcentral/ringcentral-js-widget
import React from 'react'; import { parse } from 'react-docgen'; import CodeExample from '../../../components/CodeExample'; import ComponentHeader from '../../../components/ComponentHeader'; import PropTypeDescription from '../../../components/PropTypeDescription'; import Demo from './Demo'; // eslint-disable-next-line import demoCode from '!raw-loader!./Demo'; // eslint-disable-next-line import componentCode from '!raw-loader!ringcentral-widgets/components/ActiveCallActionMenu'; const ActiveCallActionMenuPage = () => { const info = parse(componentCode); return ( <div> <ComponentHeader name="ActiveCallActionMenu" description={info.description} /> <CodeExample code={demoCode} title="ActiveCallActionMenu Example"> <Demo /> </CodeExample> <PropTypeDescription componentInfo={info} /> </div> ); }; export default ActiveCallActionMenuPage;
client/components/App.js
brucelane/react-redux
import React from 'react'; import NavigationBar from './NavigationBar'; import FlashMessagesList from './flash/FlashMessagesList'; class App extends React.Component { render() { return ( <div className="container"> <NavigationBar /> <FlashMessagesList /> {this.props.children} </div> ); } } export default App;
examples/ColorPicker/index.android.js
crowtec/react-native-pixel-color
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class ColorPicker extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('ColorPicker', () => ColorPicker);
app/javascript/mastodon/components/missing_indicator.js
pointlessone/mastodon
import React from 'react'; import { FormattedMessage } from 'react-intl'; const MissingIndicator = () => ( <div className='regeneration-indicator missing-indicator'> <div> <div className='regeneration-indicator__figure' /> <div className='regeneration-indicator__label'> <FormattedMessage id='missing_indicator.label' tagName='strong' defaultMessage='Not found' /> <FormattedMessage id='missing_indicator.sublabel' defaultMessage='This resource could not be found' /> </div> </div> </div> ); export default MissingIndicator;
packages/react-router-website/modules/examples/Basic.js
goblortikus/react-router
import React from 'react' import { BrowserRouter as Router, Route, Link } from 'react-router-dom' const BasicExample = () => ( <Router> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <li><Link to="/topics">Topics</Link></li> </ul> <hr/> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/topics" component={Topics}/> </div> </Router> ) const Home = () => ( <div> <h2>Home</h2> </div> ) const About = () => ( <div> <h2>About</h2> </div> ) const Topics = ({ match }) => ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${match.url}/rendering`}> Rendering with React </Link> </li> <li> <Link to={`${match.url}/components`}> Components </Link> </li> <li> <Link to={`${match.url}/props-v-state`}> Props v. State </Link> </li> </ul> <Route path={`${match.url}/:topicId`} component={Topic}/> <Route exact path={match.url} render={() => ( <h3>Please select a topic.</h3> )}/> </div> ) const Topic = ({ match }) => ( <div> <h3>{match.params.topicId}</h3> </div> ) export default BasicExample
src/svg-icons/action/change-history.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionChangeHistory = (props) => ( <SvgIcon {...props}> <path d="M12 7.77L18.39 18H5.61L12 7.77M12 4L2 20h20L12 4z"/> </SvgIcon> ); ActionChangeHistory = pure(ActionChangeHistory); ActionChangeHistory.displayName = 'ActionChangeHistory'; ActionChangeHistory.muiName = 'SvgIcon'; export default ActionChangeHistory;
website/src/components/gameSummary/MatchupHistory/HistoricalMatchup/index.js
jwngr/notreda.me
import _ from 'lodash'; import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {push} from 'connected-react-router'; import FootballShape from '../../../common/FootballShape'; import {Season, FootballScoreWrapper, HistoricalMatchupWrapper} from './index.styles'; const HistoricalMatchup = ({ gaps, score, season, result, weekIndex, isHomeGame, isSelected, navigateTo, isSeasonOnTop, specialPositions, }) => { let text; let title; if (result) { const ndScore = isHomeGame ? score.home : score.away; const opponentScore = isHomeGame ? score.away : score.home; text = `${ndScore}-${opponentScore}`; const winLossOrTie = result === 'W' ? 'win' : result === 'L' ? 'loss' : 'tie'; title = `${season} Notre Dame ${winLossOrTie} by a score of ${ndScore} to ${opponentScore}.`; } else { title = `${season} Notre Dame game.`; } const seasonContent = ( <Season isSeasonOnTop={isSeasonOnTop} isSelected={isSelected} onClick={() => navigateTo(`/${season}/${weekIndex + 1}`)} > {_.map(String(season), (digit, i) => ( <span key={`season-header-${season}-${weekIndex}-${i}`}>{digit}</span> ))} </Season> ); return ( <HistoricalMatchupWrapper result={result} isSeasonOnTop={isSeasonOnTop}> {isSeasonOnTop && seasonContent} <FootballScoreWrapper> <FootballShape type={result ? 'past' : 'future'} text={text} title={title} result={result} uniqueFillPatternId={`${season}-${weekIndex}`} isSelected={isSelected} isHomeGame={isHomeGame} onClick={() => navigateTo(`/${season}/${weekIndex + 1}`)} legs={ isSeasonOnTop ? { left: specialPositions.first ? false : gaps.left ? 'gap' : true, right: specialPositions.last ? false : gaps.right ? 'gap' : true, } : undefined } /> </FootballScoreWrapper> {!isSeasonOnTop && seasonContent} </HistoricalMatchupWrapper> ); }; HistoricalMatchup.propTypes = { gaps: PropTypes.shape({ left: PropTypes.bool.isRequired, right: PropTypes.bool.isRequired, }).isRequired, score: PropTypes.shape({ home: PropTypes.number.isRequired, away: PropTypes.number.isRequired, }), result: PropTypes.string, season: PropTypes.number.isRequired, weekIndex: PropTypes.number.isRequired, isHomeGame: PropTypes.bool.isRequired, navigateTo: PropTypes.func.isRequired, isSelected: PropTypes.bool.isRequired, isSeasonOnTop: PropTypes.bool.isRequired, specialPositions: PropTypes.shape({ first: PropTypes.bool.isRequired, last: PropTypes.bool.isRequired, }).isRequired, }; const mapDispatchToProps = (dispatch) => ({ navigateTo: (path) => { dispatch(push(path)); }, }); export default connect(null, mapDispatchToProps)(HistoricalMatchup);
modules/RouteUtils.js
brownbathrobe/react-router
import React from 'react' import warning from 'warning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (const propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { const error = propTypes[propName](props, propName, componentName) if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { const type = element.type const route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { const childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { const routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { const route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (!Array.isArray(routes)) { routes = [ routes ] } return routes }
server/sonar-web/src/main/js/apps/code/components/Component.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import classNames from 'classnames'; import React from 'react'; import ReactDOM from 'react-dom'; import shallowCompare from 'react-addons-shallow-compare'; import ComponentName from './ComponentName'; import ComponentMeasure from './ComponentMeasure'; import ComponentDetach from './ComponentDetach'; import ComponentPin from './ComponentPin'; const TOP_OFFSET = 200; const BOTTOM_OFFSET = 10; export default class Component extends React.Component { componentDidMount () { this.handleUpdate(); } shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } componentDidUpdate () { this.handleUpdate(); } handleUpdate () { const { selected } = this.props; // scroll viewport so the current selected component is visible if (selected) { setTimeout(() => { this.handleScroll(); }, 0); } } handleScroll () { const node = ReactDOM.findDOMNode(this); const position = node.getBoundingClientRect(); const { top, bottom } = position; if (bottom > window.innerHeight - BOTTOM_OFFSET) { window.scrollTo(0, bottom - window.innerHeight + window.scrollY + BOTTOM_OFFSET); } else if (top < TOP_OFFSET) { window.scrollTo(0, top + window.scrollY - TOP_OFFSET); } } render () { const { component, rootComponent, selected, previous, canBrowse } = this.props; const isView = ['VW', 'SVW'].includes(rootComponent.qualifier); let componentAction = null; if (!component.refKey) { switch (component.qualifier) { case 'FIL': case 'UTS': componentAction = <ComponentPin component={component}/>; break; default: componentAction = <ComponentDetach component={component}/>; } } const columns = isView ? [ { metric: 'releasability_rating', type: 'RATING' }, { metric: 'reliability_rating', type: 'RATING' }, { metric: 'security_rating', type: 'RATING' }, { metric: 'sqale_rating', type: 'RATING' }, { metric: 'ncloc', type: 'SHORT_INT' } ] : [ { metric: 'ncloc', type: 'SHORT_INT' }, { metric: 'bugs', type: 'SHORT_INT' }, { metric: 'vulnerabilities', type: 'SHORT_INT' }, { metric: 'code_smells', type: 'SHORT_INT' }, { metric: 'coverage', type: 'PERCENT' }, { metric: 'duplicated_lines_density', type: 'PERCENT' } ]; return ( <tr className={classNames({ selected })}> <td className="thin nowrap"> <span className="spacer-right"> {componentAction} </span> </td> <td className="code-name-cell"> <ComponentName component={component} rootComponent={rootComponent} previous={previous} canBrowse={canBrowse}/> </td> {columns.map(column => ( <td key={column.metric} className="thin nowrap text-right"> <div className="code-components-cell"> <ComponentMeasure component={component} metricKey={column.metric} metricType={column.type}/> </div> </td> ))} </tr> ); } }
elements/Line.js
udfalkso/react-native-svg
import React from 'react'; import createReactNativeComponentClass from 'react-native/Libraries/Renderer/src/renderers/native/createReactNativeComponentClass'; import {LineAttributes} from '../lib/attributes'; import Shape from './Shape'; import {pathProps, numberProp} from '../lib/props'; import extractProps from '../lib/extract/extractProps'; export default class extends Shape { static displayName = 'Line'; static propTypes = { ...pathProps, x1: numberProp.isRequired, x2: numberProp.isRequired, y1: numberProp.isRequired, y2: numberProp.isRequired }; static defaultProps = { x1: 0, y1: 0, x2: 0, y2: 0 }; render() { let props = this.props; return <RNSVGLine ref={ele => {this.root = ele;}} {...extractProps(props, this)} x1={props.x1.toString()} y1={props.y1.toString()} x2={props.x2.toString()} y2={props.y2.toString()} />; } } const RNSVGLine = createReactNativeComponentClass({ validAttributes: LineAttributes, uiViewClassName: 'RNSVGLine' });
src/common/components/header/index.js
canonical-ols/build.snapcraft.io
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { signOut } from '../../actions/auth-store'; import { conf } from '../../helpers/config'; import style from '../../style/vanilla/css/navigation.css'; import containerStyles from '../../containers/container.css'; import { IconUser } from '../vanilla-modules/icons'; const SNAPCRAFT_URL = conf.get('SNAPCRAFT_URL'); const brandmark = 'https://assets.ubuntu.com/v1/7f93bb62-snapcraft-logo--web-white-text.svg'; export default class Header extends Component { constructor(props) { super(props); this.state = { showUserDropdown: false }; } render() { const { authenticated, user } = this.props; return ( <header id="navigation" className={ style['p-navigation'] }> <div className={ `${containerStyles['wrapper']} ${style['row']}` }> <div className={ style['p-navigation__banner'] }> <div className={ style['p-navigation__logo'] }> <a className={ style['p-navigation__link'] } href="https://snapcraft.io"> <img className={ style['p-navigation__image'] } src={ brandmark } alt="Snapcraft" /> </a> </div> <a href="#navigation" className={ style['p-navigation__toggle--open'] } title="menu">Menu</a> <a href="#navigation-closed" className={ style['p-navigation__toggle--close'] } title="close menu">Close menu</a> </div> <nav className={ style['p-navigation__nav'] } role="menubar"> <ul className={ style['p-navigation__links'] } role="menu"> <li className={ style['p-navigation__link'] } role="menuitem"> <a href={ `${SNAPCRAFT_URL}/store` }>Store</a> </li> <li className={ style['p-navigation__link'] } role="menuitem"> <a href={ `${SNAPCRAFT_URL}/blog` }>Blog</a> </li> <li className={ style['p-navigation__link'] } role="menuitem"> <a href={ `${SNAPCRAFT_URL}/iot` }>IoT</a> </li> <li className={ `${style['p-navigation__link']} ${ authenticated ? style['is-selected'] : ''}` } role="menuitem"> <a href={ `${SNAPCRAFT_URL}/build` }>Build</a> </li> <li className={ style['p-navigation__link'] } role="menuitem"> <a href={ `${SNAPCRAFT_URL}/docs` }>Docs</a> </li> <li className={ style['p-navigation__link'] } role="menuitem"> <a className={ style['p-link--external'] } href="https://forum.snapcraft.io/categories">Forum</a> </li> </ul> { authenticated ? ( <ul className={ style['p-navigation__links'] } role="menu"> <li className={ `${style['p-navigation__link']} ${style['p-subnav']} ${this.state.showUserDropdown ? style['is-active'] : ''}` } role="menuitem"> <a className={ style['p-subnav__toggle'] } aria-controls="account-menu" aria-expanded={ this.state.showUserDropdown } onClick={ this.onDropdownClick.bind(this)} > {user.name || user.login} </a> <ul className={ style['p-subnav__items'] } id="account-menu" aria-hidden={ !this.state.showUserDropdown }> <li> <a className={ style['p-subnav__item'] } href={ `${SNAPCRAFT_URL}/account/snaps` } >My published snaps</a> </li> <li> <a className={ style['p-subnav__item'] } href={ `/user/${user.login}`}>Build with GitHub</a> </li> <li> <a className={ style['p-subnav__item'] } href={ `${SNAPCRAFT_URL}/account/details` }>Account details</a> </li> <li> <a className={ style['p-subnav__item'] } href="/auth/logout" onClick={ this.onLogoutClick.bind(this)}>Sign out</a> </li> </ul> </li> </ul> ) : ( <ul className={ style['p-navigation__links'] } role="menu"> <li className={ style['p-navigation__link'] } role="menuitem"> <a href="/auth/authenticate"> <IconUser className={ style['p-nav-icon'] }/> Developer account </a> </li> </ul> ) } </nav> </div> </header> ); } onLogoutClick() { this.props.dispatch(signOut()); } onDropdownClick() { this.setState({ showUserDropdown: !this.state.showUserDropdown }); } } Header.propTypes = { authenticated: PropTypes.bool, user: PropTypes.shape({ login: PropTypes.string, name: PropTypes.string }), dispatch: PropTypes.func.isRequired };
src/containers/Main.js
Warm-men/Investment-by-react
import React from 'react' class App extends React.Component { render() { return ( <div>{this.props.children}</div> ) } } export default App
components/Footer/Footer.js
Kudrik/ReactTest
import React, { Component } from 'react'; import './footer.scss'; class Footer extends Component { render() { return ( <footer className='footer'></footer> ); } } export default Footer;
packages/node_modules/@ciscospark/widget-message-meet-demo/src/index.js
Altocloud/alto-react-ciscospark
import React from 'react'; import ReactDOM from 'react-dom'; import {IntlProvider} from 'react-intl'; import {CookiesProvider} from 'react-cookie'; // import messages from './locales/en'; import '@ciscospark/react-component-spark-fonts'; import injectTapEventPlugin from 'react-tap-event-plugin'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import {blue600, green800} from 'material-ui/styles/colors'; import DemoWidgetMessageMeet from './components/demo-widget-message-meet'; const muiTheme = getMuiTheme({ palette: { primary1Color: blue600, accent1Color: green800 } }); injectTapEventPlugin(); ReactDOM.render( <MuiThemeProvider muiTheme={muiTheme}> <IntlProvider locale={`en`}> <CookiesProvider> <DemoWidgetMessageMeet /> </CookiesProvider> </IntlProvider> </MuiThemeProvider>, document.getElementById(`main`) );
app/main.js
DenisPronin/react-starter
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux' import DevTools from './redux/utils/DevTools' import configureStore from './redux/configureStore' import { rootReducers } from './redux/appRoot' import AppLayout from './views/AppLayout'; const store = configureStore({}, rootReducers); ReactDOM.render( <Provider store={store}> <div> <AppLayout /> {__DEBUG__ && <DevTools />} </div> </Provider>, document.getElementById('root') );
src/scenes/home/informationForm/formComponents/militaryInfo.js
NestorSegura/operationcode_frontend
import React, { Component } from 'react'; import { Line } from 'rc-progress'; import Form from 'shared/components/form/form'; import PropTypes from 'prop-types'; import FormSelect from 'shared/components/form/formSelect/formSelect'; import { MILSTATUS, BRANCH, BRANCH_PROMPT } from 'shared/constants/status'; import styles from './formComponents.css'; class MilitaryInfo extends Component { constructor(props) { super(props); this.state = { branchPrompt: BRANCH_PROMPT.other }; } onChange = (e) => { this.props.update(e, e.target.value); if (e.target.value === 'spouse') { this.setState({ branchPrompt: BRANCH_PROMPT.spouse }); } else { this.setState({ branchPrompt: BRANCH_PROMPT.other }); } }; render() { return ( <Form className={styles.signup}> <h3>Progress = {this.props.percent}%</h3> <Line percent={this.props.percent} strokeWidth="4" strokeColor="green" /> <FormSelect id="militaryStatus" options={MILSTATUS} prompt="Current Military Status" onChange={e => this.onChange(e)} /> <FormSelect id="branch" options={BRANCH} prompt={this.state.branchPrompt} onChange={e => this.props.update(e, e.target.value)} /> </Form> ); } } MilitaryInfo.propTypes = { update: PropTypes.func, percent: PropTypes.string }; MilitaryInfo.defaultProps = { update: null, percent: '0' }; export default MilitaryInfo;
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ArraySpread.js
ontruck/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load(users) { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, ...users, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load([{ id: 42, name: '42' }]); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-array-spread"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
src/components/start-screen/locale-select/LocaleSelect.js
marc-ed-raffalli/geo-game
import React from 'react'; import {Link} from 'react-router-dom'; import './_localeSelect.css'; function getLabel(name) { return <span className="mb-4 text-capitalize text-nowrap">{name}</span>; } export default props => ( <div className="gg-localeSelect d-flex flex-row flex-wrap justify-content-between mt-2 mt-md-4"> {props.locales.map(locale => ( props.selectedLocale === locale.code ? (<div key={locale.code} className="col bg-primary text-white rounded p-2 m-2"> {getLabel(locale.name)} </div>) : ( <Link to={`/${locale.code}`} key={locale.code} className="col bg-light rounded p-2 m-2"> {getLabel(locale.name)} </Link>) ))} </div> );
__tests__/index.ios.js
mrphu3074/react-native-bootstrap
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/js/modules/products/ProductTable.js
djordjes/webpack-boilerplate
import React from 'react'; import PropTypes from 'prop-types'; import ProductRow from './ProductRow'; import ProductCategoryRow from './ProductCategoryRow'; function ProductTable(props) { console.log(props); const rows = []; let lastCategory = null; props.products.forEach((product) => { if (product.name.indexOf(props.filterText) === -1 || (!product.stocked && props.inStockOnly)) { return; } if (product.category !== lastCategory) { rows.push(<ProductCategoryRow category={product.category} key={product.category}/>); } rows.push(<ProductRow product={product} key={product.name}/>); lastCategory = product.category; }); return ( <table> <thead> <tr> <th>Name</th> <th>Price</th> </tr> </thead> <tbody>{rows}</tbody> </table> ); } ProductTable.propTypes = { products: PropTypes.array, filterText: PropTypes.string, inStockOnly: PropTypes.bool }; export default ProductTable;
src/core/containers/FleetSetup.js
getfilament/Distil
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import * as hqActionCreators from '../actions/hqActionCreators'; import Section from '../components/Section'; import FleetInfoForm from '../components/forms/FleetInfoForm'; let FleetSetup = React.createClass({ handleSubmit(data) { this.props.hqActions.hqUpdateFleet(data); }, render() { return ( <div> <h1>Fleet Setup</h1> <Section> <FleetInfoForm onSubmit={this.handleSubmit}/> </Section> </div> ); } }); function mapStateToProps(state) { return {}; } function mapDispatchToProps(dispatch) { return { hqActions: bindActionCreators(hqActionCreators, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(FleetSetup);
src/utils/children.js
felipethome/material-ui
import React from 'react'; import createFragment from 'react-addons-create-fragment'; export default { create(fragments) { const newFragments = {}; let validChildrenCount = 0; let firstKey; //Only create non-empty key fragments for (const key in fragments) { const currentChild = fragments[key]; if (currentChild) { if (validChildrenCount === 0) firstKey = key; newFragments[key] = currentChild; validChildrenCount++; } } if (validChildrenCount === 0) return undefined; if (validChildrenCount === 1) return newFragments[firstKey]; return createFragment(newFragments); }, extend(children, extendedProps, extendedChildren) { return React.isValidElement(children) ? React.Children.map(children, (child) => { const newProps = typeof (extendedProps) === 'function' ? extendedProps(child) : extendedProps; const newChildren = typeof (extendedChildren) === 'function' ? extendedChildren(child) : extendedChildren ? extendedChildren : child.props.children; return React.cloneElement(child, newProps, newChildren); }) : children; }, };
src/routes.js
jch254/audio-insights
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import AboutPage from './shared-components/AboutPage'; import GlossaryPage from './shared-components/GlossaryPage'; import HomePage from './shared-components/HomePage'; import NotFoundPage from './shared-components/NotFoundPage'; import App from './app/App'; import ArtistsPage from './artists/ArtistsPage'; import SpotifyLoginCallbackHandler from './auth/SpotifyLoginCallbackHandler'; import RestrictedPage from './auth/RestrictedPage'; import MosaicPage from './mosaic/MosaicPage'; import RecommendedPage from './recommended/RecommendedPage'; export default ( <Route path="/" component={App} onChange={(prevState, nextState) => { if (nextState.location.action !== 'POP') { window.scrollTo(0, 0); } }} > <IndexRoute component={HomePage} /> <Route path="/about" component={AboutPage} /> <Route path="/glossary" component={GlossaryPage} /> <Route path="/spotifylogincallback" component={SpotifyLoginCallbackHandler} /> <Route component={RestrictedPage}> <Route path="/mosaic" component={MosaicPage} /> <Route path="/recommended" component={RecommendedPage} /> <Route path="/artists" component={ArtistsPage} /> </Route> <Route path="*" component={NotFoundPage} /> </Route> );
packages/bonde-admin/src/pages/admin/mobilizations/widgets/form/settings/finish/page.spec.js
ourcities/rebu-client
import React from 'react' import { shallow } from 'enzyme' import { expect } from 'chai' import Page from './page' describe('routes/admin/authenticated/sidebar/widgets-form-settings/finish/page', () => { let wrapper beforeAll(() => { wrapper = shallow(<Page />) }) describe('#render', () => { it('should render without crash', () => { // eslint-disable-next-line no-unused-expressions expect(wrapper).to.be.ok }) }) })
src/svg-icons/image/photo-camera.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePhotoCamera = (props) => ( <SvgIcon {...props}> <circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/> </SvgIcon> ); ImagePhotoCamera = pure(ImagePhotoCamera); ImagePhotoCamera.displayName = 'ImagePhotoCamera'; ImagePhotoCamera.muiName = 'SvgIcon'; export default ImagePhotoCamera;
app/App.js
basask/react-router-material-ui-seed
import React from 'react'; import ReactDom from 'react-dom'; import Routes from './components/Routes'; import './stylesheet/index.scss'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); ReactDom.render( <Routes />, document.getElementById('app') );
src/containers/MyAccount/MyAccount.js
petorious/dmprov-app
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { injectIntl, intlShape } from 'react-intl'; import { Activity } from '../../containers/Activity' import { setSimpleValue } from '../../store/simpleValues/actions'; import MyAccountForm from '../../components/Forms/MyAccountForm'; import { withRouter } from 'react-router-dom'; import FontIcon from 'material-ui/FontIcon'; import FlatButton from 'material-ui/FlatButton'; import Dialog from 'material-ui/Dialog'; import firebase from 'firebase'; import { withFirebase, FireForm } from 'firekit'; import { GoogleIcon, FacebookIcon, GitHubIcon, TwitterIcon } from '../../components/Icons'; import muiThemeable from 'material-ui/styles/muiThemeable'; import { change, submit, formValueSelector } from 'redux-form'; import { ResponsiveMenu } from 'material-ui-responsive-menu' const path='/users/' const form_name='my_account' class MyAccount extends Component { getProviderIcon = (provider) => { const { muiTheme } = this.props const color = muiTheme.palette.primary2Color switch (provider.PROVIDER_ID) { case 'google.com': return <GoogleIcon color={color}/> case 'facebook.com': return <FacebookIcon color={color}/> case 'twitter.com': return <TwitterIcon color={color}/> case 'github.com': return <GitHubIcon color={color}/> default: return undefined } } handleEmailVerificationsSend = () => { const { firebaseApp } = this.props; firebaseApp.auth().currentUser.sendEmailVerification().then(() => { alert('Verification E-Mail send'); }) } handlePhotoUploadSuccess = (snapshot) => { const { setSimpleValue, change}=this.props; change(form_name, 'photoURL', snapshot.downloadURL); setSimpleValue('new_company_photo', undefined); } handleUserDeletion = () => { const { change, submit } = this.props; change(form_name, 'delete_user', true); submit(form_name) } getProvider = (provider) => { if(provider.indexOf('facebook')>-1){ return new firebase.auth.FacebookAuthProvider(); } if(provider.indexOf('github')>-1){ return new firebase.auth.GithubAuthProvider(); } if(provider.indexOf('google')>-1){ return new firebase.auth.GoogleAuthProvider(); } if(provider.indexOf('twitter')>-1){ return new firebase.auth.TwitterAuthProvider(); } if(provider.indexOf('phone')>-1){ return new firebase.auth.PhoneAuthProvider(); } throw new Error('Provider is not supported!'); }; reauthenticateUser = (values, onSuccess) => { const { auth, firebaseApp, authError} = this.props; if (this.isLinkedWithProvider('password') && !values) { if(onSuccess && onSuccess instanceof Function){ onSuccess(); } } else if (this.isLinkedWithProvider('password') && values) { const credential = firebase.auth.EmailAuthProvider.credential( auth.email, values.old_password ) firebaseApp.auth().currentUser.reauthenticateWithCredential(credential) .then(() => { if(onSuccess && onSuccess instanceof Function){ onSuccess(); } }, e=>{authError(e)}) } else { firebaseApp.auth().currentUser.reauthenticateWithPopup(this.getProvider(auth.providerData[0].providerId)).then(()=>{ if(onSuccess && onSuccess instanceof Function){ onSuccess() } }, e=>{authError(e)}) } } isLinkedWithProvider = (provider) => { const { auth } = this.props; let providerId = '' if (typeof provider === 'string' || provider instanceof String) { providerId = provider } else { providerId = provider.PROVIDER_ID } try { return auth && auth.providerData && auth.providerData.find((p)=>{return p.providerId===providerId})!==undefined; } catch(e) { return false; } } linkUserWithPopup = (provider) => { const { firebaseApp, authError, authStateChanged } =this.props; firebaseApp.auth().currentUser.linkWithPopup(this.getProvider(provider.PROVIDER_ID)) .then((payload) => { authStateChanged(firebaseApp.auth().currentUser); }, e=>{authError(e)}) } handleCreateValues = (values) => { return false; } clean = (obj) => { Object.keys(obj).forEach((key) => (obj[key] === undefined) && delete obj[key]); return obj } handleUpdateValues = (values, dispatch, props) => { const { auth, firebaseApp, authStateChanged, authError }=this.props; const simpleChange=(values.displayName && values.displayName.localeCompare(auth.displayNam)) || (values.photoURL && values.photoURL.localeCompare(auth.photoURL)); let simpleValues={ displayName: values.displayName, photoURL: values.photoURL } //Change simple data if(simpleChange){ firebaseApp.auth().currentUser.updateProfile(simpleValues).then(() => { firebaseApp.database().ref(`users/${auth.uid}`).update(this.clean(simpleValues)).then(()=>{ authStateChanged(values); }, e =>{authError(e)}); }, e => {authError(e)}); } //Change email if(values.email && values.email.localeCompare(auth.email)){ this.reauthenticateUser(values, ()=>{ firebaseApp.auth().currentUser.updateEmail(values.email).then(() => { firebaseApp.database().ref(`users/${auth.uid}`).update({email: values.email}).then(()=>{ authStateChanged({email: values.email}); }, e =>{authError(e)}); }, e => { authError(e) // eslint-disable-next-line if (e.code == 'auth/requires-recent-login') { firebaseApp.auth().signOut().then(function() { setTimeout(() => { alert('Please sign in again to change your email.'); }, 1); }); } }); }) } //Change password if(values.new_password){ this.reauthenticateUser( values, ()=>{ firebaseApp.auth().currentUser.updatePassword(values.new_password).then(() => { firebaseApp.auth().signOut(); }, e => { authError(e) // eslint-disable-next-line if (e.code == 'auth/requires-recent-login') { firebaseApp.auth().signOut().then(() => { setTimeout(() => { alert('Please sign in again to change your password.'); }, 1); }); } }); }) } //We manage the data saving above return false; } handleClose = () => { const { setSimpleValue }=this.props; setSimpleValue('delete_user', false); setSimpleValue('auth_menu', false); } handleDelete = () => { const { firebaseApp, authError }=this.props; this.reauthenticateUser( false , ()=>{ firebaseApp.auth().currentUser.delete() .then(() => { this.handleClose(); }, e => { authError(e) // eslint-disable-next-line if (e.code == 'auth/requires-recent-login') { firebaseApp.auth().signOut().then(() => { setTimeout(() => { alert('Please sign in again to delete your account.'); }, 1); }); } }); }); } validate = (values) => { const { auth } =this.props; const providerId=auth.providerData[0].providerId; const errors = {} if (!values.displayName) { errors.displayName = 'Required' } if (!values.email) { errors.email = 'Required' } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address' } else if (!values.old_password && providerId==='password' && auth.email.localeCompare(values.email)){ errors.old_password = 'For email change enter your pasword' } if(values.new_password){ if(values.new_password.length <6){ errors.new_password = 'Password should be at least 6 characters' }else if (values.new_password.localeCompare(values.new_password_confirmation)) { errors.new_password = 'Must be equal' errors.new_password_confirmation = 'Must be equal' } } return errors } render() { const { history, intl, setSimpleValue, delete_user, auth, muiTheme, submit } = this.props; const actions = [ <FlatButton label={intl.formatMessage({id: 'cancel'})} primary={true} onClick={this.handleClose} />, <FlatButton label={intl.formatMessage({id: 'delete'})} secondary={true} onClick={this.handleDelete} />, ] const menuList = [ { hidden: auth.uid === undefined, text: intl.formatMessage({id: 'save'}), icon: <FontIcon className="material-icons" color={muiTheme.palette.canvasColor}>save</FontIcon>, tooltip:intl.formatMessage({id: 'save'}), onClick: () => submit('my_account') }, { hidden: auth.uid === undefined, text: intl.formatMessage({id: 'delete'}), icon: <FontIcon className="material-icons" color={muiTheme.palette.canvasColor}>delete</FontIcon>, tooltip: intl.formatMessage({id: 'delete'}), onClick: () => setSimpleValue('delete_user', true) } ] return ( <Activity iconStyleRight={{width:'50%'}} iconElementRight={ <ResponsiveMenu iconMenuColor={muiTheme.palette.canvasColor} menuList={menuList} /> } title={intl.formatMessage({id: 'my_account'})}> { auth.uid && <div style={{margin: 15, display: 'flex'}}> <FireForm validate={this.validate} name={form_name} path={path} handleUpdateValues={this.handleUpdateValues} onSubmitSuccess={(values)=>{history.push('/dashboard'); setSimpleValue('auth_menu', false)}} onDelete={(values)=>{history.push('/signin');}} handleCreateValues={this.handleCreateValues} uid={auth.uid}> <MyAccountForm linkUserWithPopup={this.linkUserWithPopup} isLinkedWithProvider={this.isLinkedWithProvider} getProviderIcon={this.getProviderIcon} handleEmailVerificationsSend={this.handleEmailVerificationsSend} handlePhotoUploadSuccess={this.handlePhotoUploadSuccess} handleUserDeletion={this.handleUserDeletion} {...this.props} /> </FireForm> </div> } <Dialog title={intl.formatMessage({id: 'delete_account_dialog_title'})} actions={actions} modal={false} open={delete_user===true} onRequestClose={this.handleClose}> {intl.formatMessage({id: 'delete_account_dialog_message'})} </Dialog> </Activity> ); } } MyAccount.propTypes = { history: PropTypes.object, setSimpleValue: PropTypes.func.isRequired, intl: intlShape.isRequired, isGranted: PropTypes.func, auth: PropTypes.object.isRequired, vehicle_types: PropTypes.array, }; const selector = formValueSelector(form_name) const mapStateToProps = (state) => { const { intl, simpleValues, auth } = state const delete_user = simpleValues.delete_user const new_user_photo = simpleValues.new_user_photo return { new_user_photo, intl, delete_user, auth, photoURL: selector(state, 'photoURL'), old_password: selector(state, 'old_password') }; }; export default connect( mapStateToProps, { setSimpleValue, change, submit } )(injectIntl(withRouter(muiThemeable()(withFirebase(MyAccount)))))
test/mochaTestHelper.js
glaserp/Maturita-Project
import Bluebird from 'bluebird'; import chai, {assert, expect} from 'chai'; import React from 'react'; import sinon from 'sinon'; import sinonAsPromised from 'sinon-as-promised'; import sinonChai from 'sinon-chai'; import TestUtils from 'react-addons-test-utils'; chai.should(); chai.use(sinonChai); // Use Bluebird Promises inside of sinon stubs. // Bluebird has better error reporting for unhandled Promises. sinonAsPromised(Bluebird); export { assert, chai, expect, React, sinon, sinonChai, TestUtils };
src/routes/app/routes/pages/routes/faqs/components/FAQs.js
ahthamrin/kbri-admin2
import React from 'react'; import QueueAnim from 'rc-queue-anim'; const Hero = () => ( <section className="hero"> <div className="hero-content"> <h1 className="hero-title">FAQs</h1> </div> <p className="hero-tagline">Frequently Asked Questions</p> </section> ); const FAQs = () => ( <article className="article padding-lg-v article-dark article-bordered"> <div className="container-fluid with-maxwidth"> <div className="row"> <div className="col-xl-6"> <h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit?</h4> <p>BEligendi amet quam inventore nam nostrum quaerat aliquam enim dicta illo laboriosam, quia odio voluptas animi consequatur non nemo deleniti, illum tempore assumenda reprehenderit corporis vel impedit nihil earum. Voluptas explicabo voluptatem iste libero officia cum voluptate, qui laboriosam atque.</p> <div className="divider divider-xl divider-dashed" /> <h4>Doloribus dolores, officia voluptatibus deserunt ratione debitis laboriosam?</h4> <p>Ut tempora, ad eos. Eveniet asperiores quaerat cupiditate quo, possimus officiis deserunt porro dolor mollitia iure minima id incidunt facilis accusamus ea quod perferendis veniam quas, et distinctio dolores corporis magni sapiente hic. Non saepe, veritatis, molestias debitis illum, quasi optio modi numquam harum repellat dolorem, velit blanditiis aliquid eveniet iusto! Sed reiciendis, tempora ex dolor fugiat temporibus, iste!</p> <div className="divider divider-xl divider-dashed" /> <h4>Illo recusandae beatae facilis?</h4> <p>Facere quo corporis distinctio recusandae pariatur possimus veniam ipsa assumenda autem, qui laborum molestias, magnam sed, voluptas optio illo. Illo, minima officia, labore ipsa fugiat, cum magnam ad error, nobis placeat suscipit? Enim magni delectus, sit, deserunt, repudiandae ratione hic et, libero nemo doloremque numquam quibusdam obcaecati pariatur dolorem.</p> <div className="divider divider-xl divider-dashed" /> <h4>Quidem doloribus, repudiandae?</h4> <p>Veniam optio iste aliquid dicta labore perspiciatis pariatur modi. Explicabo quisquam tenetur consectetur at possimus laborum aliquam a magni nulla veritatis accusamus consequuntur dolorem doloremque fugiat earum vero quos sit cumque saepe maiores sint, beatae ab..</p> <p>Nemo sed ipsa consequatur facere saepe dolore velit magni autem laborum exercitationem sequi animi vel necessitatibus veritatis, a aliquam voluptas voluptatum vitae qui harum, repellendus. Ut pariatur dignissimos dolore in repudiandae porro quos a delectus doloribus odit, maxime magnam eius soluta dolorum! Recusandae illum perferendis, expedita voluptates</p> </div> <div className="col-xl-6"> <h4>Assumenda accusamus reiciendis obcaecati iusto?</h4> <p>Delectus provident dolorum quam quae, facere dolore sint modi eius ut enim distinctio. Ratione adipisci fugiat deserunt provident tempora? Reprehenderit, perspiciatis excepturi fugiat neque atque tenetur nesciunt cum perferendis dolor ullam similique iure nulla amet, delectus consequuntur qui quaerat unde quidem assumenda!</p> <p>At quis accusamus distinctio enim quaerat laudantium veniam laborum impedit cumque, minima porro. Aliquam laborum, tempore totam temporibus ea obcaecati at aut omnis fugit natus, doloribus, labore pariatur molestias velit veritatis?</p> <div className="divider divider-xl divider-dashed" /> <h4>Alias harum culpa earum cum id aspernatur repellendus aliquam?</h4> <p>Officia placeat vero ut quis perspiciatis ad doloribus. Voluptatum unde eaque magni ullam, veniam non illo doloremque ducimus voluptatibus quisquam, labore aspernatur ipsam optio sed necessitatibus culpa numquam vel, earum, autem porro laborum reprehenderit nulla. Nam quo, sunt, nesciunt ipsum architecto ipsa cumque minima reprehenderit dignissimos quod rem, amet deserunt, cupiditate dicta!</p> <p>Natus omnis quam ad, repellat similique nesciunt, quia molestias obcaecati itaque odio animi eaque distinctio error ipsa. Dolore quod vel possimus minima, maxime aperiam magni omnis nemo ex ipsa doloribus quidem adipisci eius fugit dignissimos praesentium velit quis, et totam, tempore necessitatibus doloremque!</p> <div className="divider divider-xl divider-dashed" /> <h4>Optio doloremque suscipit aut accusantium maxime provident cumque?</h4> <p>Unde repudiandae repellat in eos, ullam, hic eveniet dolorum dignissimos illum voluptates adipisci animi vel, aspernatur quaerat quos. Accusamus nihil odit quia, eligendi molestiae necessitatibus blanditiis beatae delectus nulla quidem. Blanditiis molestias harum iste ad iure corporis culpa ratione nulla est similique incidunt nisi tempore ea dignissimos, laudantium, sequi deleniti porro veritatis. Maiores nihil, dignissimos magnam beatae quae quia natus eligendi et, quos quas. Mollitia laboriosam, magni at minus veniam voluptates ad dolor aliquid quisquam nobis maiores dolorum repudiandae, iste ea alias pariatur consectetur voluptatibus ullam repellat autem tempore necessitatibus explicabo nisi.</p> </div> </div> </div> </article> ); const Page = () => ( <section className="page-faq chapter"> <QueueAnim type="bottom" className="ui-animate"> <div key="1"><Hero /></div> <div key="2"><FAQs /></div> </QueueAnim> </section> ); module.exports = Page;
src/Textfield.js
react-mdl/react-mdl
import React from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import classNames from 'classnames'; import mdlUpgrade from './utils/mdlUpgrade'; const propTypes = { className: PropTypes.string, disabled: PropTypes.bool, error: PropTypes.node, expandable: PropTypes.bool, expandableIcon: PropTypes.string, floatingLabel: PropTypes.bool, id: (props, propName, componentName) => { const { id } = props; if (id && typeof id !== 'string') { return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. \`${propName}\` should be a string. Validation failed.`); } if (!id && typeof props.label !== 'string') { return new Error(`Invalid prop \`${propName}\` supplied to \`${componentName}\`. \`${propName}\` is required when label is an element. Validation failed.`); } return null; }, inputClassName: PropTypes.string, label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]).isRequired, maxRows: PropTypes.number, onChange: PropTypes.func, pattern: PropTypes.string, required: PropTypes.bool, rows: PropTypes.number, style: PropTypes.object, value: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]) }; class Textfield extends React.Component { componentDidMount() { if (this.props.error && !this.props.pattern) { this.setAsInvalid(); } } componentDidUpdate(prevProps) { if ( this.props.required !== prevProps.required || this.props.pattern !== prevProps.pattern || this.props.error !== prevProps.error ) { findDOMNode(this).MaterialTextfield.checkValidity(); } if (this.props.disabled !== prevProps.disabled) { findDOMNode(this).MaterialTextfield.checkDisabled(); } if (this.props.value !== prevProps.value && this.inputRef !== document.activeElement) { findDOMNode(this).MaterialTextfield.change(this.props.value); } if (this.props.error && !this.props.pattern) { // Every time the input gets updated by MDL (checkValidity() or change()) // its invalid class gets reset. We have to put it again if the input is specifically set as "invalid" this.setAsInvalid(); } } setAsInvalid() { const elt = findDOMNode(this); if (elt.className.indexOf('is-invalid') < 0) { elt.className = classNames(elt.className, 'is-invalid'); } } render() { const { className, inputClassName, id, error, expandable, expandableIcon, floatingLabel, label, maxRows, rows, style, children, ...otherProps } = this.props; const hasRows = !!rows; const customId = id || `textfield-${label.replace(/[^a-z0-9]/gi, '')}`; const inputTag = hasRows || maxRows > 1 ? 'textarea' : 'input'; const inputProps = { className: classNames('mdl-textfield__input', inputClassName), id: customId, rows, ref: (c) => (this.inputRef = c), ...otherProps }; const input = React.createElement(inputTag, inputProps); const labelContainer = <label className="mdl-textfield__label" htmlFor={customId}>{label}</label>; const errorContainer = !!error && <span className="mdl-textfield__error">{error}</span>; const containerClasses = classNames('mdl-textfield mdl-js-textfield', { 'mdl-textfield--floating-label': floatingLabel, 'mdl-textfield--expandable': expandable }, className); return expandable ? ( <div className={containerClasses} style={style}> <label className="mdl-button mdl-js-button mdl-button--icon" htmlFor={customId}> <i className="material-icons">{expandableIcon}</i> </label> <div className="mdl-textfield__expandable-holder"> {input} {labelContainer} {errorContainer} </div> {children} </div> ) : ( <div className={containerClasses} style={style}> {input} {labelContainer} {errorContainer} {children} </div> ); } } Textfield.propTypes = propTypes; export default mdlUpgrade(Textfield);
src/components/app/form/Submit.js
teamNOne/showdown
import React from 'react'; export default class Submit extends React.Component { render() { return <input type="submit" className={ `btn ${ this.props.type }` } value={ this.props.value } />; } }
packages/demo/src/index.js
marnusw/react-css-transition-replace
import React from 'react' import ReactDOM from 'react-dom' import './index.css' import './transitions.css' import Demo from './Demo' ReactDOM.render(<Demo />, document.getElementById('root'))
fields/types/password/PasswordColumn.js
helloworld3q3q/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var PasswordColumn = React.createClass({ displayName: 'PasswordColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; return value ? '********' : ''; }, render () { return ( <ItemsTableCell> <ItemsTableValue field={this.props.col.type}> {this.renderValue()} </ItemsTableValue> </ItemsTableCell> ); }, }); module.exports = PasswordColumn;
app/components/papers/album/component.js
DenQ/electron-react-lex
import React, { Component } from 'react'; import { Paper, RaisedButton, Popover, Menu, MenuItem } from 'material-ui'; import PlayIcon from 'material-ui/svg-icons/av/play-circle-filled'; import BaseComponent from 'lex/libs/base/component'; import { I18n } from 'react-redux-i18n'; import Badge from 'material-ui/Badge'; const styles = { paper: { width: 167 , height: 167, margin: 10, textAlign: 'center', display: 'inline-block', backgroundColor: 'white', }, menu: { position: 'relative', top: 20, }, text: { color: 'black', }, icon: { play: { cursor: 'pointer', position: 'relative', top: 5, width: 60, height: 60, } } }; function calculateLearning(album) { const { size, learned } = album; return Math.floor(learned * 100 / size); } export default class AlbumPaper extends BaseComponent { constructor(props) { super(props); this.state = { open: false, }; this.handlerOnClick = this.handlerOnClick.bind(this); this.handleTouchTap = this.handleTouchTap.bind(this); this.handleRequestClose = this.handleRequestClose.bind(this); } handleTouchTap = (event) => { event.stopPropagation(); // This prevents ghost click. event.preventDefault(); this.setState({ open: true, anchorEl: event.currentTarget, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; handlerOnClick() { const { record, urlManagerActions } = this.props; urlManagerActions.transitionTo(`/run-album/${record.id}`); } render() { this.decorateStyle(); const { record, handleToRun, handleToEdit, handleRemove } = this.props; return ( <Paper style={styles.paper} zDepth={2} onClick={this.handlerOnClick}> <div style={styles.text}> {record.name} </div> <Badge badgeContent={calculateLearning(record)} secondary={true} badgeStyle={{top: 27, right: 20}} title="Persent learning" > <PlayIcon style={styles.icon.play} color={this.styles.palette.primary3Color} /> </Badge> <div style={styles.menu}> <RaisedButton onClick={this.handleTouchTap} label={I18n.t('components.papers.album.options')} primary={true} fullWidth={true} /> <Popover open={this.state.open} anchorEl={this.state.anchorEl} anchorOrigin={{horizontal: 'left', vertical: 'bottom'}} targetOrigin={{horizontal: 'left', vertical: 'top'}} onRequestClose={this.handleRequestClose} > <Menu> <MenuItem primaryText={I18n.t('components.papers.album.run')} onClick={handleToRun} /> <MenuItem primaryText={I18n.t('components.papers.album.edit')} onClick={handleToEdit} /> <MenuItem primaryText={I18n.t('components.papers.album.remove')} onClick={handleRemove} /> </Menu> </Popover> </div> </Paper> ); } }
frontend/src/components/Footer.js
dimkarakostas/rupture
import React from 'react'; export default class Footer extends React.Component { render() { return( <footer> <a href='https://ruptureit.com/'>RuptureIt</a> </footer> ); } }
react-ui/src/components/NavTransition.react.js
simonlimon/varsncrafts
import React from 'react'; import { RouteTransition } from 'react-router-transition'; class NavTransition extends React.PureComponent { render() { return ( <div> <RouteTransition pathname={this.props.location.pathname} atEnter={{ opacity: 0 }} atLeave={{ opacity: 0 }} atActive={{ opacity: 1 }} runOnMount={false} > {this.props.children} </RouteTransition> </div> ); } } export default NavTransition;
src/utils/devTools.js
BenGoldstein88/redux-chartmaker
import React from 'react'; import { createStore as initialCreateStore, compose } from 'redux'; export let createStore = initialCreateStore; if (__DEV__) { createStore = compose( require('redux-devtools').devTools(), require('redux-devtools').persistState( window.location.href.match(/[?&]debug_session=([^&]+)\b/) ), createStore ); } export function renderDevTools(store) { if (__DEV__) { let {DevTools, DebugPanel, LogMonitor} = require('redux-devtools/lib/react'); return ( <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> ); } return null; }
src/svg-icons/device/battery-charging-80.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryCharging80 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V9h4.93L13 7v2h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9L11.93 9H7v11.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V9h-4v3.5z"/> </SvgIcon> ); DeviceBatteryCharging80 = pure(DeviceBatteryCharging80); DeviceBatteryCharging80.displayName = 'DeviceBatteryCharging80'; DeviceBatteryCharging80.muiName = 'SvgIcon'; export default DeviceBatteryCharging80;
packages/canvas-media/src/shared/CanvasSelect.js
djbender/canvas-lms
/* * Copyright (C) 2020 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* --- CanvasSelect is a wrapper on the new (as of instui 5 or 6 or so) controlled-only Select While CanvasSelect is also controlled-only, it has a simpler api and is almost a drop-in replacement for the old instui Select used throughout canvas at this time. One big difference is the need to pass in an options property rather than rendering <Options> children It does not currently support old-Select's allowCustom property (see https://instructure.design/#DeprecatedSelect) It only handles single-select. Multi-select will likely have to be in a separate component <CanvasSelect id="your-id" label="select's label" value={value} // should match the ID of the selected option onChange={handleChange} // function(event, selectedOption) {...otherPropsPassedToTheUnderlyingSelect} // if you need to (width="100%" is a popular one) > <CanvasSelect.Option key="1" id="1" value="1">one</CanvasSelect.Option> <CanvasSelect.Option key="2" id="2" value="2">two</CanvasSelect.Option> <CanvasSelect.Option key="3" id="3" value="3">three</CanvasSelect.Option> </CanvasSelect> --- */ /* * this file is a copy of canvas-lms/packages/canvas-planner/src/CanvasSelect.js * but with strings passed in, rather then formatMessage'd here. */ import React from 'react' import {func, node, string, shape, oneOfType} from 'prop-types' import {compact, castArray, isEqual} from 'lodash' import formatMessage from 'format-message' import {Select} from '@instructure/ui-select' import {Alert} from '@instructure/ui-alerts' import {matchComponentTypes} from '@instructure/ui-react-utils' const noOptionsOptionId = '_noOptionsOption' // CanvasSelectOption and CanvasSelectGroup are components our client can create thru CanvasSelect // to pass us our options. They are never rendered themselves, but get transformed into INSTUI's // Select.Option and Select.Group on rendering CanvasSelect. See renderChildren below. function CanvasSelectOption() { return <div /> } CanvasSelectOption.propTypes = { id: string.isRequired, // eslint-disable-line react/no-unused-prop-types value: string.isRequired // eslint-disable-line react/no-unused-prop-types } function CanvasSelectGroup() { return <div /> } CanvasSelectGroup.propTypes = { label: string.isRequired // eslint-disable-line react/no-unused-prop-types } export default class CanvasSelect extends React.Component { static Option = CanvasSelectOption static Group = CanvasSelectGroup static propTypes = { id: string, label: oneOfType([node, func]).isRequired, liveRegion: func, value: string, onChange: func.isRequired, children: node, noOptionsLabel: string, // unselectable option to display when there are no options translatedStrings: shape({ USE_ARROWS: string.isRequired, LIST_COLLAPSED: string.isRequired, LIST_EXPANDED: string.isRequired, OPTION_SELECTED: string.isRequired }), onBlur: func } static defaultProps = { noOptionsLabel: '---' } constructor(props) { super(props) const option = this.getOptionByFieldValue('value', props.value) this.state = { inputValue: option ? option.props.children : '', isShowingOptions: false, highlightedOptionId: null, selectedOptionId: option ? option.props.id : null, announcement: null } } componentDidUpdate(prevProps) { if (this.props.value !== prevProps.value || !isEqual(this.props.children, prevProps.children)) { const option = this.getOptionByFieldValue('value', this.props.value) // eslint-disable-next-line react/no-did-update-set-state this.setState({ inputValue: option ? option.props.children : '', selectedOptionId: option ? option.props.id : '' }) } } render() { const {id, label, value, onChange, children, noOptionsLabel, ...otherProps} = this.props return ( <> <Select id={id} renderLabel={() => label} assistiveText={this.props.translatedStrings.USE_ARROWS} inputValue={this.state.inputValue} isShowingOptions={this.state.isShowingOptions} onBlur={this.handleBlur} onRequestShowOptions={this.handleShowOptions} onRequestHideOptions={this.handleHideOptions} onRequestHighlightOption={this.handleHighlightOption} onRequestSelectOption={this.handleSelectOption} {...otherProps} > {this.renderChildren(children)} </Select> <Alert liveRegion={this.props.liveRegion} liveRegionPoliteness="assertive" screenReaderOnly> {this.state.announcement} </Alert> </> ) } renderChildren(children) { if (!Array.isArray(children)) { // children is 1 child if (matchComponentTypes(children, [CanvasSelectOption])) { return this.renderOption(children) } else if (matchComponentTypes(children, [CanvasSelectGroup])) { return this.renderGroup(children) } else { return this.renderNoOptionsOption() } } const opts = children .map(child => { if (Array.isArray(child)) { return this.renderChildren(child) } else if (matchComponentTypes(child, [CanvasSelectOption])) { return this.renderOption(child) } else if (matchComponentTypes(child, [CanvasSelectGroup])) { return this.renderGroup(child) } return null }) .filter(child => !!child) // instui Select blows up on undefined options if (opts.length === 0) { return this.renderNoOptionsOption() } return opts } backupKey = 0 renderOption(option) { const {id, children, ...optionProps} = option.props return ( <Select.Option id={id} key={option.key || id || ++this.backupKey} isHighlighted={id === this.state.highlightedOptionId} isSelected={id === this.state.selectedOptionId} {...optionProps} > {children} </Select.Option> ) } renderGroup(group) { const {id, label, ...otherProps} = group.props const children = compact(castArray(group.props.children)) return ( <Select.Group data-testid={`Group:${label}`} renderLabel={() => label} key={group.key || id || ++this.backupKey} {...otherProps} > {children.map(c => this.renderOption(c))} </Select.Group> ) } renderNoOptionsOption() { return ( <Select.Option id={noOptionsOptionId} isHighlighted={false} isSelected={false}> {this.props.noOptionsLabel} </Select.Option> ) } handleBlur = event => { this.setState({highlightedOptionId: null, announcement: null}) if (this.props.onBlur) { this.props.onBlur(event) } } handleShowOptions = () => { this.setState({ isShowingOptions: true }) } handleHideOptions = _event => { this.setState(state => { const text = this.getOptionLabelById(state.selectedOptionId) return { isShowingOptions: false, highlightedOptionId: null, inputValue: text } }) } /* eslint-disable react/no-access-state-in-setstate */ // Because handleShowOptions sets state.isShowingOptions:true // it's already in the value of state passed to the setState(updater) // by the time handleHighlightOption is called we miss the transition, // this.state still has the previous value as of the last render // which is what we need. This is why we use this version of setState. handleHighlightOption = (event, {id}) => { if (id === noOptionsOptionId) return const text = this.getOptionLabelById(id) const nowOpen = this.state.isShowingOptions ? '' : this.props.translatedStrings.LIST_EXPANDED const inputValue = event.type === 'keydown' ? text : this.state.inputValue this.setState({ highlightedOptionId: id, inputValue, announcement: `${text} ${nowOpen}` }) } /* eslint-enable react/no-access-state-in-setstate */ handleSelectOption = (event, {id}) => { if (id === noOptionsOptionId) { this.setState({ isShowingOptions: false, announcement: this.props.translatedStrings.LIST_COLLAPSED }) } else { const text = this.getOptionLabelById(id) const prevSelection = this.state.selectedOptionId this.setState({ selectedOptionId: id, inputValue: text, isShowingOptions: false, announcement: formatMessage(this.props.translatedStrings.OPTION_SELECTED, {option: text}) }) const option = this.getOptionByFieldValue('id', id) if (prevSelection !== id) { this.props.onChange(event, option.props.value) } } } getOptionLabelById(oid) { const option = this.getOptionByFieldValue('id', oid) return option ? option.props.children : '' } getOptionByFieldValue(field, value, options = castArray(this.props.children)) { if (!this.props.children) return null let foundOpt = null for (let i = 0; i < options.length; ++i) { const o = options[i] if (Array.isArray(o)) { foundOpt = this.getOptionByFieldValue(field, value, o) } else if (matchComponentTypes(o, [CanvasSelectOption])) { if (o.props[field] === value) { foundOpt = o } } else if (matchComponentTypes(o, [CanvasSelectGroup])) { const groupOptions = castArray(o.props.children) for (let j = 0; j < groupOptions.length; ++j) { const o2 = groupOptions[j] if (o2.props[field] === value) { foundOpt = o2 break } } } if (foundOpt) { break } } return foundOpt } }
examples/dynamic-segments/app.js
whouses/react-router
import React from 'react'; import { Router, Route, Link, Redirect } from 'react-router'; var App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/user/123">Bob</Link></li> <li><Link to="/user/abc">Sally</Link></li> </ul> {this.props.children} </div> ); } }); var User = React.createClass({ render() { var { userID } = this.props.params; return ( <div className="User"> <h1>User id: {userID}</h1> <ul> <li><Link to={`/user/${userID}/tasks/foo`}>foo task</Link></li> <li><Link to={`/user/${userID}/tasks/bar`}>bar task</Link></li> </ul> {this.props.children} </div> ); } }); var Task = React.createClass({ render() { var { userID, taskID } = this.props.params; return ( <div className="Task"> <h2>User ID: {userID}</h2> <h3>Task ID: {taskID}</h3> </div> ); } }); React.render(( <Router> <Route path="/" component={App}> <Route path="user/:userID" component={User}> <Route path="tasks/:taskID" component={Task} /> <Redirect from="todos/:taskID" to="/user/:userID/tasks/:taskID" /> </Route> </Route> </Router> ), document.getElementById('example'));
src/ui-kit/Grid/index.js
Menternship/client-web
// @flow import React from 'react'; import { Grid as GridFB } from 'react-flexbox-grid'; type $props = { children?: any, }; export default ({ children, ...props }: $props) => ( <GridFB {...props} fluid> {children} </GridFB> );
src/components/joystick/JoystickMotorSelect.js
TheGigabots/gigabots-dashboard
import React from 'react'; import PropTypes from 'prop-types' import Typography from 'material-ui/Typography'; import Paper from 'material-ui/Paper'; import Select from 'material-ui/Select'; import {MenuItem} from 'material-ui/Menu'; const style = { height: 75, width: 200, margin: 20, textAlign: 'center', display: 'inline-block', }; export default class JoystickMotorSelect extends React.Component { handleMotorChange = event => { const {button, config} = this.props; const speed = config.speedForButton(button); const direction = config.directionForButton(button); this.updateParent(event.target.value, speed, direction); }; handleSpeedChange(event) { const {button, config} = this.props; const direction = config.directionForButton(button); const motor = config.motorForButton(button); this.updateParent(motor, event.target.value, direction); } handleDirectionChange(event) { const {button, config} = this.props; const speed = config.speedForButton(button); const motor = config.motorForButton(button); this.updateParent(motor, speed, event.target.value); } updateParent(motor, speed, direction) { this.props.callback(this.props.button, motor, speed, direction) } render() { const {button, config} = this.props; const speed = config.speedForButton(button); const direction = config.directionForButton(button); const motor = config.motorForButton(button); return ( <Paper style={style}> <Typography type="subheading" color="secondary"> {button} </Typography> <Select value={motor} onChange={this.handleMotorChange} > <MenuItem value={""}>None</MenuItem> <MenuItem value={"A"}>A</MenuItem> <MenuItem value={"B"}>B</MenuItem> <MenuItem value={"C"}>C</MenuItem> <MenuItem value={"D"}>D</MenuItem> <MenuItem value={"S"}>STOP</MenuItem> </Select> <Select value={speed} onChange={(e) => this.handleSpeedChange(e)} > <MenuItem value={0}>0</MenuItem> <MenuItem value={10}>10</MenuItem> <MenuItem value={20}>20</MenuItem> <MenuItem value={30}>30</MenuItem> <MenuItem value={40}>40</MenuItem> <MenuItem value={50}>50</MenuItem> <MenuItem value={60}>60</MenuItem> <MenuItem value={70}>70</MenuItem> <MenuItem value={80}>80</MenuItem> <MenuItem value={90}>90</MenuItem> <MenuItem value={100}>100</MenuItem> </Select> <Select value={direction} onChange={(e) => this.handleDirectionChange(e)} > <MenuItem value={"f"}>fwd</MenuItem> <MenuItem value={"r"}>rvs</MenuItem> </Select> </Paper> ) } } JoystickMotorSelect.propTypes = { button: PropTypes.string.isRequired, config: PropTypes.object.isRequired, callback: PropTypes.func.isRequired }
tests/framework.spec.js
stefanosKarantin/stefanos-react-prj
import assert from 'assert' import React from 'react' import {mount, render, shallow} from 'enzyme' class Fixture extends React.Component { render () { return ( <div> <input id='checked' defaultChecked /> <input id='not' defaultChecked={false} /> </div> ) } } describe('(Framework) Karma Plugins', function () { it('Should expose "expect" globally.', function () { assert.ok(expect) }) it('Should expose "should" globally.', function () { assert.ok(should) }) it('Should have chai-as-promised helpers.', function () { const pass = new Promise(res => res('test')) const fail = new Promise((res, rej) => rej()) return Promise.all([ expect(pass).to.be.fulfilled, expect(fail).to.not.be.fulfilled ]) }) it('should have chai-enzyme working', function() { let wrapper = shallow(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() wrapper = mount(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() wrapper = render(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() }) })
src/index.js
undefinedist/sicario
import React from 'react' import ReactDOM from 'react-dom' import Docs from './docs/Docs' import '../node_modules/highlight.js/styles/ocean.css' import './index.css' import registerServiceWorker from './registerServiceWorker' ReactDOM.render(<Docs />, document.getElementById('root')) registerServiceWorker()
app/components/RentalsPage.js
stratigos/stormsreach
/****************************************************************************** * Component for composing the Rentals page of the Housing section. ******************************************************************************/ import React from 'react'; import RentalsContainer from '../containers/RentalsContainer'; import HomepageLink from './HomepageLink'; const RentalsPage = () => { return( <div className="rentals-container"> <div className='rentals-header'> <h2>Rentals</h2> <p className='subheader'>Rooms, basements, homes, and farm beds for rent.</p> </div> <div className='rentals-list-container'> <RentalsContainer /> </div> <HomepageLink /> </div> ); }; export default RentalsPage;
src/static/containers/Home/index.js
24HeuresINSA/pass-checker
import React from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import './style.scss'; import reactLogo from './images/react-logo.png'; import reduxLogo from './images/redux-logo.png'; class HomeView extends React.Component { static propTypes = { statusText: React.PropTypes.string, userName: React.PropTypes.string }; static defaultProps = { statusText: '', userName: '' }; render() { return ( <div className="container"> <div className="margin-top-medium text-center"> <img className="page-logo margin-bottom-medium" src={reactLogo} alt="ReactJs" /> <img className="page-logo margin-bottom-medium" src={reduxLogo} alt="Redux" /> </div> <div className="text-center"> <h1>Pass Checker</h1> <h4>Bienvenue, {this.props.userName || 'invité'}.</h4> </div> <div className="margin-top-medium text-center"> <p>Accéder à la recherche de <Link to="/pass"><b>laissez-passer</b></Link>.</p> </div> <div className="margin-top-medium"> {this.props.statusText ? <div className="alert alert-info"> {this.props.statusText} </div> : null } </div> </div> ); } } const mapStateToProps = (state) => { return { userName: state.auth.userName, statusText: state.auth.statusText }; }; export default connect(mapStateToProps)(HomeView); export { HomeView as HomeViewNotConnected };
src/molecules/archive/pagination/component-test.js
dsmjs/components
import React from 'react'; import {shallow} from 'enzyme'; import any from '@travi/any'; import {assert} from 'chai'; import Pagination from '.'; suite('archive pagination', () => { test('that links are rendered for each page', () => { const totalPages = any.integer({min: 2, max: 10}); const currentPage = any.integer({max: totalPages}) + 1; const wrapper = shallow(<Pagination totalPages={totalPages} currentPage={currentPage} />); const pages = wrapper.find('ol > li'); assert.equal(pages.length, totalPages); pages.forEach((page, index) => { const link = page.find('InternalLink'); const pageNumber = index + 1; assert.equal(link.prop('to'), 0 === index ? '/archive' : `/archive/page-${pageNumber}`); assert.equal(link.children().text(), `${pageNumber}`); }); }); });
src/client/components/hoc/Order/withOrders.hoc.js
DBCDK/content-first
import React from 'react'; import {connect} from 'react-redux'; export const withOrders = WrappedComponent => { const Wrapper = class extends React.Component { render() { return <WrappedComponent {...this.props} />; } }; const mapStateToProps = state => { return { orders: state.orderReducer.orders }; }; return connect(mapStateToProps)(Wrapper); };
scripts/utils/connectToStores.js
machnicki/healthunlocked
import React, { Component } from 'react'; import shallowEqual from 'react-pure-render/shallowEqual'; /** * Exports a higher-order component that connects the component to stores. * This higher-order component is most easily used as an ES7 decorator. * Decorators are just a syntax sugar over wrapping class in a function call. * * Read more about higher-order components: https://goo.gl/qKYcHa * Read more about decorators: https://github.com/wycats/javascript-decorators */ export default function connectToStores(stores, getState) { return function (DecoratedComponent) { const displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'; return class StoreConnector extends Component { static displayName = `connectToStores(${displayName})`; constructor(props) { super(props); this.handleStoresChanged = this.handleStoresChanged.bind(this); this.state = getState(props); } componentWillMount() { stores.forEach(store => store.addChangeListener(this.handleStoresChanged) ); } componentWillReceiveProps(nextProps) { if (!shallowEqual(nextProps, this.props)) { this.setState(getState(nextProps)); } } componentWillUnmount() { stores.forEach(store => store.removeChangeListener(this.handleStoresChanged) ); } handleStoresChanged() { this.setState(getState(this.props)); } render() { return <DecoratedComponent {...this.props} {...this.state} />; } }; }; }
test/CollapsibleNavSpec.js
JimiHFord/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Navbar from '../src/Navbar'; import CollapsibleNav from '../src/CollapsibleNav'; import Nav from '../src/Nav'; import NavItem from '../src/NavItem'; describe('CollapsibleNav', function () { it('Should create div and add collapse class', function () { let Parent = React.createClass({ render() { return ( <Navbar toggleNavKey={1}> <CollapsibleNav eventKey={1}> <Nav> <NavItem eventKey={1} ref='item1'>Item 1 content</NavItem> <NavItem eventKey={2} ref='item2'>Item 2 content</NavItem> </Nav> </CollapsibleNav> </Navbar> ); } }); let instance = ReactTestUtils.renderIntoDocument(<Parent />); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'navbar-collapse')); }); it('Should handle multiple Nav elements', function () { let Parent = React.createClass({ render() { return ( <Navbar toggleNavKey={1}> <CollapsibleNav eventKey={1} ref='collapsible_object'> <Nav> <NavItem eventKey={1} ref='item1'>Item 1 content</NavItem> <NavItem eventKey={2} ref='item2'>Item 2 content</NavItem> </Nav> <Nav> <NavItem eventKey={1} ref='item1'>Item 1 content</NavItem> <NavItem eventKey={2} ref='item2'>Item 2 content</NavItem> </Nav> </CollapsibleNav> </Navbar> ); } }); let instance = ReactTestUtils.renderIntoDocument(<Parent />); assert.ok(ReactTestUtils.findRenderedComponentWithType(instance.refs.collapsible_object.refs.collapsible_0, Nav)); assert.ok(ReactTestUtils.findRenderedComponentWithType(instance.refs.collapsible_object.refs.collapsible_1, Nav)); }); it('Should just render children and move along if not in <Navbar>', function () { let Parent = React.createClass({ render() { return ( <CollapsibleNav eventKey={1}> <Nav> <NavItem eventKey={1} ref='item1'>Item 1 content</NavItem> <NavItem eventKey={2} ref='item2'>Item 2 content</NavItem> </Nav> </CollapsibleNav> ); } }); let instance = ReactTestUtils.renderIntoDocument(<Parent />); let collapsibleNav = ReactTestUtils.findRenderedComponentWithType(instance, CollapsibleNav); assert.notOk(React.findDOMNode(collapsibleNav).className.match(/\navbar-collapse\b/)); let nav = ReactTestUtils.findRenderedComponentWithType(collapsibleNav.refs.nocollapse_0, Nav); assert.ok(nav); }); it('Should retain childrens classes set by className', function () { let Parent = React.createClass({ render() { return ( <Navbar toggleNavKey={1}> <CollapsibleNav eventKey={1} ref='collapsible_object'> <Nav> <NavItem eventKey={1} ref='item1' className='foo bar'>Item 1 content</NavItem> <NavItem eventKey={2} ref='item2' className='baz'>Item 2 content</NavItem> </Nav> </CollapsibleNav> </Navbar> ); } }); let instance = ReactTestUtils.renderIntoDocument(<Parent />); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.collapsible_object.refs.collapsible_0, 'foo')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.collapsible_object.refs.collapsible_0, 'bar')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.collapsible_object.refs.collapsible_0, 'baz')); }); });
packages/generator-emakinacee-react/generators/app/templates/static/src/index.js
emakina-cee-oss/generator-emakinacee-react
import React from 'react'; import ReactDOM from 'react-dom'; import { Container } from '@cerebral/react'; import App from './containers/App/App'; import controller from './controller'; import registerServiceWorker from './registerServiceWorker'; import './styles/global.scss'; ReactDOM.render( <Container controller={controller} > <App /> </Container>, document.getElementById('root') ); registerServiceWorker();
src/svg-icons/notification/drive-eta.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDriveEta = (props) => ( <SvgIcon {...props}> <path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z"/> </SvgIcon> ); NotificationDriveEta = pure(NotificationDriveEta); NotificationDriveEta.displayName = 'NotificationDriveEta'; NotificationDriveEta.muiName = 'SvgIcon'; export default NotificationDriveEta;
test/components/FileUploadProgress_spec.js
georgeOsdDev/react-fileupload-progress
'use strict'; import React from 'react'; import ReactDom from 'react-dom'; import TestUtils from 'react-dom/test-utils'; import chai from 'chai'; import sinon from 'sinon'; let expect = chai.expect; import FileUploadProgress from '../../src/components/FileUploadProgress'; describe('Test of FileUploadProgress', () => { let component; it('should have default properties', () => { component = TestUtils.renderIntoDocument( <FileUploadProgress url='https://localhost.com/api' />); expect(component.props.onProgress).to.be.a('function'); expect(component.props.onLoad).to.be.a('function'); expect(component.props.onError).to.be.a('function'); expect(component.props.onAbort).to.be.a('function'); expect(component.props.formGetter).to.be.a('undefined'); expect(component.props.formRenderer).to.be.a('function'); expect(component.props.progressRenderer).to.be.a('function'); expect(component.props.formCustomizer).to.be.a('function'); expect(component.props.beforeSend).to.be.a('function'); }); describe('Test of rendered components', () => { it('use builtin renderer by default', () => { component = TestUtils.renderIntoDocument( <FileUploadProgress url='https://localhost.com/api' />); /* Default rendered from*/ // <div> // <form ref='form' method='post' onSubmit={onSubmit}> // <div> // <input type='file' name='file' /> // </div> // <input type='submit' /> // </form> // </div> let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); expect(ReactDom.findDOMNode(form).method).to.be.eql('post'); let inputContent = TestUtils.scryRenderedDOMComponentsWithTag(component, 'input'); expect(inputContent.length).to.be.eql(2); expect(ReactDom.findDOMNode(inputContent[0]).type).to.be.eql('file'); expect(ReactDom.findDOMNode(inputContent[1]).type).to.be.eql('submit'); }); it('use provided form renderer when specified', () => { let customFormRenderer = (onSubmit) => { return ( <form id='customForm' method='get'> <button type='button' onClick={onSubmit}>Upload</button> </form> ); } component = TestUtils.renderIntoDocument( <FileUploadProgress url='https://localhost.com/api' formRenderer={customFormRenderer} />); let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); expect(ReactDom.findDOMNode(form).method).to.be.eql('get'); expect(ReactDom.findDOMNode(form).id).to.be.eql('customForm'); let inputContent = TestUtils.scryRenderedDOMComponentsWithTag(component, 'input'); expect(inputContent.length).to.be.eql(0); let buttonContent = TestUtils.scryRenderedDOMComponentsWithTag(component, 'button'); expect(buttonContent.length).to.be.eql(1); }); }); describe('Test of xhr events handler', () => { let requests; let onProgressSpy; let onLoadSpy; let onErrorSpy; let onAbortSpy; beforeEach(() => { onProgressSpy = sinon.spy(); onLoadSpy= sinon.spy(); onErrorSpy= sinon.spy(); onAbortSpy= sinon.spy(); sinon.useFakeXMLHttpRequest(); requests = []; sinon.FakeXMLHttpRequest.onCreate = function (xhr) { requests.push(xhr); }; component = TestUtils.renderIntoDocument( <FileUploadProgress url='https://localhost.com/api' onProgress={onProgressSpy} onLoad={onLoadSpy} onError={onErrorSpy} onAbort={onAbortSpy} />); let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); TestUtils.Simulate.submit(form); }); afterEach(() => { sinon.FakeXMLHttpRequest.restore(); }); describe('onProgress handler', () => { it('should handle xhr progress events', () => { requests[0].uploadProgress({ total: 100, loaded: 20 }); requests[0].uploadProgress({ total: 100, loaded: 40 }); expect(onProgressSpy.calledTwice).to.be.eql(true); let arg0 = onProgressSpy.args[0]; let arg1 = onProgressSpy.args[1]; expect(arg0.length).to.be.eql(3); expect(arg0[2]).to.be.eql(20); expect(arg1[2]).to.be.eql(40); expect(onLoadSpy.called).to.be.not.equal(true) expect(onErrorSpy.called).to.be.not.equal(true) expect(onAbortSpy.called).to.be.not.equal(true) }); }); describe('onLoad handler', () => { it('should handle xhr load event', () => { requests[0].respond(200, { 'Content-Type': 'application/json' }, '[{ "error": 0}]') expect(onProgressSpy.calledOnce).to.be.equal(true) let progress = onProgressSpy.args[0][2]; expect(progress).to.be.eql(100); // expect(onLoadSpy.calledOnce).to.be.equal(true); let event = onLoadSpy.args[0][0]; let request = onLoadSpy.args[0][1]; expect(event.type).to.be.eql('load'); expect(request.status).to.be.eql(200); // expect(onErrorSpy.called).to.be.not.equal(true) // expect(onAbortSpy.called).to.be.not.equal(true) }); }); describe('onError handler', () => { it('should handle xhr error event', () => { requests[0].dispatchEvent(new Event('error', {})); expect(onErrorSpy.calledOnce).to.be.equal(true); let event = onErrorSpy.args[0][0]; let request = onErrorSpy.args[0][1]; expect(event.type).to.be.eql('error'); expect(request.readyState).to.be.eql(sinon.FakeXMLHttpRequest.OPENED); expect(onProgressSpy.called).to.be.not.equal(true) expect(onLoadSpy.called).to.be.not.equal(true) expect(onAbortSpy.called).to.be.not.equal(true) }); }); describe('onAbort handler', () => { it('should handle xhr abort event', () => { requests[0].abort(); // FakeXMLHttpRequest respond progress event on abort // https://github.com/sinonjs/sinon/blob/master/lib/sinon/util/fake_xml_http_request.js#L454 expect(onProgressSpy.calledOnce).to.be.equal(true) let progress = onProgressSpy.args[0][2]; expect(progress).to.be.eql(0); expect(onAbortSpy.calledOnce).to.be.equal(true); let event = onAbortSpy.args[0][0]; let request = onAbortSpy.args[0][1]; expect(event.type).to.be.eql('abort'); expect(request.readyState).to.be.eql(sinon.FakeXMLHttpRequest.UNSENT); expect(onErrorSpy.called).to.be.not.equal(true) expect(onLoadSpy.called).to.be.not.equal(true) }); }); }); describe('Test of xhr custom hook', () => { let requests; let formCustomizerSpy; let beforeSendSpy; beforeEach(() => { formCustomizerSpy = sinon.spy(); let formCustomizer = (form) => { formCustomizerSpy(form); form.append('customeForm', 'myCustomForm') return form; }; beforeSendSpy = sinon.spy(); let beforeSend = (request) => { beforeSendSpy(request); request.setRequestHeader('customHeader', 'myCustomHeader'); return request; }; sinon.useFakeXMLHttpRequest(); requests = []; sinon.FakeXMLHttpRequest.onCreate = function (xhr) { requests.push(xhr); }; component = TestUtils.renderIntoDocument( <FileUploadProgress url='https://localhost.com/api' beforeSend={beforeSend} formCustomizer={formCustomizer} />); let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); TestUtils.Simulate.submit(form); }); afterEach(() => { sinon.FakeXMLHttpRequest.restore(); }); it('call custom form hook before sending xhr', () => { expect(formCustomizerSpy.calledOnce).to.be.equal(true) let form = formCustomizerSpy.args[0][0]; expect(typeof form).to.be.eql('object'); }); it('call custom request hook before sending xhr', () => { expect(beforeSendSpy.calledOnce).to.be.equal(true) let request = beforeSendSpy.args[0][0]; expect(typeof request).to.be.eql('object'); }); }); describe('Test of xhr progress component', () => { describe('use builtin renderer by default', () => { let requests; let onAbortSpy; beforeEach(() => { onAbortSpy= sinon.spy(); sinon.useFakeXMLHttpRequest(); requests = []; sinon.FakeXMLHttpRequest.onCreate = function (xhr) { requests.push(xhr); }; component = TestUtils.renderIntoDocument( <FileUploadProgress url='https://localhost.com/api' onAbort={onAbortSpy}/>); }); afterEach(() => { sinon.FakeXMLHttpRequest.restore(); }); describe('before submit', () => { it('it render nothing when progress is 0', () => { let progressBarContent = TestUtils.scryRenderedDOMComponentsWithClass(component, '_react_fileupload_progress_content'); expect(progressBarContent.length).to.be.eql(0); }); }); describe('after submit', () => { it('change bar width depends on progress', () => { let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); TestUtils.Simulate.submit(form); requests[0].uploadProgress({ total: 100, loaded: 20 }); let progressBarContent = TestUtils.scryRenderedDOMComponentsWithClass(component, '_react_fileupload_progress_content'); expect(progressBarContent.length).to.be.eql(1); let progressBar = TestUtils.findRenderedDOMComponentWithClass(component, '_react_fileupload_progress_bar'); expect(ReactDom.findDOMNode(progressBar).style.width).to.be.eql('20%'); }); }); describe('provides abort helper', () => { it('stop uploading when cancel button clicked', () => { let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); TestUtils.Simulate.submit(form); requests[0].uploadProgress({ total: 100, loaded: 20 }); let progressBarContent = TestUtils.scryRenderedDOMComponentsWithClass(component, '_react_fileupload_progress_content'); let cancelButton = progressBarContent[0].querySelector('._react_fileupload_progress_cancel'); TestUtils.Simulate.click(cancelButton); expect(onAbortSpy.calledOnce).to.be.equal(true); let event = onAbortSpy.args[0][0]; let request = onAbortSpy.args[0][1]; expect(event.type).to.be.eql('abort'); expect(request.readyState).to.be.eql(sinon.FakeXMLHttpRequest.UNSENT); }); }); }); describe('use custome progress rendere when specified', () => { let requests; let rendererSpy; let onAbortSpy; let customProgressRenderer; beforeEach(() => { rendererSpy= sinon.spy(); onAbortSpy= sinon.spy(); customProgressRenderer = (progress, hasError, cancelHandler) => { rendererSpy(progress, hasError, cancelHandler); return ( <div className='customProgress' > <button className='canceler' onClick={cancelHandler}></button> </div> ); } sinon.useFakeXMLHttpRequest(); requests = []; sinon.FakeXMLHttpRequest.onCreate = function (xhr) { requests.push(xhr); }; component = TestUtils.renderIntoDocument( <FileUploadProgress url='https://localhost.com/api' onAbort={onAbortSpy} progressRenderer={customProgressRenderer}/>); }); afterEach(() => { sinon.FakeXMLHttpRequest.restore(); }); describe('before submit', () => { it('use provided form renderer when specified', () => { let customProgress = TestUtils.scryRenderedDOMComponentsWithClass(component, 'customProgress'); expect(customProgress.length).to.be.eql(1); }); }); describe('after submit', () => { it('pass progress parameter to custom renderer', (done) => { let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); TestUtils.Simulate.submit(form); requests[0].uploadProgress({ total: 100, loaded: 20 }); requests[0].uploadProgress({ total: 100, loaded: 40 }); let customProgress = TestUtils.scryRenderedDOMComponentsWithClass(component, 'customProgress'); expect(customProgress.length).to.be.eql(1); expect(rendererSpy.callCount).to.be.equal(4); let arg0 = rendererSpy.args[0]; let arg1 = rendererSpy.args[1]; let arg2 = rendererSpy.args[2]; let arg3 = rendererSpy.args[3]; expect(arg0.length).to.be.eql(3); expect(arg0[0]).to.be.eql(-1); expect(arg0[1]).to.be.eql(false); expect(typeof arg0[2]).to.be.eql('function'); expect(arg1[0]).to.be.eql(0); expect(arg2[0]).to.be.eql(20); expect(arg3[0]).to.be.eql(40); done(); }); }); describe('on error', () => { it('pass hasError parameter to custom renderer', (done) => { let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); TestUtils.Simulate.submit(form); requests[0].dispatchEvent(new Event('error', {})); let customProgress = TestUtils.scryRenderedDOMComponentsWithClass(component, 'customProgress'); expect(customProgress.length).to.be.eql(1); expect(rendererSpy.callCount).to.be.equal(3); let arg0 = rendererSpy.args[0]; let arg1 = rendererSpy.args[1]; let arg2 = rendererSpy.args[2]; expect(arg0.length).to.be.eql(3); expect(arg0[0]).to.be.eql(-1); expect(arg0[1]).to.be.eql(false); expect(typeof arg0[2]).to.be.eql('function'); expect(arg1[0]).to.be.eql(0); expect(arg2[1]).to.be.eql(true); done(); }); }); describe('provides abort helper', () => { it('stop uploading when cancel button clicked', () => { let form = TestUtils.findRenderedDOMComponentWithTag(component, 'form'); TestUtils.Simulate.submit(form); requests[0].uploadProgress({ total: 100, loaded: 20 }); let progressBarContent = TestUtils.scryRenderedDOMComponentsWithClass(component, 'customProgress'); let cancelButton = progressBarContent[0].querySelector('.canceler'); TestUtils.Simulate.click(cancelButton); expect(onAbortSpy.calledOnce).to.be.equal(true); let event = onAbortSpy.args[0][0]; let request = onAbortSpy.args[0][1]; expect(event.type).to.be.eql('abort'); expect(request.readyState).to.be.eql(sinon.FakeXMLHttpRequest.UNSENT); expect(rendererSpy.callCount).to.be.equal(4); let arg0 = rendererSpy.args[0]; let arg1 = rendererSpy.args[1]; let arg2 = rendererSpy.args[2]; let arg3 = rendererSpy.args[3]; expect(arg0.length).to.be.eql(3); expect(arg0[0]).to.be.eql(-1); expect(arg0[1]).to.be.eql(false); expect(typeof arg0[2]).to.be.eql('function'); expect(arg1[0]).to.be.eql(0); expect(arg2[0]).to.be.eql(20); expect(arg3[0]).to.be.eql(-1); expect(arg3[1]).to.be.eql(false); }); }); }); }); });
src/index.js
papernotes/actemotion
import React from 'react'; import {render} from 'react-dom'; import {createStore, combineReducers, applyMiddleware} from 'redux'; import thunkMiddleware from 'redux-thunk' import {Provider} from 'react-redux'; import {Router, Route, IndexRoute, browserHistory} from 'react-router'; import {syncHistoryWithStore, routerReducer} from 'react-router-redux'; import App from './containers/App'; import Home from './containers/Home'; import CreateAccount from './components/CreateAccount'; import CalendarPage from './containers/CalendarPage'; import Analytics from './containers/Analytics'; import NotFound from './components/NotFound'; import Login from './components/Login'; import AddEvent from './components/AddEvent'; // unused import Home2 from './containers/Home2'; import Settings from './containers/Settings'; import Analytics2 from './containers/Analytics2'; import * as reducers from './reducers'; const reducer = combineReducers({ ...reducers, routing: routerReducer }); const store = createStore( reducer, applyMiddleware( thunkMiddleware ) ) const history = syncHistoryWithStore(browserHistory, store); render( <Provider store={store}> <Router history={history}> <Route path='/' component={App}> <IndexRoute component={Login}/> <Route path='home' component={Home}/> <Route path='calendar' component={CalendarPage}/> <Route path='home2' component={Home2}/> <Route path='create' component={CreateAccount}/> <Route path='settings' component={Settings}/> <Route path='analytics' component={Analytics}/> <Route path='analytics2' component={Analytics2}/> <Route path='editevent' component={AddEvent}/> <Route path='*' component={NotFound}/> </Route> </Router> </Provider>, document.getElementById('root') );
src/svg-icons/maps/person-pin.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsPersonPin = (props) => ( <SvgIcon {...props}> <path d="M19 2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 3.3c1.49 0 2.7 1.21 2.7 2.7 0 1.49-1.21 2.7-2.7 2.7-1.49 0-2.7-1.21-2.7-2.7 0-1.49 1.21-2.7 2.7-2.7zM18 16H6v-.9c0-2 4-3.1 6-3.1s6 1.1 6 3.1v.9z"/> </SvgIcon> ); MapsPersonPin = pure(MapsPersonPin); MapsPersonPin.displayName = 'MapsPersonPin'; MapsPersonPin.muiName = 'SvgIcon'; export default MapsPersonPin;
app-client/src/index.js
vikoperdomo/serverql
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
docs/app/Examples/collections/Form/FieldVariations/index.js
Rohanhacker/Semantic-UI-React
import React from 'react' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' const FormFieldVariationsExamples = () => ( <ExampleSection title='Field Variations'> <ComponentExample title='Inline' description='A field can have its label next to instead of above it.' examplePath='collections/Form/FieldVariations/FormExampleInlineField' /> </ExampleSection> ) export default FormFieldVariationsExamples