path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/components/SubtitleHeading/SubtitleHeading.js
scottdj92/t7-chicken-native
import React, { Component } from 'react'; import { View, Text, StyleSheet } from 'react-native'; export default class SubtitleHeading extends Component { constructor() { super(); } render() { return ( <View style={Styles.background}> <Text style={Styles.text}>{this.props.subtitle}</Text> </View> ) } }; const Styles = StyleSheet.create({ background: { backgroundColor: 'rgb(65, 18, 18)', }, text: { color: '#f0aeb1', fontSize: 12, paddingTop: 5, paddingBottom: 5, paddingLeft: 12, fontFamily: 'Exo2-Bold' } });
src/svg-icons/content/font-download.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentFontDownload = (props) => ( <SvgIcon {...props}> <path d="M9.93 13.5h4.14L12 7.98zM20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-4.05 16.5l-1.14-3H9.17l-1.12 3H5.96l5.11-13h1.86l5.11 13h-2.09z"/> </SvgIcon> ); ContentFontDownload = pure(ContentFontDownload); ContentFontDownload.displayName = 'ContentFontDownload'; ContentFontDownload.muiName = 'SvgIcon'; export default ContentFontDownload;
packages/reactor-kitchensink/src/examples/FormFields/Validation/Validation.js
dbuhrman/extjs-reactor
import React from 'react'; import { Container, Panel, FormPanel, TextField, UrlField, EmailField, NumberField, DatePickerField } from '@extjs/ext-react'; Ext.require("Ext.data.validator.*"); export default function ValidationExample() { return ( <Container scrollable platformConfig={{ desktop: { layout: 'center' } }} > <Container padding={10} platformConfig={{ desktop: { maxWidth: 400, } }} > <FormPanel padding={10} shadow defaults={{ errorTarget: 'under' }} margin="0 0 20 0" title="Using Validators" > <div style={styles.hint}>Here we use validators from <code>Ext.data.validator</code> to validate user input.</div> <TextField required label="Required Field" requiredMessage="This field is required." /> <UrlField label="URL" validators={{ type: 'url', message: 'Please enter a valid website url.' }} /> <EmailField label="Email" validators="email" /> <TextField label="Phone Number" inputMask="(999) 999-9999" // field is validated by this automatically /> <DatePickerField label="Date of Birth" placeholder="mm/dd/yyyy" validators="date" /> <TextField label="Salary" placeholder="$xx,xxx" validators={{ type: 'currency-us', message: 'Invalid salary.' }} /> <NumberField label="Rating (1-5)" decimals={0} validators={{ type: 'range', min: 1, max: 5, minOnlyMessage: 'The rating must be at least {0}', maxOnlyMessage: 'The rating must be no more than than {0}', bothMessage: 'Invalid rating, must be between {0} and {1}' }} /> <TextField label="Last Login" placeholder="YYYY/MM/DD hh:mm" validators={{ type: 'datetime', message: 'Invalid date and/or time' }} /> <TextField label="Custom Format Regex: Uppercase letters only" name="uppercase" validators={{ type: 'format', matcher: /^[A-Z]*$/, message: 'Only uppercase letters are allowed.' }} /> <TextField label="Custom Format Function: Capitalized words" validators={{ type: 'method', fn: validateCapilization }} /> </FormPanel> <FormPanel padding={10} shadow defaults={{ errorTarget: 'under' }} title="Assigning Error Messages Directly" > <div style={styles.hint}>Here we assign error messages directly using the <code>errorMessage</code> and <code>error</code> props.</div> <TextField label="Single Error" errorMessage="The value you entered is invalid." /> <TextField label="Multiple Errors" error={[ "Error 1", "Error 2", "Error 3" ]} /> </FormPanel> </Container> </Container> ) } // A method validator function returns the error message when // invalid, true when valid. function validateCapilization(value) { const words = value.split(/\s+/); for (let word of words) { if (word.length && !word.match(/^[A-Z].*$/)) { return 'All words must be capitalized.'; } } return true; } const styles = { hint: { fontSize:'13px', color: '#666' } }
src/Flags/Monaco.js
runjak/css-flags
// @flow import React from 'react'; import LinearFlag from './LinearFlag'; import gradient from '../utils/gradient'; const red = '#CF0821'; const white = '#FFFFFF'; export default function Monaco() { return ( <LinearFlag gradient={`${gradient([red, white])}`} /> ); }
test/test_helper.js
Albinovich/youtubish
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};
client/src/components/Header/components/MenuButton.js
BhaveshSGupta/FreeCodeCamp
import React from 'react'; import PropTypes from 'prop-types'; const MenuButton = props => ( <button aria-expanded={props.displayMenu} className={ 'toggle-button-nav' + (props.displayMenu ? ' reverse-toggle-color' : '') } onClick={props.onClick} ref={props.innerRef} > Menu </button> ); MenuButton.displayName = 'MenuButton'; MenuButton.propTypes = { className: PropTypes.string, displayMenu: PropTypes.bool.isRequired, innerRef: PropTypes.object, onClick: PropTypes.func.isRequired }; export default MenuButton;
geonode/contrib/monitoring/frontend/src/components/cels/table-row/index.js
MapStory/geonode
import React from 'react'; import PropTypes from 'prop-types'; import { TableRow } from 'material-ui/Table'; import styles from './styles'; class MyTableRow extends React.Component { static propTypes = { children: PropTypes.node, } render() { return ( <TableRow>{this.props.children}</TableRow> ); } } export default MyTableRow;
frontend/src/components/sidebar.js
b1naryth1ef/rowboat
import React, { Component } from 'react'; import { Link } from 'react-router-dom' import {globalState} from '../state'; import {STATS_ENABLED} from 'config'; class SidebarLink extends Component { render () { const iconClass = `fa fa-${this.props.icon} fa-fw`; return ( <li> <Link to={this.props.to}> <i className={iconClass}></i> {this.props.text} </Link> </li> ); } } class GuildLinks extends Component { render() { let links = []; if (this.props.active) { links.push( <SidebarLink icon='info' to={'/guilds/' + this.props.guild.id} text='Information' key='info' /> ); links.push( <SidebarLink icon='cog' to={'/guilds/' + this.props.guild.id + '/config'} text='Config' key='config' /> ); links.push( <SidebarLink icon='ban' to={'/guilds/' + this.props.guild.id + '/infractions'} text='Infractions' key='infractions' /> ); if (STATS_ENABLED) { links.push( <SidebarLink icon='bar-chart-o' to={'/guilds/' + this.props.guild.id + '/stats'} text='Stats' key='stats' /> ); } } return ( <li> <Link to={'/guilds/' + this.props.guild.id}> {this.props.guild.name} </Link> <ul className="nav nav-second-level collapse in"> {links} </ul> </li> ); } } class Sidebar extends Component { constructor() { super(); this.state = { guilds: null, currentGuildID: globalState.currentGuild ? globalState.currentGuild.id : null, showAllGuilds: globalState.showAllGuilds, }; globalState.events.on('showAllGuilds.set', (value) => this.setState({showAllGuilds: value})); globalState.getCurrentUser().then((user) => { user.getGuilds().then((guilds) => { this.setState({guilds}); }); }); globalState.events.on('currentGuild.set', (guild) => { this.setState({currentGuildID: guild ? guild.id : null}); }); } render() { let sidebarLinks = []; sidebarLinks.push( <SidebarLink icon='dashboard' to='/' text='Dashboard' key='dashboard' /> ); if (this.state.guilds) { for (let guild of Object.values(this.state.guilds)) { // Only show the active guild for users with a lot of them if ( !this.state.showAllGuilds && Object.keys(this.state.guilds).length > 10 && guild.id != this.state.currentGuildID ) continue; sidebarLinks.push(<GuildLinks guild={guild} active={guild.id == this.state.currentGuildID} key={guild.id} />); } } return (<div className="navbar-default sidebar" role="navigation"> <div className="sidebar-nav navbar-collapse"> <ul className="nav in" id="side-menu"> {sidebarLinks} </ul> </div> </div>); } } export default Sidebar;
src/modules/pages/feeds/js/FeedListWidget.js
lenxeon/react
import React from 'react'; import { Link } from 'react-router'; import store from './feedStore'; import TagBox from './TagBox'; class FeedListWidget extends React.Component { constructor(props) { super(props); this.state={ 'erro':'网络加载失败', 'list':[], 'loaded':false, } // console.log(this.state); } state:{ } componentWillReceiveProps() { console.log("============componentWillReceiveProps===============") this.setState({ loaded: false, }) } render () { // console.log("============FeedListWidgetrender===============") // console.log(this.state.loaded); // console.log(this.state); // console.log("=============FeedListWidget==============") if (!this.state.loaded) { let { cat, page, size } = this.props; store.list(cat, page, size, (o) => { this.setState({ loaded: true, list: o.list, }); this.props.loaded = true; }) } function createMarkup(html) { return { __html: html }; }; function createMarkup(o) { return {__html: o}; }; let feeds = (<div/>); if(this.state.list){ let i = 0; feeds = this.state.list.map((feed)=>{ i++; return ( <div className='card shadow feed-item mb-15'> <div className="feed-item-body"> <div className='' dangerouslySetInnerHTML={{__html: feed.mblog.text}} /> </div> <div className="hander-box clear"> <span className="lft ml-15">9月18日 17:41</span> <span className="rgt"> <i className="fa fa-commenting mr-15"></i> <i className="fa fa-tag mr-15"></i> <i className="fa fa-star-o mr-15"></i> </span> </div> <div className="buttom-box"> <TagBox/> </div> </div> ) }) } return ( <div ref="wrap" className="inner-wrap"> { this.state.loaded ? ( {feeds} ):( <div className="card shadow loading"> <div className="spinner"> <div className="bounce1"></div> <div className="bounce2"></div> <div className="bounce3"></div> </div> </div> ) } </div> ); } } export default FeedListWidget;
src/js/methodReact.js
majofeechiou/drawing-board
'use strict'; /* *** 這部份用 ReactJs + redux 做 *** */ import MethodOption from './MethodOption'; import MethodControl from './MethodControl'; import React from 'react'; import ReactDOM from 'react-dom'; import Settings from './Settings'; import MethodSettings from './MethodSettings'; import GloablData from './GloablData'; import GloablTools from './GloablTools'; export default class MethodReact extends React.Component { constructor( props ){ super( props ); this.arrangeStates( props ); this.handleChange = this.handleChange.bind(this); this.closeMethod = this.closeMethod.bind(this); this.default(); // setTimeout(function(){ // props.methodStore.dispatch({type:'METHOD_LOOKS_LUXURY_B'}); // setTimeout(function(){ // props.methodStore.dispatch({type:'METHOD_LOOKS_LUXURY_A'}); // },2000); // },2000); } default(){ let _scope = this ; GloablTools.Emitter().on('method.setting.opening', function(){ let _str_from = GloablData.getFrom(); _scope.arrangeStates( _scope.getDefaultMethod() ); }); } // defaultMethod = {}; defaultMethod = {...MethodSettings.getAllMethod()[0]}; getDefaultMethod(){ return this.defaultMethod; } getOutputResult(){ return this.state.outputResult; } arrangeStates(json_next){ let _json = {}; _json.outputResult = json_next.outputResult || this.getDefaultMethod(); if( this.state ){ this.setState( _json ); }else{ this.state = _json; } } closeMethod(){ GloablTools.Emitter().emit('method.setting.close.asked'); } handleChange({...json_return}){ let _json = {...this.state}; _json.outputResult = json_return.result; this.setState( _json ); } render( nextProps, nextState ){ nextProps = nextProps || {} ; nextState = nextState || {} ; let _json_result = nextState.outputResult || this.getOutputResult() ; let _json_method = nextProps.methodStore || this.props.methodStore ; let _str_cn = 'pkg-method-content'; let _str_cn_options = 'pkg-method-content-options pkg-method-wrap pkg-pagestyle-mainbtback'; let _str_cn_close = 'pkg-method-content-close ui-close'; let _str_cn_control = 'pkg-method-content-control pkg-method-wrap'; return ( <div className={_str_cn}> <MethodOption className={_str_cn_options} handleChange={ this.handleChange } outputResult={ _json_result } methodStore={ this.props.methodStore } /> <span className={_str_cn_close} onClick={ this.closeMethod }></span> <MethodControl className={_str_cn_control} outputResult={ _json_result } methodStore={ this.props.methodStore } /> </div> ); } }; MethodReact.propTypes = { methodStore: React.PropTypes.object.isRequired }, MethodReact.defaultProps = { methodStore: {} };
src/containers/search_bar.js
RolandoArroyos/weather
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from '../actions/index'; // the onChange function in the <input> tag in the render method is a //call back function which needs to be bound. We accomplish this by binding // the onChange event in our constructor using the "bind" method. //the form element needs the onFormsubmit event handler to prevent the form //from being submitted everytime a user hits "enter" or clicks the submit //button. We use the onformSubmit function to prevent this behavior by //calling the preventDefault method. class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(event) { this.setState({ term: event.target.value }); } onFormSubmit(event){ event.preventDefault(); //we need to go and fetch weather data this.props.fetchWeather(this.state.term); this.setState({ term: '' }); } render() { return ( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Get a five-day forecast in your favorite cities" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } //by passing null as the first parameter we are simply stating we don't //care about state in this container export default connect(null, mapDispatchToProps)(SearchBar);
webclient/src/edit/EditTimeline.js
jadiego/bloom
import React, { Component } from 'react'; import { Icon, Form, Input, Segment, Label, Button } from 'semantic-ui-react' import PropTypes from 'prop-types'; import TimelineItem from '../TimelineItem' class EditTimelineItem extends Component { constructor(props) { super(props); this.state = { body: "" }; } handleItemMouseEnter = () => { //console.log(this) } handleEditBody = (event) => this.setState({ body: event.target.value }) render() { return ( <li className="timeline-item" onMouseEnter={this.handleItemMouseEnter}> <div className="timeline-marker"></div> <div className="timeline-content"> <Segment> <Label attached='top'></Label> <Form size='small'> <Form.Input control='Input' label='Image' type='file' icon='image' accept='image/*'/> <Form.TextArea value={this.state.body} onChange={event => this.handleEditBody(event)} placeholder='Tell us your story' /> <Button size='tiny' className='timelineitem-submit-button'>Submit</Button> </Form> </Segment> </div> </li> ) } } EditTimelineItem.propTypes = { id: PropTypes.number.isRequired } class EditTimeline extends Component { render() { return ( <ul className='timeline'> {this.props.timelineitems.map(timelineitem => <EditTimelineItem {...timelineitem} key={timelineitem.id} /> )} <li className='timeline-item'> <div className="timeline-marker"> </div> </li> </ul> ) } } EditTimeline.propTypes = { timelineitems: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.number.isRequired, }).isRequired).isRequired } export default EditTimeline
form/RadioField.js
ExtPoint/yii2-frontend
import React from 'react'; import PropTypes from 'prop-types'; import {connect} from 'react-redux'; import {change} from 'redux-form'; import {types, view} from 'components'; class RadioField extends React.Component { static propTypes = { metaItem: PropTypes.object.isRequired, input: PropTypes.shape({ name: PropTypes.string, value: PropTypes.any, onChange: PropTypes.func, }), enumClassName: PropTypes.oneOfType([ PropTypes.string, PropTypes.func, ]), }; componentWillMount() { if (!this.props.input.value) { const keys = Object.keys(this.getItems()); if (keys.length > 0) { this.props.dispatch(change(this.props.formId, this.props.input.name, keys[0])); } } } getItems() { return types.getEnumLabels(this.props.enumClassName || this.props.metaItem.enumClassName); } render() { const items = this.getItems(); const {input, ...props} = this.props; const RadioFieldView = this.props.view || view.getFormView('RadioFieldView'); return ( <RadioFieldView {...props} inputProps={{ type: 'radio', name: input.name, }} items={Object.keys(items).map(key => ({ id: key, isChecked: input.value === key, label: items[key], onSelect: () => input.onChange(key), }))} /> ); } } export default connect()(RadioField);
src/js/components/character-list/character-dashboard.js
trwalker/marvel-react
import React from 'react'; import LoadingProgress from './../shared/loading-progress'; import CharacterListItem from './character-list-item'; import ReloadError from './../shared/reload-error'; class CharacterDashboard extends React.Component { constructor(props) { super(props); this.characterListStore_ = props.characterListStore ? props.characterListStore : require('../../stores/character-list-store'); this.characterListLoadAction_ = props.characterListLoadAction ? props.characterListLoadAction : require('../../actions/character-list-load-action'); this.state = props.initialState ? props.initialState : { characters: null }; } componentWillMount() { this.characterListStore_.addChangeListener(() => { this.onStateChange(); }); this.characterListLoadAction_.loadCharacters(); } componentWillUnmount() { this.characterListStore_.removeChangeListener(() => { this.onStateChange(); }); } render() { return renderDashboard_(this); } reloadCharacters() { this.characterListLoadAction_.loadCharacters(); } onStateChange() { var characters = this.characterListStore_.getCharacters(); this.setState({ characters: characters }); } } function renderDashboard_(instance) { var characters = instance.state.characters; if(!characters) { return renderLoadingView_(); } else if(characters.length > 0) { return renderCharacters_(characters); } else { return renderErrorView_(instance); } } function renderLoadingView_() { return ( <div id="dash-loading" className="row"> <LoadingProgress title={'Calling All Super Heroes...'} initialProgressValue={0} getCurrentProgress={function(progress) { return ++progress; }} /> </div> ); } function renderCharacters_(characters) { var characterItems = characters.map(function(character) { return <CharacterListItem key={character.id} character={character} /> }); return ( <div id="dash-characters" className="row"> {characterItems} </div> ); } function renderErrorView_(instance) { return ( <div id="dash-reload" className="row"> <ReloadError alertTitle={'Where are the Super Heroes?'} reloadButtonText={'Assemble Heroes'} reloadButtonOnClick={ function() { instance.reloadCharacters(); } } /> </div> ); } export default CharacterDashboard;
renderer/components/preferences/item/switch.js
wulkano/kap
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import {SpinnerIcon} from '../../../vectors'; import {handleKeyboardActivation} from '../../../utils/inputs'; class Switch extends React.Component { render() { const {checked, onClick, disabled, loading, onTransitionEnd, tabIndex} = this.props; const className = classNames('switch', {checked, disabled, loading}); return ( <div tabIndex={disabled ? -1 : tabIndex} className={className} onClick={disabled ? undefined : onClick} onKeyDown={disabled ? undefined : handleKeyboardActivation(onClick)} > <div className="toggle" onTransitionEnd={onTransitionEnd}> {loading && <SpinnerIcon/>} </div> <style jsx>{` .switch { display: inline-block; width: 4.8rem; height: 2.4rem; border: 1px solid var(--input-border-color); border-radius: 2.625em; position: relative; background-color: var(--input-background-color); transition: 0.2s ease-in-out; box-sizing: border-box; outline: none; box-shadow: var(--switch-box-shadow); } .switch:not(.disabled):focus { border-color: var(--kap); } .toggle { content: ''; display: block; width: 1.6rem; height: 1.6rem; border-radius: 50%; margin-top: 0.3rem; margin-left: 0.3rem; position: absolute; top: 0; left: 0; background: gray; transition: left 0.12s ease-in-out; } .checked .toggle { left: calc(100% - 2.2rem); background: var(--kap); } .disabled { cursor: not-allowed; } .disabled .toggle { margin-top: 0.2rem; border: 1px solid var(--switch-disabled-color); background-color: transparent; } .loading .toggle { border: none; background: transparent; background-size: 100%; animation: spin 3s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 50% { transform: rotate(720deg); } 100% { transform: rotate(1080deg); } } `}</style> </div> ); } } Switch.propTypes = { checked: PropTypes.bool, disabled: PropTypes.bool, loading: PropTypes.bool, onClick: PropTypes.func.isRequired, onTransitionEnd: PropTypes.func, tabIndex: PropTypes.number.isRequired }; export default Switch;
src/ContentBlocks/BlockHeading/BlockHeading.js
grommet/grommet-cms-content-blocks
import PropTypes from 'prop-types'; import React from 'react'; import Headline from 'grommet/components/Headline'; import unescape from 'unescape'; export default function BlockHeading({ content, strong, size }) { const strongProp = strong ? strong === 'True' : false; const sizeProp = size ? size.toLowerCase() : 'medium'; const unescapedContent = unescape(content || ''); const headlineProps = { size: sizeProp, strong: strongProp, }; return ( <Headline {...headlineProps}> {unescapedContent} </Headline> ); } BlockHeading.propTypes = { content: PropTypes.string, strong: PropTypes.bool, size: PropTypes.string, };
src/routes/login/index.js
peeyush1234/react-nodejs-skeleton
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Login from './Login'; const title = 'Log In'; export default { path: '/login', action() { return { title, component: <Layout><Login title={title} /></Layout>, }; }, };
demo/react/js/index.js
tmdautov/tmdautov.github.io
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
src/client/app/components/projectSummary.js
JuMBoSLICE/JuMBo
import React, { Component } from 'react'; class ProjectSummary extends Component { constructor(props){ super(props); } render(){ return ( <div id="project-summary"> <h3>Project Summary</h3> <p>{this.props.summary}</p> </div> ) } } export default ProjectSummary;
src/routes.js
polinazolotukhina/redux-movieDB
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/App'; import HomePage from './components/HomePage'; import Popular from './containers/Popular/Popular'; import Drama from './containers/Drama/Drama'; import Kids from './containers/Kids/Kids'; import Cinema from './containers/Cinema/Cinema'; import Search from './containers/Search/Search'; import Favourites from './containers/Favourites/Favourites'; import NotFoundPage from './components/NotFoundPage'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage}/> <Route path="popular" component={Popular}/> <Route path="drama" component={Drama}/> <Route path="in_cinema_now" component={Cinema}/> <Route path="kids" component={Kids}/> <Route path="search" component={Search}/> <Route path="favourites" component={Favourites}/> <Route path="*" component={NotFoundPage}/> </Route> );
src/svg-icons/hardware/cast-connected.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareCastConnected = (props) => ( <SvgIcon {...props}> <path d="M1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm18-7H5v1.63c3.96 1.28 7.09 4.41 8.37 8.37H19V7zM1 10v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm20-7H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); HardwareCastConnected = pure(HardwareCastConnected); HardwareCastConnected.displayName = 'HardwareCastConnected'; HardwareCastConnected.muiName = 'SvgIcon'; export default HardwareCastConnected;
app/javascript/mastodon/features/compose/components/compose_form.js
rainyday/mastodon
import React from 'react'; import CharacterCounter from './character_counter'; import Button from '../../../components/button'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ReplyIndicatorContainer from '../containers/reply_indicator_container'; import AutosuggestTextarea from '../../../components/autosuggest_textarea'; import AutosuggestInput from '../../../components/autosuggest_input'; import PollButtonContainer from '../containers/poll_button_container'; import UploadButtonContainer from '../containers/upload_button_container'; import { defineMessages, injectIntl } from 'react-intl'; import SpoilerButtonContainer from '../containers/spoiler_button_container'; import PrivacyDropdownContainer from '../containers/privacy_dropdown_container'; import EmojiPickerDropdown from '../containers/emoji_picker_dropdown_container'; import PollFormContainer from '../containers/poll_form_container'; import UploadFormContainer from '../containers/upload_form_container'; import WarningContainer from '../containers/warning_container'; import { isMobile } from '../../../is_mobile'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { length } from 'stringz'; import { countableText } from '../util/counter'; import Icon from 'mastodon/components/icon'; const allowedAroundShortCode = '><\u0085\u0020\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\u0009\u000a\u000b\u000c\u000d'; const messages = defineMessages({ placeholder: { id: 'compose_form.placeholder', defaultMessage: 'What is on your mind?' }, spoiler_placeholder: { id: 'compose_form.spoiler_placeholder', defaultMessage: 'Write your warning here' }, publish: { id: 'compose_form.publish', defaultMessage: 'Toot' }, publishLoud: { id: 'compose_form.publish_loud', defaultMessage: '{publish}!' }, }); export default @injectIntl class ComposeForm extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { intl: PropTypes.object.isRequired, text: PropTypes.string.isRequired, suggestions: ImmutablePropTypes.list, spoiler: PropTypes.bool, privacy: PropTypes.string, spoilerText: PropTypes.string, focusDate: PropTypes.instanceOf(Date), caretPosition: PropTypes.number, preselectDate: PropTypes.instanceOf(Date), isSubmitting: PropTypes.bool, isChangingUpload: PropTypes.bool, isUploading: PropTypes.bool, onChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, onClearSuggestions: PropTypes.func.isRequired, onFetchSuggestions: PropTypes.func.isRequired, onSuggestionSelected: PropTypes.func.isRequired, onChangeSpoilerText: PropTypes.func.isRequired, onPaste: PropTypes.func.isRequired, onPickEmoji: PropTypes.func.isRequired, showSearch: PropTypes.bool, anyMedia: PropTypes.bool, singleColumn: PropTypes.bool, }; static defaultProps = { showSearch: false, }; handleChange = (e) => { this.props.onChange(e.target.value); } handleKeyDown = (e) => { if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { this.handleSubmit(); } } handleSubmit = () => { if (this.props.text !== this.autosuggestTextarea.textarea.value) { // Something changed the text inside the textarea (e.g. browser extensions like Grammarly) // Update the state to match the current text this.props.onChange(this.autosuggestTextarea.textarea.value); } // Submit disabled: const { isSubmitting, isChangingUpload, isUploading, anyMedia } = this.props; const fulltext = [this.props.spoilerText, countableText(this.props.text)].join(''); if (isSubmitting || isUploading || isChangingUpload || length(fulltext) > 4096 || (fulltext.length !== 0 && fulltext.trim().length === 0 && !anyMedia)) { return; } this.props.onSubmit(this.context.router ? this.context.router.history : null); } onSuggestionsClearRequested = () => { this.props.onClearSuggestions(); } onSuggestionsFetchRequested = (token) => { this.props.onFetchSuggestions(token); } onSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['text']); } onSpoilerSuggestionSelected = (tokenStart, token, value) => { this.props.onSuggestionSelected(tokenStart, token, value, ['spoiler_text']); } handleChangeSpoilerText = (e) => { this.props.onChangeSpoilerText(e.target.value); } handleFocus = () => { if (this.composeForm && !this.props.singleColumn) { const { left, right } = this.composeForm.getBoundingClientRect(); if (left < 0 || right > (window.innerWidth || document.documentElement.clientWidth)) { this.composeForm.scrollIntoView(); } } } componentDidUpdate (prevProps) { // This statement does several things: // - If we're beginning a reply, and, // - Replying to zero or one users, places the cursor at the end of the textbox. // - Replying to more than one user, selects any usernames past the first; // this provides a convenient shortcut to drop everyone else from the conversation. if (this.props.focusDate !== prevProps.focusDate) { let selectionEnd, selectionStart; if (this.props.preselectDate !== prevProps.preselectDate) { selectionEnd = this.props.text.length; selectionStart = this.props.text.search(/\s/) + 1; } else if (typeof this.props.caretPosition === 'number') { selectionStart = this.props.caretPosition; selectionEnd = this.props.caretPosition; } else { selectionEnd = this.props.text.length; selectionStart = selectionEnd; } this.autosuggestTextarea.textarea.setSelectionRange(selectionStart, selectionEnd); this.autosuggestTextarea.textarea.focus(); } else if(prevProps.isSubmitting && !this.props.isSubmitting) { this.autosuggestTextarea.textarea.focus(); } else if (this.props.spoiler !== prevProps.spoiler) { if (this.props.spoiler) { this.spoilerText.input.focus(); } else { this.autosuggestTextarea.textarea.focus(); } } } setAutosuggestTextarea = (c) => { this.autosuggestTextarea = c; } setSpoilerText = (c) => { this.spoilerText = c; } setRef = c => { this.composeForm = c; }; handleEmojiPick = (data) => { const { text } = this.props; const position = this.autosuggestTextarea.textarea.selectionStart; const needsSpace = data.custom && position > 0 && !allowedAroundShortCode.includes(text[position - 1]); this.props.onPickEmoji(position, data, needsSpace); } render () { const { intl, onPaste, showSearch, anyMedia } = this.props; const disabled = this.props.isSubmitting; const text = [this.props.spoilerText, countableText(this.props.text)].join(''); const disabledButton = disabled || this.props.isUploading || this.props.isChangingUpload || length(text) > 4096 || (text.length !== 0 && text.trim().length === 0 && !anyMedia); let publishText = ''; if (this.props.privacy === 'private' || this.props.privacy === 'direct') { publishText = <span className='compose-form__publish-private'><Icon id='lock' /> {intl.formatMessage(messages.publish)}</span>; } else { publishText = this.props.privacy !== 'unlisted' ? intl.formatMessage(messages.publishLoud, { publish: intl.formatMessage(messages.publish) }) : intl.formatMessage(messages.publish); } return ( <div className='compose-form'> <WarningContainer /> <ReplyIndicatorContainer /> <div className={`spoiler-input ${this.props.spoiler ? 'spoiler-input--visible' : ''}`} ref={this.setRef}> <AutosuggestInput placeholder={intl.formatMessage(messages.spoiler_placeholder)} value={this.props.spoilerText} onChange={this.handleChangeSpoilerText} onKeyDown={this.handleKeyDown} disabled={!this.props.spoiler} ref={this.setSpoilerText} suggestions={this.props.suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSpoilerSuggestionSelected} searchTokens={[':']} id='cw-spoiler-input' className='spoiler-input__input' /> </div> <AutosuggestTextarea ref={this.setAutosuggestTextarea} placeholder={intl.formatMessage(messages.placeholder)} disabled={disabled} value={this.props.text} onChange={this.handleChange} suggestions={this.props.suggestions} onFocus={this.handleFocus} onKeyDown={this.handleKeyDown} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} onSuggestionSelected={this.onSuggestionSelected} onPaste={onPaste} autoFocus={!showSearch && !isMobile(window.innerWidth)} > <EmojiPickerDropdown onPickEmoji={this.handleEmojiPick} /> <div className='compose-form__modifiers'> <UploadFormContainer /> <PollFormContainer /> </div> </AutosuggestTextarea> <div className='compose-form__buttons-wrapper'> <div className='compose-form__buttons'> <UploadButtonContainer /> <PollButtonContainer /> <PrivacyDropdownContainer /> <SpoilerButtonContainer /> </div> <div className='character-counter__wrapper'><CharacterCounter max={4096} text={text} /></div> </div> <div className='compose-form__publish'> <div className='compose-form__publish-button-wrapper'><Button text={publishText} onClick={this.handleSubmit} disabled={disabledButton} block /></div> </div> </div> ); } }
Quiz/React/quiz/src/game.js
ChrL73/Diaphnea
/* -------------------------------------------------------------------- * * Copyright (C) 2018 * * This file is part of the Diaphnea project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * -------------------------------------------------------------------- */ import React from 'react'; import { Button, Modal } from 'react-bootstrap'; import waitGif from './wait.gif' import { Map } from './map.js'; export class Game extends React.Component { constructor(props) { super(props); this.stateReset = { showModal: false, timeWaitDisplay: 'none', questionWaitVisible: {}, stopGameWaitDisplay: 'none', texts: {}, finalTime: undefined }; this.state = this.stateReset; } render() { const ok = Boolean(this.state.questions); let questions; if (ok) { questions = this.state.questions.map((question, iQuestion) => { const choices = question.choices.map((choice, iChoice) => { const renderInput = () => { if (question.isMultiple) { return (<input id={'input' + iQuestion + '_' + iChoice} type="checkbox" checked={choice.checked} disabled={question.disabled} style={{marginLeft: '12px'}} onChange={(e) => this.handleCheckBoxChange(e.target)}/>); } else { return (<input id={'input' + iQuestion + '_' + iChoice} type="radio" name={'radio' + iQuestion} value={'_' + iChoice} checked={question.selection === '_' + iChoice} disabled={question.disabled} style={{marginLeft: '12px'}} onChange={(e) => this.handleRadioChange(e.target)}/>); } } return ( <div key={'input' + iQuestion + '_' + iChoice} > {renderInput()} <span> </span> <span className={choice.classStr}>{choice.text}</span> <span> </span> <span>{(question.disabled && choice.comment) ? (' (' + choice.comment + ')') : ''}</span><br/> </div>); }); return ( <div className="question panel panel-info" key={'question' + iQuestion} style={{display: iQuestion === this.state.displayedQuestion ? 'block' : 'none'}}> <div className="panel-heading"> {this.state.texts.question} <span> </span> {iQuestion + 1}/{this.state.questions.length} <img src={waitGif} className="waitImg" alt="Waiting for server..." style={{marginTop: '-6px', marginBottom: '-6px', display: (this.state.questionWaitVisible[iQuestion] ? 'inline' : 'none')}}/> </div> <div className="panel-body"> <p>{question.question}</p> {choices} </div> </div>); }); } return ( <div style={{display: (this.state.page === 'game' ? 'block' : 'none')}} className="game"> <div className="container-fluid"> <header className="row bg-success" id="gameHeader" style={{paddingLeft: '30px', borderBottom: '1px solid #bbd8a2'}}> <span className="gameHeader"> {this.state.texts.questionnaire}:&nbsp; <strong>{this.state.questionnaireName}</strong> </span> <span className="gameHeader"> {this.state.texts.level}:&nbsp; <strong>{this.state.levelName}</strong> </span> {this.state.texts.score}:&nbsp; <span className="gameHeader"> {this.state.rightAnswerCount}/{this.state.answerCount} </span> {this.state.texts.time}:&nbsp; {this.state.finalTime ? this.state.finalTime : Math.floor(0.001 * this.state.time)}s <img src={waitGif} alt="Waiting for server..." className="waitImg" style={{display: this.state.timeWaitDisplay}}/> </header> <Modal show={this.state.showModal} onHide={() => this.setState({ showModal: false })}> <Modal.Body>{this.state.texts.areYouSureStopGame}</Modal.Body> <Modal.Footer> <div className="row text-center"> <Button style={{marginRight: '4px'}} className="btn btn-primary input-sm" onClick={() => { this.setState({ showModal: false }); this.stopGame(); }}>{this.state.texts.yes}</Button> <Button style={{marginLeft: '4px'}} className="btn btn-warning input-sm" onClick={() => this.setState({ showModal: false })}>{this.state.texts.no}</Button> </div> </Modal.Footer> </Modal> <div className="row"> <div className="col-lg-3 col-md-4 col-sm-5"> {questions} <div style={{marginTop: '20px'}}> <button className="btn btn-primary input-sm" disabled={this.state.displayedQuestion === 0} onClick={(e) => this.handlePreviousBtnClick(e)}> {this.state.texts.previous} </button> <span> </span> <Button className="btn btn-success input-sm" onClick={(e) => this.handleSubmitBtnClick(e)} disabled={ok ? this.state.questionStates[this.state.displayedQuestion].answered : true}> {this.state.texts.submit} </Button> <span> </span> <Button className="btn btn-primary input-sm" onClick={(e) => this.handleNextBtnClick(e)} disabled={ok ? this.state.displayedQuestion === this.state.questions.length - 1 || !this.state.questionStates[this.state.displayedQuestion].answered : true}> {this.state.texts.next} </Button> </div> <div style={{marginTop: '20px', marginBottom: '20px'}}> <Button className="btn btn-warning input-sm" onClick={(e) => this.handleStopBtnClick(e)}> {ok && this.state.questionStates[this.state.questions.length - 1].answered ? this.state.texts.finish : this.state.texts.stop} </Button> <img src={waitGif} className="waitImg" alt="Waiting for server..." style={{display: this.state.stopGameWaitDisplay}}/> </div> </div> <div className="col-lg-9 col-md-8 col-sm-7" id="mapColumn"> <Map gameState={this.state} ref={(x) => { this.map = x; }}/> </div> </div> </div> </div>); } // 1- User action handlers handleStopBtnClick(e) { e.preventDefault(); if (!this.state.questionStates[this.state.questions.length - 1].answered) this.setState({ showModal: true }); else this.stopGame(); } stopGame() { this.setState({ stopGameWaitDisplay: 'inline' }); this.props.emit('stopGame', {}); } handleCheckBoxChange(target) { const x = target.id.match(/[0-9]+/g); const iQuestion = x[0]; const iChoice = x[1]; let questions = this.state.questions; questions[iQuestion].choices[iChoice].checked = target.checked; this.setState({ questions: questions }); } handleRadioChange(target) { if (target.checked) { const x = target.id.match(/[0-9]+/g); const iQuestion = x[0]; const iChoice = x[1]; let questions = this.state.questions; questions[iQuestion].selection = '_' + iChoice; this.setState({ questions: questions }); } } handlePreviousBtnClick(e) { e.preventDefault(); const oldDisplayedQuestion = this.state.displayedQuestion; if (oldDisplayedQuestion > 0) { const newDisplayedQuestion = oldDisplayedQuestion - 1; this.setState({ displayedQuestion: newDisplayedQuestion }); this.props.emit('changeQuestion', { quizId: this.state.quizId, displayedQuestion: newDisplayedQuestion }); this.map.update(newDisplayedQuestion, oldDisplayedQuestion); } } handleNextBtnClick(e) { e.preventDefault(); const oldDisplayedQuestion = this.state.displayedQuestion; if (oldDisplayedQuestion < this.state.questions.length - 1) { const newDisplayedQuestion = oldDisplayedQuestion + 1; this.setState({ displayedQuestion: newDisplayedQuestion }); this.props.emit('changeQuestion', { quizId: this.state.quizId, displayedQuestion: newDisplayedQuestion }); this.map.update(newDisplayedQuestion, oldDisplayedQuestion); } } handleSubmitBtnClick(e) { e.preventDefault(); const displayedQuestion = this.state.displayedQuestion; let questionStates = this.state.questionStates; questionStates[displayedQuestion].answered = true; let questions = this.state.questions; questions[displayedQuestion].disabled = true; let questionWaitVisible = this.state.questionWaitVisible; questionWaitVisible[displayedQuestion] = true; this.setState({ questionStates: questionStates, questions: questions, questionWaitVisible: questionWaitVisible }); let data = { quizId: this.state.quizId, question: displayedQuestion, checks: [] }; const question = questions[displayedQuestion]; question.choices.forEach((choice, iChoice) => { if (question.isMultiple) data.checks.push(choice.checked); else data.checks.push(question.selection === '_' + iChoice); }); this.props.emit('submit', data); } windowResize() { const w = document.getElementById('mapColumn').offsetWidth; if (w === 0) { setTimeout(() => this.windowResize(), 5); } else { document.getElementById('mapColumn').style.height = (window.innerHeight - 72).toString() + 'px'; this.setState( { mapWidth: w - 30, mapHeight: window.innerHeight - 72 }, () => this.map.redraw()); } } // 2- Server message handlers handleDisplayPage(data) { const date0 = Date.now(); let state = {}; Object.getOwnPropertyNames(this.stateReset).forEach((property) => { state[property] = this.stateReset[property]; }); state.questionWaitVisible = {}; if (data.page === 'game') { data.questions.forEach((question, iQuestion) => { question.disabled = data.questionStates[iQuestion].answered; if (question.isMultiple) question.selection = '_0'; question.choices.forEach((choice, iChoice) => { let checked = Boolean(data.questionStates[iQuestion].choiceStates[iChoice] & 1); if (question.isMultiple) choice.checked = checked; else if (checked) question.selection = '_' + iChoice; let rightChoice = Boolean(data.questionStates[iQuestion].choiceStates[iChoice] & 2); let classStr; if (question.disabled && rightChoice) classStr = 'boldChoice'; if (question.isMultiple) { if (question.disabled) { if (checked === rightChoice) classStr = (classStr ? classStr + ' greenChoice' : 'greenChoice'); else classStr = (classStr ? classStr + ' redChoice' : 'redChoice'); } } else { if (question.disabled && checked) { if (rightChoice) classStr = (classStr ? classStr + ' greenChoice' : 'greenChoice'); else classStr = (classStr ? classStr + ' redChoice' : 'redChoice'); } } choice.classStr = classStr; }); }); Object.getOwnPropertyNames(data).forEach((property) => { state[property] = data[property]; }); this.windowResize(); window.onresize = () => this.windowResize(); } else { state.page = data.page; } this.setState(state, () => { this.initTime(data.time, date0); if (data.page === 'game') this.map.init(); }); } initTime(t0, date0) { this.setState({ timeWaitDisplay: 'none' }); clearInterval(this.timeout); if (!this.state.finalTime && this.state.page === 'game') { let lastDisplayedTime; const updateTime = () => { let t = (Date.now() - date0) + t0; let displayedTime = Math.floor(0.001 * t); if (lastDisplayedTime && (displayedTime < lastDisplayedTime || displayedTime > lastDisplayedTime + 2)) { this.props.emit('timeRequest'); clearInterval(this.timeout); this.setState({ timeWaitDisplay: 'inline' }); } else { this.setState({ time: t }); lastDisplayedTime = displayedTime; if (!this.state.finalTime && this.state.page === 'game') { this.timeout = setTimeout(updateTime, 1000 * (1 + displayedTime) - t); } } } this.timeout = setTimeout(updateTime, 1000 * (1 + Math.floor(0.001 * t0)) - t0); } } handleUpdateQuestions(data) { if (data.quizId !== this.state.quizId) { window.location.replace('/'); } else { let questionWaitVisible = this.state.questionWaitVisible; let questionStates = this.state.questionStates; let questions = this.state.questions; data.questionStates.forEach((state) => { var i = state.index; let question = questions[i]; questionWaitVisible[i] = false; questionStates[i].answered = true; question.disabled = true; state.choiceStates.forEach((choiceState, j) => { let choice = question.choices[j]; const checked = Boolean(choiceState.state & 1); if (question.isMultiple) choice.checked = checked; else if (checked) question.selection = '_' + j; const isRight = Boolean(choiceState.state & 2); let classStr; if (isRight) classStr = 'boldChoice'; if (question.isMultiple) { if (checked === isRight) classStr = (classStr ? classStr + ' greenChoice' : 'greenChoice'); else classStr = (classStr ? classStr + ' redChoice' : 'redChoice'); } else if (checked) { if (isRight) classStr = (classStr ? classStr + ' greenChoice' : 'greenChoice'); else classStr = (classStr ? classStr + ' redChoice' : 'redChoice'); } choice.classStr = classStr; if (choiceState.comment) choice.comment = choiceState.comment; }); }); let state = { rightAnswerCount: data.rightAnswerCount, answerCount: data.answerCount, questionWaitVisible: questionWaitVisible, questionStates: questionStates, questions: questions, mapInfo: data.mapInfo }; if (data.finalTime || this.state.page !== 'game') { clearInterval(this.timeout); state.finalTime = data.finalTime; } this.setState(state, () => this.map.update(this.state.displayedQuestion)); } } }
src/components/Template/Navigation.js
karajrish/karajrish.github.io
import React from 'react'; import { Link } from 'react-router-dom'; import Hamburger from './Hamburger'; import routes from '../../data/routes'; // Websites Navbar, displays routes defined in 'src/data/routes' const Navigation = () => ( <header id="header"> <h1 className="index-link"> {routes.filter((l) => l.index).map((l) => ( <Link key={l.label} to={l.path}>{l.label}</Link> ))} </h1> <nav className="links"> <ul> {routes.filter((l) => !l.index).map((l) => ( <li key={l.label}> <Link to={l.path}>{l.label}</Link> </li> ))} </ul> </nav> <Hamburger /> </header> ); export default Navigation;
src/components/chatrooms/chatroomsList/ChatroomLi.js
AleksandrRogachev94/chat-vote-go-frontend
import React from 'react' import PropTypes from 'prop-types' import { Link } from 'react-router' const ChatroomLi = ({ title, id }) => { const handleClick = () => { document.body.scrollTop = document.body.scrollHeight } return ( <li> <Link to={`/chatrooms/${id}`} onClick={handleClick} activeClassName='active-item'> {title} </Link> </li> ) } ChatroomLi.propTypes = { title: PropTypes.string.isRequired, id: PropTypes.number.isRequired } export default ChatroomLi
src/components/Common/Categorybar.js
MattMcFarland/tw-client
import React, { Component } from 'react'; import getCategory from '../../utils/getCategory'; let pathCategory = getCategory(); let categories = [ { id: 'apps', label: 'Apps' }, { id: 'gaming', label: 'Gaming' }, { id: 'gamedev', label: 'Game Development' }, { id: 'webdev', label: 'Web Development' }, { id: 'all', label: 'All' } ] class Categorybar extends Component { render() { let current = this.props.category ? this.props.category : pathCategory; return ( <header className="categorybar"> <div className="content cf"> <ul> {categories.map(cat => <li key={cat.id} className={cat.id === current ? 'static' : ''}> <a className={cat.id === current ? 'static' : ''} href={"/category/" + cat.id}> {cat.label} </a> </li> )} </ul> </div> </header> ) } } export default Categorybar;
src/components/login_modal.js
17Q4MX2hmktmpuUKHFuoRmS5MfB5XPbhod/dropzone
import React from 'react' import { Input, Modal } from 'react-bootstrap' import Mnemonic from 'bitcore-mnemonic' import ReactCSSTransitionGroup from 'react-addons-css-transition-group' const LoginModal = React.createClass({ getInitialState() { return { isCreatingWallet: false, newWalletMnemonic: null, isLoginInvalid: false, isCreateInvalid: false, loginPassphrase: null, newWalletConfirmed: false } }, render() { let flipModal = () => { let newState = { isCreatingWallet: !this.state.isCreatingWallet, isLoginInvalid: false, isCreateInvalid: false } if (newState.isCreatingWallet && !this.state.newWalletMnemonic) { newState.newWalletMnemonic = (new Mnemonic()).toString() } this.setState(newState) } let newMnemonic = (e) => { e.preventDefault() this.setState({ newWalletMnemonic: Mnemonic().toString() }) } let saveAndClose = () => { if (this.state.isCreatingWallet) { if (this.state.newWalletConfirmed) { this.props.onHide() if (this.props.onOpenSuccess) { this.props.onOpenSuccess(this.state.newWalletMnemonic) } } else { this.setState({ isCreateInvalid: true }) } } else { if (Mnemonic.isValid(this.state.loginPassphrase)) { this.props.onHide() if (this.props.onOpenSuccess) { this.props.onOpenSuccess(this.state.loginPassphrase) } } else { this.setState({ isLoginInvalid: true }) } } } let onShow = () => { this.setState({ isLoginInvalid: false, isCreateInvalid: false, newWalletConfirmed: false, loginPassphrase: null }) } return ( <Modal id="loginModal" width="700" show={this.props.show} onShow={onShow} onHide={this.props.onHide} className={(this.state.isLoginInvalid || this.state.isCreateInvalid) ? "animated jello" : null} aria-labelledby="ModalHeader"> <Modal.Header closeButton> <Modal.Title>Open or Create a Wallet</Modal.Title> </Modal.Header> <Modal.Body> <div className={(this.state.isCreatingWallet) ? 'hidden' : 'animated flipInX'}> <p>In Drop Zone, your wallet is your 'account'. Information isn't stored on a central server, and this key unlocks that profile. </p> <p>If you don't have a wallet, it's easy to create a new one using only a random number. <a onClick={flipModal}>Click here to create an account</a>.</p> <form> <Input type="textarea" className="form-group has-error" onChange={(e) => {this.state.loginPassphrase = e.target.value}} defaultValue={this.state.loginPassphrase} label="Type in your Twelve word passphrase:" bsStyle={(this.state.isLoginInvalid) ? "error" : null} help={(this.state.isLoginInvalid) ? '(This is not a valid passphrase)' : null} placeholder="Enter your twelve word passphrase here" /> </form> </div> <div className={(this.state.isCreatingWallet) ? 'animated flipInX' : 'hidden'}> <p> We have created a passphrase for you in the box below. </p> <p> If you already have a wallet <a onClick={flipModal}>click here to login</a> to that account. </p> <p className="important"> If someone gets your passphrase, they gain access to your wallet. No one stores this passphrase, and it cannot be recovered if lost. </p> <form> <div className="row"> <div className="col-md-10"> <Input type="textarea" disabled={true} label="This is your new wallet:" value={this.state.newWalletMnemonic} bsSize="small" /> </div> <div className="col-md-2"> <button title="Action" id="refreshSeed" onClick={newMnemonic} className="btn btn-default"> <span className="glyphicon glyphicon-refresh" aria-hidden="true"></span> </button> </div> </div> <Input type="checkbox" onChange={(e) => { this.state.newWalletConfirmed = e.target.checked}} refs="newWalletConfirmed" bsStyle={(this.state.isCreateInvalid) ? "error" : null} label=" I have written down or otherwise securely stored my passphrase." /> </form> </div> </Modal.Body> <Modal.Footer> <button className='btn btn-default' onClick={this.props.onHide}> Cancel </button> <button className='btn btn-primary' onClick={saveAndClose}> {(this.state.isCreatingWallet) ? 'Create' : 'Open'} Wallet </button> </Modal.Footer> </Modal> ); } }) export default LoginModal;
app/routesConfig.js
ritishgumber/dashboard-ui
/** * Created by Darkstar on 11/30/2016. */ import React from 'react'; import {Route, IndexRoute} from 'react-router' // custom comps import App from './components/app'; import AppSelected from './components/appSelected'; import Dashboardproject from './components/dashboardproject/dashboardproject.jsx'; import TablesPage from './components/tables/tablesPage'; import Cache from './components/cache/cache'; import Queue from './components/queue/queue'; import EmailCampaign from './components/campaign/email'; import Analytics from './components/analytics/analytics'; import PushCampaign from './components/campaign/push'; import Profile from './components/profile/profile'; import Settings from './components/settings/settings'; import Admin from './components/admin/admin'; import PageNotFound from './components/pageNotFound/index' export default( <Route path="/" component={App}> <IndexRoute component={Dashboardproject}/> <Route path="admin" component={Admin}/> <Route path="profile" component={Profile}/> <Route path=":appId" component={AppSelected}> <IndexRoute component={TablesPage}/> <Route path="tables" component={TablesPage}/> <Route path="cache" component={Cache}/> <Route path="queue" component={Queue}/> <Route path="push" component={PushCampaign}/> <Route path="email" component={EmailCampaign}/> <Route path="analytics" component={Analytics}/> <Route path="settings" component={Settings}/> </Route> <Route path="*" component={PageNotFound}/> </Route> )
responsive-visualizations-with-react/examples/demo1.js
okonet/slides
import React from 'react' import { VictoryChart, VictoryLine } from 'victory/dist/victory' export default <VictoryChart width={800} height={400}> <VictoryLine y={(data) => Math.sin(1.5 * Math.PI * data.x)} /> </VictoryChart>
src/components/Notes/NoteCard.js
kesean/Dashboard-Frontend
import React from 'react' import Note from './Note' import NoteModal from './NoteModal' import Paper from 'material-ui/Paper' import Divider from 'material-ui/Divider' import CircularProgress from 'material-ui/CircularProgress' import {CardTitle} from 'material-ui/Card' import FlatButton from 'material-ui/FlatButton' import {addUserNote, fetchUserNotes, deleteUserNote} from '../dataFuncs' export default class NoteContainer extends React.Component { constructor(props){ super(props) this.state = { viewable: false, notes: [], noteTitle: "", noteBody: "", auth: localStorage.getItem("jwt") } } componentDidMount(){ fetchUserNotes(this.state.auth).then((res) => res.json()) .then(data => this.setState({ notes: data.notes })) } handleNoteTitle = (e) => { this.setState({ noteTitle: e.target.value }) } handleNoteBody = (e) => { this.setState({ noteBody: e.target.value }) } handleAddNote = (e) => { e.preventDefault() if (this.state.noteTitle.length > 0 && this.state.noteBody.length > 0) { addUserNote(this.state.noteTitle, this.state.noteBody, this.state.auth) .then(res => res.json()) .then((data) => this.setState({ notes: [...this.state.notes, data.note] })) } } deleteNote = (e) => { deleteUserNote(e.target.id, this.state.auth) this.setState({ notes: this.state.notes.filter((note) => note.id !== parseInt(e.target.id, 10)) }) } toggleModal = () => { this.setState({ viewable: !this.state.viewable }) } render(){ if (this.state.notes.length >= 0) { return( <Paper zDepth={5} className="note-card"> <CardTitle>Notes</CardTitle> <Divider /> {this.state.notes.slice(Math.max(this.state.notes.length - 5, 0)).sort().map((note) => <Note key={note.id} id={note.id} data={note} delete={this.deleteNote}/> )} <NoteModal viewable={this.state.viewable} handleAddNote={this.handleAddNote} toggle={this.toggleModal} body={this.handleNoteBody} title={this.handleNoteTitle}/> <br/> <FlatButton backgroundColor="F8F8F8" onClick={this.toggleModal} className="note-button" label={<i id="add" className="material-icons">add</i>}/> </Paper> ) }else { return( <Paper zDepth={5} className="note-card"> <CardTitle>Notes</CardTitle> <CircularProgress className="loader"/> </Paper> ) } } }
client/components/gainloss/GainLoss.js
kanehara/yostock
import React from 'react'; export function GainLoss(props) { return ( <div> <div>${ props.gainLossDollar }</div> <div>%{ (props.gainLossPercentage * 100).toFixed(2) }</div> </div> ) }
client/modules/comments/components/.stories/comment_list.js
luki21213/tripIdeas
import React from 'react'; import { storiesOf, action } from '@kadira/storybook'; import CommentList from '../comment_list'; storiesOf('comments.CommentList', module) .add('no comments', () => { return ( <CommentList comments={[]}/> ); }) .add('with comments', () => { const comments = [ {_id: 'one', text: 'This is cool.', author: 'arunoda'}, {_id: 'two', text: 'Yeah! I agree.', author: 'sacha'}, ]; return ( <CommentList comments={comments}/> ); }) .add('saving a comment', () => { const comments = [ {_id: 'one', text: 'This is a new comment.', author: 'arunoda', saving: true}, {_id: 'two', text: 'Yeah! I agree.', author: 'sacha'}, ]; return ( <CommentList comments={comments}/> ); });
lib/ui/components/Mocks/MultiSelectView.js
500tech/bdsm
import PropTypes from 'prop-types'; import React from 'react'; import OutlineButton from 'ui/components/common/OutlineButton'; import API from 'api'; import omit from 'lodash/omit'; import { Group } from 'api/models/group'; import { MultiSelectContainer, MultiSelectContainerText } from 'ui/components/Mocks/styled'; import { Div } from 'ui/components/common/base'; export class MultiSelectView extends React.PureComponent { groupMocks = () => { const group = API.addGroup({ name: 'Grouped Mocks' }); if (group) { this.props.selectedItems.forEach((item) => { if (item instanceof Group) { return; } if (item.groupId) { API.mockRequest({ ...omit(item, ['id']), groupId: group.id }); return; } API.updateMock(item.id, { ...item, groupId: group.id }) }); } const firstMock = group.mocks[0]; this.props.selectItems([firstMock]); this.props.addGroup({ id: group.id, isOpen: true, lastState: null }); }; render() { return ( <MultiSelectContainer> <Div> <OutlineButton onClick={ this.groupMocks }>Group</OutlineButton> <MultiSelectContainerText>these mocks</MultiSelectContainerText> </Div> </MultiSelectContainer> ); } } MultiSelectView.propTypes = { selectedItems: PropTypes.array.isRequired, groups: PropTypes.array.isRequired, selectItems: PropTypes.func.isRequired, setGroups: PropTypes.func.isRequired, addGroup: PropTypes.func.isRequired }; export default MultiSelectView;
src/components/antd/form/FormItem.js
hyd378008136/olymComponents
import React from 'react'; import { findDOMNode } from 'react-dom'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import PureRenderMixin from 'rc-util/lib/PureRenderMixin'; import Row from '../grid/row'; import Col from '../grid/col'; import { FIELD_META_PROP } from './constants'; import warning from '../_util/warning'; import _ from 'lodash' export default class FormItem extends React.Component { constructor() { super(...arguments); // Resolve duplicated ids bug between different forms // https://github.com/ant-design/ant-design/issues/7351 this.onLabelClick = (e) => { const id = this.props.id || this.getId(); if (!id) { return; } const controls = document.querySelectorAll(`[id="${id}"]`); if (controls.length !== 1) { e.preventDefault(); const control = findDOMNode(this).querySelector(`[id="${id}"]`); if (control && control.focus) { control.focus(); } } }; } componentDidMount() { warning(this.getControls(this.props.children, true).length <= 1, '`Form.Item` cannot generate `validateStatus` and `help` automatically, ' + 'while there are more than one `getFieldDecorator` in it.'); } shouldComponentUpdate(nextProps, nextState) { if (this.getHelpMsg()) { return true } if (_.isEqual(_.omit(nextProps, ['children']), _.omit(this.props, ['children'])) && _.isEqual(nextState, this.state) && nextProps.children && nextProps.children.props && _.isEqual(_.omit(nextProps.children.props, ['data-__meta']), _.omit(this.props.children.props, ['data-__meta']))) { return false } else { return true } } // shouldComponentUpdate(...args) { // return PureRenderMixin.shouldComponentUpdate.apply(this, args); // } getHelpMsg() { const context = this.context; const props = this.props; if (props.help === undefined && context.form) { return this.getId() ? (context.form.getFieldError(this.getId()) || []).join(', ') : ''; } return props.help; } getControls(children, recursively) { let controls = []; const childrenArray = React.Children.toArray(children); for (let i = 0; i < childrenArray.length; i++) { if (!recursively && controls.length > 0) { break; } const child = childrenArray[i]; if (child.type && (child.type === FormItem || child.type.displayName === 'FormItem')) { continue; } if (!child.props) { continue; } if (FIELD_META_PROP in child.props) { controls.push(child); } else if (child.props.children) { controls = controls.concat(this.getControls(child.props.children, recursively)); } } return controls; } getOnlyControl() { const child = this.getControls(this.props.children, false)[0]; return child !== undefined ? child : null; } getChildProp(prop) { const child = this.getOnlyControl(); return child && child.props && child.props[prop]; } getId() { return this.getChildProp('id'); } getMeta() { return this.getChildProp(FIELD_META_PROP); } renderHelp() { const prefixCls = this.props.prefixCls; const help = this.getHelpMsg(); var position = this.props.helpPosition ? '-' + this.props.helpPosition : '' return help ? (React.createElement("div", { className: `${prefixCls}-explain${position}`, key: "help" }, help)) : null; } renderExtra() { const { prefixCls, extra } = this.props; return extra ? (React.createElement("div", { className: `${prefixCls}-extra` }, extra)) : null; } getValidateStatus() { const { isFieldValidating, getFieldError, getFieldValue } = this.context.form; const fieldId = this.getId(); if (!fieldId) { return ''; } if (isFieldValidating(fieldId)) { return 'validating'; } if (!!getFieldError(fieldId)) { return 'error'; } const fieldValue = getFieldValue(fieldId); if (fieldValue !== undefined && fieldValue !== null && fieldValue !== '') { return 'success'; } return ''; } renderValidateWrapper(c1, c2, c3) { let classes = ''; const form = this.context.form; const props = this.props; const validateStatus = (props.validateStatus === undefined && form) ? this.getValidateStatus() : props.validateStatus; if (validateStatus) { classes = classNames({ 'has-feedback': props.hasFeedback || validateStatus === 'validating', 'has-success': validateStatus === 'success', 'has-warning': validateStatus === 'warning', 'has-error': validateStatus === 'error', 'is-validating': validateStatus === 'validating', }); } return (React.createElement("div", { className: `${this.props.prefixCls}-item-control ${classes}` }, c1, c2, c3)); } renderWrapper(children) { const { prefixCls, wrapperCol } = this.props; const className = classNames(`${prefixCls}-item-control-wrapper`, wrapperCol && wrapperCol.className); return (React.createElement(Col, Object.assign({}, wrapperCol, { className: className, key: "wrapper" }), children)); } isRequired() { const { required } = this.props; if (required !== undefined) { return required; } if (this.context.form) { const meta = this.getMeta() || {}; const validate = (meta.validate || []); return validate.filter((item) => !!item.rules).some((item) => { return item.rules.some((rule) => rule.required); }); } return false; } renderLabel() { const { prefixCls, label, labelCol, colon, id } = this.props; const context = this.context; const required = this.isRequired(); const labelColClassName = classNames(`${prefixCls}-item-label`, labelCol && labelCol.className); const labelClassName = classNames({ [`${prefixCls}-item-required`]: required, }); let labelChildren = label; // Keep label is original where there should have no colon const haveColon = colon && !context.vertical; // Remove duplicated user input colon if (haveColon && typeof label === 'string' && label.trim() !== '') { labelChildren = label.replace(/[:|:]\s*$/, ''); } return label ? (React.createElement(Col, Object.assign({}, labelCol, { className: labelColClassName, key: "label" }), React.createElement("label", { htmlFor: id || this.getId(), className: labelClassName, title: typeof label === 'string' ? label : '', onClick: this.onLabelClick }, labelChildren))) : null; } renderChildren() { const props = this.props; const children = React.Children.map(props.children, (child) => { if (child && typeof child.type === 'function' && !child.props.size) { return React.cloneElement(child, { size: 'large' }); } return child; }); return [ this.renderLabel(), this.renderWrapper(this.renderValidateWrapper(children, this.renderHelp(), this.renderExtra())), ]; } renderFormItem(children) { const props = this.props; const prefixCls = props.prefixCls; const style = props.style; const itemClassName = { [`${prefixCls}-item`]: true, [`${prefixCls}-item-with-help`]: !!this.getHelpMsg(), [`${prefixCls}-item-no-colon`]: !props.colon, [`${props.className}`]: !!props.className, }; return (React.createElement(Row, { className: classNames(itemClassName), style: style }, children)); } render() { const children = this.renderChildren(); return this.renderFormItem(children); } } FormItem.defaultProps = { hasFeedback: false, prefixCls: 'ant-form', colon: true, }; FormItem.propTypes = { prefixCls: PropTypes.string, label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), labelCol: PropTypes.object, help: PropTypes.oneOfType([PropTypes.node, PropTypes.bool]), validateStatus: PropTypes.oneOf(['', 'success', 'warning', 'error', 'validating']), hasFeedback: PropTypes.bool, wrapperCol: PropTypes.object, className: PropTypes.string, id: PropTypes.string, children: PropTypes.node, colon: PropTypes.bool, helpPosition: PropTypes.string }; FormItem.contextTypes = { form: PropTypes.object, vertical: PropTypes.bool, };
fields/types/number/NumberFilter.js
frontyard/keystone
import React from 'react'; import { findDOMNode } from 'react-dom'; import { Form, FormField, FormInput, FormSelect, Grid, } from '../../../admin/client/App/elemental'; const MODE_OPTIONS = [ { label: 'Exactly', value: 'equals' }, { label: 'Greater Than', value: 'gt' }, { label: 'Less Than', value: 'lt' }, { label: 'Between', value: 'between' }, ]; function getDefaultValue () { return { mode: MODE_OPTIONS[0].value, value: '', }; } var NumberFilter = React.createClass({ statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { filter: getDefaultValue(), }; }, componentDidMount () { // focus the text input findDOMNode(this.refs.focusTarget).focus(); }, handleChangeBuilder (type) { const self = this; return function handleChange (e) { const { filter, onChange } = self.props; switch (type) { case 'minValue': onChange({ mode: filter.mode, value: { min: e.target.value, max: filter.value.max, }, }); break; case 'maxValue': onChange({ mode: filter.mode, value: { min: filter.value.min, max: e.target.value, }, }); break; case 'value': onChange({ mode: filter.mode, value: e.target.value, }); } }; }, // Update the props with this.props.onChange updateFilter (changedProp) { this.props.onChange({ ...this.props.filter, ...changedProp }); }, // Update the filter mode selectMode (e) { this.updateFilter({ mode: e.target.value }); // focus on next tick setTimeout(() => { findDOMNode(this.refs.focusTarget).focus(); }, 0); }, renderControls (mode) { let controls; const { field } = this.props; const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...'; if (mode.value === 'between') { controls = ( <Grid.Row xsmall="one-half" gutter={10}> <Grid.Col> <FormInput onChange={this.handleChangeBuilder('minValue')} placeholder="Min." ref="focusTarget" type="number" /> </Grid.Col> <Grid.Col> <FormInput onChange={this.handleChangeBuilder('maxValue')} placeholder="Max." type="number" /> </Grid.Col> </Grid.Row> ); } else { controls = ( <FormInput onChange={this.handleChangeBuilder('value')} placeholder={placeholder} ref="focusTarget" type="number" /> ); } return controls; }, render () { const { filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; return ( <Form component="div"> <FormField> <FormSelect onChange={this.selectMode} options={MODE_OPTIONS} value={mode.value} /> </FormField> {this.renderControls(mode)} </Form> ); }, }); module.exports = NumberFilter;
src/components/Vote.js
jsfeb26/voting-client
import React from 'react'; import PureRenderMixin from 'react-addons-pure-render-mixin'; export default React.createClass({ mixins: [PureRenderMixin], getPair: function() { return this.props.pair || []; }, isDisabled: function() { return this.props.hasVoted; }, hasVotedFor: function(entry) { return this.props.hasVoted === entry; }, // vote function on the props is passed from the voting function when // we pass the aciton creators to the connect // clicking vote will call the vote action_creator render: function() { return <div className="voting"> {this.getPair().map(entry => <button key={entry} disabled={this.isDisabled()} onClick={() => this.props.vote(entry)}> <h1>{entry}</h1> {this.hasVotedFor(entry) ? <div className="label">Voted</div> : null} </button> )} </div>; } });
frontend/app/js/containers/service/logs.js
serverboards/serverboards
import connect from 'app/containers/connect' import View from 'app/containers/logs' import React from 'react' const Logs = function(props){ return ( <View filter={{service: props.service.uuid}}/> ) } export default Logs
src/svg-icons/communication/phonelink-ring.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationPhonelinkRing = (props) => ( <SvgIcon {...props}> <path d="M20.1 7.7l-1 1c1.8 1.8 1.8 4.6 0 6.5l1 1c2.5-2.3 2.5-6.1 0-8.5zM18 9.8l-1 1c.5.7.5 1.6 0 2.3l1 1c1.2-1.2 1.2-3 0-4.3zM14 1H4c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 19H4V4h10v16z"/> </SvgIcon> ); CommunicationPhonelinkRing = pure(CommunicationPhonelinkRing); CommunicationPhonelinkRing.displayName = 'CommunicationPhonelinkRing'; CommunicationPhonelinkRing.muiName = 'SvgIcon'; export default CommunicationPhonelinkRing;
src/components/select/Option.js
heifade/quark-ui
/** * Select Component * @author heifade */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import styles from './Select.css'; export default class Option extends Component { static displayName = 'Option'; static defaultProps = { value: '', text: undefined, children: null, }; // https://facebook.github.io/react/docs/typechecking-with-proptypes.html static propTypes = { value: PropTypes.string.isRequired, text: PropTypes.string, children: PropTypes.any, }; static contextTypes = { childContext: PropTypes.any, }; click = () => { const { context } = this; const { childContext } = context; const { value, text, children } = this.props; childContext.onOptionSelected(value, text || children); }; render() { const { children, value } = this.props; const { context } = this; const { childContext } = context; const isActived = childContext.getSelectedValue() === value; return ( <li className={classnames(styles.option, isActived ? styles.active : '')} onClick={this.click} > {children} </li> ); } }
src/App.js
clessg/react-transform-boilerplate
import React, { Component } from 'react'; import { NICE, SUPER_NICE } from './colors'; class Counter extends Component { constructor(props) { super(props); this.state = { counter: 0 }; this.interval = setInterval(() => this.tick(), 1000); } tick() { this.setState({ counter: this.state.counter + this.props.increment }); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <h1 style={{ color: this.props.color }}> Counter ({this.props.increment}): {this.state.counter} </h1> ); } } export class App extends Component { render() { return ( <div> <Counter increment={1} color={NICE} /> <Counter increment={5} color={SUPER_NICE} /> </div> ); } }
common/views/Components/Tabs/Tabs.js
sauleddy/HomePortal
import React, { Component } from 'react'; import { TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap'; import classnames from 'classnames'; class Tabs extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { activeTab: '1' }; } toggle(tab) { if (this.state.activeTab !== tab) { this.setState({ activeTab: tab }); } } render() { return ( <div className="animated fadeIn"> <div className="row"> <div className="col-md-6 mb-4"> <Nav tabs> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '1' })} onClick={() => { this.toggle('1'); }} > Home </NavLink> </NavItem> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '2' })} onClick={() => { this.toggle('2'); }} > Profile </NavLink> </NavItem> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '3' })} onClick={() => { this.toggle('3'); }} > Messages </NavLink> </NavItem> </Nav> <TabContent activeTab={this.state.activeTab}> <TabPane tabId="1"> 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> <TabPane tabId="2"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> <TabPane tabId="3"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> </TabContent> </div> <div className="col-md-6 mb-4"> <Nav tabs> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '1' })} onClick={() => { this.toggle('1'); }} > <i className="icon-calculator"></i> </NavLink> </NavItem> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '2' })} onClick={() => { this.toggle('2'); }} > <i className="icon-basket-loaded"></i> </NavLink> </NavItem> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '3' })} onClick={() => { this.toggle('3'); }} > <i className="icon-pie-chart"></i> </NavLink> </NavItem> </Nav> <TabContent activeTab={this.state.activeTab}> <TabPane tabId="1"> 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> <TabPane tabId="2"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> <TabPane tabId="3"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> </TabContent> </div> <div className="col-md-6 mb-4"> <Nav tabs> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '1' })} onClick={() => { this.toggle('1'); }} > <i className="icon-calculator"></i> Calculator </NavLink> </NavItem> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '2' })} onClick={() => { this.toggle('2'); }} > <i className="icon-basket-loaded"></i> Shoping cart </NavLink> </NavItem> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '3' })} onClick={() => { this.toggle('3'); }} > <i className="icon-pie-chart"></i> Charts </NavLink> </NavItem> </Nav> <TabContent activeTab={this.state.activeTab}> <TabPane tabId="1"> 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> <TabPane tabId="2"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> <TabPane tabId="3"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> </TabContent> </div> <div className="col-md-6 mb-4"> <Nav tabs> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '1' })} onClick={() => { this.toggle('1'); }} > <i className="icon-calculator"></i> Calculator &nbsp;<span className="badge badge-success">New</span> </NavLink> </NavItem> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '2' })} onClick={() => { this.toggle('2'); }} > <i className="icon-basket-loaded"></i> Shoping cart &nbsp;<span className="badge badge-pill badge-danger">29</span> </NavLink> </NavItem> <NavItem> <NavLink className={classnames({ active: this.state.activeTab === '3' })} onClick={() => { this.toggle('3'); }} > <i className="icon-pie-chart"></i> Charts </NavLink> </NavItem> </Nav> <TabContent activeTab={this.state.activeTab}> <TabPane tabId="1"> 1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> <TabPane tabId="2"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> <TabPane tabId="3"> 2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </TabPane> </TabContent> </div> </div> </div> ) } } export default Tabs;
src/svg-icons/notification/airline-seat-flat-angled.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatFlatAngled = (props) => ( <SvgIcon {...props}> <path d="M22.25 14.29l-.69 1.89L9.2 11.71l2.08-5.66 8.56 3.09c2.1.76 3.18 3.06 2.41 5.15zM1.5 12.14L8 14.48V19h8v-1.63L20.52 19l.69-1.89-19.02-6.86-.69 1.89zm5.8-1.94c1.49-.72 2.12-2.51 1.41-4C7.99 4.71 6.2 4.08 4.7 4.8c-1.49.71-2.12 2.5-1.4 4 .71 1.49 2.5 2.12 4 1.4z"/> </SvgIcon> ); NotificationAirlineSeatFlatAngled = pure(NotificationAirlineSeatFlatAngled); NotificationAirlineSeatFlatAngled.displayName = 'NotificationAirlineSeatFlatAngled'; NotificationAirlineSeatFlatAngled.muiName = 'SvgIcon'; export default NotificationAirlineSeatFlatAngled;
src/routes/register/index.js
momomods/momomods
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Register from './Register'; export default { path: '/register', action() { return <Register />; }, };
fields/types/relationship/RelationshipFilter.js
belafontestudio/keystone
import React from 'react'; var { Button, FormField, FormInput, InputGroup, SegmentedControl } = require('elemental'); import PopoutList from '../../../admin/src/components/PopoutList'; const TOGGLE_OPTIONS = [ { label: 'Linked To', value: true }, { label: 'NOT Linked To', value: false } ]; const RELATED_ITEMS = [ { label: 'Amazon', value: 'amazon' }, { label: 'Arnold', value: 'arnold' }, { label: 'Disrupt', value: 'disrupt' }, { label: 'Ebay', value: 'ebay' }, { label: 'Google', value: 'google' }, { label: 'Jaze', value: 'jaze' }, { label: 'Keystone', value: 'keystone' }, { label: 'Molomby Consulting', value: 'molomby_consulting' }, { label: 'Prismatik', value: 'prismatik' }, { label: 'Sweathers', value: 'sweathers' }, { label: 'Team9', value: 'team9' }, { label: 'The Means', value: 'the_means' }, { label: 'Thinkmill', value: 'thinkmill' }, { label: 'Twitter', value: 'twitter' }, { label: 'Yahoo', value: 'yahoo' }, ]; function findElement(arr, propName, propValue) { for (var i=0; i < arr.length; i++) { if (arr[i][propName] == propValue) { return arr[i]; } } }; var RelationshipFilter = React.createClass({ getInitialState () { return { activeItems: [], inactiveItems: RELATED_ITEMS, inverted: TOGGLE_OPTIONS[0].value, searchString: '', value: '', }; }, componentDidMount () { this.focusSearch(); }, toggleInverted (value) { this.setState({ inverted: value }); }, focusSearch () { React.findDOMNode(this.refs.search).focus(); }, updateSearch (e) { this.setState({ searchString: e.target.value }); }, makeSelectionActive (selectedItem) { console.log(selectedItem); let { activeItems, inactiveItems } = this.state; let newActiveItems = activeItems; let newInactiveItems = inactiveItems; // remove the item from "inactive items" let selectedItemIndex = inactiveItems.indexOf(findElement(inactiveItems, 'value', selectedItem.value)); if (selectedItemIndex > -1) { newInactiveItems.splice(selectedItemIndex, 1); } // add it to "picked up" newActiveItems.push(selectedItem); // reset verification to simulate real update // and take the user to the correct list this.setState({ activeItems: newActiveItems, inactiveItems: newInactiveItems, }); }, makeSelectionInactive (selectedItem) { console.log(selectedItem); let { activeItems, inactiveItems } = this.state; let newActiveItems = activeItems; let newInactiveItems = inactiveItems; // remove the item from "inactive items" let selectedItemIndex = activeItems.indexOf(findElement(activeItems, 'value', selectedItem.value)); if (selectedItemIndex > -1) { newActiveItems.splice(selectedItemIndex, 1); } // add it to "picked up" newInactiveItems.push(selectedItem); // reset verification to simulate real update // and take the user to the correct list this.setState({ activeItems: newActiveItems, inactiveItems: newInactiveItems, }); }, renderToggle () { return ( <FormField> <SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={this.toggleInverted} /> </FormField> ); }, renderList (active) { let self = this; let { activeItems, inactiveItems, searchString } = this.state; let searchRegex = new RegExp(searchString); let listItems = active ? activeItems : inactiveItems; let itemIconHover = active ? 'x' : 'check'; function listAction(item) { return active ? self.makeSelectionInactive(item) : self.makeSelectionActive(item); }; function searchFilter (filter) { return searchRegex.test(filter.label.toLowerCase()); }; let filteredItems = searchString ? listItems.filter(searchFilter) : listItems; var popoutList = filteredItems.map((item, i) => { return ( <PopoutList.Item key={'item_' + item.value} icon="dash" iconHover={itemIconHover} label={item.label} onClick={() => { listAction(item); }} /> ); }); return popoutList; }, renderInactiveItems () { if (!this.state.inactiveItems.length) return null; return ( <PopoutList> <PopoutList.Heading style={this.state.activeItems.length ? { marginTop: '2em' } : null}>Items</PopoutList.Heading> {this.renderList()} </PopoutList> ); }, renderActiveItems () { if (!this.state.activeItems.length) return null; return ( <PopoutList> <PopoutList.Heading>Selected</PopoutList.Heading> {this.renderList(true)} </PopoutList> ); }, render () { return ( <div> {this.renderToggle()} <FormField style={{ borderBottom: '1px dashed rgba(0,0,0,0.1)', paddingBottom: '1em' }}> <FormInput ref="search" value={this.state.searchString} onChange={this.updateSearch} placeholder={'Find a ' + this.props.field.label + '...'} /> </FormField> {this.renderActiveItems()} {this.renderInactiveItems()} </div> ); } }); module.exports = RelationshipFilter;
src/components/about/About.js
jackson-/hireblack.io
import React from 'react' import { Row, Col } from 'react-bootstrap' import './About.css' import PropTypes from 'prop-types' import { Link } from 'react-router-dom' const About = ({animated}) => { return ( <Row className={`About fadeIn ${animated}`}> <Col xs={12} sm={12} md={12} lg={12}> <Row> <Col className='About__hero' title='Photo credit - #WOCinTechChat' xs={12} sm={12} md={12} lg={12} > <div className='hero-overlay' /> <div className='About__hero-header'> <h1 className='About__hero-heading'> VAR COLOR_FOR_CODE = </h1> <h1 className='About__hero-heading'> DIVERSITY + TALENT </h1> <hr className='About__hero-separator' /> <h2 className='About__hero-text'> Join us in breathing new life into the tech industry. </h2> </div> </Col> </Row> <Row className='About__section bg-primary'> <Col className='text-center' xs={12} sm={12} md={8} mdOffset={2} lg={8} lgOffset={2} > <h2 className='section-heading'> {`Employers, we've got what you need!`} </h2> <hr className='About__separator-white' /> <p className='About__text text-faded'> {`Diversity empowers innovation. Innovation is what you're looking for in your next hire. Color for Code is a technology recruitment platform. We're connecting Black software engineers and designers with companies like yours, building teams as colorful as your growing user base.`} </p> <Link to='/register'> <span className='btn-oval btn-oval__white'> JOIN AS AN EMPLOYER </span> </Link> </Col> </Row> <Row className='About__section'> <Col className='text-center' xs={12} sm={12} md={12} lg={12}> <h2 className='section-heading'> At Your Service </h2> <hr className='About__separator' /> </Col> <Col className='text-center' xs={12} sm={6} md={3} lg={3}> <div className='service-box'> <i className='fa fa-4x fa-diamond text-primary sr-icons' /> <h3>Quality Jobs</h3> <p className='About__text text-muted'> All of our employers are vetted. </p> </div> </Col> <Col className='text-center' xs={12} sm={6} md={3} lg={3}> <div className='service-box'> <i className='fa fa-4x fa-paper-plane text-primary sr-icons' /> <h3>Easy to Apply</h3> <p className='About__text text-muted'> One click apply makes job seeking super simple! </p> </div> </Col> <Col className='text-center' xs={12} sm={6} md={3} lg={3}> <div className='service-box'> <i className='fa fa-4x fa-newspaper-o text-primary sr-icons' /> <h3>Up to Date Skills</h3> <p className='About__text text-muted'> Job seekers demonstrate prowess with projects. </p> </div> </Col> <Col className='text-center' xs={12} sm={6} md={3} lg={3}> <div className='service-box'> <i className='fa fa-4x fa-heart text-primary sr-icons' /> <h3>Made with Love</h3> <p className='About__text text-muted'> Built and founded by Black engineers! </p> </div> </Col> </Row> <Row className='About__section bg-primary'> <Col className='text-center' xs={12} sm={12} md={8} mdOffset={2} lg={8} lgOffset={2} > <h2 className='section-heading'> Job seekers, look no further! </h2> <hr className='About__separator-white' /> <p className='About__text text-faded'> {`It feels good to walk into an interview knowing the employer is looking for someone just like you. Color for Code is a technology recruitment platform that provides just that. We're connecting talented Black designers and engineers like you with innovative companies that don't just talk about the value of diversity—they cultivate it.`} </p> <Link to='/register'> <span className='btn-oval btn-oval__white'> JOIN AS AN APPLICANT </span> </Link> </Col> </Row> <Row className='About__section'> <Col className='text-center' xs={12} sm={12} md={8} mdOffset={2} lg={8} lgOffset={2} > <h2 className='section-heading'> {`Let's Get In Touch!`} </h2> <hr className='About__separator' /> <p className='About__text'> Ready to find your next employee with us? Send us an email and we'll get back to you as soon as possible. </p> </Col> <Col className='text-center' xs={12} sm={12} md={12} lg={12}> <i className='fa fa-envelope-o fa-3x sr-contact' /> <a href='mailto:info@colorforcode.com'> <p className='About__text text-primary'> info@colorforcode.com </p> </a> </Col> </Row> </Col> </Row> ) } About.propTypes = { animated: PropTypes.string } export default About
src/svg-icons/action/today.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionToday = (props) => ( <SvgIcon {...props}> <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zM7 10h5v5H7z"/> </SvgIcon> ); ActionToday = pure(ActionToday); ActionToday.displayName = 'ActionToday'; ActionToday.muiName = 'SvgIcon'; export default ActionToday;
hello world/1.6 - style/src/components/footer.js
wumouren/react-demo
import React from 'react'; export default class Footer extends React.Component { // props 演示 render() { let footer = ['2017','10','28']; return ( <footer> <hr/> <h1>这里是页脚</h1> <h2>从父组件传递过来的数据是: {this.props.info}</h2> <span>{footer}</span> </footer> ) } }
src/svg-icons/image/remove-red-eye.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageRemoveRedEye = (props) => ( <SvgIcon {...props}> <path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/> </SvgIcon> ); ImageRemoveRedEye = pure(ImageRemoveRedEye); ImageRemoveRedEye.displayName = 'ImageRemoveRedEye'; export default ImageRemoveRedEye;
src/components/manage/DistributeTokensStep.spec.js
oraclesorg/ico-wizard
import React from 'react' import { StaticRouter } from 'react-router' import { DistributeTokensStep } from './DistributeTokensStep' import renderer from 'react-test-renderer' import Adapter from 'enzyme-adapter-react-15' import { configure, mount } from 'enzyme' import ReservedTokenStore from '../../stores/ReservedTokenStore' configure({ adapter: new Adapter() }) describe('DistributeTokensStep', () => { let reservedTokenStore beforeEach(() => { reservedTokenStore = new ReservedTokenStore() }) afterEach(() => { reservedTokenStore.clearAll() }) it('should render the component with active button', () => { const distributeTokensStateParams = { disabled: false, handleClick: jest.fn(), reservedTokenStore, owner: true } expect(renderer.create( <StaticRouter location="testLocation" context={{}}> <DistributeTokensStep {...distributeTokensStateParams} /> </StaticRouter> ).toJSON()).toMatchSnapshot() }) it('should render the component with disabled button', () => { const distributeTokensStateParams = { disabled: true, handleClick: jest.fn(), reservedTokenStore, owner: true } expect(renderer.create( <StaticRouter location="testLocation" context={{}}> <DistributeTokensStep {...distributeTokensStateParams} /> </StaticRouter> ).toJSON()).toMatchSnapshot() }) it('should call handleClick', () => { const distributeTokensStateParams = { disabled: false, handleClick: jest.fn(), reservedTokenStore, owner: true } const wrapper = mount( <StaticRouter location="testLocation" context={{}}> <DistributeTokensStep {...distributeTokensStateParams} /> </StaticRouter> ) const button = wrapper.find('Link').at(0) button.simulate('click') expect(distributeTokensStateParams.handleClick).toHaveBeenCalled() }) it('should not call handleClick', () => { const distributeTokensStateParams = { disabled: true, handleClick: jest.fn(), reservedTokenStore, owner: true } const wrapper = mount( <StaticRouter location="testLocation" context={{}}> <DistributeTokensStep {...distributeTokensStateParams} /> </StaticRouter> ) const button = wrapper.find('Link').at(0) button.simulate('click') expect(distributeTokensStateParams.handleClick).toHaveBeenCalledTimes(0) }) it(`should render reserved token addresses if it's the owner`, () => { const distributeTokensStateParams = { disabled: false, handleClick: jest.fn(), reservedTokenStore, owner: true } const wrapper = mount( <StaticRouter location="testLocation" context={{}}> <DistributeTokensStep {...distributeTokensStateParams} /> </StaticRouter> ) expect(wrapper.find('.read-only')).toHaveLength(1) }) it(`should not render reserved token addresses if not the owner`, () => { const distributeTokensStateParams = { disabled: false, handleClick: jest.fn(), reservedTokenStore, owner: false } const wrapper = mount( <StaticRouter location="testLocation" context={{}}> <DistributeTokensStep {...distributeTokensStateParams} /> </StaticRouter> ) expect(wrapper.find('.read-only')).toHaveLength(0) }) })
packages/nausicaa/.storybook/config.js
accosine/poltergeist
import React from 'react'; import { configure, addDecorator } from '@storybook/react'; import Styletron from 'styletron-client'; import { withInfo, setDefaults } from '@storybook/addon-info'; import { StyletronProvider } from 'styletron-react'; import ThemeProvider from '../src/util/ThemeProvider'; import theme from '../src/theme.js'; setDefaults({ inline: true, }); addDecorator(story => { const styletron = new Styletron(); return ( <StyletronProvider styletron={styletron}> <ThemeProvider theme={theme}> {React.cloneElement(story(), { styletron })} </ThemeProvider> </StyletronProvider> ); }); // automatically import all files ending in *.stories.js const req = require.context('../src/stories', true, /.stories.js$/); function loadStories() { req.keys().forEach(filename => req(filename)); } configure(loadStories, module);
server/sonar-web/src/main/js/apps/component-measures/app/App.js
Builders-SonarSource/sonarqube-bis
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import Spinner from './../components/Spinner'; export default class App extends React.Component { componentDidMount () { this.props.setComponent(this.props.component); this.props.fetchMetrics(); } render () { const { metrics } = this.props; if (metrics == null) { return <Spinner/>; } return ( <main id="component-measures"> {this.props.children} </main> ); } }
internals/templates/containers/NotFoundPage/index.js
Dattaya/react-boilerplate-object
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; import { FormattedMessage } from 'react-intl'; import messages from './messages'; export default class NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <h1> <FormattedMessage {...messages.header} /> </h1> ); } }
docs/src/app/pages/components/PanelGroup/ExamplePanelGroupNode.js
GetAmbassador/react-ions
import React from 'react' import {PanelGroup, Panel, PanelHeader, PanelContent} from 'react-ions/lib/components/PanelGroup' import ProgressBar from 'react-ions/lib/components/ProgressBar' import Button from 'react-ions/lib/components/Button' import Chip from 'react-ions/lib/components/Chip' import style from './style.scss' class ExamplePanelGroupNode extends React.Component { constructor(props) { super(props) } state = { panels: [0], content: { lorum1: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla vehicula finibus purus, in ultrices mi ullamcorper in. Vestibulum porta varius sem, eu consectetur dui. Aliquam erat volutpat. Aliquam fringilla ullamcorper faucibus. Praesent purus lacus, interdum ac augue in, accumsan lacinia lorem. Nam pharetra lacus nisl, quis sagittis justo scelerisque ac. Phasellus euismod risus sit amet quam finibus, id sodales lectus scelerisque. Sed rhoncus magna neque, sed vulputate augue lobortis pharetra. Praesent placerat dui vitae fermentum tristique. Ut lobortis lacus scelerisque justo porta, quis porta nunc faucibus. Mauris ornare sem vel ornare ullamcorper. Nam tincidunt lacus ut varius faucibus. Maecenas varius lacus eget nisl condimentum, sed commodo justo euismod. Curabitur at justo quam.', lorum2: 'Sed rhoncus magna neque, sed vulputate augue lobortis pharetra. Praesent placerat dui vitae fermentum tristique.', lorum3: 'Ut lobortis lacus scelerisque justo porta, quis porta nunc faucibus. Mauris ornare sem vel ornare ullamcorper. Nam tincidunt lacus ut varius faucibus. Maecenas varius lacus eget nisl condimentum, sed commodo justo euismod. Curabitur at justo quam.', lorum4: 'Maecenas sit amet tellus vitae nisl gravida consectetur in vitae nibh. Quisque bibendum consectetur sagittis. Cras nec mauris maximus, egestas magna eget, vehicula ligula. Duis vestibulum leo at nisl placerat, euismod posuere ante accumsan. Vivamus gravida velit eu accumsan vulputate. Maecenas risus neque, mollis mollis est sit amet, porta feugiat nisi. Praesent maximus ut ante vel aliquet. Nunc mattis pharetra tellus, non volutpat lorem. Vestibulum odio arcu, laoreet a mi non, bibendum eleifend lorem. Nunc turpis lectus, malesuada id augue non, lacinia tristique orci. In fermentum, nibh id venenatis iaculis, lorem ipsum faucibus enim, vitae tincidunt lorem nunc eu tortor. Vestibulum gravida augue risus, non rhoncus velit feugiat vel. Vestibulum imperdiet velit a ligula eleifend rutrum. Vestibulum consequat, arcu sed aliquam pretium, metus metus consectetur lectus, in rutrum tellus metus a felis. Praesent lacus justo, pretium ac lacinia eu, luctus quis nisl.' } } panelToggle = activePanels => { this.setState({ panels: activePanels }) } render() { return ( <div> <p>Panels with the following indices are currently active: {this.state.panels.join() || '(none)'}</p> <PanelGroup activePanels={this.state.panels} onPanelToggle={this.panelToggle} optClass={'inline'}> <Panel> <PanelHeader title={<Chip text='Lorem' />} /> <PanelContent optClass={style['rating-specific']}> <p className={style.paragraph}>{this.state.content.lorum1}</p> </PanelContent> </Panel> <Panel> <PanelHeader title={<Chip text='Ipsum' />} /> <PanelContent> <p className={style.paragraph}>{this.state.content.lorum2}</p> </PanelContent> </Panel> <Panel> <PanelHeader title={<Chip text='Dolor' />} /> <PanelContent> <p className={style.paragraph}>{this.state.content.lorum3}</p> </PanelContent> </Panel> <Panel> <PanelHeader title={<Chip text='Sit' />} /> <PanelContent> <p className={style.paragraph}>{this.state.content.lorum4}</p> </PanelContent> </Panel> </PanelGroup> </div> ) } } export default ExamplePanelGroupNode
hello-team/src/App.js
spaceraccoon/code4good-crash-course
import React, { Component } from 'react'; import AppBar from 'material-ui/AppBar'; import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card'; import './App.css'; class App extends Component { render() { return ( <div className="App"> <AppBar position="static" color="default" title="Hello Team!" showMenuIconButton={false} /> <Card> <CardHeader title="Eugene Lim" subtitle="SWUG" avatar="https://scontent.fbed1-2.fna.fbcdn.net/v/t31.0-8/22051194_386103871822826_2278052418630848474_o.jpg?oh=a5c44be6d4e55aabc90888d05b11cd31&oe=5A86B375" /> <CardText> Welcome to Code4Good! Let me know what you know by filling out the form below. </CardText> <CardActions> <iframe title="form" src="https://docs.google.com/forms/d/e/1FAIpQLSeD4ESvcUyj4QORh0kqKfVyFJXK9gV9EGAD-TChTqs6w3maTQ/viewform?embedded=true" width="100%" overflow="hidden" height="1200px" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe> </CardActions> </Card> </div> ); } } export default App;
lib/button-outline/index.js
andyfen/react-native-UIKit
import React from 'react'; import { StyleSheet, Text, TouchableOpacity, } from 'react-native'; import { gutter } from '../variables'; const styles = StyleSheet.create({ text: { fontSize: 18, fontWeight: '600', textAlign: 'center', }, }); const ButtonOutline = ({ children, radius, backgroundColor, borderWidth, color, fontWeight, fontSize, gutter, onPress, style, textStyle }) => ( <TouchableOpacity style={[ styles.btn, { borderRadius: radius, backgroundColor, borderWidth, borderColor: color, padding: gutter, marginBottom: gutter, }, style]} onPress={onPress} > <Text style={[ styles.text, { color, fontSize, fontWeight, }, textStyle]} > {children} </Text> </TouchableOpacity> ); ButtonOutline.defaultProps = { radius: 4, borderWidth: 2, backgroundColor: 'transparent', color: '#fff', gutter, style: {}, textStyle: {}, }; ButtonOutline.propTypes = { radius: React.PropTypes.number, type: React.PropTypes.string, invert: React.PropTypes.bool, backgroundColor: React.PropTypes.string, color: React.PropTypes.string, borderWidth: React.PropTypes.number, gutter: React.PropTypes.number, children: React.PropTypes.string.isRequired, fontWeight: React.PropTypes.string, fontSize: React.PropTypes.number, onPress: React.PropTypes.func, }; export default ButtonOutline;
src/svg-icons/action/account-balance.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccountBalance = (props) => ( <SvgIcon {...props}> <path d="M4 10v7h3v-7H4zm6 0v7h3v-7h-3zM2 22h19v-3H2v3zm14-12v7h3v-7h-3zm-4.5-9L2 6v2h19V6l-9.5-5z"/> </SvgIcon> ); ActionAccountBalance = pure(ActionAccountBalance); ActionAccountBalance.displayName = 'ActionAccountBalance'; ActionAccountBalance.muiName = 'SvgIcon'; export default ActionAccountBalance;
src/Radio/Radio.js
dsslimshaddy/material-ui
// @flow weak import React from 'react'; import type { Element } from 'react'; import withStyles from '../styles/withStyles'; import createSwitch from '../internal/SwitchBase'; import RadioButtonCheckedIcon from '../svg-icons/radio-button-checked'; import RadioButtonUncheckedIcon from '../svg-icons/radio-button-unchecked'; export const styles = (theme: Object) => ({ default: { color: theme.palette.text.secondary, }, checked: { color: theme.palette.primary[500], }, disabled: { color: theme.palette.action.disabled, }, }); const Radio = withStyles(styles, { name: 'MuiRadio' })( createSwitch({ inputType: 'radio', defaultIcon: <RadioButtonUncheckedIcon />, defaultCheckedIcon: <RadioButtonCheckedIcon />, }), ); Radio.displayName = 'Radio'; export default Radio; export type Props = { /** * If `true`, the component is checked. */ checked?: boolean | string, /** * The CSS class name of the root element when checked. */ checkedClassName?: string, /** * The icon to display when the component is checked. * If a string is provided, it will be used as a font ligature. */ checkedIcon?: Element<*>, /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * @ignore */ defaultChecked?: boolean, /** * If `true`, the switch will be disabled. */ disabled?: boolean, /** * The CSS class name of the root element when disabled. */ disabledClassName?: string, /** * If `true`, the ripple effect will be disabled. */ disableRipple?: boolean, /** * The icon to display when the component is unchecked. * If a string is provided, it will be used as a font ligature. */ icon?: Element<*>, /** * Properties applied to the `input` element. */ inputProps?: Object, /** * Use that property to pass a ref callback to the native input component. */ inputRef?: Function, /* * @ignore */ name?: string, /** * Callback fired when the state is changed. * * @param {object} event The event source of the callback * @param {boolean} checked The `checked` value of the switch */ onChange?: Function, /** * @ignore */ tabIndex?: string, /** * The value of the component. */ value?: string, }; // This is here solely to trigger api doc generation export const RadioDocs = (props: Props) => <span />; // eslint-disable-line no-unused-vars
client/components/nav-link.js
thebearingedge/inqur
import React from 'react' import Link from 'next/link' import styled from 'styled-components' const Anchor = styled.a` vertical-align: middle; font-size: 0.938em; cursor: pointer; text-decoration: none; &:hover { border-radius: 50px; background-color: #50545c; } &:visited { color: inherit; } ` const NavLink = ({ href, children }) => <Link href={ href } prefetch={ process.env.NODE_ENV === 'production' }> <Anchor href={ href }>{ children }</Anchor> </Link> export default NavLink
src/app/components/tag/TagMenu.js
meedan/check-web
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay/classic'; import { FormattedMessage, injectIntl } from 'react-intl'; import Button from '@material-ui/core/Button'; import IconButton from '@material-ui/core/IconButton'; import Popover from '@material-ui/core/Popover'; import { withStyles } from '@material-ui/core/styles'; import LocalOfferOutlinedIcon from '@material-ui/icons/LocalOfferOutlined'; import { MultiSelector } from '@meedan/check-ui'; import { can } from '../Can'; import { withSetFlashMessage } from '../FlashMessage'; import GenericUnknownErrorMessage from '../GenericUnknownErrorMessage'; import MediaRoute from '../../relay/MediaRoute'; import RelayContainer from '../../relay/RelayContainer'; import CheckContext from '../../CheckContext'; import { createTag } from '../../relay/mutations/CreateTagMutation'; import { deleteTag } from '../../relay/mutations/DeleteTagMutation'; import { getErrorMessage } from '../../helpers'; import CheckArchivedFlags from '../../CheckArchivedFlags'; const StyledIconButton = withStyles(theme => ({ root: { padding: theme.spacing(0.5), '&:hover': { backgroundColor: 'transparent', color: theme.palette.primary.main, }, }, }))(IconButton); class TagMenuComponent extends Component { constructor(props) { super(props); this.state = { anchorEl: null, searchValue: null, }; } noop = () => {}; // FIXME: avoid this pattern and simply omit onSuccess fail = (transaction) => { const message = getErrorMessage(transaction, <GenericUnknownErrorMessage />); this.props.setFlashMessage(message, 'error'); }; handleOpenMenu = (e) => { this.setState({ anchorEl: e.currentTarget }); this.props.relay.forceFetch(); }; handleCloseMenu = () => this.setState({ anchorEl: null }); handleChange = searchValue => this.setState({ searchValue }); handleSelect = (value) => { const tags = this.props.media.tags.edges.map(tag => tag.node.tag_text); tags.forEach((text) => { if (!value.includes(text)) this.handleRemoveTag(text); }); value.forEach((val) => { if (!tags.includes(val)) this.handleCreateTag(val); }); this.handleCloseMenu(); }; handleAddNew = (value) => { this.handleCreateTag(value); this.handleCloseMenu(); }; handleCreateTag(value) { const { media } = this.props; const context = new CheckContext(this).getContextStore(); createTag( { media, value, annotator: context.currentUser, }, this.noop, this.fail, ); } handleRemoveTag = (value) => { const { media } = this.props; const removedTag = media.tags.edges.find(tag => tag.node.tag_text === value); if (!removedTag) { return; } deleteTag( { media, tagId: removedTag.node.id, }, this.noop, this.fail, ); }; render() { const { media } = this.props; const { searchValue } = this.state; if (!can(media.permissions, 'update ProjectMedia') || media.archived > CheckArchivedFlags.NONE) { return null; } const selected = media.tags.edges.map(t => t.node.tag_text); const options = media.team.tag_texts.edges.map(tt => ({ label: tt.node.text, value: tt.node.text })); const actionButton = searchValue && !options.includes(searchValue) ? ( <Button id="tag-menu__create-button" color="primary" onClick={() => this.handleAddNew(searchValue)} > <FormattedMessage id="tagMenu.create" defaultMessage="+ Create this tag" /> </Button> ) : null; return ( <React.Fragment> <StyledIconButton className="tag-menu__icon" tooltip={<FormattedMessage id="tagMenu.tooltip" defaultMessage="Edit tags" />} onClick={this.handleOpenMenu} > <LocalOfferOutlinedIcon /> </StyledIconButton> <Popover anchorEl={this.state.anchorEl} open={Boolean(this.state.anchorEl)} onClose={this.handleCloseMenu} > <FormattedMessage id="multiSelector.search" defaultMessage="Search…"> {placeholder => ( <MultiSelector actionButton={actionButton} allowSearch inputPlaceholder={placeholder} selected={selected} options={options} onDismiss={this.handleCloseMenu} onSearchChange={this.handleChange} onSubmit={this.handleSelect} notFoundLabel={ <FormattedMessage id="tagMenu.notFound" defaultMessage="No tags found" /> } submitLabel={ <FormattedMessage id="tagMenu.submit" defaultMessage="Tag" description="Verb, infinitive form. Button to commit action of tagging an item" /> } /> )} </FormattedMessage> </Popover> </React.Fragment> ); } } TagMenuComponent.contextTypes = { store: PropTypes.object, }; TagMenuComponent.propTypes = { media: PropTypes.object.isRequired, relay: PropTypes.object.isRequired, setFlashMessage: PropTypes.func.isRequired, }; const TagMenuContainer = Relay.createContainer(withSetFlashMessage(TagMenuComponent), { fragments: { media: () => Relay.QL` fragment on ProjectMedia { id dbid archived permissions tags(first: 10000) { edges { node { tag, tag_text, id } } } team { id, tag_texts(first: 10000) { edges { node { text } } } } } `, }, }); // eslint-disable-next-line react/no-multi-comp class TagMenu extends React.PureComponent { render() { const projectId = this.props.media.project_id; const ids = `${this.props.media.dbid},${projectId}`; const route = new MediaRoute({ ids }); return ( <RelayContainer Component={TagMenuContainer} route={route} renderFetched={data => <TagMenuContainer {...this.props} {...data} />} /> ); } } export default injectIntl(TagMenu);
example/with-mock-auth/template.js
iansinnott/react-static-webpack-plugin
import React from 'react'; const getRedirect = ({ reactStaticCompilation }) => { return reactStaticCompilation && reactStaticCompilation.redirectLocation; }; const Html = (props) => ( <html lang='en'> <head> <meta charSet='utf-8' /> <meta httpEquiv='X-UA-Compatible' content='IE=edge' /> <meta name='viewport' content='width=device-width, minimum-scale=1.0' /> <title>Super awesome package</title> <script dangerouslySetInnerHTML={{ __html: 'console.log("analytics")' }} /> </head> <body> {getRedirect(props) && ( <h1> <strong>{props.reactStaticCompilation.location}</strong>{' '} not found. Redirecting you to <strong>{getRedirect(props).pathname}</strong>... </h1> )} <div id='root' dangerouslySetInnerHTML={{ __html: props.body }} /> <script src='/app.js' /> </body> </html> ); export default Html;
examples/index.ios.js
mayuur/react-native-callout
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, TouchableHighlight, Animated, View, Dimensions, } from 'react-native'; let { screenWidth, screenHeight } = Dimensions.get('window'); var MJCallout = require('react-native-callout'); class calloutExample extends Component { constructor(props) { super(props); this.topButton = TouchableHighlight; this.state = { calloutOpacity: new Animated.Value(0), calloutText: 'Sample Callout Text', calloutTop:0, calloutLeft:0, calloutWidth:200, arrowPosition:'up', }; } render() { return ( <View style={styles.container}> <Text style={styles.headerText}> MJCallout Example </Text> <View style = {styles.buttonsView}> <TouchableHighlight ref = {component => this.topButton = component} style={[styles.buttonCallout, styles.buttonTop]} onPress={this.buttonClicked.bind(this,0)}> <Text style={styles.buttonText}> Top </Text> </TouchableHighlight> <TouchableHighlight ref = {component => this.leftButton = component} style={styles.buttonCallout} onPress={this.buttonClicked.bind(this,1)}> <Text style={styles.buttonText}> Left </Text> </TouchableHighlight> <TouchableHighlight ref = {component => this.rightButton = component} style={styles.buttonCallout} onPress={this.buttonClicked.bind(this,2)}> <Text style={styles.buttonText}> Right </Text> </TouchableHighlight> <TouchableHighlight ref = {component => this.downButton = component} style={styles.buttonCallout} onPress={this.buttonClicked.bind(this,3)}> <Text style={styles.buttonText}> Bottom </Text> </TouchableHighlight> </View> {this.renderCallOut()} </View> ); } renderCallOut() { //show callout only when needed if(!this.state.calloutOpacity) { return } //add callout if needed return ( <View style={{position:'absolute', top:this.state.calloutTop, left:this.state.calloutLeft}}> <MJCallout width={this.state.calloutWidth} visibility={this.state.calloutOpacity} calloutText={this.state.calloutText} arrowDirection={this.state.arrowPosition}> </MJCallout> </View> ) } buttonClicked(index) { var calloutX = 0; var calloutY = 0; if(index == 0) { this.topButton.measure( (fx, fy, width, height, px, py) => { this.setState({ calloutText:'Callout at top position', calloutOpacity: new Animated.Value(1), arrowPosition:'down', calloutTop:py-30, calloutLeft:px, calloutWidth:190, }) }) } else if(index == 1) { this.leftButton.measure( (fx, fy, width, height, px, py) => { this.setState({ calloutText:'Left Side Callout', calloutOpacity: new Animated.Value(1), arrowPosition:'left', calloutTop:py+5, calloutLeft:px-85, calloutWidth:175, }) }) } else if(index == 2) { this.rightButton.measure( (fx, fy, width, height, px, py) => { this.setState({ calloutText:'Right Side Callout', calloutOpacity: new Animated.Value(1), arrowPosition:'right', calloutTop:py+5, calloutLeft:px+120, calloutWidth:175, }) }) } else if(index == 3) { this.downButton.measure( (fx, fy, width, height, px, py) => { this.setState({ calloutText:'Callout at down position', calloutOpacity: new Animated.Value(1), arrowPosition:'up', calloutTop:py+55, calloutLeft:px, calloutWidth:200, }) }) } } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', backgroundColor: '#F5FCFF', }, headerText: { marginTop:30, fontSize: 30, fontWeight: '300', height:50, }, buttonsView: { flex:1, alignSelf:'stretch', justifyContent:'center', alignItems:'center', }, buttonCallout: { marginTop:20, justifyContent:'center', alignItems:'center', backgroundColor:'green', width:200, height: 50, borderColor: 'black', borderWidth:2, borderRadius:10, backgroundColor:'green', }, buttonTop : { marginTop:-50, }, buttonText: { textAlign:'center', color:'white', }, }); AppRegistry.registerComponent('calloutExample', () => calloutExample);
test/helpers/shallowRenderHelper.js
igor-popov/react-demo
import React from 'react'; //import TestUtils from 'react-addons-test-utils'; import {shallow} from 'enzyme'; export function renderShallow(component) { return shallow(component); }
city-forecast/src/components/weather_list_item.js
alexkovalenko/react-redux-learn
import React from 'react'; import Chart from './chart'; import GoogleMap from './google_map'; export default ({city, list}) => { const temps = list.map(weather => weather.main.temp); const pressures = list.map(weather => weather.main.pressure); const humidities = list.map(weather => weather.main.humidity); return ( <tr> <td><GoogleMap lat={city.coord.lat} lon={city.coord.lon}/></td> <td><Chart data={temps} color='red' units="K"/></td> <td><Chart data={pressures} color='green' units="hPa"/></td> <td><Chart data={humidities} color='blue' units="%"/></td> </tr> ) };
app/javascript/mastodon/components/autosuggest_textarea.js
yukimochi/mastodon
import React from 'react'; import AutosuggestAccountContainer from '../features/compose/containers/autosuggest_account_container'; import AutosuggestEmoji from './autosuggest_emoji'; import AutosuggestHashtag from './autosuggest_hashtag'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; import Textarea from 'react-textarea-autosize'; import classNames from 'classnames'; const textAtCursorMatchesToken = (str, caretPosition) => { let word; let left = str.slice(0, caretPosition).search(/\S+$/); let right = str.slice(caretPosition).search(/\s/); if (right < 0) { word = str.slice(left); } else { word = str.slice(left, right + caretPosition); } if (!word || word.trim().length < 3 || ['@', ':', '#'].indexOf(word[0]) === -1) { return [null, null]; } word = word.trim().toLowerCase(); if (word.length > 0) { return [left + 1, word]; } else { return [null, null]; } }; export default class AutosuggestTextarea extends ImmutablePureComponent { static propTypes = { value: PropTypes.string, suggestions: ImmutablePropTypes.list, disabled: PropTypes.bool, placeholder: PropTypes.string, onSuggestionSelected: PropTypes.func.isRequired, onSuggestionsClearRequested: PropTypes.func.isRequired, onSuggestionsFetchRequested: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, onKeyUp: PropTypes.func, onKeyDown: PropTypes.func, onPaste: PropTypes.func.isRequired, autoFocus: PropTypes.bool, }; static defaultProps = { autoFocus: true, }; state = { suggestionsHidden: true, focused: false, selectedSuggestion: 0, lastToken: null, tokenStart: 0, }; onChange = (e) => { const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart); if (token !== null && this.state.lastToken !== token) { this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart }); this.props.onSuggestionsFetchRequested(token); } else if (token === null) { this.setState({ lastToken: null }); this.props.onSuggestionsClearRequested(); } this.props.onChange(e); } onKeyDown = (e) => { const { suggestions, disabled } = this.props; const { selectedSuggestion, suggestionsHidden } = this.state; if (disabled) { e.preventDefault(); return; } if (e.which === 229 || e.isComposing) { // Ignore key events during text composition // e.key may be a name of the physical key even in this case (e.x. Safari / Chrome on Mac) return; } switch(e.key) { case 'Escape': if (suggestions.size === 0 || suggestionsHidden) { document.querySelector('.ui').parentElement.focus(); } else { e.preventDefault(); this.setState({ suggestionsHidden: true }); } break; case 'ArrowDown': if (suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) }); } break; case 'ArrowUp': if (suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) }); } break; case 'Enter': case 'Tab': // Select suggestion if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); e.stopPropagation(); this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion)); } break; } if (e.defaultPrevented || !this.props.onKeyDown) { return; } this.props.onKeyDown(e); } onBlur = () => { this.setState({ suggestionsHidden: true, focused: false }); } onFocus = (e) => { this.setState({ focused: true }); if (this.props.onFocus) { this.props.onFocus(e); } } onSuggestionClick = (e) => { const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index')); e.preventDefault(); this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion); this.textarea.focus(); } componentWillReceiveProps (nextProps) { if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden && this.state.focused) { this.setState({ suggestionsHidden: false }); } } setTextarea = (c) => { this.textarea = c; } onPaste = (e) => { if (e.clipboardData && e.clipboardData.files.length === 1) { this.props.onPaste(e.clipboardData.files); e.preventDefault(); } } renderSuggestion = (suggestion, i) => { const { selectedSuggestion } = this.state; let inner, key; if (suggestion.type === 'emoji') { inner = <AutosuggestEmoji emoji={suggestion} />; key = suggestion.id; } else if (suggestion.type === 'hashtag') { inner = <AutosuggestHashtag tag={suggestion} />; key = suggestion.name; } else if (suggestion.type === 'account') { inner = <AutosuggestAccountContainer id={suggestion.id} />; key = suggestion.id; } return ( <div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}> {inner} </div> ); } render () { const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus, children } = this.props; const { suggestionsHidden } = this.state; return [ <div className='compose-form__autosuggest-wrapper' key='autosuggest-wrapper'> <div className='autosuggest-textarea'> <label> <span style={{ display: 'none' }}>{placeholder}</span> <Textarea ref={this.setTextarea} className='autosuggest-textarea__textarea' disabled={disabled} placeholder={placeholder} autoFocus={autoFocus} value={value} onChange={this.onChange} onKeyDown={this.onKeyDown} onKeyUp={onKeyUp} onFocus={this.onFocus} onBlur={this.onBlur} onPaste={this.onPaste} dir='auto' aria-autocomplete='list' /> </label> </div> {children} </div>, <div className='autosuggest-textarea__suggestions-wrapper' key='suggestions-wrapper'> <div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}> {suggestions.map(this.renderSuggestion)} </div> </div>, ]; } }
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ArrayDestructuring.js
appier/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load() { return [[1, '1'], [2, '2'], [3, '3'], [4, '4']]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-array-destructuring"> {this.state.users.map(user => { const [id, name] = user; return <div key={id}>{name}</div>; })} </div> ); } }
blueocean-material-icons/src/js/components/svg-icons/action/settings-voice.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSettingsVoice = (props) => ( <SvgIcon {...props}> <path d="M7 24h2v-2H7v2zm5-11c1.66 0 2.99-1.34 2.99-3L15 4c0-1.66-1.34-3-3-3S9 2.34 9 4v6c0 1.66 1.34 3 3 3zm-1 11h2v-2h-2v2zm4 0h2v-2h-2v2zm4-14h-1.7c0 3-2.54 5.1-5.3 5.1S6.7 13 6.7 10H5c0 3.41 2.72 6.23 6 6.72V20h2v-3.28c3.28-.49 6-3.31 6-6.72z"/> </SvgIcon> ); ActionSettingsVoice.displayName = 'ActionSettingsVoice'; ActionSettingsVoice.muiName = 'SvgIcon'; export default ActionSettingsVoice;
src/parser/warrior/arms/modules/core/Dots/DeepWoundsUptime.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import Enemies from 'parser/shared/modules/Enemies'; import SPELLS from 'common/SPELLS/index'; import { formatPercentage } from 'common/format'; import SpellLink from 'common/SpellLink'; import StatisticListBoxItem from 'interface/others/StatisticListBoxItem'; class DeepWoundsUptime extends Analyzer { static dependencies = { enemies: Enemies, }; get uptime() { return this.enemies.getBuffUptime(SPELLS.MASTERY_DEEP_WOUNDS_DEBUFF.id) / this.owner.fightDuration; } get suggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.8, average: 0.7, major: 0.6, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => { return suggest(<>Your <SpellLink id={SPELLS.MASTERY_DEEP_WOUNDS.id} /> uptime can be improved. Try to use your core abilities more often to apply <SpellLink id={SPELLS.DEEP_WOUNDS.id} /> on your target</>) .icon(SPELLS.MASTERY_DEEP_WOUNDS.icon) .actual(`${formatPercentage(actual)}% Deep Wounds uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`); }); } subStatistic() { return ( <StatisticListBoxItem title={<><SpellLink id={SPELLS.MASTERY_DEEP_WOUNDS.id} /> uptime</>} value={`${formatPercentage(this.uptime)} %`} /> ); } } export default DeepWoundsUptime;
src/todo/TodoGrid.js
carlodicelico/reify
import React from 'react'; const TodoGrid = (props) => { return ( <section className='todo-grid'> <p className='notification is-warning'>Grid of todo lists</p> </section> ); }; export default TodoGrid;
docs/app/Examples/collections/Grid/ResponsiveVariations/GridExampleReversedTablet.js
aabustamante/Semantic-UI-React
import React from 'react' import { Grid } from 'semantic-ui-react' const GridExampleReversedTablet = () => ( <Grid reversed='tablet' columns='equal'> <Grid.Column>Tablet Fourth</Grid.Column> <Grid.Column>Tablet Third</Grid.Column> <Grid.Column>Tablet Second</Grid.Column> <Grid.Column>Tablet First</Grid.Column> </Grid> ) export default GridExampleReversedTablet
src/svg-icons/action/question-answer.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionQuestionAnswer = (props) => ( <SvgIcon {...props}> <path d="M21 6h-2v9H6v2c0 .55.45 1 1 1h11l4 4V7c0-.55-.45-1-1-1zm-4 6V3c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v14l4-4h10c.55 0 1-.45 1-1z"/> </SvgIcon> ); ActionQuestionAnswer = pure(ActionQuestionAnswer); ActionQuestionAnswer.displayName = 'ActionQuestionAnswer'; ActionQuestionAnswer.muiName = 'SvgIcon'; export default ActionQuestionAnswer;
src/components/Icons.js
Hum4n01d/Amango
import React from 'react' const LoadingIcon = props => ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0, 0, 32, 32"> <g id="Layer_1"> <path d="M32,12 L20,12 L24.485,7.515 C22.218,5.249 19.205,4 16,4 C12.795,4 9.781,5.248 7.515,7.515 C5.249,9.782 4,12.795 4,16 C4,19.205 5.248,22.219 7.515,24.485 C9.782,26.751 12.795,28 16,28 C19.205,28 22.219,26.752 24.485,24.485 C24.674,24.296 24.856,24.101 25.031,23.902 L28.041,26.536 C25.108,29.885 20.802,32 16,32 C7.163,32 -0,24.837 -0,16 C-0,7.163 7.163,0 16,0 C20.418,0 24.418,1.791 27.313,4.687 L32,0 L32,12 z"/> </g> </svg> ) export {LoadingIcon}
src/svg-icons/image/looks.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageLooks = (props) => ( <SvgIcon {...props}> <path d="M12 10c-3.86 0-7 3.14-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.86-3.14-7-7-7zm0-4C5.93 6 1 10.93 1 17h2c0-4.96 4.04-9 9-9s9 4.04 9 9h2c0-6.07-4.93-11-11-11z"/> </SvgIcon> ); ImageLooks = pure(ImageLooks); ImageLooks.displayName = 'ImageLooks'; ImageLooks.muiName = 'SvgIcon'; export default ImageLooks;
src-changed/containers/app.js
aryalprakash/omgyoutube
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { browserHistory, Link } from 'react-router' import {getVideoData, getChannelVideos} from '../actions/video.js' import Header from './Header.js' //import Loader from './Loader.js' //import App from './App.js' export default class App extends Component { toggleView = () => { this.setState({ renderSearch: true }) } render() { return(<div> <Header toggleView={this.toggleView} /> {this.props.children} </div>) } } Home.contextTypes = { router: React.PropTypes.object } const mapStateToProps = (state) => ({state}); export default connect(mapStateToProps)( App )
packages/react/src/components/DataTable/TableSelectRow.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React from 'react'; import classNames from 'classnames'; import { settings } from 'carbon-components'; import InlineCheckbox from '../InlineCheckbox'; import RadioButton from '../RadioButton'; const { prefix } = settings; const TableSelectRow = ({ ariaLabel, checked, id, name, onSelect, onChange, disabled, radio, className, }) => { const selectionInputProps = { id, name, onClick: onSelect, onChange, checked, disabled, }; const InlineInputComponent = radio ? RadioButton : InlineCheckbox; const tableSelectRowClasses = classNames(`${prefix}--table-column-checkbox`, { [className]: className, [`${prefix}--table-column-radio`]: radio, }); return ( <td className={tableSelectRowClasses}> <InlineInputComponent {...selectionInputProps} {...(radio && { labelText: ariaLabel, hideLabel: true, })} {...(!radio && { ariaLabel })} /> </td> ); }; TableSelectRow.propTypes = { /** * Specify the aria label for the underlying input control */ ariaLabel: PropTypes.string.isRequired, /** * Specify whether all items are selected, or not */ checked: PropTypes.bool.isRequired, /** * The CSS class names of the cell that wraps the underlying input control */ className: PropTypes.string, /** * Specify whether the control is disabled */ disabled: PropTypes.bool, /** * Provide an `id` for the underlying input control */ id: PropTypes.string.isRequired, /** * Provide a `name` for the underlying input control */ name: PropTypes.string.isRequired, /** * Provide an optional hook that is called each time the input is updated */ onChange: PropTypes.func, /** * Provide a handler to listen to when a user initiates a selection request */ onSelect: PropTypes.func.isRequired, /** * Specify whether the control should be a radio button or inline checkbox */ radio: PropTypes.bool, }; export default TableSelectRow;
src/templates/not-found-template.js
apalhu/website
// @flow strict import React from 'react'; import Sidebar from '../components/Sidebar'; import Layout from '../components/Layout'; import Page from '../components/Page'; import { useSiteMetadata } from '../hooks'; const NotFoundTemplate = () => { const { title, subtitle } = useSiteMetadata(); return ( <Layout title={`Not Found - ${title}`} description={subtitle}> <Sidebar /> <Page title="NOT FOUND"> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </Page> </Layout> ); }; export default NotFoundTemplate;
src/containers/addition.js
cyranosky/rrtimes_hlj
import React from 'react' import { connect } from 'react-redux' import { additionAChange, additionBChange } from '../actions' import Addition from '../components/addition' import { push } from 'react-router-redux' const mapStateToProps = (state) => ({ ...state.reducer.addition }) const mapDispatchToProps = { onAChange: additionAChange, onBChange: additionBChange, push } export default connect(mapStateToProps, mapDispatchToProps)(Addition)
client/src/app/components/ui/UiDialogLauncher.js
zraees/sms-project
import React from 'react' import ReactDOM from 'react-dom' $.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, { _title: function (title) { if (!this.options.title) { title.html("&#160;"); } else { title.html(this.options.title); } } })); let UiDialogLauncher = React.createClass({ openDialog: function (e) { e.preventDefault(); let $dialog = $('<div>').dialog({ title: `<div class="widget-header">${this.props.header}</div>`, width: 400, modal: !!this.props.modal, close: function (e) { ReactDOM.unmountComponentAtNode(this); $(this).remove(); } }); let closeDialog = function (e) { e.preventDefault(); $dialog.dialog('close'); }; let _content = this.props.content let content = React.createElement(_content.type, { closeDialog: closeDialog }); ReactDOM.render(content, $dialog[0]) }, render: function () { return ( <button onClick={this.openDialog} className={this.props.className}>{ this.props.children }</button> ) } }); export default UiDialogLauncher
src/components/ComboBox/ComboBox.js
jzhang300/carbon-components-react
import cx from 'classnames'; import Downshift from 'downshift'; import PropTypes from 'prop-types'; import React from 'react'; import ListBox, { PropTypes as ListBoxPropTypes } from '../ListBox'; const defaultItemToString = item => item && item.label; const defaultShouldFilterItem = ({ inputValue, item, itemToString }) => !inputValue || itemToString(item) .toLowerCase() .includes(inputValue.toLowerCase()); const getInputValue = (props, state) => { if (props.initialSelectedItem) { return props.itemToString(props.initialSelectedItem); } return state.inputValue || ''; }; export default class ComboBox extends React.Component { static propTypes = { /** * An optional className to add to the container node */ className: PropTypes.string, /** * Specify if the control should be disabled, or not */ disabled: PropTypes.bool, /** * Specify a custom `id` for the input */ id: PropTypes.string, /** * Allow users to pass in arbitrary items from their collection that are * pre-selected */ initialSelectedItem: PropTypes.object, /** * We try to stay as generic as possible here to allow individuals to pass * in a collection of whatever kind of data structure they prefer */ items: PropTypes.array.isRequired, /** * Helper function passed to downshift that allows the library to render a * given item to a string label. By default, it extracts the `label` field * from a given item to serve as the item label in the list */ itemToString: PropTypes.func, /** * `onChange` is a utility for this controlled component to communicate to a * consuming component what kind of internal state changes are occuring */ onChange: PropTypes.func.isRequired, /** * Used to provide a placeholder text node before a user enters any input. * This is only present if the control has no items selected */ placeholder: PropTypes.string.isRequired, /** * Specify your own filtering logic by passing in a `shouldFilterItem` * function that takes in the current input and an item and passes back * whether or not the item should be filtered. */ shouldFilterItem: PropTypes.func, /** * Currently supports either the default type, or an inline variant */ type: ListBoxPropTypes.ListBoxType, }; static defaultProps = { disabled: false, itemToString: defaultItemToString, shouldFilterItem: defaultShouldFilterItem, type: 'default', }; constructor(props) { super(props); this.state = { inputValue: getInputValue(props, {}), }; } componentWillReceiveProps(nextProps) { this.setState(state => ({ inputValue: getInputValue(nextProps, state), })); } filterItems = (items, itemToString, inputValue) => items.filter(item => this.props.shouldFilterItem({ item, itemToString, inputValue, }) ); handleOnChange = selectedItem => { if (this.props.onChange) { this.props.onChange({ selectedItem }); } }; handleOnInputKeyDown = event => { event.stopPropagation(); }; handleOnInputValueChange = inputValue => { this.setState(() => ({ // Default to empty string if we have a false-y `inputValue` inputValue: inputValue || '', })); }; render() { const { className: containerClassName, disabled, id, items, itemToString, placeholder, initialSelectedItem, } = this.props; const className = cx('bx--combo-box', containerClassName); return ( <Downshift onChange={this.handleOnChange} onInputValueChange={this.handleOnInputValueChange} inputValue={this.state.inputValue || ''} itemToString={itemToString} defaultSelectedItem={initialSelectedItem}> {({ getButtonProps, getInputProps, getItemProps, getRootProps, isOpen, inputValue, selectedItem, highlightedIndex, clearSelection, }) => ( <ListBox className={className} disabled={disabled} {...getRootProps({ refKey: 'innerRef' })}> <ListBox.Field {...getButtonProps({ disabled })}> <input className="bx--text-input" {...getInputProps({ disabled, id, placeholder, onKeyDown: this.handleOnInputKeyDown, })} /> {inputValue && isOpen && <ListBox.Selection clearSelection={clearSelection} />} <ListBox.MenuIcon isOpen={isOpen} /> </ListBox.Field> {isOpen && ( <ListBox.Menu> {this.filterItems(items, itemToString, inputValue).map( (item, index) => ( <ListBox.MenuItem key={itemToString(item)} isActive={selectedItem === item} isHighlighted={highlightedIndex === index} {...getItemProps({ item, index })}> {itemToString(item)} </ListBox.MenuItem> ) )} </ListBox.Menu> )} </ListBox> )} </Downshift> ); } }
app/javascript/mastodon/features/ui/components/modal_root.js
robotstart/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import MediaModal from './media_modal'; import OnboardingModal from './onboarding_modal'; import VideoModal from './video_modal'; import BoostModal from './boost_modal'; import ConfirmationModal from './confirmation_modal'; import { TransitionMotion, spring } from 'react-motion'; const MODAL_COMPONENTS = { 'MEDIA': MediaModal, 'ONBOARDING': OnboardingModal, 'VIDEO': VideoModal, 'BOOST': BoostModal, 'CONFIRM': ConfirmationModal }; class ModalRoot extends React.PureComponent { constructor (props, context) { super(props, context); this.handleKeyUp = this.handleKeyUp.bind(this); } handleKeyUp (e) { if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) && !!this.props.type) { this.props.onClose(); } } componentDidMount () { window.addEventListener('keyup', this.handleKeyUp, false); } componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp); } willEnter () { return { opacity: 0, scale: 0.98 }; } willLeave () { return { opacity: spring(0), scale: spring(0.98) }; } render () { const { type, props, onClose } = this.props; const items = []; if (!!type) { items.push({ key: type, data: { type, props }, style: { opacity: spring(1), scale: spring(1, { stiffness: 120, damping: 14 }) } }); } return ( <TransitionMotion styles={items} willEnter={this.willEnter} willLeave={this.willLeave}> {interpolatedStyles => <div className='modal-root'> {interpolatedStyles.map(({ key, data: { type, props }, style }) => { const SpecificComponent = MODAL_COMPONENTS[type]; return ( <div key={key}> <div role='presentation' className='modal-root__overlay' style={{ opacity: style.opacity }} onClick={onClose} /> <div className='modal-root__container' style={{ opacity: style.opacity, transform: `translateZ(0px) scale(${style.scale})` }}> <SpecificComponent {...props} onClose={onClose} /> </div> </div> ); })} </div> } </TransitionMotion> ); } } ModalRoot.propTypes = { type: PropTypes.string, props: PropTypes.object, onClose: PropTypes.func.isRequired }; export default ModalRoot;
pootle/static/js/admin/components/ItemDelete.js
phlax/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import React from 'react'; const ItemDelete = React.createClass({ propTypes: { item: React.PropTypes.object.isRequired, helpText: React.PropTypes.string, onDelete: React.PropTypes.func.isRequired, }, /* Lifecycle */ getInitialState() { return { buttonDisabled: true, }; }, /* Handlers */ toggleButton() { this.setState({ buttonDisabled: !this.state.buttonDisabled }); }, handleClick(e) { e.preventDefault(); this.props.item.destroy().then(this.props.onDelete); }, render() { return ( <div className="item-delete"> <input type="checkbox" checked={!this.state.buttonDisabled} onChange={this.toggleButton} /> <button className="btn btn-danger" disabled={this.state.buttonDisabled} onClick={this.handleClick} >{gettext('Delete')}</button> {this.props.helpText && <span className="helptext">{this.props.helpText}</span>} </div> ); }, }); export default ItemDelete;
src/parser/monk/windwalker/modules/spells/azeritetraits/SwiftRoundhouse.js
FaideWW/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; class SwiftRoundhouse extends Analyzer { totalStacks = 0; stacksUsed = 0; currentStacks = 0; stacksWasted = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.SWIFT_ROUNDHOUSE.id); } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId === SPELLS.SWIFT_ROUNDHOUSE_BUFF.id) { this.totalStacks += 1; this.currentStacks += 1; } } on_byPlayer_applybuffstack(event) { const spellId = event.ability.guid; if (spellId === SPELLS.SWIFT_ROUNDHOUSE_BUFF.id) { this.totalStacks += 1; this.currentStacks += 1; } } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId === SPELLS.BLACKOUT_KICK.id && this.currentStacks === 2) { this.totalStacks += 1; this.stacksWasted += 1; } else if (spellId === SPELLS.RISING_SUN_KICK.id) { this.stacksUsed += this.currentStacks; this.currentStacks = 0; } } on_byPlayer_removebuff(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.SWIFT_ROUNDHOUSE_BUFF) { return; } /** this.currentStacks is set to 0 when the stacks are consumed with Rising Sun Kick which happens before the removebuff event is triggered * this allows us to easily check whether the buff was removed by using Rising Sun Kick or by expiring */ if (this.currentStacks === 0) { this.stacksWasted += this.currentStacks; } this.currentStacks = 0; } get stackEfficiencyPercentage() { return this.stacksUsed / this.totalStacks; } statistic() { return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.SWIFT_ROUNDHOUSE.id} value={`${formatPercentage(this.stackEfficiencyPercentage)}% stacks used`} tooltip={`You wasted ${this.stacksWasted} stacks by letting them expire or by using Blackout Kick while you already had 2 stacks of Swift Roundhouse`} /> ); } } export default SwiftRoundhouse;
YEAR 3/SEM 1/MOBILE/non-native/PhotoReact/screens/HomeScreen.js
Zephyrrus/ubb
import React from 'react'; import { Image, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View, } from 'react-native'; import { WebBrowser } from 'expo'; import { MonoText } from '../components/StyledText'; export default class HomeScreen extends React.Component { render() { return ( <View style={styles.container}> <ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}> <View style={styles.welcomeContainer}> <Image source={ __DEV__ ? require('../assets/images/robot-dev.png') : require('../assets/images/robot-prod.png') } style={styles.welcomeImage} /> </View> <View style={styles.getStartedContainer}> {this._maybeRenderDevelopmentModeWarning()} <Text style={styles.getStartedText}>Get started by opening</Text> <View style={[styles.codeHighlightContainer, styles.homeScreenFilename]}> <MonoText style={styles.codeHighlightText}>screens/HomeScreen.js</MonoText> </View> <Text style={styles.getStartedText}> Change this text and your app will automatically reload. </Text> </View> <View style={styles.helpContainer}> <TouchableOpacity onPress={this._handleHelpPress} style={styles.helpLink}> <Text style={styles.helpLinkText}>Help, it didn’t automatically reload!</Text> </TouchableOpacity> </View> </ScrollView> <View style={styles.tabBarInfoContainer}> <Text style={styles.tabBarInfoText}>This is a tab bar. You can edit it in:</Text> <View style={[styles.codeHighlightContainer, styles.navigationFilename]}> <MonoText style={styles.codeHighlightText}>navigation/MainTabNavigator.js</MonoText> </View> </View> </View> ); } _maybeRenderDevelopmentModeWarning() { if (__DEV__) { const learnMoreButton = ( <Text onPress={this._handleLearnMorePress} style={styles.helpLinkText}> Learn more </Text> ); return ( <Text style={styles.developmentModeText}> Development mode is enabled, your app will be slower but you can use useful development tools. {learnMoreButton} </Text> ); } else { return ( <Text style={styles.developmentModeText}> You are not in development mode, your app will run at full speed. </Text> ); } } _handleLearnMorePress = () => { WebBrowser.openBrowserAsync('https://docs.expo.io/versions/latest/guides/development-mode'); }; _handleHelpPress = () => { WebBrowser.openBrowserAsync( 'https://docs.expo.io/versions/latest/guides/up-and-running.html#can-t-see-your-changes' ); }; } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', }, developmentModeText: { marginBottom: 20, color: 'rgba(0,0,0,0.4)', fontSize: 14, lineHeight: 19, textAlign: 'center', }, contentContainer: { paddingTop: 30, }, welcomeContainer: { alignItems: 'center', marginTop: 10, marginBottom: 20, }, welcomeImage: { width: 100, height: 80, resizeMode: 'contain', marginTop: 3, marginLeft: -10, }, getStartedContainer: { alignItems: 'center', marginHorizontal: 50, }, homeScreenFilename: { marginVertical: 7, }, codeHighlightText: { color: 'rgba(96,100,109, 0.8)', }, codeHighlightContainer: { backgroundColor: 'rgba(0,0,0,0.05)', borderRadius: 3, paddingHorizontal: 4, }, getStartedText: { fontSize: 17, color: 'rgba(96,100,109, 1)', lineHeight: 24, textAlign: 'center', }, tabBarInfoContainer: { position: 'absolute', bottom: 0, left: 0, right: 0, ...Platform.select({ ios: { shadowColor: 'black', shadowOffset: { height: -3 }, shadowOpacity: 0.1, shadowRadius: 3, }, android: { elevation: 20, }, }), alignItems: 'center', backgroundColor: '#fbfbfb', paddingVertical: 20, }, tabBarInfoText: { fontSize: 17, color: 'rgba(96,100,109, 1)', textAlign: 'center', }, navigationFilename: { marginTop: 5, }, helpContainer: { marginTop: 15, alignItems: 'center', }, helpLink: { paddingVertical: 15, }, helpLinkText: { fontSize: 14, color: '#2e78b7', }, });
src/components/DataTable/AnimTableBody.js
IssaTan1990/antd-admin
import React from 'react' import PropTypes from 'prop-types' import { TweenOneGroup } from 'rc-tween-one' const enterAnim = [ { opacity: 0, x: 30, backgroundColor: '#fffeee', duration: 0, }, { height: 0, duration: 200, type: 'from', delay: 250, ease: 'easeOutQuad', onComplete: (e) => { e.target.style.height = 'auto' }, }, { opacity: 1, x: 0, duration: 250, ease: 'easeOutQuad', }, { delay: 1000, backgroundColor: '#fff', }, ] const leaveAnim = [ { duration: 250, x: -30, opacity: 0, }, { height: 0, duration: 200, ease: 'easeOutQuad', }, ] const AnimTableBody = ({ body, page = 1, current }) => { if (current !== +page) { return body } return ( <TweenOneGroup component="tbody" className={body.props.className} enter={enterAnim} leave={leaveAnim} appear={false} > {body.props.children} </TweenOneGroup> ) } AnimTableBody.propTypes = { body: PropTypes.element, page: PropTypes.any, current: PropTypes.number.isRequired, } export default AnimTableBody
src/pages/404.js
sqrthree/MyBlog
import React from 'react' import Link from 'gatsby-link' export default () => ( <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, zIndex: 1, background: '#fff', }} > <div style={{ position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, width: '960px', height: '360px', margin: 'auto', background: 'url(/404.svg) no-repeat center left', }} > <div style={{ float: 'right', width: '40%', paddingTop: '60px', }} > <h2 style={{ fontSize: '72px', color: '#434e59', }} > 404 </h2> <p style={{ marginBottom: '16px', color: '#00000073', fontSize: '20px', lineHeight: '28px', }} > 抱歉,你访问的页面暂不存在 </p> <div> <Link to="/">查看其它文章</Link> </div> </div> </div> </div> )
newclient/scripts/components/user/travel-log/travel-log/index.js
kuali/research-coi
/* The Conflict of Interest (COI) module of Kuali Research Copyright © 2005-2016 Kuali, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ import styles from './style'; import React from 'react'; import {AppHeader} from '../../../app-header'; import {TravelLogHeader} from '../travel-log-header'; import TravelLogForm from '../travel-log-form'; import TravelLogSort from '../travel-log-sort'; import {BackToDashBoardButton} from '../back-to-dash-board-button'; import {TravelLogStore} from '../../../../stores/travel-log-store'; import {TravelLogActions} from '../../../../actions/travel-log-actions'; import Entry from '../entry'; export default class TravelLog extends React.Component { constructor() { super(); const storeState = TravelLogStore.getState(); this.state = { entries: storeState.entries, potentialEntry: storeState.potentialEntry, validating: storeState.validating, entryStates: storeState.entryStates }; this.onChange = this.onChange.bind(this); } componentDidMount() { TravelLogStore.listen(this.onChange); TravelLogActions.loadTravelLogEntries(); } componentWillUnmount() { TravelLogStore.unlisten(this.onChange); } onChange() { const storeState = TravelLogStore.getState(); this.setState({ entries: storeState.entries, potentialEntry: storeState.potentialEntry, validating: storeState.validating, entryStates: storeState.entryStates }); } render() { let travelLogs; if (this.state.entries.length > 0) { travelLogs = this.state.entries.map(travelLog => { return ( <Entry key={travelLog.relationshipId} travelLog={travelLog} editing={this.state.entryStates[travelLog.relationshipId] ? this.state.entryStates[travelLog.relationshipId].editing : false} validating={this.state.entryStates[travelLog.relationshipId] ? this.state.entryStates[travelLog.relationshipId].validating : false} /> ); }); } return ( <div className={'flexbox column'} style={{height: '100%'}} name='Travel Log'> <AppHeader className={`${styles.override} ${styles.header}`} moduleName={'Conflict Of Interest'} /> <span className={`flexbox row fill ${styles.container}`}> <span className={styles.sidebar}> <BackToDashBoardButton /> </span> <span className={`fill ${styles.content}`}> <TravelLogHeader /> <TravelLogForm entry={this.state.potentialEntry} validating={this.state.validating} /> <div className={styles.entryList}> <TravelLogSort /> {travelLogs} </div> </span> </span> </div> ); } }
app/components/Left/Title.js
SpotifiyOrganization/spotifyHack
import React from 'react'; import { Row, Col } from 'react-materialize'; const Title = () => { return ( <div> <Row style={{marginTop: '20px'}}> <Col s={12} style={{margin: 'auto', textAlign: 'center'}}> <h style={{color: 'white', fontSize: '30px'}}>Song It</h> </Col> </Row> <Row> <Col s={12} style={{margin: 'auto', textAlign: 'center'}}> <h style={{color: 'white'}}>The Song of any Site</h> </Col> </Row> <Row style={{marginTop: '40px', marginBottom: '40px'}}> <Col s={12} style={{margin: 'auto', textAlign: 'center'}}> <img style={{border: '5px solid white', borderRadius: '50%', height: '200px', width: '200px'}} src="https://image.shutterstock.com/z/stock-vector-bob-dylan-cartoon-playing-guitar-black-and-white-cartoon-january-548619394.jpg" /> </Col> </Row> </div> ); } export default Title;
src/client/assets/js/features/help/components/Schema/Schema.js
me-box/platform-sdk
import React, { Component } from 'react'; const _oneof = function(schema, id, selectedid){ return schema.map((item, i)=>{ let tail = null; if (item.type === "object"){ if (item.properties){ tail = _oneofpayload(item, id, selectedid) } } else if (item.type === "oneof"){ if (item.oneOf){ tail = _oneof(item.oneOf, id, selectedid) } } else{ //perhaps have a different format primitive for oneof items? const style = { background: '#2196F3', border: 'none', color: 'white', fontWeight: 'normal' } tail = _formatprimitive(item,`if ${item.key}=${item.value}`,id,selectedid, style); } return <div key={i}> <div className="flexcolumn"> <div> <div className="flexcolumn"> {tail} </div> </div> </div> </div> }); }; const _formatprimitive = function(item,key,id,selectedid, attributestyle={}){ return <div key={key}> <div className="flexrow"> <div className="attributetitle" style={attributestyle}> <div className="centered"> <strong>{key}</strong> </div> </div> <div className="fixed" style={{borderRight: '1px solid #b6b6b6', width:100}}> <div className="centered"> {item.type} </div> </div> <div style={{borderRight: '1px solid #b6b6b6'}}> <div className="schemadescription"> <div dangerouslySetInnerHTML={{__html: (item.description || "").replace("[id]", id).replace("[selectedid]", selectedid)}}></div> </div> </div> </div> </div> } const _formatobject = function(item,key,id,selectedid){ return <div key={key}> <div className="flexrow"> <div className="attributetitle"> <div className="centered"> <strong>{key}</strong> </div> </div> <div className="fixed" style={{borderRight: '1px solid #b6b6b6', width:100}}> <div className="centered"> {item.type} </div> </div> <div> <div className="flexcolumn"> {item.properties ? _payload(item.properties, id, selectedid) : null} {item.oneOf ? _oneof(item.oneOf, id, selectedid): null} </div> </div> </div> </div> } const _oneofpayload = function(item, id, selectedid){ const schema = item.properties; if (!schema) return null; const items = Object.keys(schema).map((key,i)=>{ const item = schema[key]; if (item.type === "object" || item.type=="oneof"){ return _formatobject(item,key,id, selectedid); } return _formatprimitive(item,key,id, selectedid); }); return <div className="flexcolumn"> <div className="objectoneoftitle"> <div className="centered"> {`if ${item.key}=${item.value}`} </div> </div> {items} </div> }; const _payload = function(schema, id, selectedid){ if (!schema) return null; return Object.keys(schema).map((key,i)=>{ const item = schema[key]; if (item.type === "object" || item.type=="oneof"){ return _formatobject(item,key,id, selectedid); } return _formatprimitive(item,key,id, selectedid); }); }; export default class Schema extends Component { render(){ const {schema=null, id="", selectedid=""} = this.props; if (!schema || (Object.keys(schema).length === 0 && schema.constructor === Object)) return null; const payload = schema.type === "object" ? _payload(schema.properties, id, selectedid) : _formatprimitive(schema,"",id, selectedid); return <div key={this.props.id} className="flexcolumn schema"> <div className="noborder"> <div className="flexrow"> <div> <div className="flexcolumn"> <div> <div className="flexrow"> <div className="headertitle"> <div className="centered"> attribute name </div> </div> <div className="header fixed" style={{width:100}}> <div className="centered"> attribute type </div> </div> <div className="header"> <div className="centered"> description </div> </div> </div> </div> {payload} </div> </div> </div> </div> </div> } }
app/react-icons/fa/twitch.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaTwitch extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m20 9.7v9.7h-3.2v-9.7h3.2z m8.9 0v9.7h-3.3v-9.7h3.3z m0 17l5.6-5.7v-17.8h-26.6v23.4h7.3v4.9l4.8-4.9h8.9z m8.9-26.7v22.6l-9.7 9.7h-7.3l-4.8 4.8h-4.9v-4.8h-8.9v-25.8l2.5-6.5h33.1z"/></g> </IconBase> ); } }
public/js/components/searchButton.js
MelanistOnca/bookList
import React from 'react'; import { render } from 'react-dom'; const rp = require('request-promise'); import axios from 'axios'; // '../../../db/isbndb' // '../../../db/isbndb' // const isbndb_fns = require('../../../db/isbndb'); //pg-native error similar to components/user/login. i'm guessing i can't import stuff from DB directory into public? maybe? ==> DUH. because the db files AREN'T public, therefore stuff in public does not have access to them export default class SearchButton extends React.Component { //NOTE: theoretically, this will receive all the info that the current button in ./components/searchFor uses, as props, and then i can replace that button with this component, but then also re-use this component in the element that lists books by an author so that the user can get the info on whichever specific book there they want the info on. searchClicked(props, e){ // console.log('seachClicked ran in components/searchButton.js '); e.preventDefault(); // console.log(props.selectedSearchType, 'was props.selectedSearchType in searchClicked'); // console.log(props.selectedSearchType[0], 'was props.selectedSearchType[0] in searchClicked'); if(!props.selectedSearchType[0]){ window.alert("Please select a search type before pressing the search button"); return } else if((props.selectedSearchType[0]==="Select")){ window.alert("Please select a search type before pressing the search button"); return } else { //nothing } let searchType = props.selectedSearchType[0].toLowerCase(); let searchTerm = props.searchTerm[0]; // console.log(searchType, 'was searchType in searchClicked() in components/searchButton'); // let forcedSearchType = props.forceSelectedSearchType ; if(props.forceSelectedSearchType) { if(props.selectedSearchType[0]!==props.forceSelectedSearchType){ //NOTE pass and use function here to change search type to get it to display results properly? // console.log(props.newSearchTerm, 'was props.newSearchTerm in second conidtional in searchButton'); props.updateSearchType(props.forceSelectedSearchType) //this works for switching the selector, but the rest of the code go bjorked because its giving me author results when i'm trying to search for the book. i've clicked on. NOTE: should i create a store for "nested author book searches" or something? no->just updating searchTerm and searchType is easier // props.updateSearchTerm(props.searchTerm) //this doesn't work because the search term is remaining the author's name, need to locate the book title and insert that here // let searchType = props.forceSelectedSearchType.toLowerCase(); // let searchTerm = [props.newSearchTerm]; props.updateSearchTerm(props.newSearchTerm) props.resultSearchClicked(props) return } } // searchType = (forcedSearchType||searchType)//NOTE or maybe use that function here instead? // console.log(searchType, 'was searchType in searchClicked() before switch in same'); // console.log(searchTerm, 'was searchTerm in searchClicked() before switch in same'); switch(searchType) { case 'isbn' : searchType = 'book'; // console.log(searchType, 'was searchType in searchClicked() in same'); break; //may need a case to re-define for 'title' case 'title' : searchType = 'book'; // let searchTermTestNoSpace = searchTerm[0].split(' ').join('_') // let dropApostrophe = searchTermTestNoSpace.split("'").join('') // let searchTermTest = searchTerm[0].split(' ').join('_').split("'").join('') // searchTerm[0] = searchTerm[0].split(' ').join('_').split("'").join('') // console.log(searchTermTestNoSpace, 'was searchTermTestNoSpace in case title in searchType switch searchClicked'); // console.log(dropApostrophe, 'was dropApostrophe in case title in searchType switch searchClicked'); // console.log(searchTermTest, 'was searchTermTest in case title in searchType switch searchClicked'); break; default: console.log(searchType, 'was searchType in default case of searchType switch'); } // console.log(searchType, 'was searchType in searchClicked() after switch in same'); // console.log(searchTerm, 'was searchTerm in searchClicked() after switch in same'); // let options = { // "authors" : { // uri: `http://isbndb.com/api/v2/json/${apiKey}/${searchType}`, // qs: { // 'q': `${searchTerm}` // }, // headers: { // 'User-Agent': 'Request-Promise' // }, // json: true // }, // "book": { // uri : `http://isbndb.com/api/v2/json/${apiKey}/book/${searchTerm}`, // headers: { // 'User-Agent': 'Request-Promise' // }, // json: true // } // } // console.log(options, 'was options in searchClicked() in components/searchButton'); let options = { searchTerm, searchType } // console.log(options, 'was options in componets/searchButton', typeof options, 'was typeof options'); // console.log(options.searchType, 'was options.searchType in same'); //returns undefined // console.log(searchType, 'was search type in searchClicked() componenets/searchButton.js'); // console.log(options[searchType], 'was options[searchType] in same'); // console.log(searchTerm, 'was searchTerm in searchClicked() componenets/searchButton.js'); // console.log(options[searchType], 'was options[searchType] before rp() in components/searchFor.js'); //need to see if i can add in a .something so that if a search fails (author?q=scalzi) it tries a more general search, i.e. authorS?q=scalzi /////////////// // console.log('axios.post runs here'); // const request = axios.post('api/isbndb', options) //may need to make the accompanying fields part of a form axios.post('api/isbndb', options) .catch( (err) => { console.log(err,'was err in the .then from the axios.post in searchClicked fn in components/searchButton.js'); }) .then( (data) => { // console.log(data,'was data in the .then from the axios.post in searchClicked fn in components/searchButton.js'); // // console.log(typeof data, 'was typeof in same'); // // console.log(data.data,'was data.data in the .then from the axios.post in searchClicked fn in components/searchButton.js'); // console.log(typeof data.data, 'was typeof in same'); // console.log(data.data.result,'was data.data.result in the .then from the axios.post in searchClicked fn in components/searchButton.js'); //NOTE NOTE TODO: i should probably clean up here so i can remove some of the nesting from the received results? // props.receiveResults(data) // console.log('props.receiveResults(data) invoked above this line'); props.receiveResults(data.data.result) // console.log('props.receiveResults(data.data.result) invoked above this line'); }) // the rp section is moved to db/isbndb.js // rp(options[searchType]) // .then( (res) => { // console.log(res,'was res in components/searchButton.js'); // // // console.log(options[searchType], 'was options[searchType] in .then in componenets/searchFor.js '); // props.receiveResults(res); // }) // .catch( (err) => { // console.log(err, 'was err in components/searchButton.js');//my impression is this will usually be a low-info response. may be confusing this err with CORS errors. // // console.log(options[searchType], 'was options[searchType] in .catch in componenets/searchFor.js'); // }) // isbndb_fns.getResultsFromSearch(options) // console.log('searchClicked reached end of function'); } resultSearchClicked(props){ // let searchType = props.selectedSearchType[0].toLowerCase(); let searchType = props.forceSelectedSearchType.toLowerCase(); let searchTerm = [props.newSearchTerm]; // let searchTerm = props.searchTerm[0]; // let searchTerm = props.searchTerm[0]; // let searchTerm = props.newSearchTerm; // console.log(searchType, 'was searchType in resultSearchClicked() before switch in same'); // console.log(searchTerm, 'was searchTerm'); switch(searchType) { case 'isbn' : searchType = 'book'; // console.log(searchType, 'was searchType in searchClicked() in same'); break; //may need a case to re-define for 'title' case 'title' : searchType = 'book'; break; default: console.log(searchType, 'was searchType in default case of searchType switch'); } let options = { searchTerm, searchType } // console.log(options, 'was options in resultSearchClicked'); console.log('axios.post runs here'); const request = axios.post('api/isbndb', options) //may need to make the accompanying fields part of a form request .catch( (err) => { console.log(err,'was err in the .then from the axios.post in searchClicked fn in components/searchButton.js'); }) .then( (data) => { // console.log(data,'was data in the .then from the axios.post in searchClicked fn in components/searchButton.js'); // // console.log(data.data.result,'was data.data.result in the .then from the axios.post in searchClicked fn in components/searchButton.js'); props.receiveResults(data.data.result) // console.log('props.receiveResults(data.data.result) invoked above this line'); }) } componentWillMount(){ // this.props.updateSearchType(this.props.selectedSearchType[0]) // console.log('theoretically, search type should have updated to ISBN here'); // console.log(this, 'was this in componentWillMount in components/searchButton.js'); } render(){ // console.log(this.props, 'was this.props in components/searchButton render'); // console.log(this.props.selectedSearchType, 'was this.props.selectedSearchType in components/searchButton render'); let searchClickedProps = { "selectedSearchType" : this.props.selectedSearchType, "forceSelectedSearchType" : this.props.forceSelectedSearchType, "searchTerm" : [this.props.searchTerm], "receiveResults" : this.props.receiveResults, "updateSearchType" : this.props.updateSearchType, "updateSearchTerm" : this.props.updateSearchTerm, "resultSearchClicked" : this.resultSearchClicked, "newSearchTerm" : this.props.newSearchTerm // "bufferDeletedBook" : this.props.bufferDeletedBook, // "clearDeletedBook" : this.props.clearDeletedBook } return( <input type="submit" value="Search" onClick={this.searchClicked.bind(this, searchClickedProps)} /> ) } }
src/routes/Reviews/components/CreateReviewBody.js
johnthedesigner/review-ui
//import React, { PropTypes } from 'react' import React from 'react' import { browserHistory } from 'react-router' import { noAuthRedirect } from '../../../utils/utils' import AddReview from './AddReview' class CreateReviewBody extends React.Component { componentWillReceiveProps(nextProps) { noAuthRedirect(nextProps) } componentDidMount() { const { loadThing, params } = this.props loadThing(params.thingId) } render() { let thing = this.props.thing let clickAddReview = this.props.clickAddReview let user = this.props.user return ( <div> <AddReview user={user} thing={thing} thingId={thing.id} clickAddReview={clickAddReview} /> </div> ) } } //ReviewList.propTypes = { // reviews: PropTypes.arrayOf(PropTypes.shape({ // title: PropTypes.string.isRequired // }).isRequired).isRequired //} export default CreateReviewBody
examples/basic-server/src/server.js
jaredpalmer/razzle
import App from './App'; import React from 'react'; import express from 'express'; import { renderToString } from 'react-dom/server'; export const renderApp = (req, res) => { const markup = renderToString(<App />); const html = // prettier-ignore `<!doctype html> <html lang=""> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charSet='utf-8' /> <title>Welcome to Razzle</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div id="root">${markup}</div> </body> </html>`; return { html }; }; const server = express(); server .disable('x-powered-by') .use(express.static(process.env.RAZZLE_PUBLIC_DIR)) .get('/*', (req, res) => { const { html } = renderApp(req, res); res.send(html); }); export default server;
test/TabSpec.js
deerawan/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Tab from '../src/Tab'; describe('Tab', function () { it('Should have class', function () { let instance = ReactTestUtils.renderIntoDocument( <Tab>Item content</Tab> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab-pane')); }); it('Should add active class', function () { let instance = ReactTestUtils.renderIntoDocument( <Tab active={true}>Item content</Tab> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'active')); }); describe('Web Accessibility', function() { it('Should have aria-hidden', function () { let instance = ReactTestUtils.renderIntoDocument( <Tab active>Item content</Tab> ); assert.equal(React.findDOMNode(instance).getAttribute('aria-hidden'), 'false'); }); it('Should have role', function () { let instance = ReactTestUtils.renderIntoDocument( <Tab active>Item content</Tab> ); assert.equal(React.findDOMNode(instance).getAttribute('role'), 'tabpanel'); }); }); });
src/svg-icons/editor/format-line-spacing.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatLineSpacing = (props) => ( <SvgIcon {...props}> <path d="M6 7h2.5L5 3.5 1.5 7H4v10H1.5L5 20.5 8.5 17H6V7zm4-2v2h12V5H10zm0 14h12v-2H10v2zm0-6h12v-2H10v2z"/> </SvgIcon> ); EditorFormatLineSpacing = pure(EditorFormatLineSpacing); EditorFormatLineSpacing.displayName = 'EditorFormatLineSpacing'; EditorFormatLineSpacing.muiName = 'SvgIcon'; export default EditorFormatLineSpacing;
kit/entry/browser.js
MoosemanStudios/app.moosecraft.us
// Browser entry point, for Webpack. We'll grab the browser-flavoured // versions of React mounting, routing etc to hook into the DOM // ---------------------- // IMPORTS /* NPM */ // Enable async/await and generators, cross-browser import 'regenerator-runtime/runtime'; // Patch global.`fetch` so that Apollo calls to GraphQL work import 'isomorphic-fetch'; // React parts import React from 'react'; import ReactDOM from 'react-dom'; // Browser routing import { BrowserRouter } from 'react-router-dom'; // Apollo Provider. This HOC will 'wrap' our React component chain // and handle injecting data down to any listening component import { ApolloProvider } from 'react-apollo'; /* ReactQL */ // Root component. This is our 'entrypoint' into the app. If you're using // the ReactQL starter kit for the first time, `src/app.js` is where // you can start editing to add your own code. Note: This first is imported // first, since it sets up our app's settings import App from 'src/app'; // Grab the shared Apollo Client import { browserClient } from 'kit/lib/apollo'; // Custom redux store creator. This will allow us to create a store 'outside' // of Apollo, so we can apply our own reducers and make use of the Redux dev // tools in the browser import createNewStore from 'kit/lib/redux'; // ---------------------- // Create a new browser Apollo client const client = browserClient(); // Create a new Redux store const store = createNewStore(client); // Create the 'root' entry point into the app. If we have React hot loading // (i.e. if we're in development), then we'll wrap the whole thing in an // <AppContainer>. Otherwise, we'll jump straight to the browser router function doRender() { ReactDOM.hydrate( <Root />, document.getElementById('main'), ); } // The <Root> component. We'll run this as a self-contained function since // we're using a bunch of temporary vars that we can safely discard. // // If we have hot reloading enabled (i.e. if we're in development), then // we'll wrap the whole thing in <AppContainer> so that our views can respond // to code changes as needed const Root = (() => { // Wrap the component hierarchy in <BrowserRouter>, so that our children // can respond to route changes const Chain = () => ( <ApolloProvider store={store} client={client}> <BrowserRouter> <App /> </BrowserRouter> </ApolloProvider> ); // React hot reloading -- only enabled in development. This branch will // be shook from production, so we can run a `require` statement here // without fear that it'll inflate the bundle size if (module.hot) { // <AppContainer> will respond to our Hot Module Reload (HMR) changes // back from WebPack, and handle re-rendering the chain as needed const AppContainer = require('react-hot-loader').AppContainer; // Start our 'listener' at the root component, so that any changes that // occur in the hierarchy can be captured module.hot.accept('src/app', () => { // Refresh the entry point of our app, to get the changes. // eslint-disable-next-line require('src/app').default; // Re-render the hierarchy doRender(); }); return () => ( <AppContainer> <Chain /> </AppContainer> ); } return Chain; })(); doRender();
classic/src/scenes/wbui/ACAvatarCircle2/ACAvatarCircle2Background.js
wavebox/waveboxapp
import React from 'react' import PropTypes from 'prop-types' import shallowCompare from 'react-addons-shallow-compare' import { withStyles } from '@material-ui/core/styles' import classNames from 'classnames' const styles = { root: { position: 'absolute', top: 1, left: 1, right: 1, bottom: 1, backgroundColor: '#FFF', borderRadius: '50%' }, rootXS: { top: 0, left: 0, bottom: 0, right: 0 }, restricted: { filter: 'grayscale(100%)' }, sleeping: { filter: 'grayscale(100%)' } } @withStyles(styles) class ACAvatarCircle2Background extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { backgroundColor: PropTypes.string, size: PropTypes.number.isRequired, showSleeping: PropTypes.bool.isRequired, showRestricted: PropTypes.bool.isRequired } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } render () { const { backgroundColor, className, style, classes, showSleeping, showRestricted, size, ...passProps } = this.props return ( <div className={classNames( classes.root, className, size < 30 ? classes.rootXS : undefined, showSleeping ? classes.sleeping : undefined, showRestricted ? classes.restricted : undefined )} style={{ backgroundColor: backgroundColor, ...style }} {...passProps} /> ) } } export default ACAvatarCircle2Background
fusion/Avatar.js
pagesource/fusion
import { css } from 'emotion'; import React from 'react'; import { withTheme } from 'theming'; import PropTypes from 'prop-types'; const avatarStyle = css` width: 96px; height: 96px; border-radius: 50%; `; const Avatar = ({ src, alt }) => ( <img src={src} className={avatarStyle} alt={alt} /> ); Avatar.propTypes = { src: PropTypes.string, alt: PropTypes.string, }; /* Default Props */ Avatar.defaultProps = { src: 'http://www.spaceandmotion.com/Images/albert-einstein-theory-general-relativity.jpg', alt: 'Avatar Image', }; export default withTheme(Avatar);
docs/app/Examples/elements/Rail/Variations/RailExampleClose.js
shengnian/shengnian-ui-react
import React from 'react' import { Grid, Image, Rail, Segment } from 'shengnian-ui-react' const RailExampleClose = () => ( <Grid centered columns={3}> <Grid.Column> <Segment> <Image src='/assets/images/wireframe/paragraph.png' /> <Rail close position='left'> <Segment>Left Rail Content</Segment> </Rail> <Rail close position='right'> <Segment>Right Rail Content</Segment> </Rail> </Segment> </Grid.Column> </Grid> ) export default RailExampleClose
src/svg-icons/action/launch.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLaunch = (props) => ( <SvgIcon {...props}> <path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/> </SvgIcon> ); ActionLaunch = pure(ActionLaunch); ActionLaunch.displayName = 'ActionLaunch'; export default ActionLaunch;
DemoApp/src/containers/all-components.js
andyfen/react-native-UIKit
import React, { Component } from 'react'; import { StyleSheet, Text, View, ScrollView } from 'react-native'; import { AlertMessage, ArticleText, ArticleList, Avatar, AvatarHeader, Button, ButtonOutline, Card, Carousel, Close, DateItem, Divider, FieldError, Grid, GalleryOffset, Heading, ImageCustom, InputField, LikeBtn, ListBasic, LoginForm, Message, ProfileHeader, MessageList, RatingBox, ReviewCell, ThumbSwiper, Time } from '../../lib' /* import { AlertMessage, ArticleText, ArticleList, Avatar, AvatarHeader, Button, ButtonOutline, Card, Carousel, Close, DateItem, Divider, FieldError, Grid, GalleryOffset, Heading, ImageCustom, InputField, LikeBtn, ListBasic, LoginForm, Message, ProfileHeader, MessageList, RatingBox, ReviewCell, ThumbSwiper, Time } from 'react-native-uikit'; */ const AllComponents = () => ( <ScrollView style={{flex:1}}> <AlertMessage message={'This is the alert message here'} onPress={() => console.log('pressed')} /> <ArticleText username={'username'} text={'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'} onPress={() => console.log('pressed')} /> <ArticleList headerContent={<Text style={{textAlign:'center', fontSize: 20, padding: 10, backgroundColor: '#eee', marginBottom: 3}}>HEADER CONTENT</Text>} items={[ {id:0, category:'Misc', timestamp: 1463338637801, title:'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', src:'https://placehold.it/200/798466'}, {id:1, category:'Misc', timestamp: 1463338637801, title:'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', src:'https://placehold.it/200/311112'}, {id:2, category:'Misc', timestamp: 1463338637801, title:'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', src:'https://placehold.it/200/D4BB69'}, {id:3, category:'Misc', timestamp: 1463338637801, title:'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', src:'https://placehold.it/200/ABB2B8'}, {id:4, category:'Misc', timestamp: 1463338637801, title:'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', src:'https://placehold.it/200/798466'}, {id:5, category:'Misc', timestamp: 1463338637801, title:'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', src:'https://placehold.it/200/919888'}, ]} footerContent={<Text style={{textAlign:'center', fontSize: 20, padding: 10, backgroundColor: '#eee'}}>FOOTER CONTENT</Text>} onPress={(id) => console.log(id)} /> <Avatar src={'https://s3.amazonaws.com/uifaces/faces/twitter/evagiselle/128.jpg'} size={40} circle={true} onPress={() => console.log('pressed')} /> <View> <AvatarHeader src={'https://s3.amazonaws.com/uifaces/faces/twitter/evagiselle/128.jpg'} heading={'Lynsey Smith'} timestamp={1460227647478} circle={true} backgroundColor={'#fff'} height={40} gutter={10} /> </View> <Button color={'#fff'} backgroundColor={'#0094EA'} radius={5}> Submit </Button> <ButtonOutline color={'#222'} borderWidth={4} fontWeight={'bold'} fontSize={19} radius={1}> Submit </ButtonOutline> <Card onPress={() => console.log('card pressed')} src={'https://s-media-cache-ak0.pinimg.com/736x/5f/70/41/5f704159cdf6512cf21000ec4827fc03.jpg'} title={'Card title - Some quick example text to build on the card title and make up the bulk of the card'} link={'www.example.com'} radius={5} marginBottom={30} /> <View> <Carousel images={[ {id:0, src:'https://placehold.it/600/311112'}, {id:1, src:'https://placehold.it/600/59C480'}, {id:2, src:'https://placehold.it/600/546C80'}, {id:3, src:'https://placehold.it/600/D58554'}, {id:4, src:'https://placehold.it/600/F0CD9B'}, {id:5, src:'https://placehold.it/600/311112'}, ]} height={300} /> </View> <Close size={50} color={'#222'} onPress={() => console.log('closed')} /> <DateItem timestamp={1460227647478} color={'#222'} marginLeft={10} /> <Divider color={'#eee'} /> <FieldError errorMsg={'error something has gone wrong!'} error={true} color={'red'} marginBottom={40} /> <View> <Grid headerContent={<Text style={{textAlign:'center', fontSize: 20, padding: 10, backgroundColor: '#eee', marginBottom: 3}}>HEADER CONTENT</Text>} images={[ {id:0, src:'https://placehold.it/200/798466'}, {id:1, src:'https://placehold.it/200/311112'}, {id:2, src:'https://placehold.it/200/ABB2B8'}, {id:3, src:'https://placehold.it/200/D4BB69'}, {id:4, src:'https://placehold.it/200/798466'}, {id:5, src:'https://placehold.it/200/919888'}, {id:6, src:'https://placehold.it/200/ABB2B8'}, {id:7, src:'https://placehold.it/200/919888'}, {id:8, src:'https://placehold.it/200/A9C781'}, {id:9, src:'https://placehold.it/200/311112'}, ]} footerContent={<Text style={{textAlign:'center', fontSize: 20, padding: 10, backgroundColor: '#eee'}}>FOOTER CONTENT</Text>} onPress={(id) => console.log(id)} itemsPerRow={3} spacing={2} /> </View> <GalleryOffset imagesArray={[ 'http://2.bp.blogspot.com/-QnUrv6hrusQ/UTuCbLI45xI/AAAAAAAAvEo/REbD2Sp3r84/s1600/benoit-paille1.jpg', 'http://justsomething.co/wp-content/uploads/2013/09/black-and-white-photography-benoit-courti-1.jpg', 'http://i.imgur.com/YaQDc.jpg?1', 'http://farm4.staticflickr.com/3284/3032859171_9a71ea30c1_z.jpg', 'http://livefastmag.com/wp-content/uploads/2011/10/1499c4834a64469dd570a47a08d503d2.jpg', 'http://41.media.tumblr.com/7fcdee1b773bda7859eee69d2eb1e0f8/tumblr_nfvzenuIqW1tof0p4o1_1280.jpg', ]} display={'row'} /> <ImageCustom src={'https://s-media-cache-ak0.pinimg.com/736x/9c/11/d8/9c11d813826489f82b3f4c02a06ea815.jpg'} height={300} overlayColor={'#222'} overlayOpacity={0.8} fullHeight={true} > <View style={{flex:1, justifyContent:'center'}}> <Text style={{color:'#fff', backgroundColor:'transparent',fontSize:90, fontWeight: '100', textAlign:'center'}}>YES HELLO</Text> </View> </ImageCustom> <InputField placeHolder={'i am the placeholder txt'} gutter={10} color={'#222'} backgroundColor={'#eee'} radius={5} /> <LikeBtn active={true} likes={322} //color={'#fa0008'} onPress={() => console.log('liked')} /> <ListBasic headerContent={<Text style={{textAlign:'center', fontSize: 20, padding: 10, backgroundColor: '#eee', marginBottom: 3}}>HEADER CONTENT</Text>} items={[ {id: 0, title:'Label'}, {id: 1, title:'Label'}, {id: 2, title:'Label'}, {id: 3, title:'Label'} ]} footerContent={<Text style={{textAlign:'center', fontSize: 20, padding: 10, backgroundColor: '#eee'}}>FOOTER CONTENT</Text>} onPress={(i) => console.log(id)} /> <LoginForm loginFb={() => console.log('login with facebook')} onSubmit={(email, password) => console.log(email, password)} error={false} errorMsg={'username or password incorrect'} /> <Message active={true} user={'Jon Snow'} title={'Winter is Coming'} message={'Hey Rob, have you seen the weather report on tv ?'} timestamp={1460227614421} /> <MessageList headerContent={<Text style={{textAlign:'center', fontSize: 20, padding: 10, backgroundColor: '#eee', marginBottom: 3}}>HEADER CONTENT</Text>} items={[ {id:0, active:false, user: 'Jon Snow', title: 'Winter is Coming', message: 'Hey Rob, have you seen the weather report on tv ?', timestamp: 1460223614421}, {id:1, active:true, user: 'Ric Lowe', title: 'Guess what I found?', message: 'Hey Rob, checkout this story ?', timestamp: 1460221614421}, {id:2, active:true ,user: 'Jon Snow', title: 'title 3', message: 'Hey Rob, have you seen the weather report on tv ?', timestamp: 1460227614421}, ]} footerContent={<Text style={{textAlign:'center', fontSize: 20, padding: 10, backgroundColor: '#eee'}}>FOOTER CONTENT</Text>} onPress={(id) => console.log(id)} /> <ProfileHeader profileImg={'https://s3.amazonaws.com/uifaces/faces/twitter/evagiselle/128.jpg'} backgroundImg={'http://petapixel.com/assets/uploads/2014/05/ae5a74db2757e40b78ad13eb119a9224.jpg'} /> <RatingBox rating={4} outOf={5}/> <View> <ReviewCell title={'Gaucho'} description={'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore'} src={'https://lh5.googleusercontent.com/proxy/lvLgnhcoHke5BEhTG-bVydssje9jV_GytcBidVZh4ADXEuiybVwXN4mlIbgxxOKn2pF1uharMho8lAqGSXcMGKJMigr42UH_qZ1THp4bZplV7uyThhmwEtq38oAhKW7V5Y_6j46jAEkxkrewm9wrd_T4K2JBUw8=w271-h180'} onPress={() => console.log('pressed')} rating={4} outOf={5} /> </View> <View> <ThumbSwiper images={[ {id:0, src:'https://placehold.it/200/798466'}, {id:1, src:'https://placehold.it/200/311112'}, {id:2, src:'https://placehold.it/200/ABB2B8'}, {id:3, src:'https://placehold.it/200/D4BB69'}, {id:4, src:'https://placehold.it/200/798466'}, {id:5, src:'https://placehold.it/200/919888'}, {id:6, src:'https://placehold.it/200/ABB2B8'}, {id:7, src:'https://placehold.it/200/919888'}, {id:8, src:'https://placehold.it/200/A9C781'}, {id:9, src:'https://placehold.it/200/311112'}, ]} onPress={(id) => console.log(id)} /> </View> <Time timestamp={1460227647478} color={'#222'} /> </ScrollView> ) export default AllComponents;
node_modules/react-bootstrap/es/Popover.js
Technaesthetic/ua-tools
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import isRequiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: isRequiredForA11y(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number])), /** * Sets the direction the Popover is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "top" position value for the Popover. */ positionTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Popover. */ positionLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]), /** * Title content */ title: React.PropTypes.node }; var defaultProps = { placement: 'right' }; var Popover = function (_React$Component) { _inherits(Popover, _React$Component); function Popover() { _classCallCheck(this, Popover); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Popover.prototype.render = function render() { var _extends2; var _props = this.props, placement = _props.placement, positionTop = _props.positionTop, positionLeft = _props.positionLeft, arrowOffsetTop = _props.arrowOffsetTop, arrowOffsetLeft = _props.arrowOffsetLeft, title = _props.title, className = _props.className, style = _props.style, children = _props.children, props = _objectWithoutProperties(_props, ['placement', 'positionTop', 'positionLeft', 'arrowOffsetTop', 'arrowOffsetLeft', 'title', 'className', 'style', 'children']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[placement] = true, _extends2)); var outerStyle = _extends({ display: 'block', top: positionTop, left: positionLeft }, style); var arrowStyle = { top: arrowOffsetTop, left: arrowOffsetLeft }; return React.createElement( 'div', _extends({}, elementProps, { role: 'tooltip', className: classNames(className, classes), style: outerStyle }), React.createElement('div', { className: 'arrow', style: arrowStyle }), title && React.createElement( 'h3', { className: prefix(bsProps, 'title') }, title ), React.createElement( 'div', { className: prefix(bsProps, 'content') }, children ) ); }; return Popover; }(React.Component); Popover.propTypes = propTypes; Popover.defaultProps = defaultProps; export default bsClass('popover', Popover);