path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
es/utils/react-if.js
cvdlab/react-planner
import React from 'react'; import PropTypes from 'prop-types'; /** * @return {null} */ export default function If(_ref) { var condition = _ref.condition, style = _ref.style, children = _ref.children; return condition ? Array.isArray(children) ? React.createElement( 'div', { style: style }, children ) : children : null; } If.propTypes = { condition: PropTypes.bool.isRequired, style: PropTypes.object };
app/javascript/mastodon/features/ui/components/column_subheading.js
tootcafe/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const ColumnSubheading = ({ text }) => { return ( <div className='column-subheading'> {text} </div> ); }; ColumnSubheading.propTypes = { text: PropTypes.string.isRequired, }; export default ColumnSubheading;
src/Parser/DemonHunter/Havoc/Modules/Spells/Momentum.js
hasseboulen/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatPercentage, formatDuration } from 'common/format'; import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox'; class Momentum extends Analyzer { static dependencies = { combatants: Combatants, }; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.MOMENTUM_TALENT.id); } statistic() { const momentumUptime = this.combatants.selected.getBuffUptime(SPELLS.MOMENTUM_TALENT.id); const momentumUptimePercentage = momentumUptime / this.owner.fightDuration; return ( <StatisticBox icon={<SpellIcon id={SPELLS.MOMENTUM_TALENT.id} />} value={`${formatPercentage(momentumUptimePercentage)}%`} label="Momentum Uptime" tooltip={`The Momentum buff total uptime was ${formatDuration(momentumUptime / 1000)}.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(3); } export default Momentum;
docs/app/Examples/collections/Message/Variations/MessageExampleNegative.js
shengnian/shengnian-ui-react
import React from 'react' import { Message } from 'shengnian-ui-react' const MessageExampleNegative = () => ( <Message negative> <Message.Header>We're sorry we can't apply that discount</Message.Header> <p>That offer has expired</p> </Message> ) export default MessageExampleNegative
examples/cra-kitchen-sink/src/stories/force-rerender.stories.js
storybooks/storybook
import React from 'react'; import { forceReRender } from '@storybook/react'; import { Button } from '@storybook/react/demo'; let count = 0; const increment = () => { count += 1; forceReRender(); }; export default { title: 'Force ReRender', }; export const DefaultView = () => ( <Button type="button" onClick={increment}> Click me to increment: {count} </Button> );
src/components/input/autocomplete-text/consult.js
KleeGroup/focus-components
import React from 'react'; function AutocompleteTextConsult({ label, name, type, value }) { return ( <div label={label} name={name} type={type}> {value} </div> ); } export default AutocompleteTextConsult;
src/js/components/postList.js
blaketarter/react-lobsters
import React from 'react'; import Post from './post'; export default class PostList extends React.Component { render() { const postNodes = this.props.posts.map(function(post) { post = post.toJS(); return ( <Post { ...post } key={post.shortId} /> ); }); return ( <ul className="post-list"> { postNodes } </ul> ); } };
app/components/Transcribe/UserForm.js
taggun/app-benchmark
/* eslint-disable react/no-array-index-key */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import styles from './Transcribe.css'; const internals = {}; internals.renderData = item => { if (!item || !item.confidenceLevel) { return ''; } if (moment(item.data, moment.ISO_8601, true).isValid()) { return `${moment .utc(item.data) .format('LL')} [${item.confidenceLevel.toFixed(2)}]`; } return `${item.data} [${item.confidenceLevel.toFixed(2)}]`; }; export default class UserForm extends Component { constructor(props) { super(props); this.state = { totalAmount: '', taxAmount: '', date: '', merchantName: '' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.setField = this.setField.bind(this); } componentWillReceiveProps(newProps) { if (this.props.md5 === newProps.md5) { this.setState({ totalAmount: '', taxAmount: '', date: '', merchantName: '' }); } } componentDidUpdate() { this.setField('totalAmount'); this.setField('taxAmount'); this.setField('date'); this.setField('merchantName'); Materialize.updateTextFields(); } setField(fieldName) { if ( !this.state[fieldName] && (this.props.userResult[fieldName] || this.props.ocrResult[fieldName].data) ) { const stateChanged = {}; const result = this.props.userResult[fieldName] || this.props.ocrResult[fieldName].data; if (moment(result, moment.ISO_8601, true).isValid()) { stateChanged[fieldName] = `${moment.utc(result).format('YYYY-MM-DD')}`; } else { stateChanged[fieldName] = result; } this.setState(stateChanged); } } handleChange(event) { const stateChanged = {}; stateChanged[event.target.id] = event.target.value; this.setState(stateChanged); } handleSubmit(event) { this.props.saveRequest(this.state, this.props.ocrResult); event.preventDefault(); } render() { return ( <div> <form onSubmit={this.handleSubmit}> <div> <div className="row valign-wrapper"> <div className="input-field browser-default col s6"> <input id="totalAmount" type="text" value={this.state.totalAmount} onChange={this.handleChange} /> <label htmlFor="totalAmount"> Total </label> </div> <div className="col s6"> {internals.renderData(this.props.ocrResult.totalAmount)} </div> </div> <div className="valign-wrapper"> <div className="input-field browser-default col s6"> <input id="taxAmount" type="text" value={this.state.taxAmount} onChange={this.handleChange} /> <label htmlFor="taxAmount"> Tax </label> </div> <div className="col s6"> {internals.renderData(this.props.ocrResult.taxAmount)} </div> </div> <div className="valign-wrapper"> <div className="input-field browser-default col s6"> <input id="date" type="date" value={this.state.date} onChange={this.handleChange} /> </div> <div className="col s6"> {internals.renderData(this.props.ocrResult.date)} </div> </div> <div className="valign-wrapper"> <div className="input-field browser-default col s6"> <input id="merchantName" type="text" value={this.state.merchantName} onChange={this.handleChange} /> <label htmlFor="merchantName"> Merchant name </label> </div> <div className="col s6"> {internals.renderData(this.props.ocrResult.merchantName)} </div> </div> <div className="row"> <div className="col s2"> <input type="submit" disabled={this.props.userResult.isLoading} value="Save" className="btn" /> </div> </div> { this.props.userForm.error ? <span className="red-text">{ this.props.userForm.error }</span> : '' } </div> <div className={styles.numbers}> <div className="col s12"> <h6>Amounts</h6> {this.props.ocrResult.amounts.map((amount, i) => ( <span key={`amounts-${i}`} className="col s2"> {amount.data} </span> ))} </div> <div className="col s12"> <h6>Line Amounts</h6> {this.props.ocrResult.lineAmounts.map((amount, i) => ( <span key={`lineAmounts-${i}`} className="col s2"> {amount.data} </span> ))} </div> <div className="col s12"> <h6>Numbers</h6> {this.props.ocrResult.numbers.map((number, i) => ( <span key={`numbers-${i}`} className="col s4"> {number.data} </span> ))} </div> </div> </form> </div> ); } } UserForm.propTypes = { id: PropTypes.string, md5: PropTypes.string, saveRequest: PropTypes.func, transcribe: PropTypes.shape({ apikey: PropTypes.string, md5: PropTypes.string, contentType: PropTypes.string, file: PropTypes.any }), ocrResult: PropTypes.shape({ totalAmount: PropTypes.object, taxAmount: PropTypes.object, date: PropTypes.object, merchantName: PropTypes.object, amounts: PropTypes.array, lineAmounts: PropTypes.array, numbers: PropTypes.array }), userResult: PropTypes.shape({ totalAmount: PropTypes.number, taxAmount: PropTypes.number, date: PropTypes.ISO_8601, merchantName: PropTypes.string, error: PropTypes.string, isLoading: PropTypes.bool }), userForm: PropTypes.shape({ error: PropTypes.string, isLoading: PropTypes.bool }) }; UserForm.defaultProps = { id: undefined, md5: undefined, saveRequest: undefined, transcribe: {}, ocrResult: { totalAmount: {}, taxAmount: {}, date: {}, merchantName: {}, amounts: [], lineAmounts: [], numbers: [] }, userResult: { totalAmount: undefined, taxAmount: undefined, date: undefined, merchantName: undefined }, userForm: { error: undefined, isLoading: undefined } };
src/scenes/home/scholarshipApplication/success/success.js
miaket/operationcode_frontend
import React from 'react'; import { Link } from 'react-router-dom'; import Section from 'shared/components/section/section'; import FormButton from 'shared/components/form/formButton/formButton'; import styles from './success.css'; const Success = () => ( <Section title="Success!" theme="white"> <span className={styles.successText}>We have recieved your application.</span> <Link to="/scholarships"> <FormButton text="Return to scholarships" /> </Link> </Section> ); export default Success;
src/shared/element-react/dist/npm/es6/src/slider/Slider.js
thundernet8/Elune-WWW
import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import { Component, PropTypes } from '../../libs'; import InputNumber from '../input-number'; import SliderButton from './Button'; var Slider = function (_Component) { _inherits(Slider, _Component); function Slider(props) { _classCallCheck(this, Slider); var _this = _possibleConstructorReturn(this, _Component.call(this, props)); _this.state = { firstValue: 0, secondValue: 0, oldValue: 0, precision: 0, inputValue: 0, dragging: false }; return _this; } Slider.prototype.getChildContext = function getChildContext() { return { component: this }; }; Slider.prototype.componentWillMount = function componentWillMount() { var _props = this.props, range = _props.range, value = _props.value, min = _props.min, max = _props.max, step = _props.step; var _state = this.state, firstValue = _state.firstValue, secondValue = _state.secondValue, oldValue = _state.oldValue, inputValue = _state.inputValue, precision = _state.precision; if (range) { if (Array.isArray(value)) { firstValue = Math.max(min, value[0]); secondValue = Math.min(max, value[1]); } else { firstValue = min; secondValue = max; } oldValue = [firstValue, secondValue]; } else { if (typeof value !== 'number' || isNaN(value)) { firstValue = min; } else { firstValue = Math.min(max, Math.max(min, value)); } oldValue = firstValue; } var precisions = [min, max, step].map(function (item) { var decimal = ('' + item).split('.')[1]; return decimal ? decimal.length : 0; }); precision = Math.max.apply(null, precisions); inputValue = inputValue || firstValue; this.setState({ firstValue: firstValue, secondValue: secondValue, oldValue: oldValue, inputValue: inputValue, precision: precision }); }; Slider.prototype.componentWillUpdate = function componentWillUpdate(props, state) { if (props.min != this.props.min || props.max != this.props.max) { this.setValues(); } if (props.value != this.props.value) { var _oldValue = this.state.oldValue; if (this.state.dragging || Array.isArray(this.props.value) && Array.isArray(props.value) && Array.isArray(_oldValue) && this.props.value.every(function (item, index) { return item === _oldValue[index]; })) { return; } this.setValues(); } }; Slider.prototype.valueChanged = function valueChanged() { var range = this.props.range; var _state2 = this.state, firstValue = _state2.firstValue, oldValue = _state2.oldValue; if (range && Array.isArray(oldValue)) { return ![this.minValue(), this.maxValue()].every(function (item, index) { return item === oldValue[index]; }); } else { return firstValue !== oldValue; } }; Slider.prototype.setValues = function setValues() { var _props2 = this.props, range = _props2.range, value = _props2.value, min = _props2.min, max = _props2.max; var _state3 = this.state, firstValue = _state3.firstValue, secondValue = _state3.secondValue, oldValue = _state3.oldValue, inputValue = _state3.inputValue; if (range && Array.isArray(value)) { if (value[1] < min) { inputValue = [min, min]; } else if (value[0] > max) { inputValue = [max, max]; } else if (value[0] < min) { inputValue = [min, value[1]]; } else if (value[1] > max) { inputValue = [value[0], max]; } else { firstValue = value[0]; secondValue = value[1]; if (this.valueChanged()) { this.onValueChanged([this.minValue(), this.maxValue()]); oldValue = value.slice(); } } } else if (!range && typeof value === 'number' && !isNaN(value)) { if (value < min) { inputValue = min; } else if (value > max) { inputValue = max; } else { inputValue = firstValue; if (this.valueChanged()) { this.onValueChanged(firstValue); oldValue = firstValue; } } } this.forceUpdate(); }; Slider.prototype.setPosition = function setPosition(percent) { var _props3 = this.props, range = _props3.range, min = _props3.min, max = _props3.max; var _state4 = this.state, firstValue = _state4.firstValue, secondValue = _state4.secondValue; var targetValue = min + percent * (max - min) / 100; if (!range) { this.refs.button1.setPosition(percent);return; } var button = void 0; if (Math.abs(this.minValue() - targetValue) < Math.abs(this.maxValue() - targetValue)) { button = firstValue < secondValue ? 'button1' : 'button2'; } else { button = firstValue > secondValue ? 'button1' : 'button2'; } this.refs[button].setPosition(percent); }; Slider.prototype.onSliderClick = function onSliderClick(event) { if (this.props.disabled || this.state.dragging) return; if (this.props.vertical) { var sliderOffsetBottom = this.refs.slider.getBoundingClientRect().bottom; this.setPosition((sliderOffsetBottom - event.clientY) / this.sliderSize() * 100); } else { var sliderOffsetLeft = this.refs.slider.getBoundingClientRect().left; this.setPosition((event.clientX - sliderOffsetLeft) / this.sliderSize() * 100); } this.setValues(); }; /* Watched Methods */ Slider.prototype.onValueChanged = function onValueChanged(val) { if (this.props.onChange) { this.props.onChange(val); } }; Slider.prototype.onInputValueChanged = function onInputValueChanged(e) { var _this2 = this; this.setState({ inputValue: e || 0, firstValue: e || 0 }, function () { _this2.setValues(); }); }; Slider.prototype.onFirstValueChange = function onFirstValueChange(e) { if (this.state.firstValue != e) { this.state.firstValue = e; this.forceUpdate(); this.setValues(); } }; Slider.prototype.onSecondValueChange = function onSecondValueChange(e) { if (this.state.secondValue != e) { this.state.secondValue = e; this.forceUpdate(); this.setValues(); } }; /* Computed Methods */ Slider.prototype.sliderSize = function sliderSize() { return parseInt(this.props.vertical ? this.refs.slider.offsetHeight : this.refs.slider.offsetWidth, 10); }; Slider.prototype.stops = function stops() { var _this3 = this; var _props4 = this.props, range = _props4.range, min = _props4.min, max = _props4.max, step = _props4.step; var firstValue = this.state.firstValue; var stopCount = (max - min) / step; var stepWidth = 100 * step / (max - min); var result = []; for (var i = 1; i < stopCount; i++) { result.push(i * stepWidth); } if (range) { return result.filter(function (step) { return step < 100 * (_this3.minValue() - min) / (max - min) || step > 100 * (_this3.maxValue() - min) / (max - min); }); } else { return result.filter(function (step) { return step > 100 * (firstValue - min) / (max - min); }); } }; Slider.prototype.minValue = function minValue() { return Math.min(this.state.firstValue, this.state.secondValue); }; Slider.prototype.maxValue = function maxValue() { return Math.max(this.state.firstValue, this.state.secondValue); }; Slider.prototype.runwayStyle = function runwayStyle() { return this.props.vertical ? { height: this.props.height } : {}; }; Slider.prototype.barStyle = function barStyle() { return this.props.vertical ? { height: this.barSize(), bottom: this.barStart() } : { width: this.barSize(), left: this.barStart() }; }; Slider.prototype.barSize = function barSize() { return this.props.range ? 100 * (this.maxValue() - this.minValue()) / (this.props.max - this.props.min) + '%' : 100 * (this.state.firstValue - this.props.min) / (this.props.max - this.props.min) + '%'; }; Slider.prototype.barStart = function barStart() { return this.props.range ? 100 * (this.minValue() - this.props.min) / (this.props.max - this.props.min) + '%' : '0%'; }; Slider.prototype.render = function render() { var _props5 = this.props, vertical = _props5.vertical, showInput = _props5.showInput, showStops = _props5.showStops, showInputControls = _props5.showInputControls, range = _props5.range, step = _props5.step, disabled = _props5.disabled, min = _props5.min, max = _props5.max; var _state5 = this.state, inputValue = _state5.inputValue, firstValue = _state5.firstValue, secondValue = _state5.secondValue; return React.createElement( 'div', { className: this.className('el-slider', { 'is-vertical': vertical, 'el-slider--with-input': showInput }) }, showInput && !range && React.createElement(InputNumber, { ref: 'input', className: 'el-slider__input', defaultValue: inputValue, value: firstValue, step: step, disabled: disabled, controls: showInputControls, min: min, max: max, size: 'small', onChange: this.onInputValueChanged.bind(this) }), React.createElement( 'div', { ref: 'slider', style: this.runwayStyle(), className: this.classNames('el-slider__runway', { 'show-input': showInput, 'disabled': disabled }), onClick: this.onSliderClick.bind(this) }, React.createElement('div', { className: 'el-slider__bar', style: this.barStyle() }), React.createElement(SliderButton, { ref: 'button1', vertical: vertical, value: firstValue, onChange: this.onFirstValueChange.bind(this) }), range && React.createElement(SliderButton, { ref: 'button2', vertical: vertical, value: secondValue, onChange: this.onSecondValueChange.bind(this) }), showStops && this.stops().map(function (item, index) { return React.createElement('div', { key: index, className: 'el-slider__stop', style: vertical ? { 'bottom': item + '%' } : { 'left': item + '%' } }); }) ) ); }; return Slider; }(Component); export default Slider; Slider.childContextTypes = { component: PropTypes.any }; Slider.propTypes = { min: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), max: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), step: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), value: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]), showInput: PropTypes.bool, showInputControls: PropTypes.bool, showTooltip: PropTypes.bool, showStops: PropTypes.bool, disabled: PropTypes.bool, range: PropTypes.bool, vertical: PropTypes.bool, height: PropTypes.string, formatTooltip: PropTypes.func, onChange: PropTypes.func }; Slider.defaultProps = { showTooltip: true, showInputControls: true, min: 0, max: 100, step: 1, value: 0 };
app/components/WhyStart.js
gidich/votrient-kiosk
import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './WhyStart.css'; export default class WhyStart extends Component { render() { return ( <div className={styles.container}> <Link to="/" className={styles.home}></Link> <Link to="/ThankYou" className={styles.powerAhead}><div /></Link> <Link to="/ProductInfo" className={styles.productInformation}></Link> <Link to="/" className={styles.logo}></Link> <Link to="/WhyStart/References" className={styles.references}></Link> <Link to="/WhyStart/Diagram" className={styles.diagram}></Link> </div> ); } }
frontend/src/components/common/grid/customGridColumn.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import Grid from 'material-ui/Grid'; import { withStyles } from 'material-ui/styles'; /** Custom grid column based on flexbox * - used instead of materia-ui one to avoid strange spacing * issues when multiple grid columns being nested in each other * currently supports only one spacing - 12px * */ const styleSheet = theme => ({ grid: { display: 'flex', flexDirection: 'column', margin: -(theme.spacing.unit * 1.5), }, gridItem: { padding: theme.spacing.unit * 1.5, }, }); function CustomGridColumn(props) { const { classes, children, spacing, ...other } = props; return ( <div className={classes.grid} > {React.Children.map(children, child => (child ? <div className={classes.gridItem} > {child} </div> : null))} </div> ); } CustomGridColumn.propTypes = { classes: PropTypes.object, children: PropTypes.node, }; export default withStyles(styleSheet, { name: 'CustomGridColumn' })(CustomGridColumn);
src/templates/categories-list-template.js
bapti/blog
// @flow strict import React from 'react'; import { Link } from 'gatsby'; import kebabCase from 'lodash/kebabCase'; import Sidebar from '../components/Sidebar'; import Layout from '../components/Layout'; import Page from '../components/Page'; import { useSiteMetadata, useCategoriesList } from '../hooks'; const CategoriesListTemplate = () => { const { title, subtitle } = useSiteMetadata(); const categories = useCategoriesList(); return ( <Layout title={`Categories - ${title}`} description={subtitle}> <Sidebar /> <Page title="Categories"> <ul> {categories.map((category) => ( <li key={category.fieldValue}> <Link to={`/category/${kebabCase(category.fieldValue)}/`}> {category.fieldValue} ({category.totalCount}) </Link> </li> ))} </ul> </Page> </Layout> ); }; export default CategoriesListTemplate;
geonode/monitoring/frontend/monitoring/src/components/atoms/hr/index.js
francbartoli/geonode
/* ######################################################################### # # Copyright (C) 2019 OSGeo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ######################################################################### */ import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles'; class HR extends React.Component { static propTypes = { children: PropTypes.node, style: PropTypes.object, } render() { return ( <hr style={styles.hr} /> ); } } export default HR;
app/redux/router.js
andreipreda/coconut
import React from 'react'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import { Wrap, Header } from './../wrap'; const NotFound = () => <div>Route not found</div>; export const AppRouter = () => <Router history={browserHistory}> <Route path="/" component={Wrap}> <IndexRoute component={Header} /> <Route path="*" component={NotFound} /> </Route> </Router>;
src/index.js
madi031/ReactRouterBlog
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import { createStore, applyMiddleware } from 'redux'; import promise from 'redux-promise'; import PostsIndex from './components/posts_index'; import PostsNew from './components/posts_new'; import PostsShow from './components/posts_show'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware(promise)(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Switch> <Route path='/posts/new' component={PostsNew} /> <Route path='/posts/:id' component={PostsShow} /> <Route path='/' component={PostsIndex} /> </Switch> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));
src/ServiceList.js
CanopyTax/sofe-inspector
import React from 'react'; import formStyles from './Form.style.css'; import buttonStyles from './Button.style.css'; export default function ServiceList({services, updateService, deleteService, renameService}) { return (services && services.length) ? <div style={{height: '240px', overflow: 'auto', marginBottom: '16px'}}> <table className={formStyles.table}> <thead> <tr className='row'> <th style={{width: '20%'}} className='col-xs-2'>Service Name</th> <th style={{width: '80%'}} className='col-xs-10'>SRC</th> </tr> </thead> <tbody> {services.map((service, index) => { return <tr style={{verticalAlign: 'top'}} className='row' key={service.id}> <td style={{padding: 8}} className='col-xs-2'> <input defaultValue={service.name} className={formStyles.formControl} onChange={(e) => renameService(e, service.src, service.name, index)} /> </td> <td style={{padding: 8}} className='col-xs-9'> <div style={{width: 'calc(100% - 40px)', display: 'inline-block'}}> <input onChange={(e) => updateService(service.name, index, e)} defaultValue={service.src} className={formStyles.formControl} /> </div> <div style={{width: 40, verticalAlign: 'top', display: 'inline-block', position: 'relative', top: -3}}> <span onClick={(e) => deleteService(service.name, e)} className={buttonStyles.closeButton}>x</span> </div> </td> </tr> })} </tbody> </table> </div>: getBlankMessage(); } function getBlankMessage() { return <p style={{padding: 15, background: 'rgba(52, 152, 219, .5)', textAlign: 'center'}}>You do not have any overriden sofe services</p> }
src/containers/Home/FormActions.js
oPauloChaves/controle-frotas
import React from 'react' import Row from 'react-bootstrap/lib/Row' import Col from 'react-bootstrap/lib/Col' import Button from 'react-bootstrap/lib/Button' import Glyphicon from 'react-bootstrap/lib/Glyphicon' import FormGroup from 'react-bootstrap/lib/FormGroup' import InputGroup from 'react-bootstrap/lib/InputGroup' import FormControl from 'react-bootstrap/lib/FormControl' const FormActions = ({ search, handleSearch, handleSearchInputChange }) => ( <Row className="AppFormAction"> <Col xs={5} sm={3} md={2}> <Button href="#/carros/novo" bsStyle="success" block className="AppBtnNew" >Novo Carro</Button> </Col> <Col xs={7} smOffset={5} sm={4} mdOffset={7} md={3}> <FormGroup> <InputGroup> <FormControl type="text" placeholder="Pesquisar" value={search} onChange={handleSearchInputChange} onKeyUp={handleSearch} /> <InputGroup.Button> <Button onClick={handleSearch}><Glyphicon glyph="search" /></Button> </InputGroup.Button> </InputGroup> </FormGroup> </Col> </Row> ) export default FormActions
src/svg-icons/social/sentiment-neutral.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialSentimentNeutral = (props) => ( <SvgIcon {...props}> <path d="M9 14h6v1.5H9z"/><circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/> </SvgIcon> ); SocialSentimentNeutral = pure(SocialSentimentNeutral); SocialSentimentNeutral.displayName = 'SocialSentimentNeutral'; SocialSentimentNeutral.muiName = 'SvgIcon'; export default SocialSentimentNeutral;
src/index.js
surongaukeys/gallery-by-react
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/svg-icons/navigation/arrow-drop-down-circle.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropDownCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 12l-4-4h8l-4 4z"/> </SvgIcon> ); NavigationArrowDropDownCircle = pure(NavigationArrowDropDownCircle); NavigationArrowDropDownCircle.displayName = 'NavigationArrowDropDownCircle'; export default NavigationArrowDropDownCircle;
docs/pages/home.js
n7best/react-weui
import React from 'react'; import FontAwesome from 'react-fontawesome'; import './home.less'; //import { Button } from 'react-weui'; const Home = () => ( <div className="App__preview background--canvas flex-center"> <div className="App__preview--none"> <FontAwesome name="weixin" size="4x" /> <p>Hello, React-WeUI</p> </div> </div> ); export default Home;
src/index.js
ianwcarlson/react-components
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
react-router-nb/react-router/examples/pinterest/app.js
zhangfaliang/learnReact
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router, Route, IndexRoute, Link } from 'react-router' import withExampleBasename from '../withExampleBasename' const PICTURES = [ { id: 0, src: 'http://placekitten.com/601/601' }, { id: 1, src: 'http://placekitten.com/610/610' }, { id: 2, src: 'http://placekitten.com/620/620' } ] const Modal = React.createClass({ styles: { position: 'fixed', top: '20%', right: '20%', bottom: '20%', left: '20%', padding: 20, boxShadow: '0px 0px 150px 130px rgba(0, 0, 0, 0.5)', overflow: 'auto', background: '#fff' }, render() { return ( <div style={this.styles}> <p><Link to={this.props.returnTo}>Back</Link></p> {this.props.children} </div> ) } }) const App = React.createClass({ componentWillReceiveProps(nextProps) { // if we changed routes... if (( nextProps.location.key !== this.props.location.key && nextProps.location.state && nextProps.location.state.modal )) { // save the old children (just like animation) this.previousChildren = this.props.children } }, render() { let { location } = this.props let isModal = ( location.state && location.state.modal && this.previousChildren ) return ( <div> <h1>Pinterest Style Routes</h1> <div> {isModal ? this.previousChildren : this.props.children } {isModal && ( <Modal isOpen={true} returnTo={location.state.returnTo}> {this.props.children} </Modal> )} </div> </div> ) } }) const Index = React.createClass({ render() { return ( <div> <p> The url `/pictures/:id` can be rendered anywhere in the app as a modal. Simply put `modal: true` in the location descriptor of the `to` prop. </p> <p> Click on an item and see its rendered as a modal, then copy/paste the url into a different browser window (with a different session, like Chrome -> Firefox), and see that the image does not render inside the overlay. One URL, two session dependent screens :D </p> <div> {PICTURES.map(picture => ( <Link key={picture.id} to={{ pathname: `/pictures/${picture.id}`, state: { modal: true, returnTo: this.props.location.pathname } }} > <img style={{ margin: 10 }} src={picture.src} height="100" /> </Link> ))} </div> <p><Link to="/some/123/deep/456/route">Go to some deep route</Link></p> </div> ) } }) const Deep = React.createClass({ render() { return ( <div> <p>You can link from anywhere really deep too</p> <p>Params stick around: {this.props.params.one} {this.props.params.two}</p> <p> <Link to={{ pathname: '/pictures/0', state: { modal: true, returnTo: this.props.location.pathname } }}> Link to picture with Modal </Link><br/> <Link to="/pictures/0"> Without modal </Link> </p> </div> ) } }) const Picture = React.createClass({ render() { return ( <div> <img src={PICTURES[this.props.params.id].src} style={{ height: '80%' }} /> </div> ) } }) render(( <Router history={withExampleBasename(browserHistory, __dirname)}> <Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="/pictures/:id" component={Picture}/> <Route path="/some/:one/deep/:two/route" component={Deep}/> </Route> </Router> ), document.getElementById('example'))
00-todo-lab4/src/TodoList.js
iproduct/course-node-express-react
import React from 'react'; const TodoList = ({todos, ...rest}) => { return ( <ul className="list-group"> { todos.map(todo => (<li>{todo.text} - {todo.status}</li>)) } </ul> ); } export default TodoList;
server/sonar-web/src/main/js/apps/overview/main/timeline.js
vamsirajendra/sonarqube
import d3 from 'd3'; import React from 'react'; import { LineChart } from '../../../components/charts/line-chart'; const HEIGHT = 80; export class Timeline extends React.Component { filterSnapshots () { return this.props.history.filter(s => { let matchBefore = !this.props.before || s.date <= this.props.before; let matchAfter = !this.props.after || s.date >= this.props.after; return matchBefore && matchAfter; }); } render () { let snapshots = this.filterSnapshots(); if (snapshots.length < 2) { return null; } let data = snapshots.map((snapshot, index) => { return { x: index, y: snapshot.value }; }); let domain = [0, d3.max(this.props.history, d => d.value)]; return <LineChart data={data} domain={domain} interpolate="basis" displayBackdrop={true} displayPoints={false} displayVerticalGrid={false} height={HEIGHT} padding={[0, 0, 0, 0]}/>; } } Timeline.propTypes = { history: React.PropTypes.arrayOf(React.PropTypes.object).isRequired, before: React.PropTypes.object, after: React.PropTypes.object };
V2-Node/esquenta.v2/UI/src/views/Base/Tables/Tables.js
leandrocristovao/esquenta
import React, { Component } from 'react'; import { Badge, Card, CardBody, CardHeader, Col, Pagination, PaginationItem, PaginationLink, Row, Table } from 'reactstrap'; class Tables extends Component { render() { return ( <div className="animated fadeIn"> <Row> <Col xs="12" lg="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Simple Table </CardHeader> <CardBody> <Table responsive> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Samppa Nori</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Estavan Lykos</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Chetan Mohamed</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Derick Maximinus</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Friderik Dávid</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <Pagination> <PaginationItem> <PaginationLink previous tag="button"></PaginationLink> </PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem> <PaginationLink tag="button">2</PaginationLink> </PaginationItem> <PaginationItem> <PaginationLink tag="button">3</PaginationLink> </PaginationItem> <PaginationItem> <PaginationLink tag="button">4</PaginationLink> </PaginationItem> <PaginationItem> <PaginationLink next tag="button"></PaginationLink> </PaginationItem> </Pagination> </CardBody> </Card> </Col> <Col xs="12" lg="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Striped Table </CardHeader> <CardBody> <Table responsive striped> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Yiorgos Avraamu</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Avram Tarasios</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Quintin Ed</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Enéas Kwadwo</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Agapetus Tadeáš</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <Pagination> <PaginationItem disabled><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </CardBody> </Card> </Col> </Row> <Row> <Col xs="12" lg="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Condensed Table </CardHeader> <CardBody> <Table responsive size="sm"> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Carwyn Fachtna</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Nehemiah Tatius</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Ebbe Gemariah</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Eustorgios Amulius</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Leopold Gáspár</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <Pagination> <PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </CardBody> </Card> </Col> <Col xs="12" lg="6"> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Bordered Table </CardHeader> <CardBody> <Table responsive bordered> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Pompeius René</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Paĉjo Jadon</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Micheal Mercurius</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Ganesha Dubhghall</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Hiroto Šimun</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <Pagination> <PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem className="page-item"><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </CardBody> </Card> </Col> </Row> <Row> <Col> <Card> <CardHeader> <i className="fa fa-align-justify"></i> Combined All Table </CardHeader> <CardBody> <Table hover bordered striped responsive size="sm"> <thead> <tr> <th>Username</th> <th>Date registered</th> <th>Role</th> <th>Status</th> </tr> </thead> <tbody> <tr> <td>Vishnu Serghei</td> <td>2012/01/01</td> <td>Member</td> <td> <Badge color="success">Active</Badge> </td> </tr> <tr> <td>Zbyněk Phoibos</td> <td>2012/02/01</td> <td>Staff</td> <td> <Badge color="danger">Banned</Badge> </td> </tr> <tr> <td>Einar Randall</td> <td>2012/02/01</td> <td>Admin</td> <td> <Badge color="secondary">Inactive</Badge> </td> </tr> <tr> <td>Félix Troels</td> <td>2012/03/01</td> <td>Member</td> <td> <Badge color="warning">Pending</Badge> </td> </tr> <tr> <td>Aulus Agmundr</td> <td>2012/01/21</td> <td>Staff</td> <td> <Badge color="success">Active</Badge> </td> </tr> </tbody> </Table> <nav> <Pagination> <PaginationItem><PaginationLink previous tag="button">Prev</PaginationLink></PaginationItem> <PaginationItem active> <PaginationLink tag="button">1</PaginationLink> </PaginationItem> <PaginationItem><PaginationLink tag="button">2</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">3</PaginationLink></PaginationItem> <PaginationItem><PaginationLink tag="button">4</PaginationLink></PaginationItem> <PaginationItem><PaginationLink next tag="button">Next</PaginationLink></PaginationItem> </Pagination> </nav> </CardBody> </Card> </Col> </Row> </div> ); } } export default Tables;
pages/404.js
ivygong/irc
import React, { Component } from 'react'; import Helmet from 'react-helmet'; import { config } from 'config'; import { Link } from 'react-router'; import { prefixLink } from 'gatsby-helpers'; export default class NotFound extends Component { render () { return ( <div className="page page--not-found"> <Helmet title={config.siteTitle} /> <h1> The page you were looking for cannot be found. </h1> </div> ); } }
src/components/logout_button.js
Helabs/handup-web
import React from 'react'; import { connect } from 'react-redux'; import { graphql, compose } from 'react-apollo'; import gql from 'graphql-tag'; import { SetCurrentUserId, SetCurrentUserToken } from '../actions'; function LogoutButton({ currentUserId, getUserQuery, SetCurrentUserId, SetCurrentUserToken }) { if (!currentUserId) { return null; } return ( <div> {renderUserAvatar()} <button className="btn btn-default faded" onClick={onClick}> <i className="fa fa-sign-out" /> </button> </div> ); function onClick() { SetCurrentUserId(null); SetCurrentUserToken(null); } function renderUserAvatar() { if (getUserQuery.loading) { return; } return <img className="circle m-r-s" src={getUserQuery.getUser.avatarImageUrl} style={{ width: '35px' }} />; } } const getUserQueryOptions = ({ currentUserId }) => ({ variables: { id: currentUserId } }); const getUserQuery = gql` query getUser($id: ID!) { getUser(id: $id) { id name avatarImageUrl } } `; const LogoutButtonWithData = compose( graphql(getUserQuery, { name: 'getUserQuery', options: getUserQueryOptions, skip: ({ currentUserId }) => !currentUserId }) )(LogoutButton); function mapStateToProps({ currentUser }) { return { currentUserId: currentUser.id }; } export default connect(mapStateToProps, { SetCurrentUserId, SetCurrentUserToken })(LogoutButtonWithData);
packages/mcs-lite-ui/src/TabItem/TabItem.example.js
MCS-Lite/mcs-lite
import React from 'react'; import PropTypes from 'prop-types'; import { storiesOf } from '@storybook/react'; import { withInfo } from '@storybook/addon-info'; import { action } from '@storybook/addon-actions'; import TabItem from '.'; class StatefulTabItems extends React.Component { static propTypes = { items: PropTypes.arrayOf(PropTypes.number).isRequired, }; state = { value: '' }; onChange = (e, value) => this.setState({ value }); render() { const { items } = this.props; const { onChange } = this; const { value } = this.state; return ( <div> {items.map(i => ( <TabItem key={i} value={i} onClick={onChange} active={i === value}> {`Tab ${i}`} </TabItem> ))} </div> ); } } storiesOf('TabItem', module) .add( 'API', withInfo({ text: '', inline: true, })(() => ( <div> <TabItem value="key" onClick={action('onClick')}> TabItem </TabItem> <TabItem value="key" active onClick={action('onClick')}> Active TabItem </TabItem> </div> )), ) .add( 'With color props', withInfo({ text: '', inline: true, })(() => ( <div> <TabItem value={1} color="warning"> TabItem 1 </TabItem> <TabItem value={2} color="warning" active> TabItem 2 </TabItem> </div> )), ) .add( 'With state', withInfo({ text: 'This is a react controlled component.', inline: true, propTables: [TabItem], })(() => <StatefulTabItems items={[1, 2, 3]} />), );
actor-apps/app-web/src/app/components/sidebar/RecentSection.react.js
TimurTarasenko/actor-platform
import _ from 'lodash'; import React from 'react'; import { Styles, RaisedButton } from 'material-ui'; import ActorTheme from 'constants/ActorTheme'; import DialogActionCreators from 'actions/DialogActionCreators'; import DialogStore from 'stores/DialogStore'; import CreateGroupActionCreators from 'actions/CreateGroupActionCreators'; import RecentSectionItem from './RecentSectionItem.react'; import CreateGroupModal from 'components/modals/CreateGroup.react'; import CreateGroupStore from 'stores/CreateGroupStore'; const ThemeManager = new Styles.ThemeManager(); const LoadDialogsScrollBottom = 100; const getStateFromStore = () => { return { isCreateGroupModalOpen: CreateGroupStore.isModalOpen(), dialogs: DialogStore.getAll() }; }; class RecentSection extends React.Component { static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillMount() { DialogStore.addChangeListener(this.onChange); DialogStore.addSelectListener(this.onChange); CreateGroupStore.addChangeListener(this.onChange); ThemeManager.setTheme(ActorTheme); } componentWillUnmount() { DialogStore.removeChangeListener(this.onChange); DialogStore.removeSelectListener(this.onChange); CreateGroupStore.removeChangeListener(this.onChange); } constructor() { super(); this.onChange = this.onChange.bind(this); this.onScroll = this.onScroll.bind(this); this.openCreateGroup = this.openCreateGroup.bind(this); this.state = getStateFromStore(); } onChange() { this.setState(getStateFromStore()); } openCreateGroup() { CreateGroupActionCreators.openModal(); } onScroll(event) { if (event.target.scrollHeight - event.target.scrollTop - event.target.clientHeight <= LoadDialogsScrollBottom) { DialogActionCreators.onDialogsEnd(); } } render() { let dialogs = _.map(this.state.dialogs, (dialog, index) => { return ( <RecentSectionItem dialog={dialog} key={index}/> ); }, this); let createGroupModal; if (this.state.isCreateGroupModalOpen) { createGroupModal = <CreateGroupModal/>; } return ( <section className="sidebar__recent"> <ul className="sidebar__list sidebar__list--recent" onScroll={this.onScroll}> {dialogs} </ul> <footer> <RaisedButton label="Create group" onClick={this.openCreateGroup} style={{width: '100%'}}/> {createGroupModal} </footer> </section> ); } } export default RecentSection;
codes/chapter03/webpack2/demo13/app/components/Welcome.js
atlantis1024/react-step-by-step
/** * Created by Zhang Peng on 2017/6/8. */ import React from 'react'; class Clock extends React.Component { constructor(props) { super(props); this.state = { date: new Date().toLocaleDateString() }; this.click = this.click.bind(this); } click() { // 动态引入import() import('moment') .then(moment => moment().format("MMMM Do YYYY, h:mm:ss a")) .then(str => this.setState({date:str})) .catch(err => console.log("Failed to load moment", err)); } render() { return ( <div> <h2>It is {this.state.date}.</h2> <p onClick={this.click}>Click here to changing the time.</p> </div> ); } } class Welcome extends React.PureComponent { render() { return ( <div> <h1>Hello, {this.props.name}</h1> <Clock /> </div> ); } } export default Welcome;
src/routes/ConnectedDevices/components/ConnectedDevicesSpeeds.js
liuyaoao/omnyiq-sc1-server-render
import React from 'react'; import {getSpeedsChartData} from './ConnectedDevicesChartData'; import TimeSelectionTab from '../../../components/TimeSelectionTab'; var ConnectedDevicesSpeeds = React.createClass({ getInitialState:function(){ return{ } }, componentDidMount:function(){ let _this = this; let deviceListUrl = APPCONFING.deviceListUrl; let deviceInfo = localStorage.getItem('deviceInfo'); deviceInfo = JSON.parse(deviceInfo); if(this.props.isAllDevices){ $.ajax({ type: "GET", url: deviceListUrl+'/GetBandwidthServlet', success: function(data){ data = JSON.parse(data); let allBandwidthList = data.AllBandwidthList || []; for(let obj of allBandwidthList){ obj.total_bandwidth = +(+obj.total_bandwidth || 0).toFixed(2); obj.used = +(obj.used || 0).toFixed(2); } _this._renderSpeedsChart(allBandwidthList); } }); } }, _onClickChartCall:function(e){ var data = zingchart.exec(e.id, 'getseriesvalues', {}); // console.log("ConnectedDevicesSpeeds_e:",e); // console.log("ConnectedDevicesSpeeds_ChartData:",data); var availableNum = data[0][e.nodeindex] ? (data[0][e.nodeindex]-data[1][e.nodeindex])/data[0][e.nodeindex] : 0; this._setSpeedsNum_SpeedsGrade(data[1][e.nodeindex], availableNum*100); }, _renderSpeedsChart:function(bandwidthList){ let _this = this; if(!bandwidthList || bandwidthList.length <= 0){ $('.connectedDevicesSpeedsContainer .noDataContainer').removeClass('hide'); $('.devicesSpeedsBottom').addClass('hide'); this._setSpeedsNum_SpeedsGrade(0, 0); return; } $('.connectedDevicesSpeedsContainer .noDataContainer').addClass('hide'); $('.devicesSpeedsBottom').removeClass('hide'); let lastObj = bandwidthList[bandwidthList.length-1]; this._setSpeedsNum_SpeedsGrade(lastObj.used||0, (+lastObj.available||0)*100); let timeLabelList=[], totalList=[] , usedList=[]; var i=0; for(let obj of bandwidthList){ if(i%3 == 0){ let hour = (new Date(obj.savetime)).getHours(); timeLabelList.push((hour<10?"0":"")+hour+':00'); }else{ timeLabelList.push(''); } totalList.push(obj.total_bandwidth||0); usedList.push(obj.used||0); i++; } var chartData = getSpeedsChartData(timeLabelList,totalList,usedList); zingchart.render({id : 'ConnectDevicesSpeedsChart',data : chartData,height: "300",width: "100%"}); zingchart.node_click = function(e){ if(e.id == 'ConnectDevicesSpeedsChart'){ _this._onClickChartCall(e); } } }, componentDidUpdate:function(){ if(!this.props.isAllDevices){ this._renderSpeedsChart(this.props.bandwidthList); } }, _setSpeedsNum_SpeedsGrade:function(speedsNum, speedsGrade){ $('.devicesSpeedsTop .speedsNum').text((+speedsNum).toFixed(2)); $('.devicesSpeedsTop .speedsGrade').text((+speedsGrade).toFixed(1)); }, componentWillUnmount:function(){ zingchart.exec('ConnectDevicesSpeedsChart', 'destroy');//不销毁的话会导致第二次加载这个路由页面的时候会报错。 }, render:function(){ return( <div className='connectedDevicesSpeedsContainer' style={{height:this.props.screenHeight-245}}> {!this.props.isAllDevices?<div onClick={this.props.onClickCloseSingleSpeeds} className='closeSingleSpeedsBtn glyphicon glyphicon-remove'></div>:''} <div className='devicesSpeedsTop'> {this.props.deviceName? <span>{this.props.deviceName} Devices</span>:<span>All Wi-Fi Devices</span>} <p className='speedsTitle'><span className='speedsNum'></span> Mbps</p> <p className='speedsState'><span className='speedsGrade'></span>% available</p> </div> <div className='noDataContainer hide' style={{height:this.props.screenHeight-325}}><p>No Speeds Data!!</p></div> <div className='devicesSpeedsBottom'> <div id={'ConnectDevicesSpeedsChart'} style={{height:'100%',width:'98%',margin:'0 auto'}}></div> </div> <TimeSelectionTab/> </div> ); } }); module.exports = ConnectedDevicesSpeeds;
__tests__/index.ios.js
Manuelandro/Universal-Commerce
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
js/cards/MarkDownCard/MarkDownCard.js
Learnone/ShanghaiTechAPP
import React, { Component } from 'react'; import { View } from 'react-native'; import { Container, Content, CardItem, Text } from 'native-base'; import Markdown from 'react-native-simple-markdown'; import { connect } from 'react-redux'; import { FlipCard } from '../../cards'; import styles from './styles'; const markDownStyle = { heading1: { fontSize: 22, flexWrap: 'wrap', wrapText: 'wrap', }, strong: { fontSize: 18, }, paragraph: { fontSize: 14, }, view: { borderWidth: 1, flex: 1, }, }; @connect(null, null) export default class MarkDownCard extends Component { static propTypes = { cardMeta: React.PropTypes.object.isRequired, }; render() { return ( <FlipCard cardMeta={this.props.cardMeta} > <View style={styles.container}> <Markdown styles={markDownStyle}> #Who is the best dev in town??????????????? {'\n\n'} Probably **the one** reading this lines 😏… </Markdown> </View> </FlipCard> ); } }
consoles/my-joy-instances/src/components/instances/__tests__/metadata.spec.js
yldio/joyent-portal
import React from 'react'; import renderer from 'react-test-renderer'; import 'jest-styled-components'; import { AddForm, EditForm } from '../metadata'; import Theme from '@mocks/theme'; it('renders <AddForm /> without throwing', () => { expect( renderer .create( <Theme> <AddForm /> </Theme> ) .toJSON() ).toMatchSnapshot(); }); it('renders <EditForm /> without throwing', () => { expect( renderer .create( <Theme> <EditForm /> </Theme> ) .toJSON() ).toMatchSnapshot(); });
packages/ui/src/components/uploadAttendance.js
she-smashes/thehub
/** * @author Thenmozhi Subramaniam * @name EventDetails * @desc renders event details component */ import React, { Component } from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import {Link} from 'react-router-dom'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import SelectField from 'material-ui/SelectField'; import TextField from 'material-ui/TextField'; import { INVALID_USER, EVENT_FAILURE } from "../constants/actions"; class UploadAttendance extends Component { constructor(props) { super(props); this.state = { eventData: {}, attendanceData: {}, attendanceDataWithUserId: {}, errors: {}, errorData: {}, fieldsDisabled: false, attendanceMessage: "" } } componentDidMount = () => { this.getEventData(); }; getEventData = () => { this.props.getEventDetails(this.props.match.params.id, this.props.userInfo).then((response, error) => { this.props.updateEventDetails(this.props.userInfo, JSON.parse(response.data)); let eventData = JSON.parse(response.data); let attendanceSubmitted = false; eventData.participants.map((participant, participantIndex) => { let userNames = ""; if (eventData.enrollments !== undefined) { eventData.enrollments.map((enrollment, enrollmentIndex) => { if(enrollment.attendanceFlag === 'submit') { attendanceSubmitted = true; } let participantIdStr = participant.id + ''; if (enrollment.enrollmentType !== undefined && enrollment.enrollmentType === participantIdStr) { userNames = enrollment.users.username + ", " + userNames; } }); } userNames = userNames.substring(0, userNames.length - 2); let attendanceData = this.state.attendanceData; attendanceData[participant.id] = userNames; this.setState({ attendanceData }); if(attendanceSubmitted) { this.setState({ fieldsDisabled: true }); this.setState({ attendanceMessage: "Attendance submitted for the event" }); } }); }, (error) => { console.log(error); }); }; showAttendancePerRole = (participants) => { if (participants !== undefined) { return participants.map((participant, participantIndex) => { console.log(this.state.attendanceData[participant.id]); let usName = "userNames_" + participant.id; return (<TableRow key={participantIndex}> <TableRowColumn key={1} > {participant.participantType} </TableRowColumn> <TableRowColumn key={2}> <div className="field-line"> <TextField floatingLabelText="Participant Names" multiLine={true} rows={2} className="align-left participant-input" name={usName} multiline="true" value={this.state.attendanceData[participant.id]} onChange={this.changeAttendanceData} errorText={this.state.errorData[participant.id]} disabled = {this.state.fieldsDisabled}/> </div> </TableRowColumn> </TableRow>); }); } }; /** * Change the user object. * * @param {object} event - the JavaScript event object */ changeAttendanceData = (event) => { let field = event.target.name; let fieldArr = field.split("_"); field = fieldArr[1]; const attendanceData = this.state.attendanceData; attendanceData[field] = event.target.value; this.setState({ attendanceData }); }; /** * verify the users. */ verifyUsers = (attendanceFlag) => { const attendanceDataWithUserId = {}; const errors = {}; const errorData = {}; this.setState({ attendanceDataWithUserId, errors, errorData }); let userArr = []; if (this.state.attendanceData !== undefined && this.state.attendanceData !== '') { console.log(this.state.attendanceData); Object.keys(this.state.attendanceData).map((event, index) => { userArr = userArr.concat(this.state.attendanceData[event].split(',')); }); let errorMap = {}; if (userArr.length > 0) { this.props.verifyUsers(userArr, this.props.userInfo, 'save') .then((response, error) => { let users = JSON.parse(response.data); Object.keys(this.state.attendanceData).map((participantId, index) => { this.state.attendanceData[participantId].split(',').map((username, usernameIndex) => { let foundUserName = false; let userId = ""; users.map((userEvent, userIndex) => { if (userEvent.username === username) { foundUserName = true; userId = userEvent.id; } }); if (foundUserName) { const attendanceDataWithUserId = this.state.attendanceDataWithUserId; let userIds = attendanceDataWithUserId[participantId]; if (userIds === undefined) { userIds = []; } userIds.push(userId); attendanceDataWithUserId[participantId] = userIds; this.setState({ attendanceDataWithUserId }); } else { const errors = this.state.errors; let errorUserNames = errors[participantId]; if (errorUserNames === undefined) { errorUserNames = []; } errorUserNames.push(username); errors[participantId] = errorUserNames; this.setState({ errors }); } }); }); if (this.handleValidation()) { this.props.saveAttendanceData(this.props.match.params.id, this.props.userInfo, this.state.attendanceDataWithUserId, attendanceFlag).then((response, error) => { if(attendanceFlag === 'submit') { this.setState({ fieldsDisabled: true }); this.setState({ attendanceMessage: "Attendance submitted for the event" }); if (this.props.userInfo.allowedActionList.indexOf('task_count')) { let notificationCount = 0; if (this.props.userInfo.notificationCount !== undefined && this.props.userInfo.notificationCount !== null && this.props.userInfo.notificationCount !== '') { notificationCount = this.props.userInfo.notificationCount; } this.props.userInfo.notificationCount = parseInt(notificationCount) + 1; let userString = JSON.stringify(this.props.userInfo) this.props.updateUserInfo(JSON.parse(userString)); } } }, (error) => { console.log(error); }); } }, (error) => { alert('Error' + error); }); } } }; handleValidation = () => { let fields = this.state.errors; let errorData = {}; let formIsValid = true; Object.keys(this.state.errors).map((participantId, index) => { let userNameString = ""; this.state.errors[participantId].map((userName, index) => { userNameString = userName + ", " + userNameString; }); if (userNameString !== '') { userNameString = userNameString.substring(0, userNameString.length - 2) + " "; formIsValid = false; errorData[participantId] = "UserName " + userNameString + "invalid."; } }); this.setState({ errorData: errorData }); return formIsValid; } saveAttendanceData = () => { this.verifyUsers('save'); } submitAttendanceData = () => { this.verifyUsers('submit'); } showAttendanceButtons = (participants) => { if (participants !== undefined) { return (<TableRow> <TableRowColumn key={1} > <div className="button-line margin35"> <RaisedButton type="submit" label="Save" primary onClick={() => { this.saveAttendanceData() }} disabled = {this.state.fieldsDisabled}/> </div> </TableRowColumn> <TableRowColumn key={2}> <div className="button-line margin35"> <RaisedButton type="submit" label="Save & Submit" primary onClick={() => { this.submitAttendanceData() }} disabled = {this.state.fieldsDisabled}/> </div> </TableRowColumn> </TableRow>); } }; renderAttendanceForm = (eventData) => { return ( <div> <br></br> { (this.state.attendanceMessage !== '' && this.state.attendanceMessage !== undefined && this.state.attendanceMessage !== null) ? <div class="alert alert-success" role="alert" style={{"width": "100%"}}> <p style={{"margin-left": "201px"}}>{this.state.attendanceMessage}</p> </div>: <div></div> } <Table style={{ "width": '100%' }}> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow className="table-header"> <TableHeaderColumn tooltip="Role" >Role</TableHeaderColumn> <TableHeaderColumn tooltip="User Name" >User Name</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false}> {this.showAttendancePerRole(eventData.participants)} {this.showAttendanceButtons(eventData.participants)} </TableBody> </Table> </div> ); }; /** * @name render * @desc render the event details in the page * @return event details */ render() { return ( <div className="widget well hub-widget"> <div className="widget-header">Upload Attendance</div> <div class="event-details"> { (this.props.eventData !== '' && this.props.eventData !== undefined && this.props.eventData !== null) ? <Link to={`/eventDetails/${this.props.eventData.id}`} style={{"color":"#337ab7"}}>Back ></Link> : <div></div> } { (this.props.eventData !== '' && this.props.eventData !== undefined && this.props.eventData !== null) ? this.renderAttendanceForm(this.props.eventData) : <div></div> } </div> </div> ); } } export default UploadAttendance;
react/src/browser/app/components/View.js
janprasil/mi-vmm-product-quality-rating
/* @flow */ import React from 'react'; import { Base } from 'rebass'; const View = (props: Object) => ( <Base {...props} is="div" /> ); export default View;
client/src/components/FocusedCrawling.js
ViDA-NYU/domain_discovery_tool_react
import React, { Component } from 'react'; import { Col, Row} from 'react-bootstrap'; // From https://github.com/oliviertassinari/react-swipeable-views import Terms from './Terms'; import ScaleBar from './ScaleBar'; import { InputGroup, FormControl , DropdownButton} from 'react-bootstrap'; import RaisedButton from 'material-ui/RaisedButton'; import IconMenu from 'material-ui/IconMenu'; import IconButton from 'material-ui/IconButton'; import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card'; import Checkbox from 'material-ui/Checkbox'; import Divider from 'material-ui/Divider'; import MenuItem from 'material-ui/MenuItem'; import Avatar from 'material-ui/Avatar'; import {List, ListItem} from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import CommunicationChatBubble from 'material-ui/svg-icons/communication/chat-bubble'; import Save from 'material-ui/svg-icons/content/save'; import Cancel from 'material-ui/svg-icons/action/highlight-off'; import Export from 'material-ui/svg-icons/file/file-download'; import Monitoring from './Monitoring.js'; import Dialog from 'material-ui/Dialog'; import {scaleLinear} from 'd3-scale'; import {range} from 'd3-array'; import CircularProgress from 'material-ui/CircularProgress'; import FlatButton from 'material-ui/FlatButton'; import { Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import $ from 'jquery'; const styles = { card: { borderStyle: 'solid', borderColor: '#C09ED7', background: 'white', borderRadius: '0px 0px 0px 0px', borderWidth: '0px 0px 0px 0px' }, avatar:{ margin:'-4px 8px 0px 0px', }, cardHeader:{ background: "white", //'#DCCCE7', padding:'10px 1px 10px 6px', borderRadius: '0px 0px 0px 0px', }, cardMedia:{ background: "white", padding:'2px 4px 2px 4px', borderRadius: '0px 0px 0px 0px', height: "382px", }, }; class CircularProgressSimple extends React.Component{ render(){ return( <div style={{borderColor:"green", marginLeft:"50%"}}> <CircularProgress size={30} thickness={7} /> </div> );} } class FocusedCrawling extends Component { constructor(props) { super(props); this.state = { slideIndex: 0, pages:{}, currentTags:undefined, selectedPosTags: ["Relevant"], selectedNegTags: ["Irrelevant"], session:{}, loadTerms:false, disableStopCrawlerSignal:true, disableAcheInterfaceSignal:true, disabledCreateModel:false, //false disabledStartCrawler:false, //false messageCrawler:"", open:false, openDialog:false, anchorEl:undefined, termsList: [], accuracyOnlineLearning:0, loadingModel:false, createModelMessage:"", openMessageModelResult:false, openDialogStatusCrawler:false, messageErrorCrawler:'', }; this.handleCloseDialogStatusCrawler = this.handleCloseDialogStatusCrawler.bind(this); } /** * Set * @method componentWillMount * @param */ componentWillMount(){ var update_disabledStartCrawler = (this.props.updateCrawlerData)?true:false; this.setState({session:this.props.session, disabledStartCrawler:update_disabledStartCrawler,}); this.forceUpdate(); var temp_session = this.props.session; this.getAvailableTags(this.props.session); this.getModelTags(this.props.domainId); } componentWillReceiveProps = (newProps, nextState) => { } setSelectedPosTags(selectedPosTags){ } loadingTerms(session, selectedPosTags){ var temp_session = session; temp_session['newPageRetrievalCriteria'] = "one"; temp_session['pageRetrievalCriteria'] = "Tags"; temp_session['selected_tags']=this.state.selectedPosTags.join(','); this.setState({session: temp_session, selectedPosTags: selectedPosTags, loadTerms:true}); this.forceUpdate(); } updateTerms(terms){ this.setState({termsList: terms}); } getAvailableTags(session){ $.post( '/getAvailableTags', {'session': JSON.stringify(session), 'event': 'Tags'}, function(tagsDomain) { this.setState({currentTags: tagsDomain['tags']}); //, session:this.props.session, tagString: JSON.stringify(this.props.session['selected_tags'])}); this.forceUpdate(); }.bind(this) ); } getModelTags(domainId){ $.post( '/getModelTags', {'domainId': domainId}, function(tags){ var session = this.props.session; session['model']['positive'] = []; session['model']['negative'] = []; if(Object.keys(tags).length > 0){ session['model']['positive'] = tags['positive'].slice(); session['model']['negative'] = tags['negative'].slice(); //setting session info for generating terms. session['newPageRetrievalCriteria'] = "one"; session['pageRetrievalCriteria'] = "Tags"; session['selected_tags']=(tags['positive'].slice()).join(','); this.updateClassifierCrawler(session); this.setState({session: session, selectedPosTags: tags['positive'].slice(), selectedNegTags: tags['negative'].slice(), loadTerms:true}); this.forceUpdate(); } else {if(!(session['model']['positive'].length>0)){ this.setState({loadTerms:false,}); this.forceUpdate(); }} }.bind(this) ); } saveInitialModel() { var session = this.props.session; session['model']['positive'] = this.state.selectedPosTags.slice(); session['model']['negative'] = this.state.selectedNegTags.slice(); //this.setState({session: session, selectedPosTags: this.state.selectedPosTags.slice(),}); if(session['model']['positive'].length>0 ){ this.loadingTerms(session, this.state.selectedPosTags); this.updateClassifierCrawler(session); $.post( '/saveModelTags', {'session': JSON.stringify(session)}, function(update){ //this.forceUpdate(); }.bind(this) ); } } handleSaveTags() { var session = this.props.session; session['model']['positive'] = this.state.selectedPosTags.slice(); session['model']['negative'] = this.state.selectedNegTags.slice(); //this.setState({session: session, selectedPosTags: this.state.selectedPosTags.slice(),}); if(session['model']['positive'].length>0 ){ this.loadingTerms(session, this.state.selectedPosTags); } else{ this.setState({openDialog:true, loadTerms:false}); } this.updateClassifierCrawler(session); $.post( '/saveModelTags', {'session': JSON.stringify(session)}, function(update){ //this.forceUpdate(); }.bind(this) ); } handleCancelTags(){ this.setState({selectedPosTags: this.state.session['model']['positive'].slice(), selectedNegTags: this.state.session['model']['negative'].slice()}) this.forceUpdate(); } addPosTags(tag){ var tags = this.state.selectedPosTags; if(tags.includes(tag)){ var index = tags.indexOf(tag); tags.splice(index, 1); } else{ tags.push(tag); } this.setState({selectedPosTags: tags}) this.forceUpdate(); } addNegTags(tag){ var tags = this.state.selectedNegTags; if(tags.includes(tag)){ var index = tags.indexOf(tag); tags.splice(index, 1); } else{ tags.push(tag); } this.setState({selectedNegTags: tags}) this.forceUpdate(); } startFocusedCrawler =()=>{ this.saveInitialModel(); this.startCrawler("focused"); this.forceUpdate(); } startCrawler(type){ var session = JSON.parse(JSON.stringify(this.state.session)); var message = "Running"; this.setState({disableAcheInterfaceSignal:false, disableStopCrawlerSignal:false, disabledStartCrawler:true, messageCrawler:message}); this.forceUpdate(); var terms = []; var pos_terms = []; terms = pos_terms = this.state.termsList.map((term)=>{ if(term['tags'].indexOf('Positive') !== -1) return term['word']; }).filter((term)=>{return term !== undefined}); if(pos_terms.length === 0){ terms = this.state.termsList.map((term)=>{ return term['word'] }); } $.post( '/startCrawler', {'session': JSON.stringify(session),'type': type, 'terms': this.state.termsList.join('|')}, function(message) { var disableStopCrawlerFlag = false; var disableAcheInterfaceFlag = false; var disabledStartCrawlerFlag = true; var crawlerIsNotRunningFlag = false; var messageErrorCrawlerTemp = ''; if(message.toLowerCase() === "no regex domain model available" || message.toLowerCase()=== "no page classifier or regex domain model available" || message.toLowerCase()==="no domain model available" || message.toLowerCase()=== "failed to connect to server. server may not be running" || message.toLowerCase()=== "failed to run crawler"){ disableStopCrawlerFlag = true; disableAcheInterfaceFlag =true; disabledStartCrawlerFlag = false; crawlerIsNotRunningFlag = true; messageErrorCrawlerTemp = message; } this.setState({ disableAcheInterfaceSignal: disableAcheInterfaceFlag, disableStopCrawlerSignal:disableStopCrawlerFlag, disabledStartCrawler:disabledStartCrawlerFlag, messageCrawler:message, openDialogStatusCrawler:crawlerIsNotRunningFlag, messageErrorCrawler:messageErrorCrawlerTemp}); this.forceUpdate(); }.bind(this) ); } stopFocusedCrawler(event) { this.stopCrawler("focused"); } stopCrawler(type){ var session = this.props.session; var message = "Terminating"; this.setState({disableAcheInterfaceSignal:true, disableStopCrawlerSignal:true, disabledStartCrawler:true, messageCrawler:message,}); this.forceUpdate(); $.post( '/stopCrawler', {'session': JSON.stringify(session), 'type' : type }, function(message) { this.setState({disableAcheInterfaceSignal:true, disableStopCrawlerSignal:true, disabledStartCrawler: false, messageCrawler:"",}); this.forceUpdate(); }.bind(this) ).fail((error) => { this.setState({disabledStartCrawler: false}); }); } handleRequestClosePopOver(){ this.setState({open:false}); } handleExport(event){ this.setState({open:true,anchorEl:event.currentTarget}) } handleOpenMenu = () => { this.setState({ openMenu: true, }); } handlecloseDialog(){ this.setState({openDialog:false}); this.forceUpdate(); } //Handling open/close 'status crawler' Dialog handleCloseDialogStatusCrawler = () => { this.setState({openDialogStatusCrawler: false, }); }; handleOnRequestChange = (value) => { this.setState({ openMenu: value, }); } //////////////////// ///Create a model//// //////////////////// getCreatedModel(session){ this.setState({loadingModel:true, disabledCreateModel:true, createModelMessage:"",}) $.post( '/createModel', {'session': JSON.stringify(session)}, function(model_file) { var url = model_file; var message = (url.indexOf("_model.zip")==-1)?"Model was not created.":"Model created successfully."; this.setState({modelDownloadURL: model_file, loadingModel:false, disabledCreateModel:false, createModelMessage:message, openMessageModelResult:true}) this.forceUpdate(); }.bind(this) ); } exportModel(){ this.getCreatedModel(this.state.session); } downloadExportedModel = (event) => { if((this.state.modelDownloadURL || "").indexOf("_model.zip") !== -1) window.open(this.state.modelDownloadURL, 'download') } handleCloseModelResult = () => { this.setState({openMessageModelResult: false}); }; //////////////////// ////////////////////// ///////////////////// updateClassifierCrawler(sessionTemp){ $.post( '/updateClassifierCrawler', {'session': JSON.stringify(sessionTemp)}, function(accuracy) { this.setState({accuracyOnlineLearning:accuracy,}); this.forceUpdate(); }.bind(this) ); } /////////////////////// ////////////////////// render() { var total_selectedPosTags=0; var total_selectedNegTags=0; var ratioPosNeg =0; var ratioAccuracy=0; var checkedTagsPosNeg = (this.state.currentTags!==undefined) ? <Row style={{height:330, overflowY: "scroll", }}> <Col xs={6} md={6} style={{marginTop:'2px'}}> Positive {Object.keys(this.state.currentTags).map((tag, index)=>{ var labelTags= tag+" (" +this.state.currentTags[tag]+")"; var checkedTag=false; var tags = this.state.selectedPosTags; if(tags.includes(tag)){ checkedTag=true; total_selectedPosTags=total_selectedPosTags +this.state.currentTags[tag]; } return <Checkbox label={labelTags} checked={checkedTag} onClick={this.addPosTags.bind(this,tag)} /> })} </Col> <Col xs={6} md={6} style={{marginTop:'2px'}}> Negative {Object.keys(this.state.currentTags).map((tag, index)=>{ var labelTags= tag+" (" +this.state.currentTags[tag]+")"; var checkedTag=false; var tags = this.state.selectedNegTags; if(tags.includes(tag)){ checkedTag=true; total_selectedNegTags=total_selectedNegTags+this.state.currentTags[tag]; } return <Checkbox label={labelTags} checked={checkedTag} onClick={this.addNegTags.bind(this,tag)} /> })} </Col> </Row>:<div />; ratioPosNeg = (total_selectedPosTags>total_selectedNegTags)?total_selectedNegTags/total_selectedPosTags:total_selectedPosTags/total_selectedNegTags; ratioAccuracy = ratioPosNeg*this.state.accuracyOnlineLearning; var barScale = scaleLinear().range([0, 240]); barScale.domain([0, 100]); var aux_ratioAccuracy = barScale(ratioAccuracy); var DialogBox= <RaisedButton disabled={false} onTouchTap={this.handlecloseDialog.bind(this)} style={{ height:20, marginTop: 15, marginRight:10, minWidth:118, width:118}} labelStyle={{textTransform: "capitalize"}} buttonStyle={{height:19}} label="Close" labelPosition="before" containerElement="label" />; var renderTerms = (this.state.loadTerms)?<Terms statedCard={true} sizeAvatar={20} showExpandableButton={false} actAsExpander={false} BackgroundColorTerm={"white"} renderAvatar={false} session={this.state.session} focusedCrawlDomains={this.state.loadTerms} fromCrawling={true} updateTerms={this.updateTerms.bind(this)}/> :<div></div>; var openMessage = (this.props.slideIndex && this.state.openDialog)?true:false; var loadingModel_signal = (this.state.disabledCreateModel)?<CircularProgressSimple style={{marginTop:"5px", marginLeft:"-30px"}} size={20} thickness={4} />:<div />; const actionsModelResult = [ <FlatButton label="Close" primary={true} onTouchTap={this.handleCloseModelResult.bind(this)} />, ]; const actionsStatusCrawler = [ <FlatButton label="Close" primary={true} onTouchTap={this.handleCloseDialogStatusCrawler.bind(this)}/>, ]; return ( <div> <Row> <Col xs={11} md={11} style={{margin:'10px'}}> <Card id={"Settings"} initiallyExpanded={true} style={{paddingBottom:0,}} containerStyle={{paddingBottom:0,}} > <CardHeader title="Model Settings" actAsExpander={false} showExpandableButton={false} style={{fontWeight:'bold', padding:'10px 1px 10px 6px', borderRadius: '0px 0px 0px 0px',}} /> <CardText expandable={true} style={{padding:'1px 16px 0px 16px',}}> <Row> <Col xs={7} md={7} style={{margin:0, padding:0,}}> <Card id={"Tags"} initiallyExpanded={true} style={styles.card}> <CardHeader title="Select postive and negative examples." actAsExpander={false} showExpandableButton={false} style={styles.cardHeader} /> <CardText expandable={true} style={styles.cardMedia}> <Divider/> <Row style={{margin:"5px 5px 10px 20px"}} title="Model Settings"> {checkedTagsPosNeg} </Row> <Row style={{margin:"-8px 5px 10px 20px"}}> <RaisedButton disabled={false} label="Save" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} icon={<Save />} //buttonStyle={{height:19}} style={{height:35, marginTop: 8, marginBottom:"-8px", marginRight:10}} disabled={false} onTouchTap={this.handleSaveTags.bind(this)} /> <RaisedButton disabled={false} label="Cancel" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} icon={<Cancel />} //buttonStyle={{height:19}} style={{height:35, marginTop: 8, marginBottom:"-8px"}} disabled={false} onTouchTap={this.handleCancelTags.bind(this)} /> </Row> <Dialog title="Select positive tags to extract terms." open={openMessage}> {DialogBox}</Dialog> </CardText> </Card> </Col> <Col xs={5} md={5} style={{margin:0, padding:0,}}> {renderTerms} </Col> </Row> </CardText> </Card> </Col> </Row> <Row> <Col xs={5} md={5} style={{margin:'10px'}}> <Card id={"Crawling"} initiallyExpanded={true} > <CardHeader title="CRAWLING" actAsExpander={false} showExpandableButton={false} style={{fontWeight:'bold',}} /> <CardText expandable={true} style={{height:212}}> <Row> <Col xs={5} md={5} style={{marginLeft:'0px'}}> <RaisedButton label="Start Crawler" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} //icon={<Search />} disable={this.state.disabledStartCrawler} style={ this.state.disabledStartCrawler ? {pointerEvents: 'none', opacity: 0.5, height:35, marginTop: 0, margin: 12} : {pointerEvents: 'auto', opacity: 1.0, height:35, marginTop: 0, margin: 12} } onClick={this.startFocusedCrawler} /> </Col> { this.state.disabledStartCrawler ? <Col xs={7} md={7} style={{marginLeft:'-70px'}}> <RaisedButton label="Crawler Monitor" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} style={{height:35, marginTop: 0, margin: 12}} href={this.props.crawlerServers['focused']+"/monitoring"} target="_blank" /> <RaisedButton label="Stop Crawler" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} style={{height:35, marginTop: 0, margin: 12}} onClick={this.stopFocusedCrawler.bind(this)} /> </Col> : null } </Row> </CardText> </Card> </Col> <Col xs={6} md={6} style={{margin:'10px', marginLeft:"-10px",}}> <Card id={"Model"} initiallyExpanded={true} > <CardHeader title="Model" actAsExpander={false} showExpandableButton={false} style={{fontWeight:'bold'}} /> <CardText expandable={true} style={{marginTop:"-12px", paddingTop:0, marginBottom:18,}}> <p><span style={{marginRight:10,}}>Total Positive: </span>{total_selectedPosTags} </p> <p><span style={{marginRight:10,}}>Total Negative: </span>{total_selectedNegTags} </p> <p><span>Domain Model (Accuracy): </span> {this.state.accuracyOnlineLearning} %</p> <Divider /> <div style={{marginLeft:10, marginTop:0, marginBottom:"-25px"}}> <ScaleBar ratioAccuracy={aux_ratioAccuracy}/> </div> <div style={{marginTop:"-20px", }}> <RaisedButton disabled={this.state.disabledCreateModel} label="Export" labelStyle={{textTransform: "capitalize", fontSize:14, fontWeight:"normal"}} backgroundColor={this.props.backgroundColor} icon={<Export />} style={{height:35, marginTop: 0, margin: 12}} onClick={this.exportModel.bind(this)} /> <div style={{marginTop:"-40px", marginLeft:"-180px"}}> {loadingModel_signal} </div> <Dialog actions={actionsModelResult} modal={false} open={this.state.openMessageModelResult} onRequestClose={this.handleCloseModelResult.bind(this)} > {this.state.createModelMessage} <RaisedButton label="Download" style={{margin: 5}} labelStyle={{textTransform: "capitalize"}} onClick={this.downloadExportedModel} /> </Dialog> <Dialog title="Status Focused Crawler" actions={actionsStatusCrawler} modal={true} open={this.state.openDialogStatusCrawler} onRequestClose={this.handleCloseDialogStatusCrawler.bind(this)}> {this.state.messageErrorCrawler} </Dialog> </div> </CardText> </Card> </Col> </Row> </div> ); } } FocusedCrawling.defaultProps = { backgroundColor:"#9A7BB0", }; export default FocusedCrawling;
components/Deadline/components/List/List.js
yabeow/sinhvienuit
import React from 'react'; import PropTypes from 'prop-types'; import { FlatList, RefreshControl } from 'react-native'; import { View } from 'native-base'; import Deadline from './Item'; import EmptyList from '../../../EmptyList'; import { ANDROID_PULL_TO_REFRESH_COLOR } from '../../../../config/config'; const sortDeadlines = deadlines => // Sắp xếp theo thứ tự thời gian còn lại tăng dần. deadlines.sort((a, b) => { let timeA = a.getTime(); let timeB = b.getTime(); if (a.getStatus() !== 0) { timeA += 999999999999999; } if (b.getStatus() !== 0) { timeB += 999999999999999; } if (timeA < timeB) return -1; if (timeA > timeB) return 1; return 0; }); class List extends React.Component { constructor(props) { super(props); const { deadlines } = this.props; this.state = { deadlines: sortDeadlines(deadlines), }; } componentWillReceiveProps(nextProps) { const { deadlines } = nextProps; if (deadlines !== this.props.deadlines) { this.setState({ deadlines: sortDeadlines(deadlines) }); } } render() { if ( typeof this.props.onRefresh !== 'undefined' && typeof this.props.refreshing !== 'undefined' ) { return ( <FlatList ListEmptyComponent={<EmptyList />} data={this.state.deadlines} horizontal={false} keyExtractor={course => course.getId()} renderItem={({ item }) => <Deadline deadline={item} />} refreshControl={ <RefreshControl refreshing={this.props.refreshing} onRefresh={() => this.props.onRefresh()} colors={ANDROID_PULL_TO_REFRESH_COLOR} /> } /> ); } return ( <View> {this.state.deadlines.map(item => <Deadline deadline={item} key={item.getId()} />)} </View> ); } } List.defaultProps = { refreshing: false, onRefresh: () => {}, }; List.propTypes = { deadlines: PropTypes.array.isRequired, refreshing: PropTypes.bool, onRefresh: PropTypes.func, }; export default List;
js/BaseComponents/ThemedMaterialIcon.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app 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 Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. */ // @flow 'use strict'; import React from 'react'; import Icon from 'react-native-vector-icons/MaterialIcons'; import { withTheme, } from '../App/Components/HOC/withTheme'; import { prepareRootPropsIcon, } from './prepareRootProps'; const ThemedMaterialIcon = (props: Object): Object => { return ( <Icon {...prepareRootPropsIcon(props)} allowFontScaling={false}/> ); }; export default (withTheme(ThemedMaterialIcon): Object);
src/components/Main.js
Amous-th/gallery-by-react
require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import {findDOMNode} from 'react-dom'; //获取图片相关的数据 var imageDatas = require('../data/imageDatas.json'); //利用自执行函数,将图片信息转成图片URL路径信息 imageDatas = (function getImageURL(imageDataArr) { for(var i = 0,j=imageDataArr.length;i<j;i++){ var singleImageData = imageDataArr[i]; singleImageData.imageURL = require('../images/'+singleImageData.fileName) imageDataArr[i] = singleImageData; } return imageDataArr; })(imageDatas); /* * 获取区间内的一个随机值 */ function getRangeRandom(low, high) { return Math.ceil(Math.random() * (high - low) + low); } /* * 获取 0~30° 之间的一个任意正负值 */ function get30DegRandom() { return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30)); } var ImgFigure = React.createClass({ /* * imgFigure 的点击处理函数 */ handleClick: function (e) { if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); }, render:function () { var styleObj = {}; // 如果props属性中指定了这张图片的位置,则使用 if (this.props.arrange.pos) { styleObj = this.props.arrange.pos; } // 如果图片的旋转角度有值并且不为0, 添加旋转角度 if (this.props.arrange.rotate) { (['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function (value) { styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)'; }.bind(this)); } // 如果是居中的图片, z-index设为11 if (this.props.arrange.isCenter) { styleObj.zIndex = 11; } var imgFigureClassName = 'img-figure'; imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : ''; return ( <figure className={imgFigureClassName} style={styleObj} onClick={this.handleClick}> <img src={this.props.data.imageURL} alt={this.props.data.title} /> <figcaption> <h2 className="img-title">{this.props.data.title}</h2> <div className="img-back" onClick={this.handleClick}> <p> {this.props.data.desc} </p> </div> </figcaption> </figure> ); } }); // 控制组件 var ControllerUnit = React.createClass({ handleClick: function (e) { // 如果点击的是当前正在选中态的按钮,则翻转图片,否则将对应的图片居中 if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.preventDefault(); e.stopPropagation(); }, render: function () { var controlelrUnitClassName = 'controller-unit'; // 如果对应的是居中的图片,显示控制按钮的居中态 if (this.props.arrange.isCenter) { controlelrUnitClassName += ' is-center'; // 如果同时对应的是翻转图片, 显示控制按钮的翻转态 if (this.props.arrange.isInverse) { controlelrUnitClassName += ' is-inverse'; } } return ( <span className={controlelrUnitClassName} onClick={this.handleClick}></span> ); } }); var GalleryByReactApp = React.createClass ({ Constant: { centerPos: { left: 0, right: 0 }, hPosRange: { // 水平方向的取值范围 leftSecX: [0, 0], rightSecX: [0, 0], y: [0, 0] }, vPosRange: { // 垂直方向的取值范围 x: [0, 0], topY: [0, 0] } }, /* * 翻转图片 * @param index 传入当前被执行inverse操作的图片对应的图片信息数组的index值 * @returns {Function} 这是一个闭包函数, 其内return一个真正待被执行的函数 */ inverse: function (index) { return function () { var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); }.bind(this); }, /* * 重新布局所有图片 * @param centerIndex 指定居中排布哪个图片 */ rearrange: function (centerIndex) { var imgsArrangeArr = this.state.imgsArrangeArr, Constant = this.Constant, centerPos = Constant.centerPos, hPosRange = Constant.hPosRange, vPosRange = Constant.vPosRange, hPosRangeLeftSecX = hPosRange.leftSecX, hPosRangeRightSecX = hPosRange.rightSecX, hPosRangeY = hPosRange.y, vPosRangeTopY = vPosRange.topY, vPosRangeX = vPosRange.x, imgsArrangeTopArr = [], topImgNum = Math.floor(Math.random() * 2), // 取一个或者不取 topImgSpliceIndex = 0, imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1); // 首先居中 centerIndex 的图片, 居中的 centerIndex 的图片不需要旋转 imgsArrangeCenterArr[0] = { pos: centerPos, rotate: 0, isCenter: true }; // 取出要布局上侧的图片的状态信息 topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum)); imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum); // 布局位于上侧的图片 imgsArrangeTopArr.forEach(function (value, index) { imgsArrangeTopArr[index] = { pos: { top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]), left: getRangeRandom(vPosRangeX[0], vPosRangeX[1]) }, rotate: get30DegRandom(), isCenter: false }; }); // 布局左右两侧的图片 for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) { var hPosRangeLORX = null; // 前半部分布局左边, 右半部分布局右边 if (i < k) { hPosRangeLORX = hPosRangeLeftSecX; } else { hPosRangeLORX = hPosRangeRightSecX; } imgsArrangeArr[i] = { pos: { top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]), left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]) }, rotate: get30DegRandom(), isCenter: false }; } if (imgsArrangeTopArr && imgsArrangeTopArr[0]) { imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]); } imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]); this.setState({ imgsArrangeArr: imgsArrangeArr }); }, /* * 利用arrange函数, 居中对应index的图片 * @param index, 需要被居中的图片对应的图片信息数组的index值 * @returns {Function} */ center: function (index) { return function () { this.rearrange(index); }.bind(this); }, getInitialState: function () { return { imgsArrangeArr: [ /*{ pos: { left: '0', top: '0' }, rotate: 0, // 旋转角度 isInverse: false, // 图片正反面 isCenter: false, // 图片是否居中 }*/ ] }; }, //组建加载后,为每张图片计算其位置的范围 componentDidMount: function () { //首先拿到舞台的大小 var stageDOM = findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW/2), halfStageH = Math.ceil(stageH/2); //拿到一个imgFilgure的大小 var imgFigureDom = findDOMNode(this.refs.imgFigure0), imgW = imgFigureDom.scrollWidth, imgH = imgFigureDom.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); // 计算中心图片的位置点 this.Constant.centerPos = { left: halfStageW - halfImgW, top: halfStageH - halfImgH }; // 计算左侧,右侧区域图片排布位置的取值范围 this.Constant.hPosRange.leftSecX[0] = -halfImgW; this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3; this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW; this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW; this.Constant.hPosRange.y[0] = -halfImgH; this.Constant.hPosRange.y[1] = stageH - halfImgH; // 计算上侧区域图片排布位置的取值范围 this.Constant.vPosRange.topY[0] = -halfImgH; this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3; this.Constant.vPosRange.x[0] = halfStageW - imgW; this.Constant.vPosRange.x[1] = halfStageW; this.rearrange(0); }, render() { var controllerUnits = [], imgFigures=[]; imageDatas.forEach(function (value,index) { if (!this.state.imgsArrangeArr[index]) { this.state.imgsArrangeArr[index] = { pos: { left: 0, top: 0 }, rotate: 0, isInverse: false //isCenter: false }; } imgFigures.push( <ImgFigure data={value} key={index} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} />); controllerUnits.push( <ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)} /> ); }.bind(this)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFigures} <nav className="controller-nav"> {controllerUnits} </nav> </section> </section> ); } }) GalleryByReactApp.defaultProps = { }; export default GalleryByReactApp;
src/frontend/src/components/DonorDetailPage.js
open-austin/influence-texas
import React from 'react' import { useParams } from 'react-router-dom' import { useQuery } from '@apollo/react-hooks' import { gql } from 'apollo-boost' import Typography from '@material-ui/core/Typography' import PaginatedList, { ShortLoadingListBody } from './PaginatedList' import { formatMoney, getDebugQuery } from 'utils' import CustomLink from 'components/CustomLink' import { BlankLoadingLine } from 'styles' import { RoundSquare } from 'styles' import { useTheme } from '@material-ui/core' const GET_DONOR = gql` query Donor($id: Int!) { donor(pk: $id) { fullName totalContributions city state employer occupation donations { cycleTotal candidateName office party legId } } ${getDebugQuery()} } ` function DonorDetailPage() { const { palette } = useTheme() const { id } = useParams() const { data, loading, error } = useQuery(GET_DONOR, { variables: { id }, }) document.title = `${data ? data.donor.fullName : ''} - Influence Texas` if (error) { return 'server error' } const fullDonorData = data ? data.donor : {} return ( <div className="detail-page"> <CustomLink to="/donors"> ← All Donors</CustomLink> <section style={{ margin: '1rem' }}> <h1> {loading ? <BlankLoadingLine width="40%" /> : fullDonorData.fullName} </h1> <div> {loading ? ( <BlankLoadingLine width="20%" /> ) : ( `Total Contributions: ${formatMoney( fullDonorData.totalContributions, )}` )} </div> {fullDonorData.occupation}{' '} {fullDonorData.occupation && fullDonorData.employer && 'at'}{' '} {fullDonorData.employer} <div> {fullDonorData.city}, {fullDonorData.state} </div> </section> <PaginatedList url="legislators/legislator" pk="legId" data={ loading ? null : { edges: fullDonorData.donations, totalCount: fullDonorData.donations.length, } } columns={[ { render: (rowData) => ( <div style={{ display: 'flex' }}> <RoundSquare style={{ marginTop: 10, width: 20, height: 20, background: rowData.legId ? palette.primary.main : '#bbb', }} /> <div style={{ margin: '0 1em' }}> <Typography>{rowData.candidateName}</Typography> <Typography variant="subtitle2"> {rowData.office} {rowData.party ? `(${rowData.party})` : ''} </Typography> </div> </div> ), }, { render: (rowData) => ( <div style={{ textAlign: 'right' }}> {formatMoney(rowData.cycleTotal)} </div> ), }, ]} showHover={(rowData) => !!rowData.legId} loading={loading} loadingListBody={ShortLoadingListBody} rowsPerPage={500} /> </div> ) } export default DonorDetailPage
packages/core/__deprecated__/Project/Project.js
romelperez/arwes
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import AnimationComponent from '../Animation'; import FrameComponent from '../Frame'; import WordsComponent from '../Words'; import HeadingComponent from '../Heading'; // TODO: // - Add a 'featured' prop to highligh item. export default function Project (props) { const { theme, classes, sounds, Animation, Frame, Words, Heading, animation, animate, show, node, header, headerSize, icon, className, children, ...etc } = props; const cls = cx(classes.root, className); return ( <Animation animate={animate} show={show} timeout={theme.animTime} {...animation} > {anim => React.createElement( node, { className: cx(cls, classes[anim.status]), ...etc }, <Frame animate={animate} show={show} timeout={theme.animTime} layer='primary' level={0} corners={4} hover noBackground onClick={() => sounds.click && sounds.click.play()} > {frameAnim => ( <div> <header className={classes.header}> <Heading node='h1'> <Words animate={animate} show={frameAnim.entered}> {header} </Words> </Heading> <div className={classes.icon}>{icon}</div> </header> <div className={classes.separator} /> <div className={classes.children}> {typeof children === 'function' ? children(frameAnim) : children} </div> </div> )} </Frame> ) } </Animation> ); } Project.propTypes = { Animation: PropTypes.any.isRequired, Frame: PropTypes.any.isRequired, Words: PropTypes.any.isRequired, Heading: PropTypes.any.isRequired, theme: PropTypes.any.isRequired, classes: PropTypes.any.isRequired, animate: PropTypes.bool, show: PropTypes.bool, animation: PropTypes.object, /** * It uses the `click` player. */ sounds: PropTypes.object, /** * The HTML tag element to use. */ node: PropTypes.string, /** * The HTML header used for the title. */ header: PropTypes.string.isRequired, /** * The actual font size to use for the HTML header. */ headerSize: PropTypes.oneOf(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']), /** * The icon to decorate the project. */ icon: PropTypes.any, /** * If function, receives the animation status object. */ children: PropTypes.any, className: PropTypes.any }; Project.defaultProps = { Animation: AnimationComponent, Frame: FrameComponent, Words: WordsComponent, Heading: HeadingComponent, show: true, sounds: {}, node: 'article', headerSize: 'h2', icon: <i className='mdi mdi-package' /> };
docs/app/Examples/modules/Dropdown/Content/DropdownExampleLabel.js
clemensw/stardust
import React from 'react' import { Dropdown } from 'semantic-ui-react' const DropdownExampleLabel = () => ( <Dropdown text='Filter' floating labeled button className='icon'> {/* <i class="filter icon"></i> */} <Dropdown.Menu> <Dropdown.Header icon='tags' content='Filter by tag' /> <Dropdown.Divider /> <Dropdown.Item label={{ color: 'red', empty: true, circular: true }} text='Important' /> <Dropdown.Item label={{ color: 'blue', empty: true, circular: true }} text='Announcement' /> <Dropdown.Item label={{ color: 'black', empty: true, circular: true }} text='Discussion' /> </Dropdown.Menu> </Dropdown> ) export default DropdownExampleLabel
components/Form/Select/Select.story.js
NGMarmaduke/bloom
import React from 'react'; import { storiesOf, action } from '@storybook/react'; import { withKnobs, boolean } from '@storybook/addon-knobs'; import Select from './Select'; import Option from './Option'; import icons from '../../Icon/icons'; const stories = storiesOf('FormComponents', module); stories.addDecorator(withKnobs); stories.add('Select', () => ( <Select name="icon" onChange={ action('onChange') } onFocus={ action('onFocus') } onBlur={ action('onBlur') } error={ boolean('Errored', false) ? 'Something went wrong' : '' } multiple={ boolean('Multiple', false) } > { Object .keys(icons) .map(option => ( <Option key={ option } value={ option }>{ option }</Option> )) } </Select> )) .add('Select w/high priority', () => ( <Select name="icon" onChange={ action('onChange') } onFocus={ action('onFocus') } onBlur={ action('onBlur') } error={ boolean('Errored', false) ? 'Something went wrong' : '' } multiple={ boolean('Multiple', false) } priority="high" > { Object .keys(icons) .map(option => ( <Option key={ option } value={ option }>{ option }</Option> )) } </Select> ));
node_modules/redbox-react/examples/react-hot-loader-example/index.js
hnikupet/dddhackaton
import React from 'react' import App from './components/App' const root = document.getElementById('root') React.render(<App />, root)
src/components/Layout/SearchDrawer/AdvancedSearch/DateField/presenter.js
ndlib/usurper
import React from 'react' import PropTypes from 'prop-types' const DateField = (props) => { // Create list of days const days = [(<option id={`${props.id}Day_00`} key={`${props.id}Day_00`}>Day</option>)] for (let i = 1; i <= 31; i++) { const id = `${props.id}${props.formatID(i, 'Day')}` days.push(<option id={id} key={id}>{i}</option>) } // Create list of months const months = [(<option id={`${props.id}Month_00`} key={`${props.id}Month_00`}>Month</option>)] for (let i = 1; i <= 12; i++) { const id = `${props.id}${props.formatID(i, 'Month')}` months.push(<option id={id} key={id}>{i}</option>) } return ( <div> <label>{props.label}: </label> <div className='dateFieldSelector'> <span className='selector'> <select id={`${props.id}Day`} onChange={props.onChange}>{days}</select> </span> <span className='selector'> <select id={`${props.id}Month`} onChange={props.onChange}>{months}</select> </span> <input type='text' id={`${props.id}Year5`} placeholder='year' onBlur={props.onChange} onKeyDown={props.onKeyDown} autoComplete='off' data-lpignore /> </div> </div> ) } DateField.propTypes = { id: PropTypes.string.isRequired, onChange: PropTypes.func, onKeyDown: PropTypes.func, label: PropTypes.string.isRequired, formatID: PropTypes.func.isRequired, } export default DateField
docs/src/pages/components/tables/CustomPaginationActionsTable.js
lgollut/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableFooter from '@material-ui/core/TableFooter'; import TablePagination from '@material-ui/core/TablePagination'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import IconButton from '@material-ui/core/IconButton'; import FirstPageIcon from '@material-ui/icons/FirstPage'; import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft'; import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight'; import LastPageIcon from '@material-ui/icons/LastPage'; const useStyles1 = makeStyles((theme) => ({ root: { flexShrink: 0, marginLeft: theme.spacing(2.5), }, })); function TablePaginationActions(props) { const classes = useStyles1(); const theme = useTheme(); const { count, page, rowsPerPage, onChangePage } = props; const handleFirstPageButtonClick = (event) => { onChangePage(event, 0); }; const handleBackButtonClick = (event) => { onChangePage(event, page - 1); }; const handleNextButtonClick = (event) => { onChangePage(event, page + 1); }; const handleLastPageButtonClick = (event) => { onChangePage(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); }; return ( <div className={classes.root}> <IconButton onClick={handleFirstPageButtonClick} disabled={page === 0} aria-label="first page" > {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />} </IconButton> <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page"> {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} </IconButton> <IconButton onClick={handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="next page" > {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </IconButton> <IconButton onClick={handleLastPageButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="last page" > {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />} </IconButton> </div> ); } TablePaginationActions.propTypes = { count: PropTypes.number.isRequired, onChangePage: PropTypes.func.isRequired, page: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired, }; function createData(name, calories, fat) { return { name, calories, fat }; } const rows = [ createData('Cupcake', 305, 3.7), createData('Donut', 452, 25.0), createData('Eclair', 262, 16.0), createData('Frozen yoghurt', 159, 6.0), createData('Gingerbread', 356, 16.0), createData('Honeycomb', 408, 3.2), createData('Ice cream sandwich', 237, 9.0), createData('Jelly Bean', 375, 0.0), createData('KitKat', 518, 26.0), createData('Lollipop', 392, 0.2), createData('Marshmallow', 318, 0), createData('Nougat', 360, 19.0), createData('Oreo', 437, 18.0), ].sort((a, b) => (a.calories < b.calories ? -1 : 1)); const useStyles2 = makeStyles({ table: { minWidth: 500, }, }); export default function CustomPaginationActionsTable() { const classes = useStyles2(); const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(5); const emptyRows = rowsPerPage - Math.min(rowsPerPage, rows.length - page * rowsPerPage); const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="custom pagination table"> <TableBody> {(rowsPerPage > 0 ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : rows ).map((row) => ( <TableRow key={row.name}> <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.calories} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.fat} </TableCell> </TableRow> ))} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]} colSpan={3} count={rows.length} rowsPerPage={rowsPerPage} page={page} SelectProps={{ inputProps: { 'aria-label': 'rows per page' }, native: true, }} onChangePage={handleChangePage} onChangeRowsPerPage={handleChangeRowsPerPage} ActionsComponent={TablePaginationActions} /> </TableRow> </TableFooter> </Table> </TableContainer> ); }
app/assets/scripts/components/map-options.js
orma/openroads-vn-analytics
import React from 'react'; import { getContext } from 'recompose'; import T, { translate } from './t'; const MapOptions = ({ layer, language, handleLayerChange, handleShowNoVpromms }) => ( <div className='panel options-panel'> <div className='panel__body'> <form className='form'> <div className='form__group'> <label className='form__label'><T>Visualized variable</T></label> <select className='form__control' onChange={ e => handleLayerChange(e) }> <option value='iri_mean'>{translate(language, 'IRI')}</option> <option value='or_section_delivery_vehicle'>{translate(language, 'CVTS')}</option> </select> </div> {layer === 'iri_mean' && ( <div className='form__group'> <label className='form__label'>{translate(language, 'Options')}</label> <label className='form__option form__option--switch option fos-io' htmlFor='show-no-vpromms' > <input type='checkbox' defaultChecked={true} name='show-no-vpromms' id='show-no-vpromms' value='show-no-vpromms' onChange={ e => handleShowNoVpromms(e) } /> <span className='form__option__ui'></span> <span className='form__option__text'><T>Road without VPRoMMS ID</T> <b>----</b></span> </label> </div> ) } </form> </div> </div> ); MapOptions.propTypes = { layer: React.PropTypes.string, handleLayerChange: React.PropTypes.func, handleShowNoVpromms: React.PropTypes.func, language: React.PropTypes.string }; export default getContext({ language: React.PropTypes.string })(MapOptions);
docs/app/Examples/elements/Icon/IconSet/IconExampleAccessibility.js
ben174/Semantic-UI-React
import React from 'react' import { Grid, Icon } from 'semantic-ui-react' const IconExampleAccessibility = () => ( <Grid columns='5' doubling> <Grid.Column> <Icon name='wheelchair' /> <p>wheelchair</p> </Grid.Column> <Grid.Column> <Icon name='asl interpreting' /> <p>asl interpreting</p> </Grid.Column> <Grid.Column> <Icon name='assistive listening systems' /> <p>assistive listening systems</p> </Grid.Column> <Grid.Column> <Icon name='audio description' /> <p>audio description</p> </Grid.Column> <Grid.Column> <Icon name='blind' /> <p>blind</p> </Grid.Column> <Grid.Column> <Icon name='braille' /> <p>braille</p> </Grid.Column> <Grid.Column> <Icon name='deafness' /> <p>deafness</p> </Grid.Column> <Grid.Column> <Icon name='low vision' /> <p>low vision</p> </Grid.Column> <Grid.Column> <Icon name='sign language' /> <p>sign language</p> </Grid.Column> <Grid.Column> <Icon name='universal access' /> <p>universal access</p> </Grid.Column> <Grid.Column> <Icon name='volume control phone' /> <p>volume control phone</p> </Grid.Column> </Grid> ) export default IconExampleAccessibility
src/svg-icons/hardware/phone-iphone.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwarePhoneIphone = (props) => ( <SvgIcon {...props}> <path d="M15.5 1h-8C6.12 1 5 2.12 5 3.5v17C5 21.88 6.12 23 7.5 23h8c1.38 0 2.5-1.12 2.5-2.5v-17C18 2.12 16.88 1 15.5 1zm-4 21c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5-4H7V4h9v14z"/> </SvgIcon> ); HardwarePhoneIphone = pure(HardwarePhoneIphone); HardwarePhoneIphone.displayName = 'HardwarePhoneIphone'; HardwarePhoneIphone.muiName = 'SvgIcon'; export default HardwarePhoneIphone;
ui/src/main/js/components/UpdateStateMachine.js
rdelval/aurora
import React from 'react'; import StateMachine from 'components/StateMachine'; import { addClass } from 'utils/Common'; import { UPDATE_STATUS } from 'utils/Thrift'; import { getClassForUpdateStatus } from 'utils/Update'; export default function UpdateStateMachine({ update }) { const events = update.updateEvents; const states = events.map((e, i) => ({ className: addClass( getClassForUpdateStatus(e.status), (i === events.length - 1) ? ' active' : ''), state: UPDATE_STATUS[e.status], message: e.message, timestamp: e.timestampMs })); const className = getClassForUpdateStatus(events[events.length - 1].status); return <StateMachine className={addClass('update-state-machine', className)} states={states} />; }
app/javascript/mastodon/features/account_gallery/components/media_item.js
im-in-space/mastodon
import Blurhash from 'mastodon/components/blurhash'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; import { autoPlayGif, displayMedia, useBlurhash } from 'mastodon/initial_state'; import { isIOS } from 'mastodon/is_mobile'; import PropTypes from 'prop-types'; import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; export default class MediaItem extends ImmutablePureComponent { static propTypes = { attachment: ImmutablePropTypes.map.isRequired, displayWidth: PropTypes.number.isRequired, onOpenMedia: PropTypes.func.isRequired, }; state = { visible: displayMedia !== 'hide_all' && !this.props.attachment.getIn(['status', 'sensitive']) || displayMedia === 'show_all', loaded: false, }; handleImageLoad = () => { this.setState({ loaded: true }); } handleMouseEnter = e => { if (this.hoverToPlay()) { e.target.play(); } } handleMouseLeave = e => { if (this.hoverToPlay()) { e.target.pause(); e.target.currentTime = 0; } } hoverToPlay () { return !autoPlayGif && ['gifv', 'video'].indexOf(this.props.attachment.get('type')) !== -1; } handleClick = e => { if (e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); if (this.state.visible) { this.props.onOpenMedia(this.props.attachment); } else { this.setState({ visible: true }); } } } render () { const { attachment, displayWidth } = this.props; const { visible, loaded } = this.state; const width = `${Math.floor((displayWidth - 4) / 3) - 4}px`; const height = width; const status = attachment.get('status'); const title = status.get('spoiler_text') || attachment.get('description'); let thumbnail, label, icon, content; if (!visible) { icon = ( <span className='account-gallery__item__icons'> <Icon id='eye-slash' /> </span> ); } else { if (['audio', 'video'].includes(attachment.get('type'))) { content = ( <img src={attachment.get('preview_url') || attachment.getIn(['account', 'avatar_static'])} alt={attachment.get('description')} onLoad={this.handleImageLoad} /> ); if (attachment.get('type') === 'audio') { label = <Icon id='music' />; } else { label = <Icon id='play' />; } } else if (attachment.get('type') === 'image') { const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0; const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0; const x = ((focusX / 2) + .5) * 100; const y = ((focusY / -2) + .5) * 100; content = ( <img src={attachment.get('preview_url')} alt={attachment.get('description')} style={{ objectPosition: `${x}% ${y}%` }} onLoad={this.handleImageLoad} /> ); } else if (attachment.get('type') === 'gifv') { content = ( <video className='media-gallery__item-gifv-thumbnail' aria-label={attachment.get('description')} role='application' src={attachment.get('url')} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} autoPlay={!isIOS() && autoPlayGif} loop muted /> ); label = 'GIF'; } thumbnail = ( <div className='media-gallery__gifv'> {content} {label && <span className='media-gallery__gifv__label'>{label}</span>} </div> ); } return ( <div className='account-gallery__item' style={{ width, height }}> <a className='media-gallery__item-thumbnail' href={status.get('url')} onClick={this.handleClick} title={title} target='_blank' rel='noopener noreferrer'> <Blurhash hash={attachment.get('blurhash')} className={classNames('media-gallery__preview', { 'media-gallery__preview--hidden': visible && loaded })} dummy={!useBlurhash} /> {visible ? thumbnail : icon} </a> </div> ); } }
src/components/foundation/original/FoundationOriginal.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './FoundationOriginal.svg' /** FoundationOriginal */ function FoundationOriginal({ width, height, className }) { return ( <SVGDeviconInline className={'FoundationOriginal' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } FoundationOriginal.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default FoundationOriginal
src/components/Home/index.js
chavisclark/chavisclark.github.io
import React from 'react'; import Button from '../Button'; import { Link } from 'react-router'; import Helmet from 'react-helmet'; import styles from './styles.css'; function Home() { return ( <article className={styles.padding}> <Helmet title="Chavis Clark | Digital Nomad & Fullstack Web Developer" meta={[ { name: 'description', content: 'Chavis Clark is a self-taught Web Application Developer who works remotely and passionately. View Chavis Clark\'s comprehensive work history and GitHub projects here.' }, ]} /> <div className={`${styles.centered} ${styles.intro}`}> <h3>I develop performance-oriented websites and web applications.</h3> When I'm not practicing Spanish or mentoring less-experienced developers, I'm exploring new places, cultures, and music! </div> </article> ); } export default Home;
examples/src/components/CustomRenderField.js
mcanthony/react-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var CustomRenderField = React.createClass({ displayName: 'CustomRenderField', propTypes: { delimiter: React.PropTypes.string, label: React.PropTypes.string, multi: React.PropTypes.bool, }, renderOption (option) { return <span style={{ color: option.hex }}>{option.label} ({option.hex})</span>; }, renderValue (option) { return <strong style={{ color: option.hex }}>{option.label}</strong>; }, render () { var ops = [ { label: 'Red', value: 'red', hex: '#EC6230' }, { label: 'Green', value: 'green', hex: '#4ED84E' }, { label: 'Blue', value: 'blue', hex: '#6D97E2' } ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select delimiter={this.props.delimiter} multi={this.props.multi} allowCreate={true} placeholder="Select your favourite" options={ops} optionRenderer={this.renderOption} valueRenderer={this.renderValue} onChange={logChange} /> </div> ); } }); module.exports = CustomRenderField;
src/results/ResultsList.react.js
codeforamerica/citybook
import React, { Component } from 'react'; import Alert from 'react-bootstrap/lib/Alert'; import LoadingSpinner from '../LoadingSpinner.react.js'; import Result from './Result.react.js'; import '../../styles/loading-spinner.scss'; export default class ResultsList extends Component { constructor(){ super(); } render() { let list; let errors; if(this.props.erros){ console.error(error); } if(this.props.loaded){ let resultsList = this.props.results; resultsList.sort(function(a, b){ if(a['Organization Name'] < b['Organization Name']) return - 1; if(a['Organization Name'] > b['Organization Name']) return 1; return 0; }); list = resultsList.map(function(result, i){ let resultName = result['Organization Name'] return ( <Result key={i} result={result} /> ) }) } else { list = <LoadingSpinner /> } return( <ul className='results-list row'> {list} </ul> ) } }
src/navigation/auth.js
banovotz/WatchBug2
/** * Auth Scenes * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React from 'react'; import { Scene, ActionConst } from 'react-native-router-flux'; // Consts and Libs import { AppConfig } from '@constants/'; // Scenes import Authenticate from '@containers/auth/AuthenticateView'; import LoginForm from '@containers/auth/Forms/LoginContainer'; import SignUpForm from '@containers/auth/Forms/SignUpContainer'; import ResetPasswordForm from '@containers/auth/Forms/ResetPasswordContainer'; import UpdateProfileForm from '@containers/auth/Forms/UpdateProfileContainer'; /* Routes ==================================================================== */ const scenes = ( <Scene key={'authenticate'}> <Scene hideNavBar key={'authLanding'} component={Authenticate} type={ActionConst.RESET} analyticsDesc={'Authentication'} /> <Scene {...AppConfig.navbarProps} key={'login'} title={'Login'} clone component={LoginForm} analyticsDesc={'Login'} /> <Scene {...AppConfig.navbarProps} key={'signUp'} title={'Sign Up'} clone component={SignUpForm} analyticsDesc={'Sign Up'} /> <Scene {...AppConfig.navbarProps} key={'passwordReset'} title={'Password Reset'} clone component={ResetPasswordForm} analyticsDesc={'Password Reset'} /> <Scene {...AppConfig.navbarProps} key={'updateProfile'} title={'Update Profile'} clone component={UpdateProfileForm} analyticsDesc={'Update Profile'} /> </Scene> ); export default scenes;
src/server/index.js
vesparny/widget
'use strict'; const env = process.env.NODE_ENV || 'development'; import http from 'http'; import path from 'path'; import cors from 'cors'; import React from 'react'; import Router from 'react-router'; import FluxComponent from 'flummox/component'; import Flux from '../shared/Flux'; import routes from '../shared/routes'; import address from 'network-address'; import api from './api'; import logger from './logger'; import { CustomError } from './errors'; import app from './app'; const webpackConfigDev = require('../../webpack.config.development'); let js = `http://${webpackConfigDev._address}:${webpackConfigDev._hotPort}/build/bundle.js`; if (app.get('env') === 'development') { // run webpack dev server require('../../dev-tools'); } if (app.get('env') === 'production') { const webpackBuildStats = require('../../public/build/webpackBuildStats'); js = `/build/bundle-${webpackBuildStats.hash}.min.js`; // jscs:disable } // register apis app.use('/api', api); // react-router will take care of the rest app.use((req, res) => { const flux = new Flux(); let appString; Router.run(routes, req.path, function (Handler, state) { let isNotFound = state.routes.some(route => route.name === 'not-found'); res.status(isNotFound ? 404 : 200); try { appString = React.renderToString( <FluxComponent flux={flux}> <Handler {...state} /> </FluxComponent>); }catch (err) { throw new CustomError({ message: err.message }); } res.render('index', { js: js, appString: appString }); }); }); app.use((err, req, res, next) => {/* eslint no-unused-vars:0 */ logger.error({ err: err.stack }); res.status(err.statusCode); res.send({ error: err.message || 'Unexpected error' }); }); app.listen(app.get('port'), () => { logger.info(`Demo app is listening on ${address()}:${app.get('port')} env=${env}`); // jscs:disable });
packages/material-ui-icons/src/Laptop.js
cherniavskii/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2h-4zM4 6h16v10H4V6z" /></g> , 'Laptop');
blueocean-material-icons/src/js/components/svg-icons/image/filter-9.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageFilter9 = (props) => ( <SvgIcon {...props}> <path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14zM15 5h-2c-1.1 0-2 .89-2 2v2c0 1.11.9 2 2 2h2v2h-4v2h4c1.1 0 2-.89 2-2V7c0-1.11-.9-2-2-2zm0 4h-2V7h2v2z"/> </SvgIcon> ); ImageFilter9.displayName = 'ImageFilter9'; ImageFilter9.muiName = 'SvgIcon'; export default ImageFilter9;
docs/src/pages/layout/hidden/BreakpointOnly.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import compose from 'recompose/compose'; import { withStyles } from 'material-ui/styles'; import Paper from 'material-ui/Paper'; import Hidden from 'material-ui/Hidden'; import withWidth from 'material-ui/utils/withWidth'; import Typography from 'material-ui/Typography'; const styles = theme => ({ root: { flexGrow: 1, }, container: { display: 'flex', }, paper: { padding: theme.spacing.unit * 2, textAlign: 'center', color: theme.palette.text.secondary, flex: '1 0 auto', margin: theme.spacing.unit, }, }); function BreakpointOnly(props) { const { classes } = props; return ( <div className={classes.root}> <Typography variant="subheading">Current width: {props.width}</Typography> <div className={classes.container}> <Hidden only="lg"> <Paper className={classes.paper}>Hidden on lg</Paper> </Hidden> <Hidden only="sm"> <Paper className={classes.paper}>Hidden on sm</Paper> </Hidden> <Hidden only={['sm', 'lg']}> <Paper className={classes.paper}>Hidden on sm and lg</Paper> </Hidden> </div> </div> ); } BreakpointOnly.propTypes = { classes: PropTypes.object.isRequired, width: PropTypes.string.isRequired, }; export default compose(withStyles(styles), withWidth())(BreakpointOnly);
server/sonar-web/src/main/js/components/shared/checkbox.js
abbeyj/sonarqube
import React from 'react'; export default React.createClass({ propTypes: { onCheck: React.PropTypes.func.isRequired, initiallyChecked: React.PropTypes.bool, thirdState: React.PropTypes.bool }, getInitialState() { return { checked: this.props.initiallyChecked || false }; }, componentWillReceiveProps(nextProps) { if (nextProps.initiallyChecked != null) { this.setState({ checked: nextProps.initiallyChecked }); } }, toggle(e) { e.preventDefault(); this.props.onCheck(!this.state.checked); this.setState({ checked: !this.state.checked }); }, render() { let classNames = ['icon-checkbox']; if (this.state.checked) { classNames.push('icon-checkbox-checked'); } if (this.props.thirdState) { classNames.push('icon-checkbox-single'); } let className = classNames.join(' '); return <a onClick={this.toggle} className={className} href="#"/>; } });
frontend/app/components/Form/FormRelatedPictures.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' // import Text from 'components/Form/Common/Text' // NOTE: importing the non-wrapped provide() version import FormRelatedPicture from 'components/Form/FormRelatedPicture' import { getIndexOfElementById, removeItem, moveItemDown, moveItemUp } from 'components/Form/FormInteractions' import ProviderHelpers from 'common/ProviderHelpers' // REDUX import { connect } from 'react-redux' // REDUX: actions/dispatch/func import { createContributor, fetchContributors } from 'reducers/fvContributor' import { fetchDialect } from 'reducers/fvDialect' import { fetchResources } from 'reducers/fvResources' import selectn from 'selectn' const { string, array, object, func, number } = PropTypes let SelectMediaComponent = null export class FormRelatedPictures extends React.Component { static propTypes = { name: string.isRequired, className: string, textInfo: string, items: array, idDescribedbyItemBrowse: string, idDescribedByItemMove: string, textDescribedbyItemBrowse: string, textDescribedByItemMove: string, textLegendItems: string, textBtnAddItem: string, textLegendItem: string, textBtnRemoveItem: string, textBtnMoveItemUp: string, textBtnMoveItemDown: string, textBtnCreateItem: string, textBtnSelectExistingItems: string, textLabelItemSearch: string, DEFAULT_PAGE: number, DEFAULT_PAGE_SIZE: number, DEFAULT_LANGUAGE: string, DEFAULT_SORT_COL: string, DEFAULT_SORT_TYPE: string, // REDUX: reducers/state computeContributor: object.isRequired, computeContributors: object.isRequired, computeCreateContributor: object, computeDialect: object.isRequired, computeDialect2: object.isRequired, splitWindowPath: array.isRequired, // REDUX: actions/dispatch/func createContributor: func.isRequired, fetchContributors: func.isRequired, fetchDialect: func.isRequired, fetchResources: func.isRequired, } static defaultProps = { className: 'FormRelatedPictures', idDescribedbyItemBrowse: 'describedbyRelatedPictureBrowse', idDescribedByItemMove: 'describedByRelatedPictureMove', name: 'FormRelatedPictures', textDescribedbyItemBrowse: 'Select a picture from previously created pictures', textDescribedByItemMove: `If you are adding multiple Related Pictures, you can change the position of the picture with the 'Move Related Picture left' and 'Move Related Picture right' buttons`, textLegendItems: 'Related Pictures', textBtnAddItem: 'Add Related Picture', textLegendItem: 'Related Picture', textBtnRemoveItem: 'Remove Related Picture', textBtnMoveItemUp: 'Move Related Picture left', textBtnMoveItemDown: 'Move Related Picture right', textBtnCreateItem: 'Create new picture', textBtnSelectExistingItems: 'Select from existing pictures', textLabelItemSearch: 'Search existing pictures', DEFAULT_PAGE: 1, DEFAULT_PAGE_SIZE: 100, DEFAULT_LANGUAGE: 'english', DEFAULT_SORT_COL: 'dc:title', DEFAULT_SORT_TYPE: 'asc', } state = { items: [], loading: true, pictures: [], } // Fetch data on initial render async componentDidMount() { const { computeDialect, splitWindowPath } = this.props // USING this.DIALECT_PATH instead of setting state // this.setState({ dialectPath: dialectPath }) this.DIALECT_PATH = ProviderHelpers.getDialectPathFromURLArray(splitWindowPath) this.CONTRIBUTOR_PATH = `${this.DIALECT_PATH}/Contributors` // Get data for computeDialect if (!computeDialect.success) { await this.props.fetchDialect('/' + this.DIALECT_PATH) } const { DEFAULT_PAGE, DEFAULT_PAGE_SIZE, DEFAULT_SORT_TYPE, DEFAULT_SORT_COL } = this.props let currentAppliedFilter = '' // eslint-disable-line // if (filter.has('currentAppliedFilter')) { // currentAppliedFilter = Object.values(filter.get('currentAppliedFilter').toJS()).join('') // } // Get contrinbutors await this.props.fetchContributors( this.CONTRIBUTOR_PATH, `${currentAppliedFilter}&currentPageIndex=${DEFAULT_PAGE - 1}&pageSize=${DEFAULT_PAGE_SIZE}&sortOrder=${DEFAULT_SORT_TYPE}&sortBy=${DEFAULT_SORT_COL}` ) // Get existing pictures // TODO: hardcoded current page and page size! await this.props.fetchResources( '/FV/Workspaces/', `AND ecm:primaryType LIKE 'FVPicture' AND ecm:isCheckedInVersion = 0 AND ecm:isTrashed = 0 AND ecm:currentLifeCycleState != 'Disabled' AND (ecm:path STARTSWITH '${ this.DIALECT_PATH }/Resources/')&currentPageIndex=${0}&pageSize=${1000}` ) const _SelectMediaComponent = await import('components/SelectMediaComponent') SelectMediaComponent = _SelectMediaComponent.default this.setState({ loading: false }) } render() { const { className, idDescribedbyItemBrowse, idDescribedByItemMove, textDescribedbyItemBrowse, textDescribedByItemMove, textLegendItems, textBtnAddItem, } = this.props const items = this.state.items return ( <fieldset className={className}> <legend>{textLegendItems}</legend> <button type="button" disabled={this.state.loading} onClick={() => { this.handleClickAddItem() }} > {textBtnAddItem} </button> {items} {this._generateHiddenInput()} {/* SCREEN READER DESCRIPTIONS --------------- */} <span id={idDescribedbyItemBrowse} className="visually-hidden"> {textDescribedbyItemBrowse} </span> <span id={idDescribedByItemMove} className="visually-hidden"> {textDescribedByItemMove} </span> </fieldset> ) } _generateHiddenInput = () => { const { items } = this.state const selectedItems = items.map((element) => { return element.props.id }) return <input type="hidden" name="fv:related_pictures" value={JSON.stringify(selectedItems)} /> } handleClickAddItem = () => { const _props = { name: this.props.name, className: this.props.className, idDescribedbyItemBrowse: this.props.idDescribedbyItemBrowse, idDescribedByItemMove: this.props.idDescribedByItemMove, textLegendItem: this.props.textLegendItem, textBtnRemoveItem: this.props.textBtnRemoveItem, textBtnMoveItemUp: this.props.textBtnMoveItemUp, textBtnMoveItemDown: this.props.textBtnMoveItemDown, textBtnCreateItem: this.props.textBtnCreateItem, textBtnSelectExistingItems: this.props.textBtnSelectExistingItems, textLabelItemSearch: this.props.textLabelItemSearch, handleClickSelectItem: this.handleClickSelectItem, handleClickRemoveItem: this.handleClickRemoveItem, handleClickMoveItemUp: this.handleClickMoveItemUp, handleClickMoveItemDown: this.handleClickMoveItemDown, handleItemSelected: this.handleItemSelected, computeDialectFromParent: this.props.computeDialect, DIALECT_PATH: this.DIALECT_PATH, } const items = this.state.items const id = `${_props.className}_${items.length}_${Date.now()}` items.push(<FormRelatedPicture key={id} id={id} {..._props} selectMediaComponent={SelectMediaComponent} />) this.setState({ items, }) } handleItemSelected = (selected, callback) => { const uid = selectn('uid', selected) let { items } = this.state const arg = { id: uid, items } if (getIndexOfElementById(arg) !== -1) { items = removeItem(arg) } const _props = { name: this.props.name, className: this.props.className, idDescribedbyItemBrowse: this.props.idDescribedbyItemBrowse, idDescribedByItemMove: this.props.idDescribedByItemMove, textLegendItem: this.props.textLegendItem, textBtnRemoveItem: this.props.textBtnRemoveItem, textBtnMoveItemUp: this.props.textBtnMoveItemUp, textBtnMoveItemDown: this.props.textBtnMoveItemDown, textBtnCreateItem: this.props.textBtnCreateItem, textBtnSelectExistingItems: this.props.textBtnSelectExistingItems, textLabelItemSearch: this.props.textLabelItemSearch, handleClickSelectItem: this.handleClickSelectItem, handleClickRemoveItem: this.handleClickRemoveItem, handleClickMoveItemUp: this.handleClickMoveItemUp, handleClickMoveItemDown: this.handleClickMoveItemDown, handleItemSelected: this.handleItemSelected, computeDialectFromParent: this.props.computeDialect, DIALECT_PATH: this.DIALECT_PATH, } this.setState( { items: [ ...items, <FormRelatedPicture componentState={3} key={uid} id={uid} {..._props} selectMediaComponent={SelectMediaComponent} />, ], }, () => { if (callback) { callback() } } ) } handleClickRemoveItem = (id) => { this.setState({ items: removeItem({ id, items: this.state.items }), }) } handleClickMoveItemDown = (id) => { this.setState({ items: moveItemDown({ id, items: this.state.items }), }) } handleClickMoveItemUp = (id) => { this.setState({ items: moveItemUp({ id, items: this.state.items }), }) } } // REDUX: reducers/state const mapStateToProps = (state /*, ownProps*/) => { const { fvContributor, fvDialect, windowPath } = state const { computeContributor, computeContributors, computeCreateContributor } = fvContributor const { computeDialect, computeDialect2 } = fvDialect const { splitWindowPath } = windowPath return { computeContributor, computeContributors, computeCreateContributor, computeDialect, computeDialect2, splitWindowPath, } } // REDUX: actions/dispatch/func const mapDispatchToProps = { createContributor, fetchContributors, fetchDialect, fetchResources, } export default connect(mapStateToProps, mapDispatchToProps)(FormRelatedPictures)
app/component/AddFriend.js
icalF/piye-kabare
'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, StyleSheet, Text, TextInput, TouchableHighlight, View } from 'react-native'; import styles from '../style/FormStyles'; export default class AddFriend extends Component { constructor(props) { super(props); this.state = { uname: '', isLoading: false, message: '' }; this.socket = this.props.socket; this.socket.on('add_friend_resp', this.addResp.bind(this)); } onUsernameChanged(ev) { this.setState({ uname: ev.nativeEvent.text }); } clearForm() { this.setState({ uname: '' }); } addResp(resp) { switch (resp) { case 300: this.clearForm(); this.setState({message: 'User had become friend', isLoading: false}); break; case 400: this.clearForm(); this.setState({message: 'Username not found', isLoading: false}); break; case 500: this.clearForm(); this.setState({message: 'Service error\nPlease try again', isLoading: false}); break; case 200: this.setState({message: 'Request has been sent', isLoading: false}); setTimeout(() => { this.setState({message: ''}); }, 500); this.props.onAdd(); break; } } onFind() { this.socket.emit('add_friend', { uname: this.props.uname, fname: this.state.uname }); this.setState({ isLoading: true }); } render() { var loading = this.state.isLoading ? <ActivityIndicator style={styles.loading} size='large'/> : <View/> return ( <View style={styles.container}> <TextInput style={styles.textInput} value={this.state.uname} onChange={this.onUsernameChanged.bind(this)} underlineColorAndroid={'transparent'} placeholder='Username'/> <TouchableHighlight style={styles.button} onPress={this.onFind.bind(this)} underlayColor='#1219FF'> <Text style={styles.buttonText}>Find</Text> </TouchableHighlight> {loading} <Text style={styles.description}>{this.state.message}</Text> </View> ); } };
src/components/form/index.js
WHCIBoys/nitpik-web
import React from 'react'; function Form({ children, handleSubmit }) { return ( <form onSubmit={(e) => { e.preventDefault(); if (document.activeElement) { document.activeElement.blur(); } handleSubmit(); }}> { children } </form> ); } Form.propTypes = { children: React.PropTypes.node, handleSubmit: React.PropTypes.func, }; export default Form;
src/lib/components/SecondExample.js
thepixelninja/react-component-test
import React from 'react'; import './SecondExample.scss'; const SecondExample = () => ( <div className="SecondExample"> <p className="SecondExample-text"> Based on Facebook's {'\u00A0'} <a className="SecondExample-link" target="_blank" rel="noopener noreferrer" href="https://github.com/facebookincubator/create-react-app" > Create react app </a> </p> <a className="SecondExample-github-link" target="_blank" rel="noopener noreferrer" href="https://github.com/Rubbby/create-react-library" > Documentation </a> </div> ); export default SecondExample;
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SvgInclusion.js
iamdoron/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React from 'react'; import logo from './assets/logo.svg'; export default () => <img id="feature-svg-inclusion" src={logo} alt="logo" />;
src/index.js
straku/react-workshop
import injectTapEventPlugin from 'react-tap-event-plugin' injectTapEventPlugin() import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import MuiTheme from './components/MuiTheme/MuiTheme' import App from './components/App/App' import store from './store' import './styles/fonts.css' import './styles/main.css' ReactDOM.render( <MuiTheme> <Provider store={store}> <App /> </Provider> </MuiTheme>, document.getElementById('root') )
frontend/src/app/components/Header.js
dannycoates/testpilot
import React from 'react'; import { Link } from 'react-router'; import classnames from 'classnames'; import LayoutWrapper from './LayoutWrapper'; import RetireConfirmationDialog from './RetireConfirmationDialog'; export default class Header extends React.Component { constructor(props) { super(props); this.closeTimer = null; this.close = this.close.bind(this); this.dismissRetireDialog = this.dismissRetireDialog.bind(this); this.state = { showRetireDialog: false }; } shouldRenderSettingsMenu() { return this.props.hasAddon; } showSettingsMenu() { return this.state.showSettings; } renderSettingsMenu() { if (this.shouldRenderSettingsMenu()) { return ( <div id="settings"> <div className="settings-contain"> <div className={classnames(['button', 'outline', 'settings-button'], { active: this.showSettingsMenu() })} onClick={e => this.toggleSettings(e)} data-l10n-id="menuTitle">Settings</div> {this.showSettingsMenu() && <div className="settings-menu" onClick={e => this.settingsClick(e)}> <ul> <li><a onClick={e => this.wiki(e)} data-l10n-id="menuWiki" href="https://wiki.mozilla.org/Test_Pilot" target="_blank">Test Pilot Wiki</a></li> <li><a onClick={() => this.discuss()} data-l10n-id="menuDiscuss" href="https://discourse.mozilla-community.org/c/test-pilot" target="_blank">Discuss Test Pilot</a></li> <li><a onClick={e => this.fileIssue(e)} data-l10n-id="menuFileIssue" href="https://github.com/mozilla/testpilot/issues/new" target="_blank">File an Issue</a></li> <li><hr /></li> <li><a onClick={e => this.retire(e)} data-l10n-id="menuRetire">Uninstall Test Pilot</a></li> </ul> </div>} </div> </div> ); } return null; } dismissRetireDialog() { this.setState({ showRetireDialog: false }); } renderRetireDialog() { if (this.state.showRetireDialog) { return ( <RetireConfirmationDialog onDismiss={this.dismissRetireDialog} {...this.props} /> ); } return null; } render() { return ( <div> {this.renderRetireDialog()} <header id="main-header"> <LayoutWrapper flexModifier="row-between-top"> <h1> <Link to="/" className="wordmark" data-l10n-id="siteName">Firefox Test Pilot</Link> </h1> {this.renderSettingsMenu()} </LayoutWrapper> </header> </div> ); } // HACK: We want to close the settings menu on any click outside the menu. // However, a manually-attached event listener on document.body seems to fire // the 'close' event before any other clicks register inside the settings // menu. So, here's a kludge to schedule a menu close on any click, but // cancel if the click was inside the menu. Sounds backwards, but it works. componentDidMount() { document.body.addEventListener('click', this.close); } componentWillUnmount() { if (this.closeTimer) { clearTimeout(this.closeTimer); } document.body.removeEventListener('click', this.close); } close() { if (!this.state.showSettings) { return; } this.closeTimer = setTimeout(() => this.setState({ showSettings: false }), 10); } settingsClick() { if (this.closeTimer) { clearTimeout(this.closeTimer); } } toggleSettings(ev) { ev.stopPropagation(); this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'Toggle Menu' }); if (this.state.showSettings) { this.close(ev); } else { this.setState({ showSettings: true }); } } retire(evt) { evt.preventDefault(); this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'Retire' }); this.setState({ showRetireDialog: true }); this.close(); } discuss() { this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'Discuss' }); this.close(); } wiki() { this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'wiki' }); this.close(); } fileIssue() { this.props.sendToGA('event', { eventCategory: 'Menu Interactions', eventAction: 'drop-down menu', eventLabel: 'file issue' }); this.close(); } } Header.propTypes = { uninstallAddon: React.PropTypes.func.isRequired, sendToGA: React.PropTypes.func.isRequired, openWindow: React.PropTypes.func.isRequired, hasAddon: React.PropTypes.bool, forceHideSettings: React.PropTypes.bool };
tests/layouts/CoreLayout.spec.js
fxghqc/svg-react-playground
import React from 'react' import TestUtils from 'react-addons-test-utils' import CoreLayout from 'layouts/CoreLayout/CoreLayout' function shallowRender (component) { const renderer = TestUtils.createRenderer() renderer.render(component) return renderer.getRenderOutput() } function shallowRenderWithProps (props = {}) { return shallowRender(<CoreLayout {...props} />) } describe('(Layout) Core', function () { let _component let _props let _child beforeEach(function () { _child = <h1 className='child'>Child</h1> _props = { children : _child } _component = shallowRenderWithProps(_props) }) it('Should render as a <div>.', function () { expect(_component.type).to.equal('div') }) })
src/routes/Home/components/HomeView.js
dmassaneiro/integracao-continua
import React from 'react' import DuckImage from '../assets/Duck.jpg' import './HomeView.scss' export const HomeView = () => ( <div> <h4>Welcome!</h4> <img alt='This is a duck, because Redux!' className='duck' src={DuckImage} /> </div> ) export default HomeView
src/components/Home/Shows/Views/Desktop/tpl.js
HopeUA/tv.hope.ua-react
/** * [IL] * Library Import */ import React from 'react'; import Slider from 'vendor/Slider/SliderComponent'; /** * [IS] * Style Import */ import Styles from './Styles/main.scss'; import Grids from 'theme/Grid.scss'; function Desktop() { const styles = { backgroundImage: 'url(https://cdn.hope.ua/media/shows/ALKU/episodes/02816/ALKU02816-cover.jpg)' }; const properties = { slider: Styles.slider, arrowLeft: Styles.arrowLeft, arrowRight: Styles.arrowRight, list: Styles.list, wrap: Styles.wrap, arrow: Styles.arrow }; return ( <section className={ Grids.container }> <section className={ Styles.showsComponent }> <h1 className={ Styles.title }>Популярные программы</h1> <Slider { ...properties }> <div className={ Styles.row }> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> <div className={ Styles.item } style={ styles }/> </div> </Slider> </section> </section> ); } /** * [IE] * Export */ export default Desktop;
src/js/components/input_error_body.js
frig-js/frigging-bootstrap
import React from 'react' export default class InputErrorBody extends React.Component { static propTypes = { msg: React.PropTypes.string.isRequired, i: React.PropTypes.number, } static defaultProps = { i: 0, } render() { return ( <span className="help-block" key={`error-${this.props.i}`}> <i className="fa fa-exclamation-circle" key={`error-label-${this.props.i}`} ></i> {' '} {this.props.msg} </span> ) } }
admin/client/App/screens/Home/components/ListTile.js
xyzteam2016/keystone
import React from 'react'; import { Link } from 'react-router'; /** * Displays information about a list and lets you create a new one. */ var ListTile = React.createClass({ propTypes: { count: React.PropTypes.string, href: React.PropTypes.string, label: React.PropTypes.string, path: React.PropTypes.string, spinner: React.PropTypes.object, }, render () { var opts = { 'data-list-path': this.props.path, }; return ( <div className="dashboard-group__list" {...opts}> <span className="dashboard-group__list-inner"> <Link to={this.props.href} className="dashboard-group__list-tile"> <div className="dashboard-group__list-label">{this.props.label}</div> <div className="dashboard-group__list-count">{this.props.spinner || this.props.count}</div> </Link> {/* If we want to create a new list, we append ?create, which opens the create form on the new page! */} <Link to={this.props.href + '?create'} className="dashboard-group__list-create octicon octicon-plus" title="Create" tabIndex="-1" /> </span> </div> ); }, }); module.exports = ListTile;
client/components/Breakpoints.js
HelpAssistHer/help-assist-her
import React from 'react' import Responsive from 'react-responsive' const PHONE_MIN_BREAKPOINT = 320 const PHONE_MAX_BREAKPOINT = 439 const BIG_PHONE_MIN_BREAKPOINT = 440 const BIG_PHONE_MAX_BREAKPOINT = 699 const TABLET_MIN_BREAKPOINT = 700 const TABLET_MAX_BREAKPOINT = 1099 const DESKTOP_MIN_BREAKPOINT = 1100 const Desktop = (props) => ( <Responsive {...props} minWidth={DESKTOP_MIN_BREAKPOINT} /> ) const Tablet = (props) => ( <Responsive {...props} minWidth={TABLET_MIN_BREAKPOINT} maxWidth={TABLET_MAX_BREAKPOINT} /> ) const BigPhone = (props) => ( <Responsive {...props} minWidth={BIG_PHONE_MIN_BREAKPOINT} maxWidth={BIG_PHONE_MAX_BREAKPOINT} /> ) const Phone = (props) => ( <Responsive {...props} minWidth={PHONE_MIN_BREAKPOINT} maxWidth={PHONE_MAX_BREAKPOINT} /> ) export { Desktop, Tablet, BigPhone, Phone, DESKTOP_MIN_BREAKPOINT, TABLET_MIN_BREAKPOINT, BIG_PHONE_MIN_BREAKPOINT, PHONE_MIN_BREAKPOINT, }
src/schema/test.dataSchema.js
jiangxy/react-antd-admin
import React from 'react'; import {Icon} from 'antd'; // 定义某个表的dataSchema, 结构跟querySchema很相似, 见下面的例子 // 注意: 所有的key不能重复 // 这个配置不只决定了table的schema, 也包括用于新增/删除的表单的schema module.exports = [ { key: 'id', // 传递给后端的key title: 'ID', // 前端显示的名字 // 其实dataType对前端的意义不大, 更重要的是生成后端接口时要用到, 所以要和DB中的类型一致 // 对java而言, int/float/varchar/datetime会映射为Long/Double/String/Date dataType: 'int', // 数据类型, 目前可用的: int/float/varchar/datetime // 这一列是否是主键? // 如果不指定主键, 不能update/delete, 但可以insert // 如果指定了主键, insert/update时不能填写主键的值; // 只有int/varchar可以作为主键, 但是实际上主键一般都是自增id primary: true, // 可用的showType: normal/radio/select/checkbox/multiSelect/textarea/image/file/cascader showType: 'normal', // 默认是normal, 就是最普通的输入框 showInTable: true, // 这一列是否要在table中展示, 默认true disabled: false, // 表单中这一列是否禁止编辑, 默认false // 扩展接口, 决定了这一列渲染成什么样子 render: (text, record) => text, }, { key: 'name', title: '用户名', dataType: 'varchar', // 对于普通的input框, 可以设置addonBefore/addonAfter placeholder: '请输入用户名', addonBefore: (<Icon type="user"/>), addonAfter: '切克闹', defaultValue: 'foolbear', // 默认值, 只在insert时生效, update时不生效 }, { key: 'weight', title: '体重(千克)', dataType: 'int', min: 10, defaultValue: 70, // 默认值 disabled: true, showInForm: false, // 这一列是否要在表单中展示, 默认true. 这种列一般都是不需要用户输入的, DB就会给一个默认值那种 }, { key: 'gender', title: '性别', dataType: 'int', showType: 'radio', options: [{key: '1', value: '男'}, {key: '2', value: '女'}], defaultValue: '1', disabled: true, }, { key: 'marriage', title: '婚否', dataType: 'varchar', showType: 'select', options: [{key: 'yes', value: '已婚'}, {key: 'no', value: '未婚'}], // 对于dataSchema可以设置校验规则, querySchema不能设置 // 设置校验规则, 参考https://github.com/yiminghe/async-validator#rules validator: [{type: 'string', required: true, message: '必须选择婚否!'}], }, { key: 'interest', title: '兴趣爱好', dataType: 'int', showType: 'checkbox', options: [{key: '1', value: '吃饭'}, {key: '2', value: '睡觉'}, {key: '3', value: '打豆豆'}], defaultValue: ['1', '2'], validator: [{type: 'array', required: true, message: '请至少选择一项兴趣'}], width: 120, // 指定这一列的宽度 }, { key: 'good', title: '优点', dataType: 'varchar', showType: 'multiSelect', options: [{key: 'lan', value: '懒'}, {key: 'zhai', value: '宅'}], validator: [{type: 'array', required: true, message: '请选择优点'}], }, { key: 'pic1', title: '头像', dataType: 'varchar', showType: 'image', // 后端必须提供图片上传接口 showInTable: false, }, { key: 'desc', title: '个人简介', dataType: 'varchar', showType: 'textarea', // 用于编辑大段的文本 showInTable: false, defaultValue: '个人简介个人简介个人简介', validator: [{type: 'string', max: 20, message: '最长20个字符'}], }, { key: 'score', title: '分数', dataType: 'int', max: 99, min: 9, }, { key: 'gpa', title: 'GPA', dataType: 'float', max: 9.9, placeholder: '哈哈', width: 50, }, { key: 'birthday', title: '生日', // 对于日期类型要注意下, 在js端日期被表示为yyyy-MM-dd HH:mm:ss的字符串, 在java端日期被表示为java.util.Date对象 // fastjson反序列化时可以自动识别 // 序列化倒是不用特别配置, 看自己需求, fastjson会序列化为一个字符串, 前端原样展示 dataType: 'datetime', // 对于datetime而言, 配置showType是无意义的 placeholder: 'happy!', }, { key: 'xxday', title: 'xx日期', dataType: 'datetime', defaultValue: '2017-01-01 11:22:33', showInTable: false, showInForm: false, // 这个只是测试下...如果一列在table和form中都不出现, 那就不如直接去掉. // 另外showInForm=false时, 很多针对form的字段都没意义了, 比如defaultValue/placeholder/validator等等 }, ];
DataRepository.js
dcy0701/ReactNativeServer
'use strict'; import { AsyncStorage, } from 'react-native'; import React, { Component } from 'react'; var API_COVER_URL = "http://news-at.zhihu.com/api/4/start-image/1080*1776"; var KEY_COVER = '@Cover'; function parseDateFromYYYYMMdd(str) { if (!str) return new Date(); return new Date(str.slice(0, 4),str.slice(4, 6) - 1,str.slice(6, 8)); } Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear().toString(); var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based var dd = this.getDate().toString(); return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding }; function DataRepository() { // Singleton pattern if (typeof DataRepository.instance === 'object') { return DataRepository.instance; } DataRepository.instance = this; } DataRepository.prototype._safeStorage = function(key: string) { return new Promise((resolve, reject) => { AsyncStorage.getItem(key, (error, result) => { var retData = JSON.parse(result); if (error) { console.error(error); resolve(null); } else { resolve(retData); } }); }); }; DataRepository.prototype.getCover = function() { return this._safeStorage(KEY_COVER); } DataRepository.prototype.updateCover = function() { fetch(API_COVER_URL) .then((response) => response.json()) .then((responseData) => { AsyncStorage.setItem(KEY_COVER, JSON.stringify(responseData)); }) .catch((error) => { console.error(error); }) .done(); }; module.exports = DataRepository;
src/components/index.js
ctrl-alt-p/born-to-sell
import React from 'react'; import App from './app'; import CommentBox from './comment_box'; import CommentList from './comment_list'; export default App; export default CommentList; export default CommentBox;
docs/src/PropTable.js
herojobs/react-bootstrap
import merge from 'lodash/object/merge'; import React from 'react'; import Glyphicon from '../../src/Glyphicon'; import Label from '../../src/Label'; import Table from '../../src/Table'; let cleanDocletValue = str => str.trim().replace(/^\{/, '').replace(/\}$/, ''); let capitalize = str => str[0].toUpperCase() + str.substr(1); function getPropsData(component, metadata){ let componentData = metadata[component] || {}; let props = componentData.props || {}; if (componentData.composes) { componentData.composes.forEach(other => { if (other !== component) { props = merge({}, getPropsData(other, metadata), props); } }); } if (componentData.mixins) { componentData.mixins.forEach( other => { if (other !== component && componentData.composes.indexOf(other) === -1) { props = merge({}, getPropsData(other, metadata), props); } }); } return props; } const PropTable = React.createClass({ contextTypes: { metadata: React.PropTypes.object }, componentWillMount(){ this.propsData = getPropsData(this.props.component, this.context.metadata); }, render(){ let propsData = this.propsData; if ( !Object.keys(propsData).length){ return <span/>; } return ( <Table bordered striped className="prop-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> { this._renderRows(propsData) } </tbody> </Table> ); }, _renderRows(propsData){ return Object.keys(propsData) .sort() .filter(propName => propsData[propName].type && !propsData[propName].doclets.private ) .map(propName => { let propData = propsData[propName]; return ( <tr key={propName} className='prop-table-row'> <td> {propName} {this.renderRequiredLabel(propData)} </td> <td> <div>{this.getType(propData)}</div> </td> <td>{propData.defaultValue}</td> <td> { propData.doclets.deprecated && <div className='prop-desc-heading'> <strong className='text-danger'>{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong> </div> } { this.renderControllableNote(propData, propName) } <div className='prop-desc' dangerouslySetInnerHTML={{__html: propData.descHtml }} /> </td> </tr> ); }); }, renderRequiredLabel(prop) { if (!prop.required) { return null; } return ( <Label>required</Label> ); }, renderControllableNote(prop, propName){ let controllable = prop.doclets.controllable; let isHandler = this.getDisplayTypeName(prop.type.name) === 'function'; if (!controllable) { return false; } let text = isHandler ? ( <span> controls <code>{controllable}</code> </span> ) : ( <span> controlled by: <code>{controllable}</code>, initial prop: <code>{'default' + capitalize(propName)}</code> </span> ); return ( <div className='prop-desc-heading'> <small> <em className='text-info'> <Glyphicon glyph='info-sign'/> &nbsp;{ text } </em> </small> </div> ); }, getType(prop) { let type = prop.type || {}; let name = this.getDisplayTypeName(type.name); let doclets = prop.doclets || {}; switch (name) { case 'object': return name; case 'union': return type.value.reduce((current, val, i, list) => { let item = this.getType({ type: val }); if (React.isValidElement(item)) { item = React.cloneElement(item, {key: i}); } current = current.concat(item); return i === (list.length - 1) ? current : current.concat(' | '); }, []); case 'array': let child = this.getType({ type: type.value }); return <span>{'array<'}{ child }{'>'}</span>; case 'enum': return this.renderEnum(type); case 'custom': return cleanDocletValue(doclets.type || name); default: return name; } }, getDisplayTypeName(typeName) { if (typeName === 'func') { return 'function'; } else if (typeName === 'bool') { return 'boolean'; } else { return typeName; } }, renderEnum(enumType) { const enumValues = enumType.value || []; const renderedEnumValues = []; enumValues.forEach(function renderEnumValue(enumValue, i) { if (i > 0) { renderedEnumValues.push( <span key={`${i}c`}>, </span> ); } renderedEnumValues.push( <code key={i}>{enumValue}</code> ); }); return ( <span>one of: {renderedEnumValues}</span> ); } }); export default PropTable;
src/components/LoggedInPage.js
KingCountySAR/database-frontend
import React from 'react'; import { withRouter } from 'react-router-dom'; import { CallbackComponent } from 'redux-oidc'; import userManager from '../userManager'; class CallbackPage extends React.Component { successCallback = () => { this.props.history.push(sessionStorage.redirect || '/'); } render() { return ( <CallbackComponent userManager={userManager} successCallback={this.successCallback} errorCallback={this.successCallback}> <div> Redirecting... </div> </CallbackComponent> ); } } export default withRouter(CallbackPage);
src/svg-icons/action/account-box.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAccountBox = (props) => ( <SvgIcon {...props}> <path d="M3 5v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5c-1.11 0-2 .9-2 2zm12 4c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3zm-9 8c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1H6v-1z"/> </SvgIcon> ); ActionAccountBox = pure(ActionAccountBox); ActionAccountBox.displayName = 'ActionAccountBox'; ActionAccountBox.muiName = 'SvgIcon'; export default ActionAccountBox;
7.Middlewares/src/components/app.js
Branimir123/Learning-React
import React, { Component } from 'react'; import UserList from './user_list'; export default class App extends Component { render() { return ( <div> <UserList /> </div> ); } }
src/app/components/Home.js
maria-robobug/react-js-basics
import React from 'react'; export class Home extends React.Component { constructor (props) { super(); this.state = { age: props.initialAge, status: 0, homeLink: props.initialLinkName }; setTimeout(() => { this.setState({ status: 1 }); },3000); console.log('Constructor'); } componentWillMount () { console.log('Component will mount'); } componentDidMount () { console.log('Component did mount'); } componentWillReceiveProps (nextProps) { console.log('Component will receive props', nextProps); } shouldComponentUpdate (nextProps, nextState) { console.log('Should Component update', nextProps, nextState); return true; } componentWillUpdate (nextProps, nextState) { console.log('Component will update', nextProps, nextState); } componentDidUpdate (previousProps, previousState) { console.log('Component did update', previousProps, previousState); } componentWillUnmount () { console.log('Component will unmount'); } onMakeOlder () { this.setState({ age: this.state.age + 3 }); } onChangeLink () { this.props.changeLink(this.state.homeLink); } onHandleChange (event) { this.setState({ homeLink: event.target.value }); } render () { return ( <div> <p>Your name is {this.props.name}, your age is {this.state.age}</p> <p>Status: {this.state.status}</p> <hr/> <button onClick={() => this.onMakeOlder()} className="btn btn-primary">Make me older!</button> <hr/> <button onClick={this.props.greet} className="btn btn-primary">Greet</button> <hr/> <input type="text" value={this.state.homeLink} onChange={(event) => this.onHandleChange(event)} /> <button onClick={(newName) => this.onChangeLink(newName)} className="btn btn-primary">Change Header</button> </div> ); } } Home.propTypes = { name: React.PropTypes.string, initialAge: React.PropTypes.number, greet: React.PropTypes.func };
app/components/Journal.js
csreyes/TLCJournal
import React from 'react'; import {Link} from 'react-router'; import {Pager, PageItem} from 'react-bootstrap'; import moment from 'moment'; import JournalStore from '../stores/JournalStore' import JournalActions from '../actions/JournalActions'; // import HomeStore from '../stores/HomeStore' // import HomeActions from '../actions/HomeActions'; import JournalMainContainer from './JournalMainContainer'; class Journal extends React.Component { constructor(props) { super(props); this.state = JournalStore.getState(); } componentDidMount() { JournalStore.listen(this.onChange.bind(this)); } componentWillUnmount() { JournalStore.unlisten(this.onChange.bind(this)); } onChange(state) { this.setState(state) } updateDate(update) { JournalActions.updateDate(update); } render() { var weeklyQuote = 'Plan well and follow through. It\'ll take you places you didn\'t know you could go.' return ( <div className='journal-outer-container test'> <div className='journal-outer-container-header test'> <Pager className='journal-outer-container-header-pager test'> <PageItem onClick={this.updateDate.bind(this, -1)} className='journal-outer-container-header-page-item test' previous href='#'>&larr;</PageItem> <span className='journal-outer-container-header-current-date'>{this.state.formattedCurrentDate}</span> <PageItem onClick={this.updateDate.bind(this, 1)}className='journal-outer-container-header-page-item test' next href='#'>&rarr;</PageItem> </Pager> <h3 className='journal-outer-container-header-innertext'>TLC Journal</h3> </div> <JournalMainContainer /> <div className='journal-footer'> <span className='journal-footer-text'>{weeklyQuote}</span> </div> </div> ); } } export default Journal;
src/components/RefreshableListView.js
yogakurniawan/phoney-mobile
/* * Component Name: RefreshableListView * Author: Simar Singh (github/iSimar) * Description: This component is used to render a listview that can be * pulled down to refresh * Dependencies: * -> react-native-gifted-listview 0.0.15 (https://github.com/FaridSafi/react-native-gifted-listview) * * Properties: * -> renderRow * render function for rows or cells in the listview * -> onRefresh * used for filling the listview on ethier pull to refresh or pagination (load more), * it is called with 2 arugments page number and callback. see react-native-gifted-listview docs. * -> backgroundColor (optional) * default = '#FFFFFF', background color of the listview * -> loadMoreText (optional) * default = '+', text used at the end of the listview - pagination * -> renderHeader (optional) * rendering not sticky header of the listview * Example: * <RefreshableListView renderRow={(row)=>this.renderListViewRow(row)} * renderHeader={this.renderListViewHeader} * onRefresh={(page, callback)=>this.listViewOnRefresh(page, callback)} * backgroundColor={'#F6F6EF'} * loadMoreText={'Load More...'}/> */ import React from 'react'; import { Platform, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import GiftedListView from 'react-native-gifted-listview'; export default class RefreshableListView extends React.Component { static propTypes = { renderRow: React.PropTypes.func, backgroundColor: React.PropTypes.string, loadMoreText: React.PropTypes.string, renderHeader: React.PropTypes.func, onRefresh: React.PropTypes.func }; getInititalState() { const { renderRow, backgroundColor, loadMoreText, renderHeader } = this.props; return { renderRow, backgroundColor: backgroundColor ? backgroundColor : '#FFFFFF', loadMoreText: loadMoreText ? loadMoreText : 'Load More...', renderHeader: renderHeader ? renderHeader : null }; } onRefresh(page = 1, callback) { this.props.onRefresh(page, callback); } renderRow(row) { return this.state.renderRow(row); } renderPaginationWaitingView(callback) { return ( <TouchableOpacity style={styles.paginationView} onPress={callback}> <Text style={styles.loadMoreText}> {this.state.loadMoreText} </Text> </TouchableOpacity> ); } renderHeaderView() { if (this.state.renderHeader) { return this.props.renderHeader(); } return (null); } renderPaginationAllLoadedView() { return ( <View /> ); } render() { return ( <View style={[styles.container, { backgroundColor: this.state.backgroundColor }, this.props.style]}> <View style={styles.navBarSpace}> <GiftedListView rowView={this.renderRow} onFetch={this.onRefresh} paginationAllLoadedView={this.renderPaginationAllLoadedView} paginationWaitingView={this.renderPaginationWaitingView} headerView={this.renderHeaderView} PullToRefreshViewAndroidProps={{ colors: ['#F6F6EF'], progressBackgroundColor: '#FF6600' }} customStyles={{ refreshableView: { backgroundColor: this.state.backgroundColor, justifyContent: 'flex-end', paddingBottom: 12 }, paginationView: { backgroundColor: this.state.backgroundColor, height: 60 } }} /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1 }, navBarSpace: { height: (Platform.OS !== 'android') ? 64 : 0 }, rowContainer: { paddingRight: 15, paddingLeft: 10, flexDirection: 'row' }, paginationView: { justifyContent: 'center', alignItems: 'center', paddingTop: 20, paddingBottom: 20 }, loadMoreText: { fontSize: 15, color: 'gray' } });
src/routes/admin/Admin.js
ben-miller/adddr.io
/** * adddr (https://www.adddr.io/) * * 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 PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Admin.css'; class Admin extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1> {this.props.title} </h1> <p>...</p> </div> </div> ); } } export default withStyles(s)(Admin);
src/index.js
superpersonman/react-raf-parallax
import React from 'react'; var lastTime = 0, lastTimeSelected = 0, elementCache = []; export default React.createClass({ getDefaultProps() { return { perspective: 100, x: false, y: true, relativeToParent: true } }, componentDidMount() { this._raf = window.requestAnimationFrame(this.tick); }, componentWillUnmount() { window.cancelAnimationFrame(this._raf); }, tick(t) { // Cap updates to near 60fps if (t-lastTime < 1000/60) { window.requestAnimationFrame(this.tick); lastTime = t; return; } // Only update element cache every 500ms to avoid bottlenecks // caused by repeatedly selecting elements if (t-lastTimeSelected > 500) { elementCache = this.node.getElementsByClassName('parallax'); lastTimeSelected = t; } var depthElements = elementCache, yOffset = window.pageYOffset, xOffset = window.pageXOffset, viewportHeight = window.innerHeight, viewportWidth = window.innerWidth, i = depthElements.length - 1, el, elOffsetX, elOffsetY, depth, x, y, parent, parentRect; for (i; i >= 0; i--) { el = depthElements[i]; depth = el.getAttribute('data-parallax-depth'); elOffsetX = el.getAttribute('data-parallax-offset-x') || 0; elOffsetY = el.getAttribute('data-parallax-offset-y') || 0; parent = el.parentElement; if (this.props.relativeToParent && parent) { parentRect = parent.getBoundingClientRect(); y = this.props.y ? -parentRect.top * depth / this.props.perspective : 0; x = this.props.x ? -parentRect.left * depth / this.props.perspective : 0; } else { y = this.props.y ? yOffset * depth / this.props.perspective : 0; x = this.props.x ? xOffset * depth / this.props.perspective : 0; } x += +elOffsetX; y += +elOffsetY; el.style.transform = 'translate3d('+ x +'px,'+ y +'px, 0)'; } lastTime = t; window.requestAnimationFrame(this.tick); }, render() { return ( <div className='parallax' ref={(el) => {this.node = el}}> {this.props.children} </div> ); } });
dist/lib/carbon-fields/assets/js/fields/components/checkbox/index.js
ArtFever911/statrer-kit
/** * The external dependencies. */ import React from 'react'; import PropTypes from 'prop-types'; import { compose, withProps, withHandlers, setStatic } from 'recompose'; /** * The internal dependencies. */ import Field from 'fields/components/field'; import withStore from 'fields/decorators/with-store'; import withSetup from 'fields/decorators/with-setup'; import { TYPE_CHECKBOX } from 'fields/constants'; /** * Render a checkbox input field. * * @param {Object} props * @param {String} props.name * @param {Object} props.field * @param {Boolean} props.checked * @param {Function} props.handleChange * @return {React.Element} */ export const CheckboxField = ({ name, field, checked, handleChange }) => { return <Field field={field} showLabel={false} showRequiredLabel={false}> <label> <input type="checkbox" name={name} value={field.option_value} checked={checked} disabled={!field.ui.is_visible} onChange={handleChange} {...field.attributes} /> {field.option_label} { field.required ? <span className="carbon-required">*</span> : null } </label> </Field>; }; /** * Validate the props. * * @type {Object} */ CheckboxField.propTypes = { name: PropTypes.string, field: PropTypes.shape({ id: PropTypes.string, value: PropTypes.bool, option_value: PropTypes.string, attributes: PropTypes.object, }), checked: PropTypes.bool, handleChange: PropTypes.func, }; /** * The enhancer. * * @type {Function} */ export const enhance = compose( /** * Connect to the Redux store. */ withStore(), /** * Attach the setup hooks. */ withSetup(), /** * Pass some props to the component. */ withProps(({ field }) => ({ checked: field.value, })), /** * Pass some handlers to the component. */ withHandlers({ handleChange: ({ field, setFieldValue }) => ({ target }) => { setFieldValue(field.id, target.checked); }, }) ); export default setStatic('type', [ TYPE_CHECKBOX, ])(enhance(CheckboxField));
app/javascript/mastodon/features/public_timeline/index.js
primenumber/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import StatusListContainer from '../ui/containers/status_list_container'; import Column from '../../components/column'; import ColumnHeader from '../../components/column_header'; import { expandPublicTimeline } from '../../actions/timelines'; import { addColumn, removeColumn, moveColumn } from '../../actions/columns'; import ColumnSettingsContainer from './containers/column_settings_container'; import { connectPublicStream } from '../../actions/streaming'; const messages = defineMessages({ title: { id: 'column.public', defaultMessage: 'Federated timeline' }, }); const mapStateToProps = (state, { columnId }) => { const uuid = columnId; const columns = state.getIn(['settings', 'columns']); const index = columns.findIndex(c => c.get('uuid') === uuid); const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']); const onlyRemote = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyRemote']) : state.getIn(['settings', 'public', 'other', 'onlyRemote']); const timelineState = state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`]); return { hasUnread: !!timelineState && timelineState.get('unread') > 0, onlyMedia, onlyRemote, }; }; export default @connect(mapStateToProps) @injectIntl class PublicTimeline extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static defaultProps = { onlyMedia: false, }; static propTypes = { dispatch: PropTypes.func.isRequired, shouldUpdateScroll: PropTypes.func, intl: PropTypes.object.isRequired, columnId: PropTypes.string, multiColumn: PropTypes.bool, hasUnread: PropTypes.bool, onlyMedia: PropTypes.bool, onlyRemote: PropTypes.bool, }; handlePin = () => { const { columnId, dispatch, onlyMedia, onlyRemote } = this.props; if (columnId) { dispatch(removeColumn(columnId)); } else { dispatch(addColumn(onlyRemote ? 'REMOTE' : 'PUBLIC', { other: { onlyMedia, onlyRemote } })); } } handleMove = (dir) => { const { columnId, dispatch } = this.props; dispatch(moveColumn(columnId, dir)); } handleHeaderClick = () => { this.column.scrollTop(); } componentDidMount () { const { dispatch, onlyMedia, onlyRemote } = this.props; dispatch(expandPublicTimeline({ onlyMedia, onlyRemote })); this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote })); } componentDidUpdate (prevProps) { if (prevProps.onlyMedia !== this.props.onlyMedia || prevProps.onlyRemote !== this.props.onlyRemote) { const { dispatch, onlyMedia, onlyRemote } = this.props; this.disconnect(); dispatch(expandPublicTimeline({ onlyMedia, onlyRemote })); this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote })); } } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } setRef = c => { this.column = c; } handleLoadMore = maxId => { const { dispatch, onlyMedia, onlyRemote } = this.props; dispatch(expandPublicTimeline({ maxId, onlyMedia, onlyRemote })); } render () { const { intl, shouldUpdateScroll, columnId, hasUnread, multiColumn, onlyMedia, onlyRemote } = this.props; const pinned = !!columnId; return ( <Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}> <ColumnHeader icon='globe' active={hasUnread} title={intl.formatMessage(messages.title)} onPin={this.handlePin} onMove={this.handleMove} onClick={this.handleHeaderClick} pinned={pinned} multiColumn={multiColumn} > <ColumnSettingsContainer columnId={columnId} /> </ColumnHeader> <StatusListContainer timelineId={`public${onlyRemote ? ':remote' : ''}${onlyMedia ? ':media' : ''}`} onLoadMore={this.handleLoadMore} trackScroll={!pinned} scrollKey={`public_timeline-${columnId}`} emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other servers to fill it up' />} shouldUpdateScroll={shouldUpdateScroll} bindToDocument={!multiColumn} /> </Column> ); } }
components/Html.js
hobinjk/illuminate
import React from 'react'; class Html extends React.Component { render() { return ( <html> <head> <meta charSet="utf-8" /> <title>{this.props.title}</title> <meta name="viewport" content="width=device-width, user-scalable=no" /> <link rel="stylesheet" href="/assets/style.css" /> </head> <body> <div id="app" dangerouslySetInnerHTML={{__html: this.props.markup}}></div> </body> <script dangerouslySetInnerHTML={{__html: this.props.state}}></script> <script src={'/public/js/' + this.props.clientFile}></script> </html> ); } } export default Html;
packages/react-events/src/FocusScope.js
VioletLife/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type { ReactResponderEvent, ReactResponderContext, } from 'shared/ReactTypes'; import React from 'react'; type FocusScopeProps = { autoFocus: Boolean, contain: Boolean, restoreFocus: Boolean, }; type FocusScopeState = { nodeToRestore: null | HTMLElement, currentFocusedNode: null | HTMLElement, }; const targetEventTypes = [{name: 'keydown', passive: false}]; const rootEventTypes = [{name: 'focus', passive: true}]; function focusElement(element: ?HTMLElement) { if (element != null) { try { element.focus(); } catch (err) {} } } function getFirstFocusableElement( context: ReactResponderContext, state: FocusScopeState, ): ?HTMLElement { const elements = context.getFocusableElementsInScope(); if (elements.length > 0) { return elements[0]; } } const FocusScopeResponder = { targetEventTypes, rootEventTypes, createInitialState(): FocusScopeState { return { nodeToRestore: null, currentFocusedNode: null, }; }, allowMultipleHostChildren: true, stopLocalPropagation: false, onEvent( event: ReactResponderEvent, context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ) { const {type, nativeEvent} = event; const hasOwnership = context.hasOwnership() || context.requestResponderOwnership(); if (!hasOwnership) { return; } if (type === 'keydown' && nativeEvent.key === 'Tab') { const focusedElement = context.getActiveDocument().activeElement; if ( focusedElement !== null && context.isTargetWithinEventComponent(focusedElement) ) { const {altkey, ctrlKey, metaKey, shiftKey} = (nativeEvent: any); // Skip if any of these keys are being pressed if (altkey || ctrlKey || metaKey) { return; } const elements = context.getFocusableElementsInScope(); const position = elements.indexOf(focusedElement); const lastPosition = elements.length - 1; let nextElement = null; if (shiftKey) { if (position === 0) { if (props.contain) { nextElement = elements[lastPosition]; } else { // Out of bounds context.releaseOwnership(); return; } } else { nextElement = elements[position - 1]; } } else { if (position === lastPosition) { if (props.contain) { nextElement = elements[0]; } else { // Out of bounds context.releaseOwnership(); return; } } else { nextElement = elements[position + 1]; } } // If this element is possibly inside the scope of another // FocusScope responder or is out of bounds, then we release ownership. if (nextElement !== null) { if (!context.isTargetWithinEventResponderScope(nextElement)) { context.releaseOwnership(); } focusElement(nextElement); state.currentFocusedNode = nextElement; ((nativeEvent: any): KeyboardEvent).preventDefault(); } } } }, onRootEvent( event: ReactResponderEvent, context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ) { const {target} = event; // Handle global focus containment if (props.contain) { if (!context.isTargetWithinEventComponent(target)) { const currentFocusedNode = state.currentFocusedNode; if (currentFocusedNode !== null) { focusElement(currentFocusedNode); } else if (props.autoFocus) { const firstElement = getFirstFocusableElement(context, state); focusElement(firstElement); } } } }, onMount( context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ): void { if (props.restoreFocus) { state.nodeToRestore = context.getActiveDocument().activeElement; } if (props.autoFocus) { const firstElement = getFirstFocusableElement(context, state); focusElement(firstElement); } }, onUnmount( context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ): void { if ( props.restoreFocus && state.nodeToRestore !== null && context.hasOwnership() ) { focusElement(state.nodeToRestore); } }, onOwnershipChange( context: ReactResponderContext, props: FocusScopeProps, state: FocusScopeState, ): void { if (!context.hasOwnership()) { state.currentFocusedNode = null; } }, }; export default React.unstable_createEventComponent( FocusScopeResponder, 'FocusScope', );
packages/material-ui-icons/src/EventBusy.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let EventBusy = props => <SvgIcon {...props}> <path d="M9.31 17l2.44-2.44L14.19 17l1.06-1.06-2.44-2.44 2.44-2.44L14.19 10l-2.44 2.44L9.31 10l-1.06 1.06 2.44 2.44-2.44 2.44L9.31 17zM19 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 16H5V8h14v11z" /> </SvgIcon>; EventBusy = pure(EventBusy); EventBusy.muiName = 'SvgIcon'; export default EventBusy;
components/HighlightGrid.js
RomainInnocent/tpdevops
/** * Created by Adrien on 30/06/2017. */ import React from 'react'; import {GridList, GridTile} from 'material-ui/GridList'; import IconButton from 'material-ui/IconButton'; import Subheader from 'material-ui/Subheader'; import StarBorder from 'material-ui/svg-icons/toggle/star-border'; import StartupCard from './StartupCard'; import fetch from 'isomorphic-unfetch' const styles = { root: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', }, gridList: { width: '100%', height: 'auto', overflowY: 'auto', } }; /** * A simple example of a scrollable `GridList` containing a [Subheader](/#/components/subheader). */ const HighlightGridList = (props) => ( <div style={styles.root}> {props.highlights.map((high) => ( <GridList cols={2} cellHeight="auto" style={styles.gridList} key={high.periode}> <Subheader>{high.periode}</Subheader> {high.startups.map((tile) => ( <GridTile cols={tile.size} rows={tile.size} key={tile.img}> <StartupCard title={tile.title} pretty={tile.pretty} author={tile.author} avatar={tile.avatar} subtitle={tile.subtitle} description={tile.description} website={tile.website} youtubeLink={tile.youtubeLink} _id={tile._id} img={tile.img} /> </GridTile> ))} </GridList> ))} </div> ); HighlightGridList.getInitialProps = async function (context) { const res = await fetch('/api/s/all') const data = await res.json() console.log(`Show data fetched. Count: ${data.length}`) return { shows: data } } export default HighlightGridList;
test/TabSpec.js
jakubsikora/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'); }); }); });
packages/showcase/plot/grid.js
uber/react-vis
// Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import {XYPlot, XAxis, YAxis, VerticalGridLines, LineSeries} from 'react-vis'; export default function Example() { return ( <XYPlot width={300} height={300}> <VerticalGridLines values={[2, 2.3, 2.7]} /> <XAxis /> <YAxis /> <LineSeries data={[ {x: 1, y: 10}, {x: 2, y: 5}, {x: 3, y: 15} ]} /> </XYPlot> ); }
src/containers/AddTodo.js
lingxiao-Zhu/react-redux-demo
/** * Created by larry on 2017/1/4. */ import React from 'react'; import { connect } from 'react-redux'; import { addTodo } from '../actions'; let AddTodo = ({ dispatch }) => { let input; return( <div> <form onSubmit={e=>{ e.preventDefault(); if(!input.value.trim()){ return } dispatch(addTodo(input.value)) input.value = '' }}> <input ref={node=>{input=node}}/> <button type="submit"> Add Todo </button> </form> </div> ) } AddTodo = connect()(AddTodo) export default AddTodo
humantest/App.js
gutenye/react-mc
/* eslint-disable */ import React from 'react' import '../docs/docs' import '../docs/docs.css' import { render } from 'react-dom' import { Button, Card, Dialog, Drawer, Elevation, Checkbox, Fab, FormField, GridList, IconToggle, LayoutGrid, LinearProgress, Menu, List, Radio, Select, Slider, Snackbar, Switch, Tabs, Toolbar, Textfield, } from '../src' const log = console.log.bind(console) const getPages = () => [ //MyButton, //MyCard, // MyDialog, //MyCheckbox, //MyPermanentDrawer, // MyPersistentDrawer, // MyTemporaryDrawer, //MyElevation, //MyFab, //MyFormField, //MyGridList, //MyIconToggle, //MyLayoutGrid, //MyLinearProgress, //MyList, // MyMenu, // MyRadio, // MySelect, // MySlider, // MySnackbar, // MySwitch, // MyTabs, MyToolbar, // MyTextfield, ] const MyButton = () => <Button>hello</Button> class MyCard extends React.Component { //{{{1 render() { return ( <Card> <Card.Primary> <Card.Title>Title</Card.Title> <Card.Subtitle>Subtitle</Card.Subtitle> </Card.Primary> <Card.SupportingText>hello world</Card.SupportingText> <Card.Actions> <Card.Action>Action 1</Card.Action> <Card.Action>Action 2</Card.Action> </Card.Actions> </Card> ) } } class MyDialog extends React.Component { state = { open: false, } render() { return ( <div> <button onClick={() => this.setState({ open: true })}> Open Dialog </button> <Dialog open={this.state.open} onClose={() => this.setState({ open: false })} onAccept={() => console.log('onAccept')} onCancel={() => console.log('onCancel')} > <Dialog.Surface> <Dialog.Header> <Dialog.Header.Title> Use Google's location service? </Dialog.Header.Title> </Dialog.Header> <Dialog.Body> Let Google help apps determine location. This means sending anonymous location data to Google, even when no apps are running. </Dialog.Body> <Dialog.Footer> <Dialog.Footer.Button cancel>Cancel</Dialog.Footer.Button> <Dialog.Footer.Button accept>Accept</Dialog.Footer.Button> </Dialog.Footer> </Dialog.Surface> <Dialog.Backdrop /> </Dialog> </div> ) } } class MyCheckbox extends React.Component { state = { checked: false, } render() { return ( <Checkbox checked={this.state.checked} onChange={e => this.setState({ checked: e.target.checked })} /> ) } } class MyPermanentDrawer extends React.Component { render() { return ( <div> <DemoDrawerToolbar fixed /> <Toolbar.FixedAdjust style={{ display: 'flex' }}> <Drawer.Permanent> <DemoDrawerContent /> </Drawer.Permanent> <main>Page content goes here</main> </Toolbar.FixedAdjust> </div> ) } } class MyPersistentDrawer extends React.Component { state = { open: false, } render() { return ( <div style={{ display: 'flex' }}> <Drawer.Persistent open={this.state.open} onOpen={() => log('onOpen')} onClose={() => log('onClose')} > <Drawer.Persistent.Drawer> <Drawer.Persistent.ToolbarSpacer /> <DemoDrawerContent /> </Drawer.Persistent.Drawer> </Drawer.Persistent> <div> <DemoDrawerToolbar menu onMenuClick={() => this.setState({ open: !this.state.open })} /> <main> <div>{JSON.stringify(this.state)}</div> <DemoParagraphs count={10} /> </main> </div> </div> ) } } class MyTemporaryDrawer extends React.Component { state = { open: false, } render() { return ( <div> <Drawer.Temporary open={this.state.open} onOpen={() => log('onOpen')} onClose={() => this.setState({ open: false })} > <Drawer.Temporary.Drawer> <Drawer.Temporary.Header> <Drawer.Temporary.HeaderContent> Header here </Drawer.Temporary.HeaderContent> </Drawer.Temporary.Header> <nav className="mdc-persistent-drawer__content mdc-list"> <a className="mdc-list-item mdc-persistent-drawer--selected" href="#" > <i className="material-icons mdc-list-item__start-detail" aria-hidden="true" > inbox </i>Inbox </a> <a className="mdc-list-item" href="#"> <i className="material-icons mdc-list-item__start-detail" aria-hidden="true" > star </i>Star </a> </nav> </Drawer.Temporary.Drawer> </Drawer.Temporary> <button onClick={() => this.setState({ open: !this.state.open })}> Toggle Drawer: {JSON.stringify(this.state.open)} </button> </div> ) } } class MyElevation extends React.Component { render() { return <Elevation z="20">hello</Elevation> } } class MyFab extends React.Component { render() { return ( <Fab className="material-icons"> <Fab.Icon>favorite</Fab.Icon> </Fab> ) } } class MyFormField extends React.Component { render() { return ( <FormField> <input type="checkbox" id="input" /> <label htmlFor="input">Input Label</label> </FormField> ) } } class MyGridList extends React.Component { render() { return ( <GridList> <GridList.Tiles> {[1, 2].map(v => ( <GridList.Tile key={v}> <GridList.Tile.Primary> <GridList.Tile.PrimaryContent src="//via.placeholder.com/300x300" /> </GridList.Tile.Primary> <GridList.Tile.Secondary> <GridList.Tile.Title>Title</GridList.Tile.Title> </GridList.Tile.Secondary> </GridList.Tile> ))} </GridList.Tiles> </GridList> ) } } class MyIconToggle extends React.Component { state = { on: true, } render() { return ( <div> <IconToggle on={this.state.on} onChange={e => this.setState({ on: e.detail.isOn })} className="material-icons" dataToggleOn={{ label: 'Remove from favorites', content: 'favorite' }} dataToggleOff={{ label: 'Add to favorites', content: 'favorite_border', }} > favorite_border </IconToggle> {JSON.stringify(this.state.on)} </div> ) } } class MyLayoutGrid extends React.Component { render() { return ( <LayoutGrid> <LayoutGrid.Inner> <LayoutGrid.Cell order="2"> a </LayoutGrid.Cell> <LayoutGrid.Cell order="1"> b </LayoutGrid.Cell> <LayoutGrid.Cell> c </LayoutGrid.Cell> </LayoutGrid.Inner> </LayoutGrid> ) } } class MyLinearProgress extends React.Component { render() { return ( <div> <p> <LinearProgress progress={0.5} /> Determinate </p> <p> <LinearProgress progress={0.5} indeterminate /> Indeterminate </p> <p> <LinearProgress progress={0.5} buffer={0.75} /> Buffer </p> <p> <LinearProgress progress={0.5} reversed /> Reversed </p> <p> <LinearProgress progress={0.5} indeterminate reversed /> Indeterminate Reversed </p> <p> <LinearProgress progress={0.5} buffer={0.75} reversed /> Buffer Reversed </p> <p> <LinearProgress progress={0.5} accent /> Secondary </p> </div> ) } } class MyList extends React.Component { render() { return ( <div> <List>{[1, 2].map(i => <List.Item key={i}>hello {i}</List.Item>)}</List> <List twoLine> {[1, 2].map(i => ( <List.Item key={i}> <List.Item.Text> Two-line item {i} <List.Item.Text.Secondary> Seconday Text </List.Item.Text.Secondary> </List.Item.Text> </List.Item> ))} </List> </div> ) } } class MyMenu extends React.Component { state = { open: false, } render() { return ( <div> <div>{JSON.stringify(this.state)}</div> <Menu.Simple open={this.state.open} onClose={() => this.setState({ open: false })} onSelected={e => log('onSelected', e.detail)} items={[ { text: 'Facebook', onClick: () => log('Facebook') }, { text: 'Google', onClick: () => log('Google') }, { text: 'Apple', disabled: true }, ]} /> <button onClick={() => this.setState({ open: !this.state.open })}> toggle menu </button> <button onClick={() => this.setState({ open: 0 })}> open with selectedIndex </button> </div> ) } } class MyRadio extends React.Component { state = { company: 'google', } render() { return ( <div> <Radio name="company" id="Radio1" value="facebook" checked={this.state.company === 'facebook'} onChange={e => this.setState({ company: e.target.value })} /> <label htmlFor="Radio1">Facebook</label> <Radio name="company" id="Radio2" value="google" checked={this.state.company === 'google'} onChange={e => this.setState({ company: e.target.value })} /> <label htmlFor="Radio2">Google</label> <div>{JSON.stringify(this.state)}</div> </div> ) } } class MySelect extends React.Component { state = { value: null, // value: 'google', // value: 'wrong', } render() { const items = [ { text: 'Facebook', value: 'facebook' }, { text: 'Google', value: 'google' }, { text: 'Apple', value: 'apple', disabled: true }, ] return ( <div> <Select value={this.state.value} onChange={e => this.setState({ value: e.detail.value })} placeholder="Select a company" items={items} /> <div>{JSON.stringify(this.state)}</div> </div> ) } } class MySlider extends React.Component { state = { value: 10, } render() { return ( <div> <Slider value={this.state.value} onChange={({ detail }) => this.setState({ value: detail.value })} /> {this.state.value} </div> ) } } class MySnackbar extends React.Component { render() { return ( <div> <Snackbar ref={v => (this.snackbar = v)} /> <div onClick={() => this.snackbar.show({ message: new Date(), actionText: 'undo', actionHandler: () => log('actionhandler'), })} > open snackbar </div> </div> ) } } class MySwitch extends React.Component { state = { checked: true, } render() { return ( <div> <label className="mdc-switch-label"> <Switch checked={this.state.checked} onChange={e => this.setState({ checked: e.target.checked })} /> on/off </label> {JSON.stringify(this.state.checked)} </div> ) } } class MyTabs extends React.Component { render() { const items = [ { text: 'Recents', icon: <i className="mdc-tab__icon material-icons">phone</i>, }, { text: 'Favorites', icon: <i className="mdc-tab__icon material-icons">favorite</i>, active: true, }, { text: 'Nearby', icon: <i className="mdc-tab__icon material-icons">person_pin</i>, }, ] return <Tabs indicator="primary" items={items} onChange={pd} /> } } class MyToolbar extends React.Component { render() { return <MyWaterfallFlexibleToolbar /> } } const MyWaterfallFlexibleToolbar = () => { const self = {} return ( <div style={{ width: 320 }}> <Toolbar fixed waterfall flexible flexibleDefaultBehavior ref={v => (self.toolbar = v)} > <Toolbar.Row> <Toolbar.Section align="start"> <Toolbar.Icon menu className="material-icons"> menu </Toolbar.Icon> <Toolbar.Title>Title</Toolbar.Title> </Toolbar.Section> <Toolbar.Section align="end"> <Toolbar.Icon className="material-icons"> file_download </Toolbar.Icon> <Toolbar.Icon className="material-icons">print</Toolbar.Icon> <Toolbar.Icon className="material-icons">more_vert</Toolbar.Icon> </Toolbar.Section> </Toolbar.Row> </Toolbar> <Toolbar.FixedAdjust ref={v => (self.toolbar.fixedAdjustElement = v)} style={{ minHeight: 1000 }} > <DemoParagraphs count={3} /> </Toolbar.FixedAdjust> </div> ) } class MyTextfield extends React.Component { render() { return <Textfield label="Name" helptext="name is required" persistent /> } } class App extends React.Component { render() { const pages = getPages() return <div>{pages.map((v, i) => React.createElement(v, { key: i }))}</div> } } render(<App />, document.querySelector('#app')) // vim: fdm=marker
src/UnmountClosed.js
nkbt/react-collapse
import React from 'react'; import PropTypes from 'prop-types'; import {Collapse} from './Collapse'; export class UnmountClosed extends React.PureComponent { static propTypes = { isOpened: PropTypes.bool.isRequired, onWork: PropTypes.func, onRest: PropTypes.func }; static defaultProps = { onWork: undefined, onRest: undefined }; constructor(props) { super(props); this.state = {isResting: true, isOpened: props.isOpened, isInitialRender: true}; } componentDidUpdate(prevProps) { const {isOpened} = this.props; if (prevProps.isOpened !== isOpened) { // eslint-disable-next-line react/no-did-update-set-state this.setState({isResting: false, isOpened, isInitialRender: false}); } } onWork = ({isOpened, ...rest}) => { this.setState({isResting: false, isOpened}); const {onWork} = this.props; if (onWork) { onWork({isOpened, ...rest}); } }; onRest = ({isOpened, ...rest}) => { this.setState({isResting: true, isOpened, isInitialRender: false}); const {onRest} = this.props; if (onRest) { onRest({isOpened, ...rest}); } }; getInitialStyle = () => { const {isOpened, isInitialRender} = this.state; if (isInitialRender) { return isOpened ? {height: 'auto', overflow: 'initial'} : {height: '0px', overflow: 'hidden'}; } return {height: '0px', overflow: 'hidden'}; }; render() { const {isResting, isOpened} = this.state; return isResting && !isOpened ? null : ( <Collapse {...this.props} initialStyle={this.getInitialStyle()} onWork={this.onWork} onRest={this.onRest} /> ); } }