path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
client/src/components/App.js
jobn/iceman
// @flow import React, { Component } from 'react'; import { Route, Redirect, withRouter } from 'react-router-dom' import { connect } from 'react-redux'; import { authenticationSelector } from '../selectors/authentication' import Dashboard from './Dashboard' type Props = { authenticated: boolean, } class App extends Component<Props> { props: Props render() { const { authenticated } = this.props return ( <Route path="/app" render={() => authenticated ? <Dashboard /> : <Redirect to="/login" /> } /> ); } } export default withRouter(connect( authenticationSelector, )(App));
src/views/PostManage/AddEditPostBox.js
halo-design/halo-optimus
import React from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { Form, Button, Input, Row, Col, message, Modal, Radio } from 'antd' import Spin from 'COMPONENT/effects/Spin' import { closeAddEditBox, addPostList, modifyPost } from 'REDUCER/pages/postManage' const FormItem = Form.Item const RadioGroup = Radio.Group @connect( state => { const { pages: { postManage: { addEditBoxVisible, addEditBoxType, addEditBoxInitVals } } } = state return { visible: addEditBoxVisible, formType: addEditBoxType, initVals: addEditBoxInitVals } }, dispatch => bindActionCreators({ closeAddEditBox, addPostList, modifyPost }, dispatch) ) @Form.create() export default class AddEditPostBoxView extends React.Component { constructor (props) { super(props) this.state = { loading: false } } componentWillMount () { this.props.form.resetFields() } onClose () { this.props.closeAddEditBox() this.onClear() } onClear () { this.props.form.resetFields() } onSubmit () { const { form, formType, addPostList, modifyPost, initVals } = this.props const { getFieldsValue, validateFields } = form validateFields((errors, values) => { if (errors) { message.error('请正确填写内容!') } else { let formData = getFieldsValue() let handle = addPostList if (formType === 'edit') { formData.postId = initVals.postId handle = modifyPost } const showSpin = () => { this.setState({ loading: true }) } const hideSpin = () => { this.setState({ loading: false }) } showSpin() handle(formData, () => { this.onClear() this.onClose() hideSpin() }, hideSpin) } }) } render () { const { visible, formType, initVals, form } = this.props const { getFieldDecorator } = form const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } } let addType = formType === 'add' return ( <div className='AddRoleBox'> <Modal title={addType ? '新增岗位' : '修改岗位'} width={600} visible={visible} onOk={this.onSubmit} onCancel={e => this.onClose()} footer={[ <Button key='back' type='ghost' size='large' onClick={e => this.onClose()} > 返 回 </Button>, addType ? <Button key='clean' type='ghost' size='large' onClick={e => this.onClear()} > 清除 </Button> : '', <Button key='submit' type='primary' size='large' onClick={e => this.onSubmit()} > 提 交 </Button> ]} > <Form layout='horizontal'> <Row> <Col span={11}> <FormItem label='岗位名称:' {...formItemLayout} required > { getFieldDecorator('postName', { initialValue: addType ? '' : initVals.postName, rules: [ { required: true, message: '请输入岗位名称' } ] })( <Input placeholder='请输入岗位名称' size='large' /> ) } </FormItem> <FormItem label='状态:' {...formItemLayout} required > { getFieldDecorator('state', { initialValue: addType ? '0' : initVals.state, rules: [{ message: ' ' }] })( <RadioGroup> <Radio key='a' value='1'>可用</Radio> <Radio key='b' value='0'>禁用</Radio> </RadioGroup> ) } </FormItem> </Col> <Col span={13}> <FormItem label='备注:' {...formItemLayout} > { getFieldDecorator('remark', { initialValue: addType ? '' : initVals.remark })( <Input placeholder='请输入备注' size='large' /> ) } </FormItem> </Col> </Row> </Form> <Spin loading={this.state.loading} /> </Modal> </div> ) } }
webpack/scenes/RedHatRepositories/components/RepositorySetRepositories.js
johnpmitsch/katello
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Alert, Spinner } from 'patternfly-react'; import { translate as __ } from 'foremanReact/common/I18n'; import loadRepositorySetRepos from '../../../redux/actions/RedHatRepositories/repositorySetRepositories'; import RepositorySetRepository from './RepositorySetRepository/'; import { yStream } from './RepositorySetRepositoriesHelpers'; export class RepositorySetRepositories extends Component { componentDidMount() { const { contentId, productId } = this.props; if (this.props.data.loading) { this.props.loadRepositorySetRepos(contentId, productId); } } sortedRepos = repos => [...repos.filter(({ enabled }) => !enabled)] .sort((repo1, repo2) => { const repo1YStream = yStream(repo1.releasever || ''); const repo2YStream = yStream(repo2.releasever || ''); if (repo1YStream < repo2YStream) { return -1; } if (repo2YStream < repo1YStream) { return 1; } if (repo1.arch === repo2.arch) { const repo1MajorMinor = repo1.releasever.split('.'); const repo2MajorMinor = repo2.releasever.split('.'); const repo1Major = parseInt(repo1MajorMinor[0], 10); const repo2Major = parseInt(repo2MajorMinor[0], 10); if (repo1Major === repo2Major) { const repo1Minor = parseInt(repo1MajorMinor[1], 10); const repo2Minor = parseInt(repo2MajorMinor[1], 10); if (repo1Minor === repo2Minor) { return 0; } return (repo1Minor > repo2Minor) ? -1 : 1; } return (repo1Major > repo2Major) ? -1 : 1; } return (repo1.arch > repo2.arch) ? -1 : 1; }); render() { const { data, type } = this.props; if (data.error) { return ( <Alert type="danger"> <span>{data.error.displayMessage}</span> </Alert> ); } const availableRepos = this.sortedRepos(data.repositories).map(repo => ( <RepositorySetRepository key={repo.arch + repo.releasever} type={type} {...repo} /> )); const repoMessage = (data.repositories.length > 0 && availableRepos.length === 0 ? __('All available architectures for this repo are enabled.') : __('No repositories available.')); return ( <Spinner loading={data.loading}> {availableRepos.length ? availableRepos : <div>{repoMessage}</div>} </Spinner> ); } } RepositorySetRepositories.propTypes = { loadRepositorySetRepos: PropTypes.func.isRequired, contentId: PropTypes.number.isRequired, productId: PropTypes.number.isRequired, type: PropTypes.string, data: PropTypes.shape({ loading: PropTypes.bool.isRequired, repositories: PropTypes.arrayOf(PropTypes.object), error: PropTypes.shape({ displayMessage: PropTypes.string, }), }).isRequired, }; RepositorySetRepositories.defaultProps = { type: '', }; const mapStateToProps = ( { katello: { redHatRepositories: { repositorySetRepositories } } }, props, ) => ({ data: repositorySetRepositories[props.contentId] || { loading: true, repositories: [], error: null, }, }); export default connect(mapStateToProps, { loadRepositorySetRepos, })(RepositorySetRepositories);
containers/counter.js
gor181/react-redux-simple-counter
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as actions from '../actions/Counter.actions'; const Counter = React.createClass({ displayName: 'Counter', render() { const { increment, decrement, count } = this.props; return ( <div> Current counter value: {count} <div><button onClick={(e) => increment()}>Increment</button></div> <div><button onClick={(e) => decrement()}>Decrement</button></div> </div> ); } }); function mapStateToProps(state) { return { count: state }; } function mapDispatchToProps(dispatch) { return bindActionCreators(actions, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(Counter);
src/components/AppRoutes.js
rksaxena/wedding
// src/components/AppRoutes.js import React from 'react'; import { Router, browserHistory } from 'react-router'; import routes from '../routes'; export default class AppRoutes extends React.Component { render() { return ( <Router history={browserHistory} routes={routes} onUpdate={() => window.scrollTo(0, 0)}/> ); } }
src/skeletons/firstIter/layout/sidebar/Separator.js
WapGeaR/react-redux-boilerplate-auth
import React from 'react' export default class Component extends React.Component { constructor(props) { super(props); } render() { return(<li className="nav-separator">{this.props.name}</li>) } }
src/templates/feeds/components/FeedSubject.js
PatrickHai/react-client-changers
import React from 'react'; class FeedSubject extends React.Component{ render(){ let subject = this.props.subject; if(this.props.type === 0){ return ( <div className="subject"> <img className="hotel-logo" src={subject.logo} /> <div className="hotel"> <span className="hotel-name">{subject.name}</span> <span className="hotel-category" style={{'backgroundColor':'#00a0ea'}}>{subject.category}</span> <div className="hotel-score"> <span className="hotel-score-value" style={{'backgroundColor':'orange'}}>{subject.score}</span> <span className="hotel-score-item">{subject.score_item}</span> </div> </div> </div> ) }else if(this.props.type === 1){ return ( <div className="subject"> <div className="flight-airline"> <span className="flight-aircraft-lying">{subject.lying}</span> <span className="flight-aircraft">{subject.aircraft}</span> <span className="flight-airline-name">{subject.airline_name}</span> </div> <img className="flight-logo" src={subject.logo} /> <span className="flight-name">{subject.airline_name}</span> <span className="flight-airport">{subject.flight_line}</span> </div> ) }else if(this.props.type === 2){ return ( <div className="subject"> <img className="hotel-logo rights-logo" src={subject.logo} /> <div className="hotel rights"> <span className="hotel-name" style={{'overflow':'hidden', 'whiteSpace':'nowrap', 'textOverflow':'ellipsis'}}> {subject.name}</span> <span className="shop-count">{subject.shop_count}</span> </div> </div> ) } } } export default FeedSubject;
src/svg-icons/action/settings-input-composite.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsInputComposite = (props) => ( <SvgIcon {...props}> <path d="M5 2c0-.55-.45-1-1-1s-1 .45-1 1v4H1v6h6V6H5V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2H9v2zm-8 0c0 1.3.84 2.4 2 2.82V23h2v-4.18C6.16 18.4 7 17.3 7 16v-2H1v2zM21 6V2c0-.55-.45-1-1-1s-1 .45-1 1v4h-2v6h6V6h-2zm-8-4c0-.55-.45-1-1-1s-1 .45-1 1v4H9v6h6V6h-2V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2h-6v2z"/> </SvgIcon> ); ActionSettingsInputComposite = pure(ActionSettingsInputComposite); ActionSettingsInputComposite.displayName = 'ActionSettingsInputComposite'; ActionSettingsInputComposite.muiName = 'SvgIcon'; export default ActionSettingsInputComposite;
src/client/app/header.react.js
messa/itsrazy.cz-web
import Component from '../components/component.react'; import React from 'react'; import {FormattedHTMLMessage} from 'react-intl'; import {Link} from 'react-router'; export default class Header extends Component { static propTypes = { msg: React.PropTypes.object.isRequired, viewer: React.PropTypes.object } render() { const {msg: {app: {header}}, viewer} = this.props; return ( <header> <h1> <FormattedHTMLMessage message={header.h1Html} /> </h1> </header> ); } }
client/index.js
jhabdas/12roads
import 'babel-polyfill' import { trigger } from 'redial' import React from 'react' import ReactDOM from 'react-dom' import Router from 'react-router/lib/Router' import match from 'react-router/lib/match' import browserHistory from 'react-router/lib/browserHistory' import { Provider } from 'react-redux' import { StyleSheet } from 'aphrodite' import injectTapEventPlugin from 'react-tap-event-plugin' import { configureStore } from '../common/store' const initialState = window.INITIAL_STATE || {} // Set up Redux (note: this API requires redux@>=3.1.0): const store = configureStore(initialState) const { dispatch } = store const container = document.getElementById('root') StyleSheet.rehydrate(window.renderedClassNames) // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin() const render = () => { const { pathname, search, hash } = window.location const location = `${pathname}${search}${hash}` // We need to have a root route for HMR to work. const createRoutes = require('../common/routes/root').default const routes = createRoutes(store) // Pull child routes using match. Adjust Router for vanilla webpack HMR, // in development using a new key every time there is an edit. match({ routes, location }, () => { // Render app with Redux and router context to container element. // We need to have a random in development because of `match`'s dependency on // `routes.` Normally, we would want just one file from which we require `routes` from. ReactDOM.render( <Provider store={store}> <Router routes={routes} history={browserHistory} key={Math.random()} /> </Provider>, container ) }) return browserHistory.listen(location => { // Match routes based on location object: match({ routes, location }, (error, redirectLocation, renderProps) => { if (error) console.log(error) // Get array of route handler components: const { components } = renderProps // Define locals to be provided to all lifecycle hooks: const locals = { path: renderProps.location.pathname, query: renderProps.location.query, params: renderProps.params, // Allow lifecycle hooks to dispatch Redux actions: dispatch } // Don't fetch data for initial route, server has already done the work: if (window.INITIAL_STATE) { // Delete initial data so that subsequent data fetches can occur: delete window.INITIAL_STATE } else { // Fetch mandatory data dependencies for 2nd route change onwards: trigger('fetch', components, locals) } // Fetch deferred, client-only data dependencies: trigger('defer', components, locals) }) }) } const unsubscribeHistory = render() if (module.hot) { module.hot.accept('../common/routes/root', () => { unsubscribeHistory() setTimeout(render) }) }
docs/app/Examples/elements/Button/GroupVariations/ButtonExampleGroupFloated.js
shengnian/shengnian-ui-react
import React from 'react' import { Button } from 'shengnian-ui-react' const ButtonExampleGroupFloated = () => ( <div> <Button.Group floated='left'> <Button>One</Button> <Button>Two</Button> <Button>Three</Button> </Button.Group> <Button.Group floated='right'> <Button>One</Button> <Button>Two</Button> <Button>Three</Button> </Button.Group> </div> ) export default ButtonExampleGroupFloated
src/svg-icons/action/view-list.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionViewList = (props) => ( <SvgIcon {...props}> <path d="M4 14h4v-4H4v4zm0 5h4v-4H4v4zM4 9h4V5H4v4zm5 5h12v-4H9v4zm0 5h12v-4H9v4zM9 5v4h12V5H9z"/> </SvgIcon> ); ActionViewList = pure(ActionViewList); ActionViewList.displayName = 'ActionViewList'; ActionViewList.muiName = 'SvgIcon'; export default ActionViewList;
src/parser/shared/modules/items/bfa/enchants/Navigation.js
sMteX/WoWAnalyzer
import React from 'react'; import SpellIcon from 'common/SpellIcon'; import { formatDuration, formatPercentage } from 'common/format'; import SpellLink from 'common/SpellLink'; import StatisticBox from 'interface/others/StatisticBox'; import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY'; import UptimeIcon from 'interface/icons/Uptime'; import CriticalStrikeIcon from 'interface/icons/CriticalStrike'; import Analyzer from 'parser/core/Analyzer'; /** * Navigation Enchants * Permanently enchant a weapon to sometimes increase <stat> by 50 for 30 sec, stacking up to 5 times. Upon reaching 5 stacks, all stacks are consumed to grant you 600 <stat> for 10 sec. */ class Navigation extends Analyzer { static enchantableSlots = { 15: 'MainHand', 16: 'OffHand', }; static enchantId = null; static smallBuffId = null; static bigBuffId = null; static primaryStat = ""; static statPerStack = 50; static statAtMax = 600; getEnchantableGear() { return Object.keys(this.constructor.enchantableSlots).reduce((obj, slot) => { obj[slot] = this.selectedCombatant._getGearItemBySlotId(slot); return obj; }, {}); } itemHasTrackedEnchant(item) { return item && item.permanentEnchant === this.constructor.enchantId; } hasTrackedEnchant() { const items = this.getEnchantableGear(); return Object.values(items).some(item => this.itemHasTrackedEnchant(item)); } constructor(...args) { super(...args); this.active = this.hasTrackedEnchant(); } get smallStackBuffUptime() { return this.selectedCombatant.getBuffUptime(this.constructor.smallBuffId); } get maxStackBuffUptime() { return this.selectedCombatant.getBuffUptime(this.constructor.bigBuffId); } get averageStat() { const buffStacks = this.selectedCombatant.getStackBuffUptimes(this.constructor.smallBuffId); const smallBuffDuration = Object.keys(buffStacks).reduce((total, stackSize) => { return total + (buffStacks[stackSize] * stackSize); }, 0); const smallBuffIncrease = smallBuffDuration * this.constructor.statPerStack; const bigBuffIncrease = this.maxStackBuffUptime * this.constructor.statAtMax; return ((smallBuffIncrease + bigBuffIncrease) / this.owner.fightDuration).toFixed(0); } statistic() { const buffStacks = this.selectedCombatant.getStackBuffUptimes(this.constructor.smallBuffId); const maxStackBuffDuration = this.maxStackBuffUptime; return ( <StatisticBox icon={<SpellIcon id={this.constructor.smallBuffId} />} value={( <> <UptimeIcon /> {formatPercentage((this.smallStackBuffUptime + maxStackBuffDuration) / this.owner.fightDuration, 0)}% <small>uptime</small><br /> <CriticalStrikeIcon /> {this.averageStat} <small>average {this.constructor.primaryStat} gained</small> </> )} label={<SpellLink id={this.constructor.smallBuffId} icon={false} />} category={STATISTIC_CATEGORY.ITEMS} > <table className="table table-condensed"> <thead> <tr> <th>{this.constructor.primaryStat}-Bonus</th> <th>Time (s)</th> <th>Time (%)</th> </tr> </thead> <tbody> { Object.keys(buffStacks).map((stackSize) => { let totalStackDuration = buffStacks[stackSize]; if (stackSize === '0'){ totalStackDuration -= maxStackBuffDuration; } return ( <tr key={stackSize}> <th>{(stackSize * this.constructor.statPerStack).toFixed(0)}</th> <td>{formatDuration(totalStackDuration / 1000)}</td> <td>{formatPercentage(totalStackDuration / this.owner.fightDuration)}%</td> </tr> ); }) } <tr key="max"> <th>{this.constructor.statAtMax}</th> <td>{formatDuration(maxStackBuffDuration / 1000)}</td> <td>{formatPercentage(maxStackBuffDuration / this.owner.fightDuration)}%</td> </tr> </tbody> </table> </StatisticBox> ); } } export default Navigation;
src/header.js
jenstitterness/pix
import _ from 'lodash'; import React from 'react'; import Colors from 'material-ui/lib/styles/colors'; import FontIcon from 'material-ui/lib/font-icon'; import DropDownMenu from 'material-ui/lib/drop-down-menu'; import DropDownIcon from 'material-ui/lib/drop-down-icon'; import Toolbar from 'material-ui/lib/toolbar/toolbar'; import ToolbarGroup from 'material-ui/lib/toolbar/toolbar-group'; import ToolbarSeparator from 'material-ui/lib/toolbar/toolbar-separator'; import ToolbarTitle from 'material-ui/lib/toolbar/toolbar-title'; import RaisedButton from 'material-ui/lib/raised-button'; import TextField from 'material-ui/lib/text-field'; const Header = React.createClass({ refreshButton: function() { app.refreshFeed(); }, search: function(evt) { app.loadSearchList(evt.target.value); }, getStyles: function() { let styles = { button: { margin: '10px', display: 'inline' }, pullRight: { float: "right" }, searchBar: { width: "200px" } }; return styles; }, render: function() { var headerStyle = { position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100 }; const styles = this.getStyles(); const rightButton = _.extend({}, styles.button, styles.pullRight); console.log(this); return ( <div style={headerStyle}> <Toolbar> <ToolbarGroup key={0} float="left"> <RaisedButton label="Popular" primary={false} onClick={this.props.popular} /> <RaisedButton label="Profile" primary={false} onClick={this.props.profile} /> <FontIcon className="material-icons refreshIcon" onClick={this.refreshButton}>&#xE863;</FontIcon> </ToolbarGroup> <ToolbarGroup key={1} float="right"> <div className="searchBar"styles={styles.searchBar}> <TextField floatingLabelText="Search" onBlur={this.search}/> </div> </ToolbarGroup> </Toolbar> </div> ); } }); module.exports = Header;
src/routes/home/index.js
codyromano/destiny
import React from 'react'; import Home from './Home'; export default { path: '/', action() { return <Home/>; } };
webpack/__mocks__/foremanReact/components/SearchBar.js
theforeman/foreman_remote_execution
import React from 'react'; import PropTypes from 'prop-types'; const SearchBar = ({ onChange }) => ( <input className="foreman-search" onChange={onChange} placeholder="Filter..." /> ); export default SearchBar; SearchBar.propTypes = { onChange: PropTypes.func, }; SearchBar.defaultProps = { onChange: () => null, };
src/parser/shared/modules/items/PrePotion.js
FaideWW/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS/index'; import SPECS from 'game/SPECS'; import ITEMS from 'common/ITEMS/index'; import RESOURCE_TYPES from 'game/RESOURCE_TYPES'; import ItemLink from 'common/ItemLink'; import Analyzer from 'parser/core/Analyzer'; import SUGGESTION_IMPORTANCE from 'parser/core/ISSUE_IMPORTANCE'; const debug = false; // these suggestions are all based on Icy Veins guide recommendations, i.e. which potion to use in which situation. // most guides recommend to use Battle Potion of Primary Stat, but I have broken out the class/spec combos whose guides // recommend to use Rising Death or Bursting Blood in certain situations. const AGI_SPECS = [ SPECS.GUARDIAN_DRUID.id, SPECS.FERAL_DRUID.id, SPECS.BEAST_MASTERY_HUNTER.id, SPECS.MARKSMANSHIP_HUNTER.id, SPECS.ASSASSINATION_ROGUE.id, SPECS.OUTLAW_ROGUE.id, SPECS.SUBTLETY_ROGUE.id, SPECS.ENHANCEMENT_SHAMAN.id, SPECS.BREWMASTER_MONK.id, SPECS.WINDWALKER_MONK.id, SPECS.VENGEANCE_DEMON_HUNTER.id, SPECS.HAVOC_DEMON_HUNTER.id, SPECS.SURVIVAL_HUNTER.id, //They use agi pot for AoE ]; const STR_SPECS = [ SPECS.PROTECTION_PALADIN.id, SPECS.PROTECTION_WARRIOR.id, SPECS.BLOOD_DEATH_KNIGHT.id, SPECS.RETRIBUTION_PALADIN.id, SPECS.ARMS_WARRIOR.id, //They use str pot for AoE SPECS.FURY_WARRIOR.id, //They use str pot for AoE SPECS.FROST_DEATH_KNIGHT.id, //They str agi pot for AoE SPECS.UNHOLY_DEATH_KNIGHT.id, //They str agi pot for AoE ]; const INT_SPECS = [ SPECS.SHADOW_PRIEST.id, //They use int pot for AoE SPECS.FROST_MAGE.id, //They use int pot for AoE SPECS.AFFLICTION_WARLOCK.id, SPECS.DEMONOLOGY_WARLOCK.id, SPECS.DESTRUCTION_WARLOCK.id, SPECS.ELEMENTAL_SHAMAN.id, SPECS.FIRE_MAGE.id, SPECS.ARCANE_MAGE.id, SPECS.BALANCE_DRUID.id, ]; const HEALER_SPECS = [ SPECS.HOLY_PALADIN.id, SPECS.RESTORATION_DRUID.id, SPECS.HOLY_PRIEST.id, SPECS.DISCIPLINE_PRIEST.id, SPECS.MISTWEAVER_MONK.id, SPECS.RESTORATION_SHAMAN.id, ]; const BURSTING_BLOOD = [ SPECS.SURVIVAL_HUNTER.id, SPECS.ARMS_WARRIOR.id, SPECS.FURY_WARRIOR.id, SPECS.FROST_DEATH_KNIGHT.id, SPECS.UNHOLY_DEATH_KNIGHT.id, ]; const RISING_DEATH = [ SPECS.SHADOW_PRIEST.id, SPECS.FROST_MAGE.id, ]; const PRE_POTIONS = [ SPELLS.BATTLE_POTION_OF_INTELLECT.id, SPELLS.BATTLE_POTION_OF_STRENGTH.id, SPELLS.BATTLE_POTION_OF_AGILITY.id, SPELLS.BATTLE_POTION_OF_STAMINA.id, SPELLS.POTION_OF_RISING_DEATH.id, SPELLS.POTION_OF_BURSTING_BLOOD.id, SPELLS.STEELSKIN_POTION.id, ]; const SECOND_POTIONS = [ SPELLS.BATTLE_POTION_OF_INTELLECT.id, SPELLS.BATTLE_POTION_OF_STRENGTH.id, SPELLS.BATTLE_POTION_OF_AGILITY.id, SPELLS.BATTLE_POTION_OF_STAMINA.id, SPELLS.POTION_OF_RISING_DEATH.id, SPELLS.POTION_OF_BURSTING_BLOOD.id, SPELLS.STEELSKIN_POTION.id, SPELLS.COASTAL_MANA_POTION.id, SPELLS.COASTAL_REJUVENATION_POTION.id, SPELLS.POTION_OF_REPLENISHMENT.id, ]; const COMMON_MANA_POTION_AMOUNT = 11084; class PrePotion extends Analyzer { usedPrePotion = false; usedSecondPotion = false; neededManaSecondPotion = false; potionId = ITEMS.BATTLE_POTION_OF_INTELLECT.id; //Giving it an initial value to prevent crashing potionIcon = ITEMS.BATTLE_POTION_OF_INTELLECT.icon; //Giving it an initial value to prevent crashing addedSuggestionText = false; alternatePotion = null; isHealer = false; on_toPlayer_applybuff(event) { const spellId = event.ability.guid; if (PRE_POTIONS.includes(spellId) && event.prepull) { this.usedPrePotion = true; } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (SECOND_POTIONS.includes(spellId)) { this.usedSecondPotion = true; } if (event.classResources && event.classResources[0] && event.classResources[0].type === RESOURCE_TYPES.MANA.id) { const resource = event.classResources[0]; const manaLeftAfterCast = resource.amount - resource.cost; if (manaLeftAfterCast < COMMON_MANA_POTION_AMOUNT) { this.neededManaSecondPotion = true; } } } on_finished() { if (debug) { console.log(`used potion:${this.usedPrePotion}`); console.log(`used 2nd potion:${this.usedSecondPotion}`); } } get prePotionSuggestionThresholds() { return { actual: this.usedPrePotion, isEqual: false, style: 'boolean', }; } get secondPotionSuggestionThresholds() { return { actual: this.usedSecondPotion, isEqual: false, style: 'boolean', }; } potionAdjuster(specID) { this.alternatePotion = STR_SPECS.includes(specID) ? ITEMS.BATTLE_POTION_OF_STRENGTH.id : AGI_SPECS.includes(specID) ? ITEMS.BATTLE_POTION_OF_AGILITY.id : ITEMS.BATTLE_POTION_OF_INTELLECT.id; if (BURSTING_BLOOD.includes(specID)) { this.potionId = ITEMS.POTION_OF_BURSTING_BLOOD.id; this.potionIcon = ITEMS.POTION_OF_BURSTING_BLOOD.icon; this.addedSuggestionText += true; } else if (RISING_DEATH.includes(specID)) { this.potionId = ITEMS.POTION_OF_RISING_DEATH.id; this.potionIcon = ITEMS.POTION_OF_RISING_DEATH.icon; this.addedSuggestionText = true; } else if (AGI_SPECS.includes(specID)) { this.potionId = ITEMS.BATTLE_POTION_OF_AGILITY.id; this.potionIcon = ITEMS.BATTLE_POTION_OF_AGILITY.icon; } else if (STR_SPECS.includes(specID)) { this.potionId = ITEMS.BATTLE_POTION_OF_STRENGTH.id; this.potionIcon = ITEMS.BATTLE_POTION_OF_STRENGTH.icon; } else if (INT_SPECS.includes(specID)) { this.potionId = ITEMS.BATTLE_POTION_OF_INTELLECT.id; this.potionIcon = ITEMS.BATTLE_POTION_OF_INTELLECT.icon; } else if (HEALER_SPECS.includes(specID)) { this.isHealer = true; } } suggestions(when) { this.potionAdjuster(this.selectedCombatant.specId); when(this.prePotionSuggestionThresholds) .addSuggestion((suggest) => { return suggest(<>You did not use a potion before combat. Using a potion before combat allows you the benefit of two potions in a single fight. A potion such as <ItemLink id={this.potionId} /> can be very effective, especially during shorter encounters. {this.addedSuggestionText ? <>In a multi-target encounter, a potion such as <ItemLink id={this.alternatePotion} /> could be very effective.</> : ''}</> ) .icon(this.potionIcon) .staticImportance(SUGGESTION_IMPORTANCE.MINOR); } ); when(this.secondPotionSuggestionThresholds) .addSuggestion((suggest) => { return suggest(<>You forgot to use a potion during combat. Using a potion during combat allows you the benefit of {this.isHealer ? 'either' : ''} increasing output through <ItemLink id={this.potionId} />{this.isHealer ? <> or allowing you to gain mana using <ItemLink id={ITEMS.COASTAL_MANA_POTION.id} /> or <ItemLink id={ITEMS.POTION_OF_REPLENISHMENT.id} /></> : ''}. {this.addedSuggestionText ? <>In a multi-target encounter, a potion such as <ItemLink id={this.alternatePotion} /> could be very effective.</> : ''}</>) .icon(this.potionIcon) .staticImportance(SUGGESTION_IMPORTANCE.MINOR); }) ; } } export default PrePotion;
src/main/jsx/client/BuildMetricsPageActions.js
suryagaddipati/DotCi
import ReactDOM from 'react-dom'; import React from 'react'; import BuildMetricsPage from './../pages/BuildMetricsPage.jsx'; import {job} from './../api/Api.jsx'; import {removeFilter,addFilter} from './../api/Api.jsx'; import Drawer from './../Drawer.jsx'; function dataChange(buildMetrics){ ReactDOM.render(<BuildMetricsPage buildMetrics={buildMetrics}/>, document.getElementById('content')); ReactDOM.render(<Drawer menu="job"/>, document.getElementById('nav')); } function queryChange(buildMetrics){ const actions = buildMetrics.actions; let query = buildMetrics.query; job("buildHistoryTabs,metrics[title,chart[*,dataSets[*]]]",query.filter ,query.limit).then(data => { actions.DataChange({...data, filters: data.buildHistoryTabs}); }); } export default function(buildHistory){ const actions = buildHistory.actions; actions.DataChange.onAction = dataChange; actions.QueryChange.onAction = queryChange; actions.RemoveFilter.onAction = removeFilter; actions.AddFilter.onAction = addFilter; }
src/components/Sidebar/index.js
civic-tech-lab/commonplace-frontend
// @flow import React from 'react'; import Root from './Root'; const Sidebar = () => <Root>Sidebar goes here</Root>; export default Sidebar;
node_modules/react-bootstrap/es/utils/ValidComponentChildren.js
C0deSamurai/muzjiks
// TODO: This module should be ElementChildren, and should use named exports. import React from 'react'; /** * Iterates through children that are typically specified as `props.children`, * but only maps over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @return {object} Object containing the ordered map of results. */ function map(children, func, context) { var index = 0; return React.Children.map(children, function (child) { if (!React.isValidElement(child)) { return child; } return func.call(context, child, index++); }); } /** * Iterates through children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for context. */ function forEach(children, func, context) { var index = 0; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } func.call(context, child, index++); }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function count(children) { var result = 0; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } ++result; }); return result; } /** * Finds children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} func. * @param {*} context Context for func. * @returns {array} of children that meet the func return statement */ function filter(children, func, context) { var index = 0; var result = []; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result.push(child); } }); return result; } function find(children, func, context) { var index = 0; var result = undefined; React.Children.forEach(children, function (child) { if (result) { return; } if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = child; } }); return result; } function every(children, func, context) { var index = 0; var result = true; React.Children.forEach(children, function (child) { if (!result) { return; } if (!React.isValidElement(child)) { return; } if (!func.call(context, child, index++)) { result = false; } }); return result; } function some(children, func, context) { var index = 0; var result = false; React.Children.forEach(children, function (child) { if (result) { return; } if (!React.isValidElement(child)) { return; } if (func.call(context, child, index++)) { result = true; } }); return result; } function toArray(children) { var result = []; React.Children.forEach(children, function (child) { if (!React.isValidElement(child)) { return; } result.push(child); }); return result; } export default { map: map, forEach: forEach, count: count, find: find, filter: filter, every: every, some: some, toArray: toArray };
examples/macosx/segment-control.js
firejune/react-desktop-playground
import React, { Component } from 'react'; import { SegmentedControl, Box, Window, TitleBar, Toolbar, Form, Label, Button, TextInput } from 'react-desktop/osx'; export default class extends Component { constructor() { super(); this.state = {selectedTab: 'login'}; } render() { return ( <Window chrome style={{width: '465px', height: '305px'}} > <TitleBar title="TitleBar with Toolbar" controls> <Toolbar/> </TitleBar> <Box className="box"> <SegmentedControl> <SegmentedControl.Item title="Selected" selected={this.state.selectedTab === 'login'} onPress={() => { this.setState({ selectedTab: 'login' }) }} className="form" > <Form onSubmit={() => { alert('form submitted'); }}> <Label color="red" align="center"> There was an error submitting this form. </Label> <Form.Row> <Label>Label:</Label> <TextInput defaultValue="" placeholder="TextField" style={{width: '200px'}}/> </Form.Row> <Form.Row> <Label>Longer label:</Label> <TextInput defaultValue="" placeholder="TextField" style={{width: '200px'}}/> </Form.Row> <Form.Row> <Button onPress="submit" push color="blue">Button With Color</Button> <Button push>Button</Button> </Form.Row> </Form> </SegmentedControl.Item> <SegmentedControl.Item title="Segmented" selected={this.state.selectedTab === 'segmented'} onPress={() => { this.setState({ selectedTab: 'segmented' }) }} > Hello2 </SegmentedControl.Item> <SegmentedControl.Item title="Control" selected={this.state.selectedTab === 'control'} onPress={() => { this.setState({ selectedTab: 'control' }) }} > </SegmentedControl.Item> </SegmentedControl> </Box> </Window> ) } }
fields/types/html/editor/quote/block-quote-editing-block.js
nickhsine/keystone
'use strict'; import EntityEditingBlockMixin from '../mixins/entity-editing-block-mixin'; import React from 'react'; class BlockQuoteEditingBlock extends EntityEditingBlockMixin(React.Component) { constructor (props) { super(props); } // overwrite EntityEditingBlock._composeEditingFields _composeEditingFields (props) { return { quoteBy: { type: 'text', value: props.quoteBy, }, quote: { type: 'textarea', value: props.quote, }, }; } // overwrite EntityEditingBlock._decomposeEditingFields _decomposeEditingFields (fields) { return { quoteBy: fields.quoteBy.value, quote: fields.quote.value, }; } }; BlockQuoteEditingBlock.displayName = 'BlockQuoteEditingBlock'; BlockQuoteEditingBlock.propTypes = { isModalOpen: React.PropTypes.bool, onToggle: React.PropTypes.func.isRequired, quote: React.PropTypes.string, quoteBy: React.PropTypes.string, toggleModal: React.PropTypes.func, }; BlockQuoteEditingBlock.defaultProps = { isModalOpen: false, quote: '', quoteBy: '', }; export default BlockQuoteEditingBlock;
src/js/ui/components/errorMessage.js
heartnotes/heartnotes
import React from 'react'; module.exports = React.createClass({ propTypes: { error: React.PropTypes.object.isRequired, }, render() { return ( <div className="error-message">{'' + this.props.error}</div> ); } });
src/components/Skills/SkillIcon.js
ICalvinG/icalving.github.io
import React from 'react'; import PropTypes from 'prop-types'; // Components import SkillLevel from './SkillLevel.js'; const SkillIcon = ({ type, level }) => ( <div className="skill__icon-container"> <i className={`devicon-${type}-plain skill__icon`}></i> <SkillLevel level={level} /> </div> ); SkillIcon.propTypes = { type: PropTypes.string.isRequired, level: PropTypes.number.isRequired, }; export default SkillIcon;
src/components/topic/description/render-content.js
nickhsine/twreporter-react
import { renderElement as renderV2Element } from '@twreporter/react-article-components/lib/components/body' import { sourceHanSansTC as fontWeight } from '@twreporter/core/lib/constants/font-weight' import alignmentConsts from '@twreporter/react-article-components/lib/constants/element-alignment' import ArticleYoutube from '@twreporter/react-article-components/lib/components/body/youtube' import Img from '@twreporter/react-article-components/lib/components/img-with-placeholder' import mq from '../../../utils/media-query' import React from 'react' import styled, { css } from 'styled-components' // lodash import get from 'lodash/get' const _ = { get, } const buildElementMarginCss = (horizontalMargin = '') => css` margin: 1.5em ${horizontalMargin}; &:first-child { margin-top: 0; } &:last-child { margin-bottom: 0; } ` const BlockQuote = styled.blockquote` ${buildElementMarginCss('1.33rem')} font-style: italic; padding-left: 18px; line-height: 1.85; font-size: 18px; font-weight: 300; white-space: pre-wrap; ` const YouTube = styled(ArticleYoutube)` ${buildElementMarginCss('auto')} max-width: 100%; ${mq.tabletAndAbove` width: 560px; `} iframe { width: 100%; } ` export const Paragraph = styled.div` ${buildElementMarginCss('auto')} color: #262626; font-size: 18px; line-height: 1.8; text-align: center; letter-spacing: 0.4px; white-space: pre-wrap; font-weight: ${fontWeight.normal}; ` const ImageContainer = styled.div` ${buildElementMarginCss('auto')} max-width: 100%; ${mq.tabletAndAbove` width: 560px; `} ` const ElementCaption = styled.div` color: #808080; font-size: 16px; line-height: 1.8; margin: 0.6em 1.33em 0 1.33em; ` /** * * * @export * @param {Array} data - An array of element data * @returns {Array} - An array of React elements */ export default function renderTopicContent(data) { if (!Array.isArray(data)) { return [] } return data .map(ele => { switch (ele.type) { case 'blockquote': return ( <BlockQuote key={ele.id} dangerouslySetInnerHTML={{ __html: _.get(ele, 'content.0', '') }} /> ) case 'youtube': { const { description, youtubeId } = _.get(ele, 'content.0', {}) if (!youtubeId) { return null } return ( <React.Fragment key={ele.id}> <YouTube data={{ content: [{ youtubeId }], }} /> {description ? ( <ElementCaption>{description}</ElementCaption> ) : null} </React.Fragment> ) } case 'image': { const { description, desktop, mobile, tablet, tiny } = _.get( ele, 'content.0', {} ) return ( <ImageContainer key={ele.id}> <div> <Img alt={description} imageSet={[tiny, mobile, tablet, desktop]} defaultImage={mobile} /> </div> {description ? ( <ElementCaption>{description}</ElementCaption> ) : null} </ImageContainer> ) } case 'unstyled': { const innerHTML = _.get(ele, 'content.0', '') if (!innerHTML) return null return ( <Paragraph key={ele.id} dangerouslySetInnerHTML={{ __html: innerHTML }} /> ) } default: // Force alignment to be `center-small` return renderV2Element({ ...ele, alignment: alignmentConsts.centerSmall, }) } }) .filter(Boolean) }
Libraries/Components/TextInput/TextInput.js
Livyli/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 TextInput * @flow */ 'use strict'; const ColorPropType = require('ColorPropType'); const DocumentSelectionState = require('DocumentSelectionState'); const EventEmitter = require('EventEmitter'); const NativeMethodsMixin = require('NativeMethodsMixin'); const Platform = require('Platform'); const React = require('React'); const PropTypes = require('prop-types'); const ReactNative = require('ReactNative'); const StyleSheet = require('StyleSheet'); const Text = require('Text'); const TextInputState = require('TextInputState'); const TimerMixin = require('react-timer-mixin'); const TouchableWithoutFeedback = require('TouchableWithoutFeedback'); const UIManager = require('UIManager'); const ViewPropTypes = require('ViewPropTypes'); const emptyFunction = require('fbjs/lib/emptyFunction'); const invariant = require('fbjs/lib/invariant'); const requireNativeComponent = require('requireNativeComponent'); const warning = require('fbjs/lib/warning'); const onlyMultiline = { onTextInput: true, children: true, }; if (Platform.OS === 'android') { var AndroidTextInput = requireNativeComponent('AndroidTextInput', null); } else if (Platform.OS === 'ios') { var RCTTextView = requireNativeComponent('RCTTextView', null); var RCTTextField = requireNativeComponent('RCTTextField', null); } type Event = Object; type Selection = { start: number, end?: number, }; const DataDetectorTypes = [ 'phoneNumber', 'link', 'address', 'calendarEvent', 'none', 'all', ]; /** * A foundational component for inputting text into the app via a * keyboard. Props provide configurability for several features, such as * auto-correction, auto-capitalization, placeholder text, and different keyboard * types, such as a numeric keypad. * * The simplest use case is to plop down a `TextInput` and subscribe to the * `onChangeText` events to read the user input. There are also other events, * such as `onSubmitEditing` and `onFocus` that can be subscribed to. A simple * example: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, TextInput } from 'react-native'; * * export default class UselessTextInput extends Component { * constructor(props) { * super(props); * this.state = { text: 'Useless Placeholder' }; * } * * render() { * return ( * <TextInput * style={{height: 40, borderColor: 'gray', borderWidth: 1}} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * ); * } * } * * // skip this line if using Create React Native App * AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput); * ``` * * Note that some props are only available with `multiline={true/false}`. * Additionally, border styles that apply to only one side of the element * (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if * `multiline=false`. To achieve the same effect, you can wrap your `TextInput` * in a `View`: * * ```ReactNativeWebPlayer * import React, { Component } from 'react'; * import { AppRegistry, View, TextInput } from 'react-native'; * * class UselessTextInput extends Component { * render() { * return ( * <TextInput * {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below * editable = {true} * maxLength = {40} * /> * ); * } * } * * export default class UselessTextInputMultiline extends Component { * constructor(props) { * super(props); * this.state = { * text: 'Useless Multiline Placeholder', * }; * } * * // If you type something in the text box that is a color, the background will change to that * // color. * render() { * return ( * <View style={{ * backgroundColor: this.state.text, * borderBottomColor: '#000000', * borderBottomWidth: 1 }} * > * <UselessTextInput * multiline = {true} * numberOfLines = {4} * onChangeText={(text) => this.setState({text})} * value={this.state.text} * /> * </View> * ); * } * } * * // skip these lines if using Create React Native App * AppRegistry.registerComponent( * 'AwesomeProject', * () => UselessTextInputMultiline * ); * ``` * * `TextInput` has by default a border at the bottom of its view. This border * has its padding set by the background image provided by the system, and it * cannot be changed. Solutions to avoid this is to either not set height * explicitly, case in which the system will take care of displaying the border * in the correct position, or to not display the border by setting * `underlineColorAndroid` to transparent. * * Note that on Android performing text selection in input can change * app's activity `windowSoftInputMode` param to `adjustResize`. * This may cause issues with components that have position: 'absolute' * while keyboard is active. To avoid this behavior either specify `windowSoftInputMode` * in AndroidManifest.xml ( https://developer.android.com/guide/topics/manifest/activity-element.html ) * or control this param programmatically with native code. * */ // $FlowFixMe(>=0.41.0) const TextInput = React.createClass({ statics: { /* TODO(brentvatne) docs are needed for this */ State: TextInputState, }, propTypes: { ...ViewPropTypes, /** * Can tell `TextInput` to automatically capitalize certain characters. * * - `characters`: all characters. * - `words`: first letter of each word. * - `sentences`: first letter of each sentence (*default*). * - `none`: don't auto capitalize anything. */ autoCapitalize: PropTypes.oneOf([ 'none', 'sentences', 'words', 'characters', ]), /** * If `false`, disables auto-correct. The default value is `true`. */ autoCorrect: PropTypes.bool, /** * If `false`, disables spell-check style (i.e. red underlines). * The default value is inherited from `autoCorrect`. * @platform ios */ spellCheck: PropTypes.bool, /** * If `true`, focuses the input on `componentDidMount`. * The default value is `false`. */ autoFocus: PropTypes.bool, /** * If `false`, text is not editable. The default value is `true`. */ editable: PropTypes.bool, /** * Determines which keyboard to open, e.g.`numeric`. * * The following values work across platforms: * * - `default` * - `numeric` * - `email-address` * - `phone-pad` */ keyboardType: PropTypes.oneOf([ // Cross-platform 'default', 'email-address', 'numeric', 'phone-pad', // iOS-only 'ascii-capable', 'numbers-and-punctuation', 'url', 'number-pad', 'name-phone-pad', 'decimal-pad', 'twitter', 'web-search', ]), /** * Determines the color of the keyboard. * @platform ios */ keyboardAppearance: PropTypes.oneOf([ 'default', 'light', 'dark', ]), /** * Determines how the return key should look. On Android you can also use * `returnKeyLabel`. * * *Cross platform* * * The following values work across platforms: * * - `done` * - `go` * - `next` * - `search` * - `send` * * *Android Only* * * The following values work on Android only: * * - `none` * - `previous` * * *iOS Only* * * The following values work on iOS only: * * - `default` * - `emergency-call` * - `google` * - `join` * - `route` * - `yahoo` */ returnKeyType: PropTypes.oneOf([ // Cross-platform 'done', 'go', 'next', 'search', 'send', // Android-only 'none', 'previous', // iOS-only 'default', 'emergency-call', 'google', 'join', 'route', 'yahoo', ]), /** * Sets the return key to the label. Use it instead of `returnKeyType`. * @platform android */ returnKeyLabel: PropTypes.string, /** * Limits the maximum number of characters that can be entered. Use this * instead of implementing the logic in JS to avoid flicker. */ maxLength: PropTypes.number, /** * Sets the number of lines for a `TextInput`. Use it with multiline set to * `true` to be able to fill the lines. * @platform android */ numberOfLines: PropTypes.number, /** * When `false`, if there is a small amount of space available around a text input * (e.g. landscape orientation on a phone), the OS may choose to have the user edit * the text inside of a full screen text input mode. When `true`, this feature is * disabled and users will always edit the text directly inside of the text input. * Defaults to `false`. * @platform android */ disableFullscreenUI: PropTypes.bool, /** * If `true`, the keyboard disables the return key when there is no text and * automatically enables it when there is text. The default value is `false`. * @platform ios */ enablesReturnKeyAutomatically: PropTypes.bool, /** * If `true`, the text input can be multiple lines. * The default value is `false`. */ multiline: PropTypes.bool, /** * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` * The default value is `simple`. * @platform android */ textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']), /** * Callback that is called when the text input is blurred. */ onBlur: PropTypes.func, /** * Callback that is called when the text input is focused. */ onFocus: PropTypes.func, /** * Callback that is called when the text input's text changes. */ onChange: PropTypes.func, /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText: PropTypes.func, /** * Callback that is called when the text input's content size changes. * This will be called with * `{ nativeEvent: { contentSize: { width, height } } }`. * * Only called for multiline text inputs. */ onContentSizeChange: PropTypes.func, /** * Callback that is called when text input ends. */ onEndEditing: PropTypes.func, /** * Callback that is called when the text input selection is changed. * This will be called with * `{ nativeEvent: { selection: { start, end } } }`. */ onSelectionChange: PropTypes.func, /** * Callback that is called when the text input's submit button is pressed. * Invalid if `multiline={true}` is specified. */ onSubmitEditing: PropTypes.func, /** * Callback that is called when a key is pressed. * This will be called with `{ nativeEvent: { key: keyValue } }` * where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and * the typed-in character otherwise including `' '` for space. * Fires before `onChange` callbacks. * @platform ios */ onKeyPress: PropTypes.func, /** * Invoked on mount and layout changes with `{x, y, width, height}`. */ onLayout: PropTypes.func, /** * Invoked on content scroll with `{ nativeEvent: { contentOffset: { x, y } } }`. * May also contain other properties from ScrollEvent but on Android contentSize * is not provided for performance reasons. */ onScroll: PropTypes.func, /** * The string that will be rendered before text input has been entered. */ placeholder: PropTypes.node, /** * The text color of the placeholder string. */ placeholderTextColor: ColorPropType, /** * If `true`, the text input obscures the text entered so that sensitive text * like passwords stay secure. The default value is `false`. */ secureTextEntry: PropTypes.bool, /** * The highlight and cursor color of the text input. */ selectionColor: ColorPropType, /** * An instance of `DocumentSelectionState`, this is some state that is responsible for * maintaining selection information for a document. * * Some functionality that can be performed with this instance is: * * - `blur()` * - `focus()` * - `update()` * * > You can reference `DocumentSelectionState` in * > [`vendor/document/selection/DocumentSelectionState.js`](https://github.com/facebook/react-native/blob/master/Libraries/vendor/document/selection/DocumentSelectionState.js) * * @platform ios */ selectionState: PropTypes.instanceOf(DocumentSelectionState), /** * The start and end of the text input's selection. Set start and end to * the same value to position the cursor. */ selection: PropTypes.shape({ start: PropTypes.number.isRequired, end: PropTypes.number, }), /** * The value to show for the text input. `TextInput` is a controlled * component, which means the native value will be forced to match this * value prop if provided. For most uses, this works great, but in some * cases this may cause flickering - one common cause is preventing edits * by keeping value the same. In addition to simply setting the same value, * either set `editable={false}`, or set/update `maxLength` to prevent * unwanted edits without flicker. */ value: PropTypes.string, /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you do not want to deal with listening * to events and updating the value prop to keep the controlled state in sync. */ defaultValue: PropTypes.string, /** * When the clear button should appear on the right side of the text view. * @platform ios */ clearButtonMode: PropTypes.oneOf([ 'never', 'while-editing', 'unless-editing', 'always', ]), /** * If `true`, clears the text field automatically when editing begins. * @platform ios */ clearTextOnFocus: PropTypes.bool, /** * If `true`, all text will automatically be selected on focus. */ selectTextOnFocus: PropTypes.bool, /** * If `true`, the text field will blur when submitted. * The default value is true for single-line fields and false for * multiline fields. Note that for multiline fields, setting `blurOnSubmit` * to `true` means that pressing return will blur the field and trigger the * `onSubmitEditing` event instead of inserting a newline into the field. */ blurOnSubmit: PropTypes.bool, /** * Note that not all Text styles are supported, * see [Issue#7070](https://github.com/facebook/react-native/issues/7070) * for more detail. * * [Styles](docs/style.html) */ style: Text.propTypes.style, /** * The color of the `TextInput` underline. * @platform android */ underlineColorAndroid: ColorPropType, /** * If defined, the provided image resource will be rendered on the left. * @platform android */ inlineImageLeft: PropTypes.string, /** * Padding between the inline image, if any, and the text input itself. * @platform android */ inlineImagePadding: PropTypes.number, /** * Determines the types of data converted to clickable URLs in the text input. * Only valid if `multiline={true}` and `editable={false}`. * By default no data types are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes: PropTypes.oneOfType([ PropTypes.oneOf(DataDetectorTypes), PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)), ]), /** * If `true`, caret is hidden. The default value is `false`. */ caretHidden: PropTypes.bool, }, /** * `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We * make `this` look like an actual native component class. */ mixins: [NativeMethodsMixin, TimerMixin], /** * Returns `true` if the input is currently focused; `false` otherwise. */ isFocused: function(): boolean { return TextInputState.currentlyFocusedField() === ReactNative.findNodeHandle(this._inputRef); }, contextTypes: { onFocusRequested: PropTypes.func, focusEmitter: PropTypes.instanceOf(EventEmitter), }, _inputRef: (undefined: any), _focusSubscription: (undefined: ?Function), _lastNativeText: (undefined: ?string), _lastNativeSelection: (undefined: ?Selection), componentDidMount: function() { this._lastNativeText = this.props.value; if (!this.context.focusEmitter) { if (this.props.autoFocus) { this.requestAnimationFrame(this.focus); } return; } this._focusSubscription = this.context.focusEmitter.addListener( 'focus', (el) => { if (this === el) { this.requestAnimationFrame(this.focus); } else if (this.isFocused()) { this.blur(); } } ); if (this.props.autoFocus) { this.context.onFocusRequested(this); } }, componentWillUnmount: function() { this._focusSubscription && this._focusSubscription.remove(); if (this.isFocused()) { this.blur(); } }, getChildContext: function(): Object { return {isInAParentText: true}; }, childContextTypes: { isInAParentText: PropTypes.bool }, /** * Removes all text from the `TextInput`. */ clear: function() { this.setNativeProps({text: ''}); }, render: function() { if (Platform.OS === 'ios') { return this._renderIOS(); } else if (Platform.OS === 'android') { return this._renderAndroid(); } }, _getText: function(): ?string { return typeof this.props.value === 'string' ? this.props.value : ( typeof this.props.defaultValue === 'string' ? this.props.defaultValue : '' ); }, _setNativeRef: function(ref: any) { this._inputRef = ref; }, _renderIOS: function() { var textContainer; var props = Object.assign({}, this.props); props.style = [this.props.style]; if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } if (!props.multiline) { if (__DEV__) { for (var propKey in onlyMultiline) { if (props[propKey]) { const error = new Error( 'TextInput prop `' + propKey + '` is only supported with multiline.' ); warning(false, '%s', error.stack); } } } textContainer = <RCTTextField ref={this._setNativeRef} {...props} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} />; } else { var children = props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(props.value && childCount), 'Cannot specify both value and children.' ); if (childCount >= 1) { children = <Text style={props.style}>{children}</Text>; } if (props.inputView) { children = [children, props.inputView]; } props.style.unshift(styles.multilineInput); textContainer = <RCTTextView ref={this._setNativeRef} {...props} children={children} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onContentSizeChange={this.props.onContentSizeChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue} text={this._getText()} dataDetectorTypes={this.props.dataDetectorTypes} onScroll={this._onScroll} />; } return ( <TouchableWithoutFeedback onLayout={props.onLayout} onPress={this._onPress} rejectResponderTermination={true} accessible={props.accessible} accessibilityLabel={props.accessibilityLabel} accessibilityTraits={props.accessibilityTraits} nativeID={this.props.nativeID} testID={props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _renderAndroid: function() { const props = Object.assign({}, this.props); props.style = [this.props.style]; props.autoCapitalize = UIManager.AndroidTextInput.Constants.AutoCapitalizationType[this.props.autoCapitalize]; var children = this.props.children; var childCount = 0; React.Children.forEach(children, () => ++childCount); invariant( !(this.props.value && childCount), 'Cannot specify both value and children.' ); if (childCount > 1) { children = <Text>{children}</Text>; } if (props.selection && props.selection.end == null) { props.selection = {start: props.selection.start, end: props.selection.start}; } const textContainer = <AndroidTextInput ref={this._setNativeRef} {...props} mostRecentEventCount={0} onFocus={this._onFocus} onBlur={this._onBlur} onChange={this._onChange} onSelectionChange={this._onSelectionChange} onTextInput={this._onTextInput} text={this._getText()} children={children} disableFullscreenUI={this.props.disableFullscreenUI} textBreakStrategy={this.props.textBreakStrategy} onScroll={this._onScroll} />; return ( <TouchableWithoutFeedback onLayout={this.props.onLayout} onPress={this._onPress} accessible={this.props.accessible} accessibilityLabel={this.props.accessibilityLabel} accessibilityComponentType={this.props.accessibilityComponentType} nativeID={this.props.nativeID} testID={this.props.testID}> {textContainer} </TouchableWithoutFeedback> ); }, _onFocus: function(event: Event) { if (this.props.onFocus) { this.props.onFocus(event); } if (this.props.selectionState) { this.props.selectionState.focus(); } }, _onPress: function(event: Event) { if (this.props.editable || this.props.editable === undefined) { this.focus(); } }, _onChange: function(event: Event) { // Make sure to fire the mostRecentEventCount first so it is already set on // native when the text value is set. if (this._inputRef) { this._inputRef.setNativeProps({ mostRecentEventCount: event.nativeEvent.eventCount, }); } var text = event.nativeEvent.text; this.props.onChange && this.props.onChange(event); this.props.onChangeText && this.props.onChangeText(text); if (!this._inputRef) { // calling `this.props.onChange` or `this.props.onChangeText` // may clean up the input itself. Exits here. return; } this._lastNativeText = text; this.forceUpdate(); }, _onSelectionChange: function(event: Event) { this.props.onSelectionChange && this.props.onSelectionChange(event); if (!this._inputRef) { // calling `this.props.onSelectionChange` // may clean up the input itself. Exits here. return; } this._lastNativeSelection = event.nativeEvent.selection; if (this.props.selection || this.props.selectionState) { this.forceUpdate(); } }, componentDidUpdate: function () { // This is necessary in case native updates the text and JS decides // that the update should be ignored and we should stick with the value // that we have in JS. const nativeProps = {}; if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') { nativeProps.text = this.props.value; } // Selection is also a controlled prop, if the native value doesn't match // JS, update to the JS value. const {selection} = this.props; if (this._lastNativeSelection && selection && (this._lastNativeSelection.start !== selection.start || this._lastNativeSelection.end !== selection.end)) { nativeProps.selection = this.props.selection; } if (Object.keys(nativeProps).length > 0 && this._inputRef) { this._inputRef.setNativeProps(nativeProps); } if (this.props.selectionState && selection) { this.props.selectionState.update(selection.start, selection.end); } }, _onBlur: function(event: Event) { this.blur(); if (this.props.onBlur) { this.props.onBlur(event); } if (this.props.selectionState) { this.props.selectionState.blur(); } }, _onTextInput: function(event: Event) { this.props.onTextInput && this.props.onTextInput(event); }, _onScroll: function(event: Event) { this.props.onScroll && this.props.onScroll(event); }, }); var styles = StyleSheet.create({ multilineInput: { // This default top inset makes RCTTextView seem as close as possible // to single-line RCTTextField defaults, using the system defaults // of font size 17 and a height of 31 points. paddingTop: 5, }, }); module.exports = TextInput;
src/components/NameFilterForm/NameFilterForm.js
labzero/lunch
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './NameFilterForm.scss'; class NameFilterForm extends Component { static propTypes = { nameFilter: PropTypes.string.isRequired, restaurantIds: PropTypes.array.isRequired, setFlipMove: PropTypes.func.isRequired, setNameFilter: PropTypes.func.isRequired, }; constructor(props) { super(props); if (props.nameFilter.length) { this.state = { shown: true, }; } else { this.state = { shown: false, }; } } componentDidUpdate(prevProps, prevState) { if (this.state.shown !== prevState.shown) { if (this.state.shown) { this.input.focus(); } else { this.setFlipMoveTrue(); } } } setFlipMoveFalse = () => { this.props.setFlipMove(false); } setFlipMoveTrue = () => { this.props.setFlipMove(true); } setNameFilterValue = (event) => { this.props.setNameFilter(event.target.value); } hideForm = () => { this.props.setFlipMove(false); this.props.setNameFilter(''); this.setState(() => ({ shown: false, })); } showForm = () => { this.setState(() => ({ shown: true, })); } render() { const { nameFilter, restaurantIds, } = this.props; const { shown } = this.state; let child; if (!restaurantIds.length) { return null; } if (shown) { child = ( <form className={s.form}> <div className={s.container}> <input className={`${s.input} form-control`} placeholder="filter" value={nameFilter} onChange={this.setNameFilterValue} onFocus={this.setFlipMoveFalse} onBlur={this.setFlipMoveTrue} ref={i => { this.input = i; }} /> </div> <button className="btn btn-default" type="button" onClick={this.hideForm} > cancel </button> </form> ); } else { child = ( <button className="btn btn-default" onClick={this.showForm} type="button"> filter by name </button> ); } return ( <div className={s.root}>{child}</div> ); } } export const undecorated = NameFilterForm; export default withStyles(s)(NameFilterForm);
packages/material-ui-icons/src/FiberSmartRecord.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><g><circle cx="9" cy="12" r="8" /><path d="M17 4.26v2.09c2.33.82 4 3.04 4 5.65s-1.67 4.83-4 5.65v2.09c3.45-.89 6-4.01 6-7.74s-2.55-6.85-6-7.74z" /></g></g> , 'FiberSmartRecord');
examples/files/gestures/panResponder.js
dabbott/react-native-express
import React from 'react' import { StyleSheet, Text, View } from 'react-native' import usePanResponder from './usePanResponder' export default function App() { const [state, panHandlers] = usePanResponder() const { dragging, initialY, initialX, offsetY, offsetX } = state const style = { backgroundColor: dragging ? '#2DC' : '#0BA', transform: [ { translateX: initialX + offsetX }, { translateY: initialY + offsetY }, ], } return ( <View style={styles.container}> <View // Put all panHandlers into the View's props {...panHandlers} style={[styles.square, style]} > <Text style={styles.text}>DRAG ME</Text> </View> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, }, square: { position: 'absolute', width: 100, height: 100, borderRadius: 50, justifyContent: 'center', alignItems: 'center', }, text: { color: 'white', fontWeight: 'bold', fontSize: 16, }, })
app/javascript/mastodon/features/compose/components/search.js
hugogameiro/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { searchEnabled } from '../../../initial_state'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class SearchPopout extends React.PureComponent { static propTypes = { style: PropTypes.object, }; render () { const { style } = this.props; const extraInformation = searchEnabled ? <FormattedMessage id='search_popout.tips.full_text' defaultMessage='Simple text returns statuses you have written, favourited, boosted, or have been mentioned in, as well as matching usernames, display names, and hashtags.' /> : <FormattedMessage id='search_popout.tips.text' defaultMessage='Simple text returns matching display names, usernames and hashtags' />; return ( <div style={{ ...style, position: 'absolute', width: 285 }}> <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( <div className='search-popout' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}> <h4><FormattedMessage id='search_popout.search_format' defaultMessage='Advanced search format' /></h4> <ul> <li><em>#example</em> <FormattedMessage id='search_popout.tips.hashtag' defaultMessage='hashtag' /></li> <li><em>@username@domain</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li> <li><em>URL</em> <FormattedMessage id='search_popout.tips.user' defaultMessage='user' /></li> <li><em>URL</em> <FormattedMessage id='search_popout.tips.status' defaultMessage='status' /></li> </ul> {extraInformation} </div> )} </Motion> </div> ); } } export default @injectIntl class Search extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, submitted: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, onShow: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { expanded: false, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleClear = (e) => { e.preventDefault(); if (this.props.value.length > 0 || this.props.submitted) { this.props.onClear(); } } handleKeyDown = (e) => { if (e.key === 'Enter') { e.preventDefault(); this.props.onSubmit(); } else if (e.key === 'Escape') { document.querySelector('.ui').parentElement.focus(); } } noop () { } handleFocus = () => { this.setState({ expanded: true }); this.props.onShow(); } handleBlur = () => { this.setState({ expanded: false }); } render () { const { intl, value, submitted } = this.props; const { expanded } = this.state; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.placeholder)}</span> <input className='search__input' type='text' placeholder={intl.formatMessage(messages.placeholder)} value={value} onChange={this.handleChange} onKeyUp={this.handleKeyDown} onFocus={this.handleFocus} onBlur={this.handleBlur} /> </label> <div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}> <i className={`fa fa-search ${hasValue ? '' : 'active'}`} /> <i aria-label={intl.formatMessage(messages.placeholder)} className={`fa fa-times-circle ${hasValue ? 'active' : ''}`} /> </div> <Overlay show={expanded && !hasValue} placement='bottom' target={this}> <SearchPopout /> </Overlay> </div> ); } }
clients/packages/admin-client/src/components/data-grid/hocs/data-grid-hoc.js
nossas/bonde-client
import React from 'react' import PropTypes from 'prop-types' import classnames from 'classnames' export default ({ rowComponent: RowComponent }) => (WrappedComponent) => { class PP extends React.Component { render () { const { children, data, fieldIndex, rowIndex: rowSelectedIndex, onSelectRow } = this.props const dataGridProps = { className: classnames('flex flex-column', this.props.className), data: WrappedComponent !== 'div' ? data : null } return ( <WrappedComponent {...this.props} {...dataGridProps}> {data && data.map((item, rowIndex) => ( <RowComponent key={`rowIndex-${rowIndex}`} actived={rowSelectedIndex === rowIndex} onSelectRow={() => { onSelectRow && onSelectRow(item, rowIndex) }} data={item} rowIndex={fieldIndex ? item[fieldIndex] : rowIndex} > {children} </RowComponent> ))} </WrappedComponent> ) } } PP.propTypes = { data: PropTypes.array } PP.defaultProps = { data: [] } return PP }
src/index.js
loadedsith/smb3memories
import 'babel-polyfill'; import React from 'react'; import {render} from 'react-dom'; import {Provider} from 'react-redux'; import App from './app/containers/App'; import configureStore from './app/store/configureStore'; import './index.scss'; const store = configureStore(); render( <Provider store={store}> <App/> </Provider>, document.getElementById('root') );
src/browser/lib/Loading.react.js
nikolalosic/este-app--assignment
import './Loading.scss'; import Component from 'react-pure-render/component'; import Helmet from 'react-helmet'; import React from 'react'; import { FormattedMessage, defineMessages } from 'react-intl'; const messages = defineMessages({ loadingText: { defaultMessage: 'Loading', id: 'loading.loadingText' }, longLoadingText: { defaultMessage: 'Still loading, please check your connection', id: 'loading.longLoadingText' } }); export default class Loading extends Component { constructor() { super(); this.state = { currentText: null }; } componentDidMount() { // www.nngroup.com/articles/response-times-3-important-limits this.timer = setTimeout(() => { this.setState({ currentText: messages.loadingText }); }, 1000); this.longTimer = setTimeout(() => { this.setState({ currentText: messages.longLoadingText }); }, 10000); } componentWillUnmount() { clearTimeout(this.timer); clearTimeout(this.longTimer); } render() { const { currentText } = this.state; if (!currentText) { return <div className="este-loading">{String.fromCharCode(160)}</div>; } return ( <div className="este-loading"> <FormattedMessage {...currentText}> {title => <Helmet title={title} />} </FormattedMessage> <FormattedMessage {...currentText} /> </div> ); } }
app/src/index.js
pqmcgill/greenlight-archives
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render( <Router> <App /> </Router>, document.getElementById('root') ); registerServiceWorker();
framework/react/react-tutorials/src/demo/clock/ClockClass.js
yhtml5/YHTML5-Tutorial
import React from 'react'; class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; console.log('constructor: ', this) } componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date() }); } render() { return ( <div>It is {this.state.date.toLocaleTimeString()}.</div> ) } } export default Clock
src/components/Meetup.js
bow-paris/bow-paris.github.io
import React from 'react' export default ({ name, logo, backgroundColor = 'transparent', isPartner = false, }) => ( <li className={`meetup${isPartner ? ' partner' : ''}`}> <img src={logo} width="auto" alt="" height="100px" style={{ backgroundColor }} /> <p>{name}</p> </li> )
definitions/npm/react-helmet_v3.x.x/test_react-helmet.js
altano/flow-typed
// @flow import React from 'react'; import Helmet from 'react-helmet'; const HelmetComponent = () => ( <Helmet htmlAttributes={{"lang": "en", "amp": undefined}} // amp takes no value title="My Title" titleTemplate="MySite.com - %s" defaultTitle="My Default Title" base={{"target": "_blank", "href": "http://mysite.com/"}} meta={[ {"name": "description", "content": "Helmet application"}, {"property": "og:type", "content": "article"} ]} link={[ {"rel": "canonical", "href": "http://mysite.com/example"}, {"rel": "apple-touch-icon", "href": "http://mysite.com/img/apple-touch-icon-57x57.png"}, {"rel": "apple-touch-icon", "sizes": "72x72", "href": "http://mysite.com/img/apple-touch-icon-72x72.png"} ]} script={[ {"src": "http://include.com/pathtojs.js", "type": "text/javascript"}, {"type": "application/ld+json", innerHTML: `{ "@context": "http://schema.org" }`} ]} onChangeClientState={(newState) => console.log(newState)} /> ) const fail = () => ( // $ExpectError <Helmet title={{}} /> ) const head = Helmet.rewind(); (head.htmlAttributes.toString(): string); (head.title.toString(): string); (head.base.toString(): string); (head.meta.toString(): string); (head.link.toString(): string); (head.script.toString(): string); (head.style.toString(): string); // $ExpectError (head.htmlAttributes.toString(): boolean); // $ExpectError (head.title.toString(): boolean); // $ExpectError (head.base.toString(): boolean); // $ExpectError (head.meta.toString(): boolean); // $ExpectError (head.link.toString(): boolean); // $ExpectError (head.script.toString(): boolean); // $ExpectError (head.style.toString(): boolean);
ui/src/components/App/App.js
ebradshaw/insight
import React, { Component } from 'react'; import Navigation from '../Navigation/Navigation' import Footer from '../Footer/Footer' import SearchBar from '../SearchBar/SearchBar' import Metrics from '../Metrics/Metrics' import ResultsTable from '../ResultsTable/ResultsTable' import Grid from 'react-bootstrap/lib/Grid' import './App.css' class App extends Component { constructor(props){ super(props) this.refreshData = this.refreshData.bind(this) this.getFilteredData = this.getFilteredData.bind(this) this.state = { data: [], filter: "" } } componentDidMount() { this.mounted = true this.refreshData() } componentWillUnmount() { this.mounted = false } refreshData() { fetch('api/metrics') .then((res) => res.json()) .then((data) => this.setState({ data: data.reverse() })) if(this.mounted) { setTimeout(this.refreshData, 1000) } } getFilteredData(){ let { data, filter } = this.state return data.filter(entry => entry.url.includes(filter)) } render() { let data = this.getFilteredData() let { filter } = this.state return <div className="app"> <Navigation /> <Grid> <SearchBar value={filter} onChange={filter => this.setState({ filter }) } /> <div className="row-spacer" /> <Metrics data={data} /> <div className="row-spacer" /> <div style={{flex:"1 0 0%", overflowY:"auto"}}> <ResultsTable data={data} /> </div> <div className="row-spacer" /> </Grid> <Footer/> </div> } } export default App;
client/admin/settings/inputs/BooleanSettingInput.js
subesokun/Rocket.Chat
import { Field, ToggleSwitch } from '@rocket.chat/fuselage'; import React from 'react'; import { ResetSettingButton } from '../ResetSettingButton'; export function BooleanSettingInput({ _id, label, disabled, readonly, value, hasResetButton, onChangeValue, onResetButtonClick, }) { const handleChange = (event) => { const value = event.currentTarget.checked; onChangeValue && onChangeValue(value); }; return <Field.Row> <ToggleSwitch data-qa-setting-id={_id} id={_id} value='true' checked={value === true} disabled={disabled} readOnly={readonly} onChange={handleChange} /> <Field.Label htmlFor={_id} title={_id}>{label}</Field.Label> {hasResetButton && <ResetSettingButton data-qa-reset-setting-id={_id} onClick={onResetButtonClick} />} </Field.Row>; }
src/svg-icons/av/av-timer.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvAvTimer = (props) => ( <SvgIcon {...props}> <path d="M11 17c0 .55.45 1 1 1s1-.45 1-1-.45-1-1-1-1 .45-1 1zm0-14v4h2V5.08c3.39.49 6 3.39 6 6.92 0 3.87-3.13 7-7 7s-7-3.13-7-7c0-1.68.59-3.22 1.58-4.42L12 13l1.41-1.41-6.8-6.8v.02C4.42 6.45 3 9.05 3 12c0 4.97 4.02 9 9 9 4.97 0 9-4.03 9-9s-4.03-9-9-9h-1zm7 9c0-.55-.45-1-1-1s-1 .45-1 1 .45 1 1 1 1-.45 1-1zM6 12c0 .55.45 1 1 1s1-.45 1-1-.45-1-1-1-1 .45-1 1z"/> </SvgIcon> ); AvAvTimer = pure(AvAvTimer); AvAvTimer.displayName = 'AvAvTimer'; AvAvTimer.muiName = 'SvgIcon'; export default AvAvTimer;
tests/fixtures/fixture-blog-post-jsx.js
brekk/glass-menagerie
import React from 'react' const {PropTypes: types} = React export const propTypes = { title: types.string, number: types.number, description: types.string } export const Blog = (props) => (<div className="blog-post"> <h1>{props.title}</h1> <strong>{props.number}</strong> <p>{props.description}</p> </div>) Blog.propTypes = propTypes export default Blog
packages/mineral-ui-icons/src/IconSpeakerPhone.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconSpeakerPhone(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M7 7.07L8.43 8.5c.91-.91 2.18-1.48 3.57-1.48s2.66.57 3.57 1.48L17 7.07C15.72 5.79 13.95 5 12 5s-3.72.79-5 2.07zM12 1C8.98 1 6.24 2.23 4.25 4.21l1.41 1.41C7.28 4 9.53 3 12 3s4.72 1 6.34 2.62l1.41-1.41A10.963 10.963 0 0 0 12 1zm2.86 9.01L9.14 10C8.51 10 8 10.51 8 11.14v9.71c0 .63.51 1.14 1.14 1.14h5.71c.63 0 1.14-.51 1.14-1.14v-9.71c.01-.63-.5-1.13-1.13-1.13zM15 20H9v-8h6v8z"/> </g> </Icon> ); } IconSpeakerPhone.displayName = 'IconSpeakerPhone'; IconSpeakerPhone.category = 'communication';
src/routes/home/index.js
niketpathak/npk-website
/** * @author Niket Pathak. (http://www.niketpathak.com/) * * Copyright © 2014-present. 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 Home from './Home'; import Layout from '../../components/Layout'; async function action({ fetch }) { const resp = await fetch('/graphql', { body: JSON.stringify({ query: '{news{title,link,content}}', }), }); const { data } = await resp.json(); if (!data || !data.news) throw new Error('Failed to load the news feed.'); return { chunks: ['home'], title: 'React Starter Kit', component: <Layout><Home news={data.news} /></Layout>, }; } export default action;
examples/huge-apps/components/Dashboard.js
rdjpalmer/react-router
import React from 'react' import { Link } from 'react-router' class Dashboard extends React.Component { render() { const { courses } = this.props return ( <div> <h2>Super Scalable Apps</h2> <p> Open the network tab as you navigate. Notice that only the amount of your app that is required is actually downloaded as you navigate around. Even the route configuration objects are loaded on the fly. This way, a new route added deep in your app will not affect the initial bundle of your application. </p> <h2>Courses</h2>{' '} <ul> {courses.map(course => ( <li key={course.id}> <Link to={`/course/${course.id}`}>{course.name}</Link> </li> ))} </ul> </div> ) } } export default Dashboard
src/components/ShareExperience/common/SubmitArea.js
goodjoblife/GoodJobShare
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { Link } from 'react-router-dom'; import ButtonSubmit from 'common/button/ButtonSubmit'; import Checkbox from 'common/form/Checkbox'; import Modal from 'common/Modal'; const SubmitArea = ({ auth, agree, handleAgree, isOpen, feedback, hasClose, closableOnClickOutside, isSubmitting, onSubmit, login, handleIsOpen, }) => ( <div style={{ display: 'flex', flexDirection: 'column', marginTop: '57px', }} > <label style={{ display: 'flex', marginBottom: '28px', alignItems: 'center', justifyContent: 'center', }} htmlFor="submitArea-checkbox" > <Checkbox margin={'0'} value={''} label={''} checked={agree} onChange={e => handleAgree(e.target.checked)} id="submitArea-checkbox" /> <p style={{ color: '#3B3B3B', }} > 我分享的是真實資訊,並且遵守本站 <Link to="/guidelines" target="_blank" style={{ color: '#02309E', }} > 發文留言規定 </Link> 、 <Link to="/user-terms" target="_blank" style={{ color: '#02309E', }} > 使用者條款 </Link> 以及中華民國法律。 </p> </label> <div> <ButtonSubmit text="送出資料" onSubmit={onSubmit} disabled={isSubmitting || !agree} auth={auth} login={login} /> </div> <Modal isOpen={isOpen} close={() => handleIsOpen(!isOpen)} hasClose={hasClose} closableOnClickOutside={closableOnClickOutside} > {feedback} </Modal> </div> ); SubmitArea.propTypes = { auth: ImmutablePropTypes.map.isRequired, agree: PropTypes.bool.isRequired, handleAgree: PropTypes.func.isRequired, isOpen: PropTypes.bool.isRequired, feedback: PropTypes.node, hasClose: PropTypes.bool.isRequired, closableOnClickOutside: PropTypes.bool.isRequired, isSubmitting: PropTypes.bool.isRequired, onSubmit: PropTypes.func.isRequired, login: PropTypes.func.isRequired, handleIsOpen: PropTypes.func.isRequired, }; export default SubmitArea;
packages/material-ui-icons/src/LaptopMac.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /></g> , 'LaptopMac');
node_modules/react-router/es/Redirect.js
saltypaul/SnipTodo
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { formatPattern } from './PatternUtils'; import { falsy } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes, string = _React$PropTypes.string, object = _React$PropTypes.object; /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ /* eslint-disable react/require-render-return */ var Redirect = React.createClass({ displayName: 'Redirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element) { var route = _createRouteFromReactElement(element); if (route.from) route.path = route.from; route.onEnter = function (nextState, replace) { var location = nextState.location, params = nextState.params; var pathname = void 0; if (route.to.charAt(0) === '/') { pathname = formatPattern(route.to, params); } else if (!route.to) { pathname = location.pathname; } else { var routeIndex = nextState.routes.indexOf(route); var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1); var pattern = parentPattern.replace(/\/*$/, '/') + route.to; pathname = formatPattern(pattern, params); } replace({ pathname: pathname, query: route.query || location.query, state: route.state || location.state }); }; return route; }, getRoutePattern: function getRoutePattern(routes, routeIndex) { var parentPattern = ''; for (var i = routeIndex; i >= 0; i--) { var route = routes[i]; var pattern = route.path || ''; parentPattern = pattern.replace(/\/*$/, '/') + parentPattern; if (pattern.indexOf('/') === 0) break; } return '/' + parentPattern; } }, propTypes: { path: string, from: string, // Alias for path to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default Redirect;
src/components/InterestedForm.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import SignInUp from './SignInUp'; import { FormattedMessage } from 'react-intl'; class InterestedForm extends React.Component { static propTypes = { onSubmit: PropTypes.func, }; constructor(props) { super(props); this.onSubmit = props.onSubmit; this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(user) { this.onSubmit(user); } render() { return ( <div className="InterestedPane"> <style jsx> {` .InterestedPane { position: absolute; display: flex; justify-content: center; width: 100%; } .InterestedForm { width: 100%; background: white; max-width: 500px; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); border-radius: 0px 0px 10px 10px; margin: 0px auto 40px auto; padding: 10px 20px 20px 20px; } `} </style> <div className="InterestedForm"> <SignInUp label={<FormattedMessage id="InterestedForm.RemindMe" defaultMessage="remind me" />} emailOnly={true} showLabels={false} onSubmit={this.handleSubmit} /> </div> </div> ); } } export default InterestedForm;
src/layouts/PageLayout/PageLayout.js
janoist1/route-share
import React from 'react' import PropTypes from 'prop-types' import NavBar from '../../components/NavBar' import './PageLayout.scss' export const PageLayout = ({ children }) => ( <div className='container-element d-flex flex-column'> <NavBar /> <div className='d-flex align-items-stretch page-layout__viewport'> {children} </div> </div> ) PageLayout.propTypes = { children: PropTypes.node, } export default PageLayout
packages/react-server-examples/bike-share/components/footer.js
doug-wade/react-server
import React from 'react'; import {logging} from 'react-server'; const logger = logging.getLogger(__LOGGER__); export default () => { logger.info('rendering the footer'); return (<div className="footer"> <span>Brought to you by </span> <a href="http://github.com/redfin/react-server">React Server</a> <span> and </span> <a href="http://api.citybik.es/v2/">citybik.es</a> </div>); };
server/sonar-web/src/main/js/apps/account/components/Favorites.js
joansmith/sonarqube
/* * 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 React from 'react'; import Favorite from '../../../components/shared/favorite'; import QualifierIcon from '../../../components/shared/qualifier-icon'; import { translate } from '../../../helpers/l10n'; import { getComponentUrl } from '../../../helpers/urls'; const Favorites = ({ favorites }) => ( <section> <h2 className="spacer-bottom"> {translate('my_account.favorite_components')} </h2> {!favorites.length && ( <p className="note"> {translate('my_account.no_favorite_components')} </p> )} <table id="favorite-components" className="data"> <tbody> {favorites.map(f => ( <tr key={f.key}> <td className="thin"> <Favorite component={f.key} favorite={true}/> </td> <td> <a href={getComponentUrl(f.key)} className="link-with-icon"> <QualifierIcon qualifier={f.qualifier}/> {' '} <span>{f.name}</span> </a> </td> </tr> ))} </tbody> </table> </section> ); export default Favorites;
Paths/React/05.Building Scalable React Apps/8-react-boilerplate-building-scalable-apps-m8-exercise-files/Before/app/containers/LinkListContainer/index.js
phiratio/Pluralsight-materials
/* * * LinkListContainer * */ import React from 'react'; import { connect } from 'react-redux'; import selectLinkListContainer from './selectors'; import LinkList from '../../components/LinkList'; import { requestLinks } from './actions'; export class LinkListContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { topicName: React.PropTypes.string.isRequired, requestLinks: React.PropTypes.func.isRequired, } componentWillMount() { this.props.requestLinks(this.props.topicName); } componentWillReceiveProps(newProps) { if (newProps.topicName !== this.props.topicName) { this.props.requestLinks(newProps.topicName); } } render() { return ( <LinkList {...this.props} /> ); } } const mapStateToProps = selectLinkListContainer(); function mapDispatchToProps(dispatch) { return { requestLinks: (topicName) => dispatch(requestLinks(topicName)), }; } export default connect(mapStateToProps, mapDispatchToProps)(LinkListContainer);
src/components/DatePicker/example.js
InsideSalesOfficial/insidesales-components
// A simple dexample wrapper for use in stories only. Not intended for use as // an app component // TODO: Create another decorator for being able to display the markup of each example import React from 'react'; import styled from 'styled-components'; import { colors } from '../styles/colors'; import { fontSizes, fontFamilies, fontWeights } from '../styles/typography'; const BaseExample = styled.div` fontFamily: ${fontFamilies.roboto}, marginBottom: 25px, padding: 10px, position: relative, WebkitFontSmoothing: antialiased `; const DescriptionExample = styled.p` color: ${colors.renderThemeIfPresentOrDefault({key: 'white90', defaultValue: colors.grayD})}; fontWeight: ${fontWeights.light}, marginTop: 10px `; const TitleExample = styled.h2` color: ${colors.renderThemeIfPresentOrDefault({key: 'white90', defaultValue: colors.grayE})}; fontWeight: ${fontWeights.regular}, fontSize: ${fontSizes.large}, margin: 0 `; const ComponentWrapperExample = styled.div` width: 440px, boxSizing: border-box, padding: 0 10px `; const WrapperExample = styled.div` border: 1px solid ${colors.white60}, padding: 0px 20px 20px 20px, display: flex, flex: 0 0 100%, flexDirection: column `; const ExampleText = styled.p` color: ${colors.renderThemeIfPresentOrDefault({key: 'white90', defaultValue: colors.grayE})}; display: inline-flex, flex: 0 0 100%, flexDirection: column, fontSize: ${fontSizes.xSmall}, fontWeight: ${fontWeights.bold}, textTransform: uppercase `; export const Example = ({ children, title, description }) => { return ( // The example div gets class isdc-ext-wrap because our component styles are all wrapped in this prefix to work // with the existing extension syles. <BaseExample className="isdc-ext-wrap"> <TitleExample>{ title }</TitleExample> <DescriptionExample>{ description }</DescriptionExample> <WrapperExample> <ExampleText>Example</ExampleText> <ComponentWrapperExample> { children } </ComponentWrapperExample> </WrapperExample> </BaseExample> ); }; export default Example;
examples/counter/index.js
glifchits/redux
import React from 'react'; import Root from './containers/Root'; React.render( <Root />, document.getElementById('root') );
client/src/pages/login/ResetForm.js
ccwukong/lfcommerce-react
import React from 'react'; import PropTypes from 'prop-types'; import { Formik, Form } from 'formik'; import * as Yup from 'yup'; import { injectIntl, FormattedMessage } from 'react-intl'; import { Input, Button } from 'reactstrap'; const accountValidation = Yup.object().shape({ username: Yup.string().required('Required'), }); const ResetForm = props => { const { intl: { formatMessage }, } = props; return ( <Formik enableReinitialize onSubmit={(values, { setSubmitting }) => { setSubmitting(true); //TODO: send new password to email setSubmitting(false); }} validationSchema={accountValidation} > {({ handleChange, isSubmitting, errors }) => ( <Form id="reset-form"> <Input type="email" name="username" id="username" placeholder={formatMessage({ id: 'sys.email' })} onChange={handleChange} /> {errors.username && ( <div className="text-danger">{errors.username}</div> )} <br /> <Button color="secondary" type="submit" block disabled={isSubmitting}> <FormattedMessage id="sys.send" /> </Button> </Form> )} </Formik> ); }; ResetForm.propTypes = { intl: PropTypes.object.isRequired, }; export default injectIntl(ResetForm);
src/views/App.js
Afrostream/react-redux-universal-hot-example
/*global __CLIENT__*/ import React from 'react'; import {Link} from 'react-router'; import {load} from '../actions/infoActions'; import InfoBar from '../components/InfoBar'; if (__CLIENT__) { require('./App.scss'); } export default class App { render() { return ( <div className="container app"> <div className="jumbotron"> <h1>React Redux Example</h1> <p> by <a href="https://twitter.com/erikras" target="_blank">@erikras</a> <a className="github" href="https://github.com/erikras/react-redux-universal-hot-example" target="_blank"> <i className="fa fa-github"/> View on Github </a> </p> <iframe src="https://ghbtns.com/github-btn.html?user=erikras&repo=react-redux-universal-hot-example&type=star&count=true&size=large" frameBorder="0" allowTransparency="true" scrolling="0" width="160px" height="30px"></iframe> <iframe src="https://ghbtns.com/github-btn.html?user=erikras&amp;repo=react-redux-universal-hot-example&amp;type=fork&amp;count=true&size=large" allowTransparency="true" frameBorder="0" scrolling="0" width="160px" height="30px"></iframe> </div> <nav className="navbar navbar-default"> <div className="container-fluid"> <ul className="nav navbar-nav"> <li><Link to="/">Home</Link></li> <li><Link to="/sign-up">Sign Up</Link></li> <li><Link to="/login">Login</Link></li> </ul> </div> </nav> <InfoBar/> <div className="app-content"> {this.props.children} </div> </div> ); } static fetchData(dispatch) { return dispatch(load()); } }
src/scene/GroupPurchase/GroupPurchaseCell.js
Cowboy1995/JZWXZ
/** * Copyright (c) 2017-present, Liu Jinyong * All rights reserved. * * https://github.com/huanxsd/MeiTuan * @flow */ //import liraries import React, { Component } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native'; import { Heading1, Heading2, Paragraph } from '../../widget/Text' import { screen } from '../../common' import { color } from '../../widget' // create a component class GroupPurchaseCell extends Component { render() { let { info } = this.props let imageUrl = info.imageUrl.replace('w.h', '160.0') return ( <TouchableOpacity style={styles.container} onPress={() => this.props.onPress()}> <Image source={{ uri: imageUrl }} style={styles.icon} /> <View style={styles.rightContainer}> <Heading1>{info.title}</Heading1> <View> </View> <Paragraph numberOfLines={0} style={{ marginTop: 8 }}>{info.subtitle}</Paragraph> <View style={{ flex: 1, justifyContent: 'flex-end' }}> <Heading1 style={styles.price}>{info.price}元</Heading1> </View> </View> </TouchableOpacity> ); } } // define your styles const styles = StyleSheet.create({ container: { flexDirection: 'row', padding: 10, borderBottomWidth: screen.onePixel, borderColor: color.border, backgroundColor: 'white', }, icon: { width: 80, height: 80, borderRadius: 5, }, rightContainer: { flex: 1, paddingLeft: 20, paddingRight: 10, }, price: { color: color.theme } }); //make this component available to the app export default GroupPurchaseCell;
site/components/NavBar.js
colbyr/react-dnd
import React from 'react'; import { DOCS_DEFAULT, EXAMPLES_DEFAULT } from '../Constants'; import './NavBar.less'; const GITHUB_URL = 'https://github.com/gaearon/react-dnd'; const DOCS_LOCATION = DOCS_DEFAULT.location; const EXAMPLES_LOCATION = EXAMPLES_DEFAULT.location; export default class NavBar { render() { return ( <div className="NavBar"> <div className="NavBar-container"> <div className="NavBar-logo"> <a href="./" target="_self" className="NavBar-logoTitle">React <i>DnD</i></a> <p className="NavBar-logoDescription">Drag and Drop for React</p> </div> <div className="NavBar-item"> <a className="NavBar-link" href={DOCS_LOCATION} target="_self">Docs</a> <a className="NavBar-link" href={EXAMPLES_LOCATION} target="_self">Examples</a> <a className="NavBar-link" href={GITHUB_URL}>GitHub</a> </div> </div> </div> ); } }
src/components/Context.js
gaearon/react-redux
import React from 'react' export const ReactReduxContext = React.createContext(null) export default ReactReduxContext
src/svg-icons/notification/do-not-disturb-alt.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationDoNotDisturbAlt = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zM4 12c0-4.4 3.6-8 8-8 1.8 0 3.5.6 4.9 1.7L5.7 16.9C4.6 15.5 4 13.8 4 12zm8 8c-1.8 0-3.5-.6-4.9-1.7L18.3 7.1C19.4 8.5 20 10.2 20 12c0 4.4-3.6 8-8 8z"/> </SvgIcon> ); NotificationDoNotDisturbAlt = pure(NotificationDoNotDisturbAlt); NotificationDoNotDisturbAlt.displayName = 'NotificationDoNotDisturbAlt'; NotificationDoNotDisturbAlt.muiName = 'SvgIcon'; export default NotificationDoNotDisturbAlt;
client/modules/Home/components/HomeTabs.js
XuHaoJun/tiamat
import React from 'react'; import PropTypes from 'prop-types'; import _reduce from 'lodash/reduce'; import { shouldComponentUpdate } from 'react-immutable-render-mixin'; import Tabs, { Tab } from '../../../components/Tabs'; import ForumBoardList from '../../ForumBoard/components/ForumBoardList'; import EnhancedSwipeableViews from '../../../components/EnhancedSwipableViews'; export const HOME_SLIDE = 0; export const WHAT_HOT_SLIDE = 1; export const WIKI_SLIDE = 2; export const SLIDE_COUNT = 3; const _slideIndexEnMapping = { [HOME_SLIDE]: 'home', [WHAT_HOT_SLIDE]: 'what_hot', [WIKI_SLIDE]: 'wiki', }; const _slideIndexEnReverseMapping = _reduce( _slideIndexEnMapping, (result, v, k) => { const en = v; const i = Number.parseInt(k, 10); return Object.assign(result, { [en]: i }); }, {} ); export const getSlideIndexEnAlias = slideIndex => { return _slideIndexEnMapping[slideIndex]; }; export const getSlideIndexFromEnAlias = enAlias => { return _slideIndexEnReverseMapping[enAlias]; }; class HomeTabs extends React.Component { static propTypes = { slideContainerStyle: PropTypes.object, forumBoardListProps: PropTypes.object, }; static defaultProps = { slideIndex: 0, // eslint-disable-line slideContainerStyle: { height: '100%', }, forumBoardListProps: {}, }; constructor(props) { super(props); this.shouldComponentUpdate = shouldComponentUpdate.bind(this); this.state = { slideIndex: props.slideIndex, }; } componentWillReceiveProps(nextProps) { if (nextProps.slideIndex !== this.state.slideIndex) { this.setState({ slideIndex: nextProps.slideIndex }); } } handleChange = (event, value) => { this.setState({ slideIndex: value }); }; handleChangeIndex = value => { this.setState({ slideIndex: value }); }; handleTransitionEnd = () => { if (this.props.onTransitionEnd) { this.props.onTransitionEnd(this.state.slideIndex); } }; render() { const { id, forumBoardListProps } = this.props; const { slideIndex } = this.state; return ( <div> <Tabs onChange={this.handleChange} value={slideIndex}> <Tab label="首頁" value={HOME_SLIDE} /> <Tab label="熱門看板" value={WHAT_HOT_SLIDE} /> <Tab label="今日維基" value={WIKI_SLIDE} /> </Tabs> <EnhancedSwipeableViews id={id ? `${id}/EnhancedSwipeableViews` : null} index={slideIndex} style={this.props.swipeableViewsStyle} containerStyle={this.props.slideContainerStyle} slideClassName={this.props.slideClassName} onChangeIndex={this.handleChangeIndex} onTransitionEnd={this.handleTransitionEnd} > <div>首頁,放推薦內容(尚未完成)</div> <ForumBoardList id={id ? `${id}/ForumBoardList` : null} {...forumBoardListProps} /> <div>維基特色條目(尚未完成)</div> </EnhancedSwipeableViews> </div> ); } } export default HomeTabs;
techCurriculum/ui/solutions/2.5/src/components/Message.js
jennybkim/engineeringessentials
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. **/ import React from 'react'; function Message() { return ( <div className='message-text'> <p>React is so cool!</p> </div> ); } export default Message;
admin/client/App/components/Footer/index.js
cermati/keystone
/** * The global Footer, displays a link to the website and the current Keystone * version in use */ import React from 'react'; import { css, StyleSheet } from 'aphrodite/no-important'; import { Container } from '../../elemental'; import theme from '../../../theme'; var Footer = React.createClass({ displayName: 'Footer', propTypes: { appversion: React.PropTypes.string, backUrl: React.PropTypes.string, brand: React.PropTypes.string, user: React.PropTypes.object, User: React.PropTypes.object, // eslint-disable-line react/sort-prop-types version: React.PropTypes.string, }, // Render the user renderUser () { const { User, user } = this.props; if (!user) return null; return ( <span> <span> Signed in as </span> <a href={`${Keystone.adminPath}/${User.path}/${user.id}`} tabIndex="-1" className={css(classes.link)}> {user.name} </a> <span>.</span> </span> ); }, render () { const { backUrl, brand, appversion, version } = this.props; return ( <footer className={css(classes.footer)} data-keystone-footer> <Container> <a href={backUrl} tabIndex="-1" className={css(classes.link)} > {brand + (appversion ? (' ' + appversion) : '')} </a> <span> powered by </span> <a href="http://keystonejs.com" target="_blank" className={css(classes.link)} tabIndex="-1" > KeystoneJS </a> <span> version {version}.</span> {this.renderUser()} </Container> </footer> ); }, }); /* eslint quote-props: ["error", "as-needed"] */ const linkHoverAndFocus = { color: theme.color.gray60, outline: 'none', }; const classes = StyleSheet.create({ footer: { boxShadow: '0 -1px 0 rgba(0, 0, 0, 0.1)', color: theme.color.gray40, fontSize: theme.font.size.small, paddingBottom: 30, paddingTop: 40, textAlign: 'center', }, link: { color: theme.color.gray60, ':hover': linkHoverAndFocus, ':focus': linkHoverAndFocus, }, }); module.exports = Footer;
src/svg-icons/social/pages.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialPages = (props) => ( <SvgIcon {...props}> <path d="M3 5v6h5L7 7l4 1V3H5c-1.1 0-2 .9-2 2zm5 8H3v6c0 1.1.9 2 2 2h6v-5l-4 1 1-4zm9 4l-4-1v5h6c1.1 0 2-.9 2-2v-6h-5l1 4zm2-14h-6v5l4-1-1 4h5V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); SocialPages = pure(SocialPages); SocialPages.displayName = 'SocialPages'; SocialPages.muiName = 'SvgIcon'; export default SocialPages;
src/components/MainContainer/MainContainer.js
ateev/starWars
import React, { Component } from 'react'; import { readBrowserCookie } from '../../helpers/cookieHandler.js'; import { checkCreds } from '../../actions/userActions.js'; import Login from '../Login/login.js'; import PlanetsContainer from '../PlanetsContainer/PlanetsContainer'; import { connect } from 'react-redux'; class MainContainer extends Component { loginUser = (username, password) => { this.context.store.dispatch(checkCreds(username, password)); } render() { const userName = readBrowserCookie('LoggedIn username')[0]; let appBlock; if(typeof userName !== 'undefined') { appBlock = <PlanetsContainer userName={userName} />; } else { appBlock = <Login submitCallback={ this.loginUser } /> } return ( <div className="main-container"> { appBlock } </div> ); } } MainContainer.contextTypes = { store: React.PropTypes.object, }; function mapStateToProps(state) { return { user: state.user, }; } export default connect(mapStateToProps)(MainContainer);
src/components/todos/todos-header.js
MaxMooc/react-gallery
import React from 'react'; class Header extends React.Component{ constructor(props){ super(props); this.state = { value: '' } } handleChange = (e) =>{ this.setState({ value: e.target.value }) } handleKeyDown = (e) => { if(e.keyCode != 13 || !e.target.value)return; this.props.onHeaderKeyDown(e.target.value); this.state.value = ''; } handleCheck = (e) => { this.props.onHeaderCheck(e.target.checked); } render(){ return( <header> <h2>Todos</h2> <p> <input type="text" onKeyDown={this.handleKeyDown} onChange={this.handleChange} value={this.state.value} placeholder="What needs to be done?" /> </p> <label> <input type="checkbox" onChange={this.handleCheck} checked={this.props.checked} /> <span>Mark all as complete</span> </label> </header> ) } } export default Header;
src/scenes/home/mentor/mentorRequestsTable/mentorRequestsTable.js
miaket/operationcode_frontend
import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; import PropTypes from 'prop-types'; import { MENTOR_REQUEST_COLUMNS } from 'shared/constants/table'; import * as ApiHelpers from 'shared/utils/apiHelper'; import IndexTable from 'shared/components/indexTable/indexTable'; import RequestModal from 'scenes/home/requestModal/requestModal'; class MentorRequestsTable extends Component { state = { requests: [], mentors: [], activeRequest: null } componentDidMount() { Promise.all([ApiHelpers.getRequests(), ApiHelpers.getMentors()]) .then((data) => { this.setState({ requests: data[0], mentors: data[1] }); }); } buildMentorOptions = () => this.state.mentors.map(mentor => ({ value: mentor.id, label: `${mentor.first_name} ${mentor.last_name}` })); handleModalClose = () => this.setState({ activeRequest: null }); rowClickHandler = (request) => { const activeRequest = this.state.requests.find(x => x.id === request.id); this.setState({ activeRequest }); } render() { const { activeRequest } = this.state; const { signedIn } = this.props; return ( <div style={{ width: '100%' }} > <IndexTable heading="Pending Requests" columns={MENTOR_REQUEST_COLUMNS} onRowClick={this.rowClickHandler} fetchRecords={ApiHelpers.getRequests} /> <RequestModal request={activeRequest} mentors={this.buildMentorOptions()} isOpen={!!activeRequest} onRequestClose={this.handleModalClose} /> {!signedIn && <Redirect to="/login" />} </div> ); } } MentorRequestsTable.propTypes = { signedIn: PropTypes.bool }; MentorRequestsTable.defaultProps = { signedIn: true, }; export default MentorRequestsTable;
src/index.js
nick81/portfolio
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();
src/helpers/Html.js
PhilNorfleet/pBot
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom/server'; import serialize from 'serialize-javascript'; import Helmet from 'react-helmet'; /** * Wrapper component containing HTML metadata and boilerplate tags. * Used in server-side code only to wrap the string output of the * rendered route component. * * The only thing this component doesn't (and can't) include is the * HTML doctype declaration, which is added to the rendered output * by the server.js file. */ export default class Html extends Component { static propTypes = { assets: PropTypes.object, component: PropTypes.node.isRequired, store: PropTypes.object.isRequired }; static defaultProps = { assets: {} }; render() { const { assets, component, store } = this.props; const content = component ? ReactDOM.renderToString(component) : ''; const head = Helmet.renderStatic(); return ( <html lang="en-US"> <head> {head.base.toComponent()} {head.title.toComponent()} {head.meta.toComponent()} {head.link.toComponent()} {head.script.toComponent()} <link rel="shortcut icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="manifest" href="/manifest.json" /> <meta name="mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="application-name" content="React Hot" /> <meta name="apple-mobile-web-app-status-bar-style" content="black" /> <meta name="apple-mobile-web-app-title" content="React Hot" /> <meta name="theme-color" content="#3677dd" /> {/* styles (will be present only in production with webpack extract text plugin) */} {assets.styles && Object.keys(assets.styles).map(style => ( <link href={assets.styles[style]} key={style} media="screen, projection" rel="stylesheet" type="text/css" charSet="UTF-8" /> ))} {/* (will be present only in development mode) */} {assets.styles && Object.keys(assets.styles).length === 0 ? <style dangerouslySetInnerHTML={{ __html: '#content{display:none}' }} /> : null} </head> <body> <div id="content" dangerouslySetInnerHTML={{ __html: content }} /> {store && <script dangerouslySetInnerHTML={{ __html: `window.__data=${serialize(store.getState())};` }} charSet="UTF-8" />} {__DLLS__ && <script key="dlls__vendor" src="/dist/dlls/dll__vendor.js" charSet="UTF-8" />} {assets.javascript && <script src={assets.javascript.main} charSet="UTF-8" />} {/* (will be present only in development mode) */} {assets.styles && Object.keys(assets.styles).length === 0 ? <script dangerouslySetInnerHTML={{ __html: 'document.getElementById("content").style.display="block";' }} /> : null} </body> </html> ); } }
app/components/AvatarGrid/index.js
ReelTalkers/reeltalk-web
/** * * AvatarGrid * */ import React from 'react' import styles from './styles.css' function AvatarGrid() { return ( <div className={ styles.avatarGrid }> </div> ) } export default AvatarGrid
src/components/tabPhotos/PhotoAlbum.js
timLoewel/sites
'use strict'; import React from 'react'; import ReactNative from 'react-native'; import {newObjectId} from '../../utils/objectId'; import getDimensions from '../../utils/dimensions'; import LightBox from './Lightbox.android'; let { Image, ListView, TouchableOpacity, View, RefreshControl, LayoutAnimation, } = ReactNative; const THUMBNAIL_MARGIN = 5; const allVisiblePhotos = []; const {width: windowWidth, height: windowHeight} = getDimensions(); for (let i = 20; i < 200; ++i) { allVisiblePhotos.push({ localObjectId: newObjectId(), thumbnailData: 'https://unsplash.it/40/60?image=' + i, uriPhotoLocal: 'https://unsplash.it/1500/2500?image=' + i, shareableUri: 'obob.work/' + i, description: 'text ' + i, creatorObjectId: 'asfd', creatorName: 'tim', selectedLocation: {longitude: 33.0 + 0.1 * i, latitude: 22.0 + 0.1 * i}, systemLocation: {longitude: 33.0 + 0.11 * i, latitude: 22.0 + 0.12 * i}, }) } class PhotoAlbum extends React.Component { constructor(props) { super(props); const listViewDataSource = new ListView.DataSource({rowHasChanged: (p1, p2) => p1.objectId === p2.objectId}); let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { listViewDataSource: listViewDataSource, showSinglePhotoRowID: undefined, refreshing: false, thumbnailsPerRow: 2, }; this._pressData = ({}: { [key: number]: boolean }) }; componentWillMount() { this._pressData = {}; }; _onRefresh() { this.setState({refreshing: true}); // this.props.fetchData().then(() => { // this.setState({refreshing: false}); // }); this.setState({refreshing: false}); } _getThumbnailSize() { return (windowWidth / this.state.thumbnailsPerRow) - (3 * THUMBNAIL_MARGIN) } _changePhotoRowIDCallback(selectedPhotoRowID) { if (this.state.showSinglePhotoRowID != selectedPhotoRowID) { let imgNum = selectedPhotoRowID - this.state.thumbnailsPerRow; if (imgNum < 1) { imgNum = 0; } const pixelPerRow = this._getThumbnailSize() + 2 * THUMBNAIL_MARGIN; this.listView.scrollTo({x: 0, y: Math.floor(imgNum / this.state.thumbnailsPerRow) * pixelPerRow, animated: false}) } } _closeLightboxCallback(selectedPhotoRowID) { this.setState({showSinglePhotoRowID: undefined}); } _renderLightbox() { if (this.state.showSinglePhotoRowID) { return <LightBox mediaList={this.props.allVisiblePhotos} currentlySelectedRowID = {this.state.showSinglePhotoRowID} changePhotoRowIDCallback = {this._changePhotoRowIDCallback.bind(this)} closeCallback={this._closeLightboxCallback.bind(this)}/> } else { return undefined; } } render() { const listData = this.state.listViewDataSource.cloneWithRows(this.props.allVisiblePhotos); return ( <View> <ListView ref={component => this.listView = component} enableEmptySections={true} contentContainerStyle={{ justifyContent: 'center', flexDirection: 'row', flexWrap: 'wrap', alignItems: 'flex-start' }} style={{position: 'absolute', top: 0, left: 0, width: windowWidth, height: windowHeight}} dataSource={listData} renderRow={this._renderRow.bind(this)} refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} tintColor="#ff0000" title="Loading..." titleColor="#00ff00" colors={['#ff00aaaa', '#00ffbbaa', '#0000ffaa']} progressBackgroundColor="#ffff00cc" enabled /> } /> {this._renderLightbox()} </View> ); } _onPressImage(rowID) { return () => { this.setState({showSinglePhotoRowID: rowID}) } } _renderRow(rowData: object, sectionID: number, rowID: number) { const imageSize = this._getThumbnailSize() return ( <TouchableOpacity key={rowID} onPress={this._onPressImage(rowID).bind(this)} activeOpacity={0.7} > <View style={ { justifyContent: 'center', margin: THUMBNAIL_MARGIN, width: imageSize, height: imageSize, backgroundColor: '#F6F6F6', alignItems: 'center', borderWidth: 0, borderRadius: 0, borderColor: '#CCC' }}> <Image resizeMode="cover" style={{ width: imageSize, height: imageSize, top: 0, left: 0, position: 'absolute', }} source={{uri: rowData.thumbnailData}}/> <Image resizeMode="cover" style={{ width: imageSize, height: imageSize, top: 0, left: 0, position: 'absolute', }} source={{uri: 'file://' + rowData.uriPhotoLocal}}/> </View> </TouchableOpacity> ); } }; export default PhotoAlbum;
src/playlist-container.js
cutofmyjib/podcast-house
import React, { Component } from 'react'; import Playlist from './playlists' export default class PlaylistContainer extends Component { render() { // const podcastPlaylists = this.props.data.map(function(data){ // return <Playlist {...data} /> // }) const podcastPlaylists = this.props.data.map((data, i) => { data = { ...data, id: i } return <Playlist { ...data } /> }) return ( <div className="playlists"> {podcastPlaylists} </div> ); } }
examples/react-redux-example/app/todomvc/index.js
demones/react-guide
import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; import 'todomvc-app-css/index.css'; const store = configureStore(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('layout') );
src/index.js
Dremora/mondo-hackathon-webapp
import React from 'react'; import { render } from 'react-dom'; import { App } from './App'; import { Router, Route, Link } from 'react-router' import { createHistory } from 'history' import moment from 'moment' moment.locale('en-gb') render(( <Router history={createHistory()}> <Route path="/" component={App}> </Route> </Router> ), document.getElementById('root'))
spa/react-stateless/client-demo/src/components/Nav.js
networknt/light-java-example
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import '../App.css'; class Nav extends Component { render() { return ( <nav className="navbar navbar-default"> <div className="navbar-header"> <Link className="navbar-brand" to="/">OAuth 2.0 JWT Demo</Link> </div> <ul className="nav navbar-nav"> <li> <Link to="/">Home</Link> </li> <li> <Link to="/special">API</Link> </li> <li> <Link to="/login">Log In</Link> </li> <li> <Link to="/logout">Log Out</Link> </li> </ul> </nav> ); } } export default Nav;
tests/react/default_props_undefined.js
TiddoLangerak/flow
// @flow import React from 'react'; class Foo extends React.Component<{bar: number}, void> { static defaultProps = {bar: 42}; } <Foo bar={42}/>; // OK <Foo bar="42"/>; // Error <Foo bar={undefined}/>; // OK: React will replace `undefined` with the default.
server/sonar-web/src/main/js/apps/about/components/AboutScanners.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info 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 React from 'react'; import { translate } from '../../../helpers/l10n'; const scanners = [ { key: 'sonarqube', link: 'https://redirect.sonarsource.com/doc/install-configure-scanner.html' }, { key: 'msbuild', link: 'https://redirect.sonarsource.com/doc/install-configure-scanner-msbuild.html' }, { key: 'maven', link: 'https://redirect.sonarsource.com/doc/install-configure-scanner-maven.html' }, { key: 'gradle', link: 'https://redirect.sonarsource.com/doc/gradle.html' }, { key: 'jenkins', link: 'https://redirect.sonarsource.com/plugins/jenkins.html' }, { key: 'ant', link: 'https://redirect.sonarsource.com/doc/install-configure-scanner-ant.html' } ]; export default class AboutScanners extends React.Component { render() { return ( <div className="boxed-group"> <h2>{translate('about_page.scanners')}</h2> <div className="boxed-group-inner"> <p className="about-page-text">{translate('about_page.scanners.text')}</p> <div className="about-page-analyzers"> {scanners.map(scanner => ( <a key={scanner.key} className="about-page-analyzer-box" href={scanner.link}> <img src={`${window.baseUrl}/images/scanner-logos/${scanner.key}.svg`} height={60} alt={translate('about_page.scanners', scanner.key)} /> </a> ))} </div> </div> </div> ); } }
src/components/BeerBarsComponent.js
jezzasan/taproom-react
'use strict'; import React from 'react'; let BeerBarsListComponent = require('./BeerBarsListComponent.js'); class BeerBarsComponent extends React.Component { constructor(props) { super(props); this.state= { bars: null, ready: false }; } componentDidMount() { //Have to do DB call in here to get infor for BeerBarsList //do jQuery call instead } render() { //Not sure how to make this interface with map //Loop through results in `bars` and render out components return ( <div className="beerbars-component"> <div className="beer-bars-container"> <h1>Craft Beer Bars Chicago</h1> <BeerBarsListComponent /> <BeerBarsListComponent /> <BeerBarsListComponent /> <BeerBarsListComponent /> </div> </div> ); } } BeerBarsComponent.displayName = 'BeerBarsComponent'; // Uncomment properties you need // BeerBarsComponent.propTypes = {}; // BeerBarsComponent.defaultProps = {}; export default BeerBarsComponent;
test/test_helper.js
pornvutp/tact
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
app/react-icons/fa/sort-alpha-asc.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaSortAlphaAsc extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m27.6 9.1h3.9l-1.6-4.9-0.2-1q-0.1-0.4-0.1-0.5h-0.1l0 0.5q0 0-0.1 0.4t-0.2 0.6z m-10.2 23q0 0.3-0.2 0.6l-7.1 7.1q-0.2 0.2-0.5 0.2-0.3 0-0.5-0.2l-7.2-7.1q-0.3-0.4-0.1-0.8 0.1-0.5 0.6-0.5h4.3v-30.7q0-0.3 0.2-0.5t0.5-0.2h4.3q0.3 0 0.5 0.2t0.2 0.5v30.7h4.3q0.3 0 0.5 0.2t0.2 0.5z m18.7 2.7v5.2h-13v-2l8.2-11.8q0.3-0.4 0.5-0.6l0.2-0.2v-0.1q0 0-0.1 0t-0.2 0q-0.3 0.1-0.7 0.1h-5.2v2.6h-2.6v-5.1h12.6v1.9l-8.2 11.9q-0.2 0.2-0.5 0.6l-0.2 0.2v0l0.3 0q0.2 0 0.7 0h5.5v-2.7h2.7z m2-20v2.3h-6.5v-2.3h1.7l-1-3.2h-5.5l-1 3.2h1.7v2.3h-6.4v-2.3h1.5l5.2-14.8h3.6l5.1 14.8h1.6z"/></g> </IconBase> ); } }
node_modules/react-icons/md/desktop-windows.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const MdDesktopWindows = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m35 26.6v-20h-30v20h30z m0-23.2c1.8 0 3.4 1.4 3.4 3.2v20c0 1.8-1.6 3.4-3.4 3.4h-11.6v3.4h3.2v3.2h-13.2v-3.2h3.2v-3.4h-11.6c-1.8 0-3.4-1.6-3.4-3.4v-20c0-1.8 1.6-3.2 3.4-3.2h30z"/></g> </Icon> ) export default MdDesktopWindows
debugger/function-tree-debugger/src/components/Debugger/Signals/index.js
idream3/cerebral
import './styles.css' import React from 'react' import classNames from 'classnames' import {connect} from 'cerebral/react' import signalsList from '../../../common/computed/signalsList' import connector from 'connector' import List from './List' import Signal from './Signal' export default connect({ currentPage: 'debugger.currentPage', signalsList: signalsList, useragent: 'useragent.**', currentSignalExecutionId: 'debugger.currentSignalExecutionId', isExecuting: 'debugger.isExecuting' }, { resetClicked: 'debugger.resetClicked' }, class Signals extends React.Component { constructor (props) { super(props) this.state = {copiedSignals: null} } shouldComponentUpdate (nextProps, nextState) { return ( this.props.currentPage !== nextProps.currentPage || this.props.useragent.media.small !== nextProps.useragent.media.small || this.props.currentSignalExecutionId !== nextProps.currentSignalExecutionId || this.props.mutationsError !== nextProps.mutationsError || this.state.copiedSignals !== nextState.copiedSignals || this.props.isExecuting !== nextProps.isExecuting ) } onResetClick () { this.props.resetClicked() connector.sendEvent('reset') } onCopySignalsClick () { this.setState({copiedSignals: JSON.stringify(this.props.signalsList.reverse(), null, 2)}, () => { this.textarea.select() }) } render () { const currentSignalExecutionId = this.props.currentSignalExecutionId return ( <div className={classNames('signals', this.props.className)}> <div className='signals-list'> <List /> <button onClick={() => this.onCopySignalsClick()} className='signals-rewrite' disabled={!currentSignalExecutionId}> Copy signals data </button> <button onClick={() => this.onResetClick()} className='signals-reset' disabled={!currentSignalExecutionId || this.props.isExecuting}> Reset all state </button> </div> <div className='signals-signal'> <Signal currentSignalExecutionId={currentSignalExecutionId} /> </div> { this.state.copiedSignals ? <li className='signals-textarea'> <textarea ref={(node) => { this.textarea = node }} value={this.state.copiedSignals} onBlur={() => this.setState({copiedSignals: null})} /> </li> : null } </div> ) } } )
packages/material-ui-icons/src/Loop.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z" /></g> , 'Loop');
src/svg-icons/action/timeline.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTimeline = (props) => ( <SvgIcon {...props}> <path d="M23 8c0 1.1-.9 2-2 2-.18 0-.35-.02-.51-.07l-3.56 3.55c.05.16.07.34.07.52 0 1.1-.9 2-2 2s-2-.9-2-2c0-.18.02-.36.07-.52l-2.55-2.55c-.16.05-.34.07-.52.07s-.36-.02-.52-.07l-4.55 4.56c.05.16.07.33.07.51 0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2c.18 0 .35.02.51.07l4.56-4.55C8.02 9.36 8 9.18 8 9c0-1.1.9-2 2-2s2 .9 2 2c0 .18-.02.36-.07.52l2.55 2.55c.16-.05.34-.07.52-.07s.36.02.52.07l3.55-3.56C19.02 8.35 19 8.18 19 8c0-1.1.9-2 2-2s2 .9 2 2z"/> </SvgIcon> ); ActionTimeline = pure(ActionTimeline); ActionTimeline.displayName = 'ActionTimeline'; ActionTimeline.muiName = 'SvgIcon'; export default ActionTimeline;
src/js/components/n-icon.js
bradwoo8621/parrot2
import React from 'react' import ReactDOM from 'react-dom' import jQuery from 'jquery' import classnames from 'classnames' let $ = jQuery; import {Envs} from '../envs' import {NComponent} from './n-component' let prefixFA = function(str) { if (str) { return str.split(' ').map(classname => { if (classname.startsWith('!')) { return classname.substr(1); } else { return classname.replace(/^(?!fa-)(.*)$/, 'fa-$1'); } }).join(' '); } else { return str; } }; // icon has no standard line-height // default is font-awesome class NIcon extends NComponent { static defaultProps = { defaultOptions: { fontAwesome: true } } renderInNormal() { return (<i className={prefixFA(this.getRenderedClassName())} onClick={this.onComponentClicked} ref='me' />); } // style getComponentClassName() { return '!n-icon'; } getRenderedClassName() { return classnames(this.getComponentStyle(), { '!fa fw': this.isFontAwesome() }, classnames(this.getFontClassName()), { '!n-clickable': this.isClickable() }); } // option value isFontAwesome() { return this.getLayoutOptionValue('fontAwesome'); } // all font class names should be defined here // if it is from font-awesome, the first 'fa-' can be ignored // such as 'ban', equals 'fa-ban'. // but others cannot be ignored // such as 'ban fa-spin', equals 'fa-ban fa-spin' // can be any format which can be parsed by classnames getFontClassName() { return this.getLayoutOptionValue('icon'); } onComponentClicked = (evt) => { if (this.isClickable()) { this.fireEventToMonitor(evt); } } } // only for font-awesome class NStackIcon extends NComponent { renderInNormal() { return (<span className={prefixFA(this.getRenderedClassName())} onClick={this.onComponentClicked} ref='me' > <i className={prefixFA(classnames('!fa stack-1x', this.getForeClassName()))} /> <i className={prefixFA(classnames('!fa stack-2x', this.getBackClassName()))} /> </span>); } // style getComponentClassName() { return '!n-stack-icon'; } getRenderedClassName() { return classnames(this.getComponentStyle(), 'stack fw', this.getBackgroundClassName(), { '!n-clickable': this.isClickable() }); } // option value getBackgroundClassName() { return this.getLayoutOptionValue('background'); } getForeClassName() { return this.getLayoutOptionValue('foreicon'); } getBackClassName() { return this.getLayoutOptionValue('backicon'); } onComponentClicked = (evt) => { if (this.isClickable()) { this.fireEventToMonitor(evt); } } } Envs.COMPONENT_TYPES.ICON = {type: 'n-icon', label: false, error: false}; Envs.setRenderer(Envs.COMPONENT_TYPES.ICON.type, function (options) { return <NIcon {...options} />; }); Envs.COMPONENT_TYPES.STACK_ICON = {type: 'n-stack-icon', label: false, error: false}; Envs.setRenderer(Envs.COMPONENT_TYPES.STACK_ICON.type, function (options) { return <NStackIcon {...options} />; }); export {NIcon, NStackIcon}
src/interface/character/Search.js
FaideWW/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { withRouter } from 'react-router-dom'; import SelectSearch from 'react-select-search'; import { Trans, t } from '@lingui/macro'; import REALMS from 'common/REALMS'; import { makeCharacterApiUrl } from 'common/makeApiUrl'; import { i18n } from 'interface/RootLocalizationProvider'; import makeUrl from './makeUrl'; class Search extends React.PureComponent { static propTypes = { history: PropTypes.shape({ push: PropTypes.func.isRequired, }), }; state = { currentRegion: 'EU', currentRealm: '', }; constructor() { super(); this.handleSubmit = this.handleSubmit.bind(this); } componentDidMount() { if (this.regionInput) { this.regionInput.focus(); } } async handleSubmit(e) { e.preventDefault(); const region = this.regionInput.value; const realm = this.state.currentRealm; const char = this.charInput.value; if (!region || !realm || !char) { alert(i18n._(t`Please select a region, realm and player.`)); return; } if (this.state.loading) { alert(i18n._(t`Still working...`)); return; } // Checking here makes it more userfriendly and saves WCL-requests when char doesn't even exist for the bnet-api this.setState({ loading: true, }); // Skip CN-API due to blizzard restrictions (aka there is no API for CN) if (region !== 'CN') { const response = await fetch(makeCharacterApiUrl(null, region, realm, char, 'talents')); if (response.status === 500) { alert(i18n._(t`It looks like we couldn't get a response in time from the API. Try and paste your report-code manually.`)); this.setState({ loading: false, }); return; } if (!response.ok) { alert(i18n._(t`It looks like we couldn't get a response in time from the API, this usually happens when the servers are under heavy load. Please try and use your report-code or try it again later.`)); this.setState({ loading: false, }); return; } const data = await response.json(); if (data.status === 'nok') { alert(i18n._(t`${char} of ${realm} could not be found.`)); this.setState({ loading: false, }); return; } } this.props.history.push(makeUrl(region, realm, char)); } render() { return ( <form onSubmit={this.handleSubmit} className="form-inline"> <div className="character-selector"> <select className="form-control" ref={elem => { this.regionInput = elem; }} defaultValue={this.state.currentRegion} onChange={e => this.setState({ currentRegion: e.target.value })} > {Object.keys(REALMS).map(elem => <option key={elem} value={elem}>{elem}</option> )} </select> <SelectSearch options={REALMS[this.state.currentRegion].map(elem => ({ value: elem.name, name: elem.name, }))} className="realm-search" onChange={value => { this.setState({ currentRealm: value.name }); }} placeholder={i18n._(t`Realm`)} /> <input type="text" name="code" ref={elem => { this.charInput = elem; }} className="form-control" autoCorrect="off" autoCapitalize="off" spellCheck="false" placeholder={i18n._(t`Character`)} /> <button type="submit" className={`btn btn-primary analyze animated-button ${this.state.loading ? 'fill-button' : ''}`}> <Trans>Search</Trans> <span className="glyphicon glyphicon-chevron-right" aria-hidden /> </button> </div> </form> ); } } export default withRouter(Search);
src/utils/reactUtils.js
vikrantd/excel-react-redux
import React from 'react'; export function h(...args) { const p = args[1]; if (typeof p === 'string' || typeof p === 'number' || Array.isArray(p) || React.isValidElement(p)) { args.splice(1, 0, null); } return React.createElement(...args); } export function classNames(names) { return Object.keys(names).filter(key => names[key]).join(' '); }
blueocean-material-icons/src/js/components/svg-icons/action/open-with.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionOpenWith = (props) => ( <SvgIcon {...props}> <path d="M10 9h4V6h3l-5-5-5 5h3v3zm-1 1H6V7l-5 5 5 5v-3h3v-4zm14 2l-5-5v3h-3v4h3v3l5-5zm-9 3h-4v3H7l5 5 5-5h-3v-3z"/> </SvgIcon> ); ActionOpenWith.displayName = 'ActionOpenWith'; ActionOpenWith.muiName = 'SvgIcon'; export default ActionOpenWith;
app/components/LoadingIndicator/Circle.js
andresol/homepage
import React from 'react'; import PropTypes from 'prop-types'; import styled, { keyframes } from 'styled-components'; const circleFadeDelay = keyframes` 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } `; const Circle = (props) => { const CirclePrimitive = styled.div` width: 100%; height: 100%; position: absolute; left: 0; top: 0; ${props.rotate && ` -webkit-transform: rotate(${props.rotate}deg); -ms-transform: rotate(${props.rotate}deg); transform: rotate(${props.rotate}deg); `} &:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #999; border-radius: 100%; animation: ${circleFadeDelay} 1.2s infinite ease-in-out both; ${props.delay && ` -webkit-animation-delay: ${props.delay}s; animation-delay: ${props.delay}s; `} } `; return <CirclePrimitive />; }; Circle.propTypes = { delay: PropTypes.number, rotate: PropTypes.number, }; export default Circle;
src/js/components/icons/base/DocumentText.js
odedre/grommet-final
/** * @description DocumentText SVG Icon. * @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon. * @property {string} colorIndex - The color identifier to use for the stroke color. * If not specified, this component will default to muiTheme.palette.textColor. * @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small. * @property {boolean} responsive - Allows you to redefine what the coordinates. * @example * <svg width="24" height="24" ><path d="M6,16 L16,16 L6,16 L6,16 Z M6,12 L18,12 L6,12 L6,12 Z M6,8 L11,8 L6,8 L6,8 Z M14,1 L14,8 L21,8 M3,23 L3,1 L15,1 L21,7 L21,23 L3,23 Z"/></svg> */ // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-document-text`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-text'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M6,16 L16,16 L6,16 L6,16 Z M6,12 L18,12 L6,12 L6,12 Z M6,8 L11,8 L6,8 L6,8 Z M14,1 L14,8 L21,8 M3,23 L3,1 L15,1 L21,7 L21,23 L3,23 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'DocumentText'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
storybook/stories/bar-stack/index.js
JesperLekland/react-native-svg-charts
import React from 'react' import { storiesOf } from '@storybook/react-native' import Standard from './standard' import Horizontal from './horizontal' import WithOnPress from './with-on-press' import Grouped from './grouped' import HorizontalGrouped from './horizontal-grouped' import ShowcaseCard from '../showcase-card' storiesOf('BarStack', module) .addDecorator((getStory) => <ShowcaseCard>{getStory()}</ShowcaseCard>) .add('Standard', () => <Standard />) .add('Horizontal', () => <Horizontal />) .add('With onPress', () => <WithOnPress />) .add('Grouped', () => <Grouped />) .add('Horizontal - grouped', () => <HorizontalGrouped />)
app/javascript/mastodon/features/bookmarked_statuses/index.js
kazh98/social.arnip.org
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { fetchBookmarkedStatuses, expandBookmarkedStatuses } from '../../actions/bookmarks'; import Column from '../ui/components/column'; import ColumnHeader from '../../components/column_header'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import StatusList from '../../components/status_list'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { debounce } from 'lodash'; const messages = defineMessages({ heading: { id: 'column.bookmarks', defaultMessage: 'Bookmarks' }, }); const mapStateToProps = state => ({ statusIds: state.getIn(['status_lists', 'bookmarks', 'items']), isLoading: state.getIn(['status_lists', 'bookmarks', 'isLoading'], true), hasMore: !!state.getIn(['status_lists', 'bookmarks', 'next']), }); export default @connect(mapStateToProps) @injectIntl class Bookmarks extends ImmutablePureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, statusIds: ImmutablePropTypes.list.isRequired, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasMore: PropTypes.bool, isLoading: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchBookmarkedStatuses()); } handlePin = () => { const { columnId, dispatch } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn('BOOKMARKS', {})); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } handleLoadMore = debounce(() => { this.props.dispatch(expandBookmarkedStatuses()); }, 300, { leading: true }) render () { const { intl, shouldUpdateScroll, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props; const pinned = !!columnId; const emptyMessage = <FormattedMessage id='empty_column.bookmarked_statuses' defaultMessage="You don't have any bookmarked toots yet. When you bookmark one, it will show up here." />; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.heading)}> <ColumnHeader icon='bookmark' title={intl.formatMessage(messages.heading)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} showBackButton /> <StatusList trackScroll={!pinned} statusIds={statusIds} scrollKey={`bookmarked_statuses-${columnId}`} hasMore={hasMore} isLoading={isLoading} onLoadMore={this.handleLoadMore} shouldUpdateScroll={shouldUpdateScroll} emptyMessage={emptyMessage} bindToDocument={!multiColumn} /> </Column> ); } }
thinking-in-react/04_identify_where_your_state_should_live/program.js
kwpeters/workshopper-solutions
import React from 'react'; export const ProductCategoryRow = React.createClass({ render() { return ( <tr> <th colSpan={2}>{this.props.category}</th> </tr> ); } }); export const ProductRow = React.createClass({ render() { const product = this.props.product; const style = { color: product.stocked ? null : 'red' }; return ( <tr> <td style={style}>{product.name}</td> <td>{product.price}</td> </tr> ); } }); export const ProductTable = React.createClass({ render() { const { products, filterText, inStockOnly } = this.props; const rows = []; let currentCategory; products.filter((product) => { const stockCond = !inStockOnly || inStockOnly && product.stocked; const nameCond = product.name.toLowerCase().indexOf(filterText) !== -1; return stockCond && nameCond; }).forEach((product) => { if (product.category !== currentCategory) { currentCategory = product.category; rows.push(( <ProductCategoryRow key={currentCategory} category={currentCategory} /> )); } rows.push(( <ProductRow key={product.name} product={product}/> )); }); return ( <table> <thead> <tr> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } }); export const SearchBar = React.createClass({ render() { const {filterText, inStockOnly} = this.props; return ( <form> <input type="search" placeholder="Search..." value={filterText}/> <label> <input type="checkbox" value={inStockOnly} /> Only show products in stock </label> </form> ); } }); export const FilterableProductTable = React.createClass({ getInitialState() { return { filterText: "", inStockOnly: false }; }, render() { const products = this.props.products; const { filterText, inStockOnly } = this.state; return ( <div> <SearchBar filterText={filterText} inStockOnly={inStockOnly} /> <ProductTable products={products} filterText={filterText} inStockOnly={inStockOnly} /> </div> ); } });
src/components/buttons/demos/FabPrimary.js
isogon/material-components
import React from 'react' import { Button, Icon } from '../../../' export default () => ( <Button fab primary> <Icon name="add" /> </Button> )
app/javascript/mastodon/features/compose/components/upload_progress.js
tootcafe/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import Icon from 'mastodon/components/icon'; export default class UploadProgress extends React.PureComponent { static propTypes = { active: PropTypes.bool, progress: PropTypes.number, icon: PropTypes.string.isRequired, message: PropTypes.node.isRequired, }; render () { const { active, progress, icon, message } = this.props; if (!active) { return null; } return ( <div className='upload-progress'> <div className='upload-progress__icon'> <Icon id={icon} /> </div> <div className='upload-progress__message'> {message} <div className='upload-progress__backdrop'> <Motion defaultStyle={{ width: 0 }} style={{ width: spring(progress) }}> {({ width }) => <div className='upload-progress__tracker' style={{ width: `${width}%` }} /> } </Motion> </div> </div> </div> ); } }
client/js/components/Hello.js
maoqifeng/hello-react
import React from 'react' class Hello extends React.Component { render() { return <div className = 'hello'> Helo </div> } } export default Hello
src/components/HomePage.js
oshalygin/react-slingshot
import React from 'react'; import {Link} from 'react-router'; const HomePage = () => { return ( <div> <h1>React Slingshot</h1> <h2>Get Started</h2> <ol> <li>Review the <Link to="fuel-savings">demo app</Link></li> <li>Remove the demo and start coding: npm run remove-demo</li> </ol> </div> ); }; export default HomePage;
src/server.js
mattijsbliek/record-client
import Express from 'express'; import React from 'react'; import ReactDOM from 'react-dom/server'; import config from './config'; import favicon from 'serve-favicon'; import compression from 'compression'; import httpProxy from 'http-proxy'; import path from 'path'; import createStore from './redux/create'; import ApiClient from './helpers/ApiClient'; import Html from './helpers/Html'; import PrettyError from 'pretty-error'; import http from 'http'; import SocketIo from 'socket.io'; import {ReduxRouter} from 'redux-router'; import createHistory from 'history/lib/createMemoryHistory'; import {reduxReactRouter, match} from 'redux-router/server'; import {Provider} from 'react-redux'; import qs from 'query-string'; import getRoutes from './routes'; import getStatusFromRoutes from './helpers/getStatusFromRoutes'; const pretty = new PrettyError(); const app = new Express(); const server = new http.Server(app); const proxy = httpProxy.createProxyServer({ target: 'http://' + config.apiHost + ':' + config.apiPort, ws: true }); app.use(compression()); app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico'))); app.use(Express.static(path.join(__dirname, '..', 'static'))); // Proxy to API server app.use('/api', (req, res) => { proxy.web(req, res); }); // added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527 proxy.on('error', (error, req, res) => { let json; if (error.code !== 'ECONNRESET') { console.error('proxy error', error); } if (!res.headersSent) { res.writeHead(500, {'content-type': 'application/json'}); } json = {error: 'proxy_error', reason: error.message}; res.end(JSON.stringify(json)); }); app.use((req, res) => { if (__DEVELOPMENT__) { // Do not cache webpack stats: the script file would change since // hot module replacement is enabled in the development env webpackIsomorphicTools.refresh(); } const client = new ApiClient(req); const store = createStore(reduxReactRouter, getRoutes, createHistory, client); function hydrateOnClient() { res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>)); } if (__DISABLE_SSR__) { hydrateOnClient(); return; } store.dispatch(match(req.originalUrl, (error, redirectLocation, routerState) => { if (redirectLocation) { res.redirect(redirectLocation.pathname + redirectLocation.search); } else if (error) { console.error('ROUTER ERROR:', pretty.render(error)); res.status(500); hydrateOnClient(); } else if (!routerState) { res.status(500); hydrateOnClient(); } else { // Workaround redux-router query string issue: // https://github.com/rackt/redux-router/issues/106 if (routerState.location.search && !routerState.location.query) { routerState.location.query = qs.parse(routerState.location.search); } store.getState().router.then(() => { const component = ( <Provider store={store} key="provider"> <ReduxRouter/> </Provider> ); const status = getStatusFromRoutes(routerState.routes); if (status) { res.status(status); } res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>)); }).catch((err) => { console.error('DATA FETCHING ERROR:', pretty.render(err)); res.status(500); hydrateOnClient(); }); } })); }); if (config.port) { if (config.isProduction) { const io = new SocketIo(server); io.path('/api/ws'); } server.listen(config.port, (err) => { if (err) { console.error(err); } console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort); console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port); }); } else { console.error('==> ERROR: No PORT environment variable has been specified'); }
pages/api/switch-base.js
cherniavskii/material-ui
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './switch-base.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
src/svg-icons/places/fitness-center.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesFitnessCenter = (props) => ( <SvgIcon {...props}> <path d="M20.57 14.86L22 13.43 20.57 12 17 15.57 8.43 7 12 3.43 10.57 2 9.14 3.43 7.71 2 5.57 4.14 4.14 2.71 2.71 4.14l1.43 1.43L2 7.71l1.43 1.43L2 10.57 3.43 12 7 8.43 15.57 17 12 20.57 13.43 22l1.43-1.43L16.29 22l2.14-2.14 1.43 1.43 1.43-1.43-1.43-1.43L22 16.29z"/> </SvgIcon> ); PlacesFitnessCenter = pure(PlacesFitnessCenter); PlacesFitnessCenter.displayName = 'PlacesFitnessCenter'; PlacesFitnessCenter.muiName = 'SvgIcon'; export default PlacesFitnessCenter;