path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
dashboard/app/components/AddButton/AddButton.js
tlisonbee/cerberus-management-service
import React from 'react' import { Component } from 'react' import PropTypes from 'prop-types' import './AddButton.scss' import '../../assets/images/add-green.svg' /** * Component for an Add Button (a button with a plus and a message) */ export default class AddButton extends Component { static propTypes = { handleClick: PropTypes.func.isRequired, message: PropTypes.string.isRequired } render() { const {handleClick, message} = this.props return ( <div className='permissions-add-new-permission-button-container clickable' onClick={() => { handleClick() }}> <div className='permissions-add-new-permission-add-icon'></div> <div className='permissions-add-new-permission-add-label'>{message}</div> </div> ) } }
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/antd/es/upload/UploadList.js
bhathiya/test
import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import React from 'react'; import Animate from 'rc-animate'; import Icon from '../icon'; import Tooltip from '../tooltip'; import Progress from '../progress'; import classNames from 'classnames'; // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL var previewFile = function previewFile(file, callback) { var reader = new FileReader(); reader.onloadend = function () { return callback(reader.result); }; reader.readAsDataURL(file); }; var UploadList = function (_React$Component) { _inherits(UploadList, _React$Component); function UploadList() { _classCallCheck(this, UploadList); var _this = _possibleConstructorReturn(this, (UploadList.__proto__ || Object.getPrototypeOf(UploadList)).apply(this, arguments)); _this.handleClose = function (file) { var onRemove = _this.props.onRemove; if (onRemove) { onRemove(file); } }; _this.handlePreview = function (file, e) { var onPreview = _this.props.onPreview; if (!onPreview) { return; } e.preventDefault(); return onPreview(file); }; return _this; } _createClass(UploadList, [{ key: 'componentDidUpdate', value: function componentDidUpdate() { var _this2 = this; if (this.props.listType !== 'picture' && this.props.listType !== 'picture-card') { return; } (this.props.items || []).forEach(function (file) { if (typeof document === 'undefined' || typeof window === 'undefined' || !window.FileReader || !window.File || !(file.originFileObj instanceof File) || file.thumbUrl !== undefined) { return; } /*eslint-disable */ file.thumbUrl = ''; /*eslint-enable */ previewFile(file.originFileObj, function (previewDataUrl) { /*eslint-disable */ file.thumbUrl = previewDataUrl; /*eslint-enable */ _this2.forceUpdate(); }); }); } }, { key: 'render', value: function render() { var _this3 = this, _classNames2; var _props = this.props, prefixCls = _props.prefixCls, _props$items = _props.items, items = _props$items === undefined ? [] : _props$items, listType = _props.listType, showPreviewIcon = _props.showPreviewIcon, showRemoveIcon = _props.showRemoveIcon, locale = _props.locale; var list = items.map(function (file) { var _classNames; var progress = void 0; var icon = React.createElement(Icon, { type: file.status === 'uploading' ? 'loading' : 'paper-clip' }); if (listType === 'picture' || listType === 'picture-card') { if (file.status === 'uploading' || !file.thumbUrl && !file.url) { if (listType === 'picture-card') { icon = React.createElement( 'div', { className: prefixCls + '-list-item-uploading-text' }, locale.uploading ); } else { icon = React.createElement(Icon, { className: prefixCls + '-list-item-thumbnail', type: 'picture' }); } } else { icon = React.createElement( 'a', { className: prefixCls + '-list-item-thumbnail', onClick: function onClick(e) { return _this3.handlePreview(file, e); }, href: file.url || file.thumbUrl, target: '_blank', rel: 'noopener noreferrer' }, React.createElement('img', { src: file.thumbUrl || file.url, alt: file.name }) ); } } if (file.status === 'uploading') { // show loading icon if upload progress listener is disabled var loadingProgress = 'percent' in file ? React.createElement(Progress, _extends({ type: 'line' }, _this3.props.progressAttr, { percent: file.percent })) : null; progress = React.createElement( 'div', { className: prefixCls + '-list-item-progress', key: 'progress' }, loadingProgress ); } var infoUploadingClass = classNames((_classNames = {}, _defineProperty(_classNames, prefixCls + '-list-item', true), _defineProperty(_classNames, prefixCls + '-list-item-' + file.status, true), _classNames)); var preview = file.url ? React.createElement( 'a', { href: file.url, target: '_blank', rel: 'noopener noreferrer', className: prefixCls + '-list-item-name', onClick: function onClick(e) { return _this3.handlePreview(file, e); }, title: file.name }, file.name ) : React.createElement( 'span', { className: prefixCls + '-list-item-name', onClick: function onClick(e) { return _this3.handlePreview(file, e); }, title: file.name }, file.name ); var style = file.url || file.thumbUrl ? undefined : { pointerEvents: 'none', opacity: 0.5 }; var previewIcon = showPreviewIcon ? React.createElement( 'a', { href: file.url || file.thumbUrl, target: '_blank', rel: 'noopener noreferrer', style: style, onClick: function onClick(e) { return _this3.handlePreview(file, e); }, title: locale.previewFile }, React.createElement(Icon, { type: 'eye-o' }) ) : null; var removeIcon = showRemoveIcon ? React.createElement(Icon, { type: 'delete', title: locale.removeFile, onClick: function onClick() { return _this3.handleClose(file); } }) : null; var removeIconCross = showRemoveIcon ? React.createElement(Icon, { type: 'cross', title: locale.removeFile, onClick: function onClick() { return _this3.handleClose(file); } }) : null; var actions = listType === 'picture-card' && file.status !== 'uploading' ? React.createElement( 'span', { className: prefixCls + '-list-item-actions' }, previewIcon, removeIcon ) : removeIconCross; var message = file.response || file.error && file.error.statusText || locale.uploadError; var iconAndPreview = file.status === 'error' ? React.createElement( Tooltip, { title: message }, icon, preview ) : React.createElement( 'span', null, icon, preview ); return React.createElement( 'div', { className: infoUploadingClass, key: file.uid }, React.createElement( 'div', { className: prefixCls + '-list-item-info' }, iconAndPreview ), actions, React.createElement( Animate, { transitionName: 'fade', component: '' }, progress ) ); }); var listClassNames = classNames((_classNames2 = {}, _defineProperty(_classNames2, prefixCls + '-list', true), _defineProperty(_classNames2, prefixCls + '-list-' + listType, true), _classNames2)); var animationDirection = listType === 'picture-card' ? 'animate-inline' : 'animate'; return React.createElement( Animate, { transitionName: prefixCls + '-' + animationDirection, component: 'div', className: listClassNames }, list ); } }]); return UploadList; }(React.Component); export default UploadList; UploadList.defaultProps = { listType: 'text', progressAttr: { strokeWidth: 2, showInfo: false }, prefixCls: 'ant-upload', showRemoveIcon: true, showPreviewIcon: true };
client/modules/Admin/pages/Admin.js
lordknight1904/bigvnadmin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import AdminNavBar from '../components/AdminNavBar/AdminNavBar'; import AdminList from '../components/AdminList/AdminList'; import { getId } from '../../Login/LoginReducer'; import { Modal, Button, Form, FormGroup, FormControl, Col, Row, ControlLabel, Panel, HelpBlock } from 'react-bootstrap'; import { deleteAdmin, recoverAdmin, createAdmin, getAdminSearch } from '../AdminActions'; import { getSearch, getCurrentPage } from '../AdminReducer'; class Admin extends Component { constructor(props) { super(props); this.state = { type: '', idSelected: '', show: false, message: '', register: false, userName: '', password: '', role: 'admin', userNameError: '', passwordError: '', isSigningIn: false, error: '', } } componentWillMount() { if (this.props.id === '') { this.context.router.push('/'); } } showDialog = (type, id) => { console.log('alo'); this.setState({ show: true, type, idSelected: id }); }; hideDialog = () => { this.setState({ show: false }); }; onXacNhan = () => { switch (this.state.type) { case 'Delete': { const del = { id: this.state.idSelected }; this.props.dispatch(deleteAdmin(del)).then((res) => { if (res.admin !== 'success') { this.setState({ message: res.admin }); } else { this.setState({ message: '', show: false }); this.props.dispatch(getAdminSearch(this.props.search, this.props.currentPage -1)); } }); break; } case 'Recover': { const recover = { id: this.state.idSelected }; this.props.dispatch(recoverAdmin(recover)).then((res) => { if (res.admin !== 'success') { this.setState({ message: res.admin }); } else { this.setState({ message: '', show: false }); this.props.dispatch(getAdminSearch(this.props.search, this.props.currentPage -1)); } }); break; } default: break; } }; translateType = (type) => { switch (type) { case 'Recover': return 'Khôi phục'; case 'Delete': return 'Tước quyền'; default: return ''; } }; onRegister = () => { this.setState({ register: true }); }; hideRegister = () => { this.setState({ register: false }); }; onCreateAdmin = () => { const admin = { userName: this.state.userName, password: this.state.password, role: this.state.role, }; this.setState({ isSigningIn: true }); this.props.dispatch(createAdmin(admin)).then((res) => { const response = res ? res.code : ''; switch (response) { case 'error': { this.setState({ error: 'Không thể đăng nhập.', isSigningIn: false }); break; } case 'Thiếu thông tin': { this.setState({ error: 'Vui lòng nhập đủ thông tin', isSigningIn: false }); break; } case 'success': { this.setState({ isSigningIn: false, register: false }); this.props.dispatch(getAdminSearch(this.props.search, this.props.currentPage -1)); break; } default: { } } }) }; handleUserName = (event) => { if (event.target.value.trim() === '') { this.setState({ userName: event.target.value.trim(), userNameError: 'Trường này không được trống.' }); } else { this.setState({ userName: event.target.value.trim(), userNameError: ''}); } }; handlePassword = (event) => { if (event.target.value.trim() === '') { this.setState({ password: event.target.value.trim(), passwordError: 'Trường này không được trống.' }); } else { this.setState({ password: event.target.value.trim(), passwordError: '' }); } }; handleUserNameBlur = (event) => { if (event.target.value.trim() === '') { this.setState({ userNameError: 'Trường này không được trống.'}); } else { this.setState({ userNameError: ''}); } }; handlePasswordBlur = (event) => { if (event.target.value.trim() === '') { this.setState({ passwordError: 'Trườg này không được trống.'}); } else { this.setState({ passwordError: ''}); } }; handleRole = (event) => { this.setState({ role: event.target.value }); }; render() { return ( <div> <Row> <AdminNavBar onRegister={this.onRegister}/> </Row> <Row style={{ paddingLeft: '20px', paddingRight: '20px' }}> <AdminList showDialog={this.showDialog}/> </Row> <Modal show={this.state.show} onHide={this.hideDialog} > <Modal.Header> <Modal.Title>Xác nhận</Modal.Title> </Modal.Header> <Modal.Body> {`${this.translateType(this.state.type)} quản trị viên này.`} <br/> <FormGroup controlId="error" validationState='error' > <HelpBlock>{this.state.message}</HelpBlock> </FormGroup> </Modal.Body> <Modal.Footer> <Button onClick={this.hideDialog}>Hủy</Button> <Button bsStyle="primary" onClick={this.onXacNhan}>{this.translateType(this.state.type)}</Button> </Modal.Footer> </Modal> <Modal show={this.state.register} onHide={this.hideRegister} > <Modal.Header> <Modal.Title>Tạo quản trị viên mới</Modal.Title> </Modal.Header> <Modal.Body> <Form horizontal> <FormGroup controlId="formHorizontalEmail"> <Col componentClass={ControlLabel} sm={2}> Tên tài khoản </Col> <Col sm={10}> <FormControl type="text" value={this.state.userName} onChange={this.handleUserName} onBlur={this.handleUserNameBlur} /> </Col> </FormGroup> <FormGroup controlId="formHorizontalPassword"> <Col componentClass={ControlLabel} sm={2}> Mật khẩu </Col> <Col sm={10}> <FormControl type="password" value={this.state.password} onChange={this.handlePassword} onBlur={this.handlePasswordBlur} /> </Col> </FormGroup> <FormGroup controlId="formControlsSelect"> <Col componentClass={ControlLabel} sm={2}> Chức vụ </Col> <Col sm={10}> <FormControl componentClass="select" onChange={this.handleRole} > <option value="admin">Quản trị viên</option> <option value="employee">Nhân viên</option> </FormControl> </Col> </FormGroup> <FormGroup controlId="error" validationState='error' > <Col sm={6} smOffset={3} > <HelpBlock>{this.state.error}</HelpBlock> </Col> </FormGroup> </Form> </Modal.Body> <Modal.Footer> <Button onClick={this.hideRegister} disabled={this.state.isSigningIn}>Hủy</Button> <Button bsStyle="primary" onClick={this.onCreateAdmin} disabled={this.state.isSigningIn}>Tạo</Button> </Modal.Footer> </Modal> </div> ); } } // Retrieve data from store as props function mapStateToProps(state) { return { id: getId(state), search: getSearch(state), currentPage: getCurrentPage(state), }; } Admin.propTypes = { dispatch: PropTypes.func.isRequired, search: PropTypes.string.isRequired, currentPage: PropTypes.number.isRequired, id: PropTypes.string.isRequired, }; Admin.contextTypes = { router: PropTypes.object, }; export default connect(mapStateToProps)(Admin);
examples/huge-apps/routes/Course/routes/Announcements/components/Announcements.js
mozillo/react-router
import React from 'react' class Announcements extends React.Component { render() { return ( <div> <h3>Announcements</h3> {this.props.children || <p>Choose an announcement from the sidebar.</p>} </div> ) } } export default Announcements
assets/react/src/components/task/cron_container.js
khoa-le/crontask
import React, { Component } from 'react'; import Tasks from './tasks'; import TaskDetail from './task_detail'; export default class TaskContainer extends Component { getChildContext() { return { lang: this.state.lang, t: this.state.t } } constructor(props) { super(props); this.state = { lang: window.lang, pagination_limit:5, viewMode: 'list', navRef: 'inbox', data: [], offset: 0, totalInbox: 0 } if(window.viewDetailId>0){ this.state.viewMode='detail'; this.state.item=window.viewDetailData; } } loadCounterFromServer() { } componentDidMount() { this.loadCounterFromServer(); } handleViewDetail = (data) => { this.setState({ 'viewMode': 'detail', 'item': data },()=>{ }); } handleCreateNew = (data) => { this.setState({ 'viewMode': 'detail', 'item': {} },()=>{ }); } handleBackToList = (data) => { this.setState({viewMode: 'list'}); } render() { if (this.state.viewMode == 'detail') { return ( <div className="row"> <TaskDetail handleBack={this.handleBackToList} data={this.state.item} /> </div> ) } else{ return ( <div className="row " > <div className="col-md-12 col-lg-12 animated fadeInRight"> <div id="messageInbox"> <div className="mail-box-header"> <div className="pull-right"> <div className="tooltip-demo buttons text-right"> <div className="btn-group"> <a onClick={this.handleCreateNew} className="btn btn-white btn-sm btn-trash" data-toggle="tooltip" data-placement="top" title="Create new"><i className="fa fa-plus"></i> Create</a> </div> </div> </div> </div> <div className="mail-box"> <div className="mailbox"> <Tasks handleViewDetail={this.handleViewDetail} perPage='5' url='api/tasks' /> </div> </div> </div> </div> </div> ); } } }; TaskContainer.childContextTypes = { lang: React.PropTypes.number,t:React.PropTypes.any};
inc/option_fields/vendor/htmlburger/carbon-fields/assets/js/fields/components/textarea/index.js
wpexpertsio/WP-Secure-Maintainance
/** * The external dependencies. */ import React from 'react'; import PropTypes from 'prop-types'; import { compose, 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_TEXTAREA, TYPE_HEADER_SCRIPTS, TYPE_FOOTER_SCRIPTS } from 'fields/constants'; /** * Render a multiline text input field. * * @param {Object} props * @param {String} props.name * @param {Object} props.field * @param {Function} props.handleChange * @return {React.Element} */ export const TextareaField = ({ name, field, handleChange }) => { return <Field field={field}> <textarea id={field.id} name={name} value={field.value} rows={field.rows} disabled={!field.ui.is_visible} onChange={handleChange} {...field.attributes} /> </Field>; }; /** * Validate the props. * * @type {Object} */ TextareaField.propTypes = { name: PropTypes.string, field: PropTypes.shape({ id: PropTypes.string, value: PropTypes.string, rows: PropTypes.number, attributes: PropTypes.object, }), handleChange: PropTypes.func, }; /** * The enhancer. * * @type {Function} */ export const enhance = compose( withStore(), withSetup(), /** * The handlers passed to the component. */ withHandlers({ handleChange: ({ field, setFieldValue }) => ({ target: { value } }) => setFieldValue(field.id, value), }) ); export default setStatic('type', [ TYPE_TEXTAREA, TYPE_HEADER_SCRIPTS, TYPE_FOOTER_SCRIPTS, ])(enhance(TextareaField));
admin/client/App/components/Navigation/Mobile/SectionItem.js
joerter/keystone
/** * A mobile section */ import React from 'react'; import MobileListItem from './ListItem'; import { Link } from 'react-router'; const MobileSectionItem = React.createClass({ displayName: 'MobileSectionItem', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, currentListKey: React.PropTypes.string, href: React.PropTypes.string.isRequired, lists: React.PropTypes.array, }, // Render the lists renderLists () { if (!this.props.lists || this.props.lists.length <= 1) return null; const navLists = this.props.lists.map((item) => { // Get the link and the classname const href = item.external ? item.path : `${Keystone.adminPath}/${item.path}`; const className = (this.props.currentListKey && this.props.currentListKey === item.path) ? 'MobileNavigation__list-item is-active' : 'MobileNavigation__list-item'; return ( <MobileListItem key={item.path} href={href} className={className}> {item.label} </MobileListItem> ); }); return ( <div className="MobileNavigation__lists"> {navLists} </div> ); }, render () { return ( <div className={this.props.className}> <Link className="MobileNavigation__section-item" to={this.props.href} tabIndex="-1" > {this.props.children} </Link> {this.renderLists()} </div> ); }, }); module.exports = MobileSectionItem;
ui/src/plugins/epl-dashboard/components/SystemOverview.js
Hajto/erlangpl
// @flow import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Row, Col, ListGroup, ListGroupItem } from 'react-bootstrap'; import Measure from 'react-measure'; import Chart from './SystemOverviewChart'; import './SystemOverview.css'; class SystemOverview extends Component { state: { width: number }; constructor(props) { super(props); this.state = { width: 0 }; } render() { const { info, overview } = this.props; const mem = ['KB', 'MB', 'GB']; const memory = mem.reduce( (acc, a) => { if (acc.v > 1000) { return { v: acc.v / 1000, t: a }; } else { return acc; } }, { v: parseInt(info.memoryTotal, 10), t: 'B' } ); const systemOverview = [ ['Throughput', info.receive ? `${info.receive.count} msg` : undefined], ['Throughput', info.receive ? `${info.receive.sizes} B` : undefined], ['Processes', info.processCount], ['Spawns', info.spawn ? info.spawn.count : undefined], ['Exits', info.exit ? info.exit.count : undefined], ['Abnormal Exits', info.exit ? info.exit.abnormal : undefined], [ 'Memory', info.memoryTotal ? `${memory.v.toFixed(2)} ${memory.t}` : undefined ] ]; const throughputData = overview.receive.map(a => ({ name: 'Throughput (msg)', count: parseInt(a.count, 10) })); const memoryData = overview.memoryTotal.map(a => { return { name: 'Memory (MB)', usage: Number((parseInt(a, 10) / 1000000).toFixed(2)) }; }); const processesData = overview.processCount.map(a => ({ name: 'Processes', count: parseInt(a, 10) })); const maxProcesses = Math.max(...overview.processCount); const dimensions = { width: this.state.width - this.state.width / 10, height: 210 }; return ( <Row className="SystemOverview"> <Col xs={4}> <h5 className="SystemInfo-list-header"> Overview (last 5 sec) </h5> <ListGroup className="SystemInfo-list"> {systemOverview.map(([name, value], i) => ( <ListGroupItem key={i}> <span>{name}</span> <span className="value">{value || 'N/A'}</span> </ListGroupItem> ))} </ListGroup> </Col> <Measure includeMargin={false} onMeasure={({ width }) => this.setState({ width })} > <Col xs={8} className="charts"> <Chart title="Memory usage" height={dimensions.height} width={dimensions.width} data={memoryData} color="#8FBF47" dataKey="usage" domain={['dataMin', 'dataMax']} loaderText="Gathering memory usage data" /> <Chart title="Processes" height={dimensions.height} width={dimensions.width} data={processesData} color="#227A50" dataKey="count" domain={[ `dataMin - ${Math.floor(maxProcesses / 5)}`, `dataMax + ${Math.floor(maxProcesses / 5)}` ]} loaderText="Gathering processes data" /> <Chart title="Throughput" height={dimensions.height} width={dimensions.width} data={throughputData} color="#1F79B7" dataKey="count" loaderText="Gathering throughput data" /> </Col> </Measure> </Row> ); } } export default connect(state => { return { info: state.eplDashboard.systemInfo, overview: state.eplDashboard.systemOverview }; }, {})(SystemOverview);
webapp/app/components/Software/Table/index.js
EIP-SAM/SAM-Solution-Node-js
// // Table page software // import React from 'react'; import { Table } from 'react-bootstrap'; import Tr from 'components/Tr'; import Th from 'components/Th'; import Td from 'components/Td'; /* eslint-disable react/prefer-stateless-function */ export default class SoftwareTable extends React.Component { render() { const names = ['#', 'Username', 'OS']; if (!this.props.users) { return null; } return ( <div> <Table responsive hover striped key={this.props.refresh}> <thead> <Tr items={names} component={Th} /> </thead> <tbody> {this.props.users.map((user, index) => <Tr key={`item-${index}-${user.os}`} items={[ { isLink: false, value: user.id }, { isLink: true, link: `/software/${user.name}/${user.id}`, value: user.name }, { isLink: false, value: user.os }]} component={Td} /> )} </tbody> </Table> </div> ); } } SoftwareTable.propTypes = { users: React.PropTypes.arrayOf(React.PropTypes.object), refresh: React.PropTypes.bool, };
src/routes/route.js
sourabh-garg/react-starter-kit
import React from 'react'; import Main from '../components/main'; import HomePage from '../components/Homepage/homepage'; import { Route, IndexRoute } from "react-router"; module.exports = ( <Route path="/" component={Main}> <IndexRoute component={HomePage}/> </Route> );
client/src/components/Listing/AddListing/AddListingComponents/ListingDisplayImages.js
bwuphan/raptor-ads
import React from 'react'; import { Grid, Image } from 'semantic-ui-react'; import ListingDisplayImage from './ListingDisplayImage'; const ListingDisplayImages = ({ images, handleDelete }) => { return ( <Grid width={16}> <Grid.Column width={5} /> <Grid.Column width={6}> <div> {images.map((currentImage, index) => <ListingDisplayImage image={currentImage} key={index} handleDelete={handleDelete} index={index} />)} </div> </Grid.Column> </Grid> ); }; ListingDisplayImages.propTypes = { images: React.PropTypes.arrayOf(React.PropTypes.object).isRequired, }; export default ListingDisplayImages;
src/svg-icons/content/report.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentReport = (props) => ( <SvgIcon {...props}> <path d="M15.73 3H8.27L3 8.27v7.46L8.27 21h7.46L21 15.73V8.27L15.73 3zM12 17.3c-.72 0-1.3-.58-1.3-1.3 0-.72.58-1.3 1.3-1.3.72 0 1.3.58 1.3 1.3 0 .72-.58 1.3-1.3 1.3zm1-4.3h-2V7h2v6z"/> </SvgIcon> ); ContentReport = pure(ContentReport); ContentReport.displayName = 'ContentReport'; ContentReport.muiName = 'SvgIcon'; export default ContentReport;
src/routes/Library/views/LibraryView.js
bhj/karaoke-forever
import PropTypes from 'prop-types' import React from 'react' import { Link } from 'react-router-dom' import ArtistList from '../components/ArtistList' import SearchResults from '../components/SearchResults' import TextOverlay from 'components/TextOverlay' import Spinner from 'components/Spinner' import styles from './LibraryView.css' const LibraryView = (props) => { const { isAdmin, isEmpty, isLoading, isSearching } = props return ( <> {!isSearching && <ArtistList {...props} /> } {isSearching && <SearchResults {...props} /> } {isLoading && <Spinner /> } {!isLoading && isEmpty && <TextOverlay className={styles.empty}> <h1>Library Empty</h1> {isAdmin && <p><Link to='/account'>Add media folders</Link> to get started.</p> } </TextOverlay> } </> ) } LibraryView.propTypes = { isAdmin: PropTypes.bool.isRequired, isLoading: PropTypes.bool.isRequired, isSearching: PropTypes.bool.isRequired, isEmpty: PropTypes.bool.isRequired, } export default LibraryView
src/components/pinning-manager/pinning-manager-service-modal/PinningManagerServiceModal.js
ipfs/webui
import React from 'react' import classNames from 'classnames' import PropTypes from 'prop-types' import { connect } from 'redux-bundler-react' import { withTranslation, Trans } from 'react-i18next' import { useForm } from 'react-hook-form' // Components import { Modal, ModalBody, ModalActions } from '../../modal/Modal' import Button from '../../button/Button' import './PinningManagerServiceModal.css' const PinningManagerServiceModal = ({ t, onLeave, onSuccess, className, service, tReady, doAddPinningService, nickname, apiEndpoint, visitServiceUrl, secretApiKey, ...props }) => { const { register, errors, clearErrors, setError, handleSubmit } = useForm({ defaultValues: { nickname, apiEndpoint, secretApiKey: null } }) const inputClass = 'w-100 lh-copy f5 ph2 pv1 input-reset ba b--black-20 br1 focus-outline' const onSubmit = async data => { try { await doAddPinningService(data) onSuccess() } catch (error) { console.error(error) setError('apiValidation', { type: 'manual', message: error.message }) } } const cleanErrors = () => { clearErrors('apiValidation') } return ( <Modal {...props} className={className} onCancel={onLeave} style={{ maxWidth: '34em' }}> <form onSubmit={handleSubmit(onSubmit)} onChange={cleanErrors}> <ModalBody> <p>{ t('pinningServiceModal.title') }</p> <div className='pa2 pinningManagerServiceModalContainer'> { service.icon && service.name && ( <> <label> { t('pinningServiceModal.service') } </label> <div className="flex w-100 items-center"> <img className="mr3" src={service.icon} alt={service.name} height={42} style={{ objectFit: 'contain' }} /> <span>{ service.name }</span> </div> </> )} <label htmlFor="cm-nickname"> { t('pinningServiceModal.nickname') } </label> <div className='relative'> <input id='cm-nickname' name='nickname' ref={ register({ required: true }) } type='text' className={ classNames(inputClass, errors.nickname ? 'bg-red white' : 'charcoal') } placeholder={ t('pinningServiceModal.nicknamePlaceholder') } /> {errors.nickname && (<ErrorMsg text={ t('errors.nickname') }/>)} </div> <label htmlFor="cm-apiEndpoint"> { t('pinningServiceModal.apiEndpoint') } </label> <div className='relative'> <input id='cm-apiEndpoint' name='apiEndpoint' ref={ register({ required: true, pattern: 'http(s){0,1}://.*' }) } type='url' className={ classNames(inputClass, errors.apiEndpoint ? 'bg-red white' : 'charcoal') } placeholder={ t('pinningServiceModal.apiEndpointPlaceholder') } /> {errors.apiEndpoint && (<ErrorMsg text={`${t('errors.apiError')}: ${t('errors.apiEndpoint')}`}/>)} </div> <label htmlFor="cm-secretApiKey"> { t('pinningServiceModal.secretApiKey') } { service.icon && service.name && visitServiceUrl && ( <a className='f7 link pv0 lh-copy dib' href={ visitServiceUrl } rel='noopener noreferrer' target="_blank"> { t('pinningServiceModal.secretApiKeyHowToLink') }</a> )} </label> <div className='relative'> <input id='cm-secretApiKey' ref={ register({ required: true }) } name='secretApiKey' type='password' autoComplete='off' className={ classNames(inputClass, errors.secretApiKey ? 'bg-red white' : 'charcoal') } placeholder="••••••••••••••••••••" /> {errors.secretApiKey && (<ErrorMsg text={ t('errors.secretApiKey') }/>)} </div> </div> <div> { errors.apiValidation && <p className='red f5 ttc'>{ errors.apiValidation.message}</p> } </div> <p className='f6'> <Trans i18nKey="pinningServiceModal.description" t={t}> Want to make your custom pinning service available to others? <a href='https://docs.ipfs.io/how-to/work-with-pinning-services/' rel='noopener noreferrer' target="_blank" className='pv0 dib link' type='link'>Learn how.</a> </Trans> </p> </ModalBody> <ModalActions justify="center" className='flex flex-row-reverse'> {/* Button that actually submits the form needs to be first in HTML, that's why we reverse the order with css */} <Button className='ma2 tc' type="submit">{t('actions.save')}</Button> <Button className='ma2 tc' bg='bg-gray' onClick={onLeave}>{t('actions.cancel')}</Button> </ModalActions> </form> </Modal> ) } PinningManagerServiceModal.propTypes = { className: PropTypes.string, nickname: PropTypes.string, apiEndpoint: PropTypes.string, t: PropTypes.func.isRequired, onLeave: PropTypes.func.isRequired, onSuccess: PropTypes.func.isRequired } PinningManagerServiceModal.defaultProps = { className: '', nickname: null, apiEndpoint: null } const ErrorMsg = ({ text }) => (<p className='red absolute f7' style={{ top: 26, left: 2 }}>{text}</p>) export default connect( 'doAddPinningService', withTranslation('settings')(PinningManagerServiceModal) )
src/components/Layout/Footer.js
wolfpilot/Traveller
import React from 'react'; import { Link } from 'react-router-dom'; const Footer = () => { return ( <footer className="footer"> <div className="container container--padded"> <Link className="footer__credit hyperlink hyperlink--bordered" to="https://unsplash.com/developers" target="_blank">Made with <span className="char char--heart">&#10084;</span> using Unsplash API</Link> </div> </footer> ); } export default Footer;
blueprints/view/files/__root__/views/__name__View/__name__View.js
febobo/react-redux-start
import React from 'react' type Props = { }; export class <%= pascalEntityName %> extends React.Component { props: Props; render () { return ( <div></div> ) } } export default <%= pascalEntityName %>
react-router/components/Nav.js
ybbkrishna/flux-examples
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import React from 'react'; import {Link} from 'react-router'; class Nav extends React.Component { static contextTypes = { router: React.PropTypes.func.isRequired }; render() { return ( <ul className="pure-menu pure-menu-open pure-menu-horizontal"> <li className={this.context.router.isActive('/') ? 'pure-menu-selected' : ''}><Link to='/'>Home</Link></li> <li className={this.context.router.isActive('/about') ? 'pure-menu-selected' : ''}><Link to='/about'>About</Link></li> </ul> ); } } export default Nav;
packages/cf-component-label/example/basic/component.js
koddsson/cf-ui
import React from 'react'; import { Label } from 'cf-component-label'; const LabelComponent = () => ( <p> <Label type="default">Default</Label> <Label type="info">Info</Label> <Label type="success">Success</Label> <Label type="warning">Warning</Label> <Label type="error">Error</Label> </p> ); export default LabelComponent;
src/js/components/app-dataitem.js
maxkernw/React-Flux
import React from 'react'; import {Link} from 'react-router'; export default (props) => { let itemStyle = { borderBottom: '1px solid #ccc', paddingBottom: 15 } return ( <div className="col-xs-8 col-sm-2 col-md-6" style={itemStyle}> <h4>{props.item.name}</h4> <Link to={`/user/${props.item.id}`} className="btn btn-default btn-sm"><h6>Contact</h6> <img className="img-responsive" width="5%" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/LinkedIn_logo_initials.png/768px-LinkedIn_logo_initials.png" /> </Link> </div> ) }
quick-bench/src/index.js
FredTingaud/quick-bench-front-end
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.scss'; import { unregister } from './registerServiceWorker'; ReactDOM.render( <App className="full-size" />, document.getElementById('root') ); unregister();
test/test_helper.js
dragonman225/TODO-React
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/clincoded/static/components/variant_interpretation_summary/evaluations.js
ClinGen/clincoded
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import * as evidenceCodes from '../variant_central/interpretation/mapping/evidence_code.json'; class VariantInterpretationSummaryEvaluation extends Component { constructor(props) { super(props); } render() { const { interpretation, classification } = this.props; let evaluations = interpretation ? interpretation.evaluations : null; let sortedEvaluations = evaluations ? sortByStrength(evaluations) : null; return ( <div className="evaluation-summary panel-evaluation-summary"> <div className="panel panel-info datasource-evaluation-summary"> <div className="panel-heading"> <h3 className="panel-title">Criteria meeting an evaluation strength</h3> </div> {sortedEvaluations && sortedEvaluations.met ? <table className="table"> <thead> {tableHeader()} </thead> <tbody> {sortedEvaluations.met.map(function(item, i) { return (renderMetCriteriaRow(item, i)); })} </tbody> </table> : <div className="panel-body"> <span>No criteria meeting an evaluation strength.</span> </div> } </div> <div className="panel panel-info datasource-evaluation-summary"> <div className="panel-heading"> <h3 className="panel-title">Criteria evaluated as "Not met"</h3> </div> {sortedEvaluations && sortedEvaluations.not_met ? <table className="table"> <thead> {tableHeader()} </thead> <tbody> {sortedEvaluations.not_met.map(function(item, i) { return (renderNotMetCriteriaRow(item, i)); })} </tbody> </table> : <div className="panel-body"> <span>No criteria evaluated as "Not met".</span> </div> } </div> <div className="panel panel-info datasource-evaluation-summary"> <div className="panel-heading"> <h3 className="panel-title">Criteria "Not yet evaluated"</h3> </div> {sortedEvaluations && sortedEvaluations.not_evaluated ? <table className="table"> <thead> {tableHeader()} </thead> <tbody> {sortedEvaluations.not_evaluated.map(function(item, i) { return (renderNotEvalCriteriaRow(item, i)); })} </tbody> </table> : <div className="panel-body"> <span>No criteria yet to be evaluated.</span> </div> } </div> </div> ); } } VariantInterpretationSummaryEvaluation.propTypes = { interpretation: PropTypes.object, classification: PropTypes.object }; export default VariantInterpretationSummaryEvaluation; // Method to render static table header function tableHeader() { return ( <tr> <th className="col-md-1"><span className="label-benign">B</span>/<span className="label-pathogenic">P</span></th> <th className="col-md-1">Criteria</th> <th className="col-md-3">Criteria Descriptions</th> <th className="col-md-1">Modified</th> <th className="col-md-2">Evaluation Status</th> <th className="col-md-4">Evaluation Explanation</th> </tr> ); } // Method to render "met" criteria table rows function renderMetCriteriaRow(item, key) { return ( <tr key={key} className="row-criteria-met" data-evaltype={getCriteriaType(item)}> <td className="criteria-class col-md-1"> <span className={getCriteriaType(item) === 'benign' ? 'benign' : 'pathogenic'}><i className="icon icon-check-circle"></i></span> </td> <td className={'criteria-code col-md-1 ' + getCriteriaClass(item)}>{item.criteria}</td> <td className="criteria-description col-md-3">{getCriteriaDescription(item)}</td> <td className="criteria-modified col-md-1" data-modlevel={getModifiedLevel(item)}> {item.criteriaModifier ? 'Yes' : 'No'} </td> <td className="evaluation-status col-md-2"> {item.criteriaModifier ? item.criteria + '_' + item.criteriaModifier : getCriteriaStrength(item)} </td> <td className="evaluation-description col-md-4">{item.explanation}</td> </tr> ); } // Method to render "not-met" criteria table rows function renderNotMetCriteriaRow(item, key) { return ( <tr key={key} className="row-criteria-not-met"> <td className="criteria-class col-md-1"> <span className={getCriteriaType(item) === 'benign' ? 'benign' : 'pathogenic'}><i className="icon icon-times-circle"></i></span> </td> <td className={'criteria-code col-md-1 ' + getCriteriaClass(item)}>{item.criteria}</td> <td className="criteria-description col-md-3">{getCriteriaDescription(item)}</td> <td className="criteria-modified col-md-1">N/A</td> <td className="evaluation-status col-md-2">Not Met</td> <td className="evaluation-description col-md-4">{item.explanation}</td> </tr> ); } // Method to render "not-evaluated" criteria table rows function renderNotEvalCriteriaRow(item, key) { return ( <tr key={key} className="row-criteria-not-evaluated"> <td className="criteria-class col-md-1"> <span className={getCriteriaType(item) === 'benign' ? 'benign' : 'pathogenic'}><i className="icon icon-circle-o"></i></span> </td> <td className={'criteria-code col-md-1 ' + getCriteriaClass(item)}>{item.criteria}</td> <td className="criteria-description col-md-3">{getCriteriaDescription(item)}</td> <td className="criteria-modified col-md-1">N/A</td> <td className="evaluation-status col-md-2">Not Evaluated</td> <td className="evaluation-description col-md-4">{item.explanation ? item.explanation : null}</td> </tr> ); } // Method to get critetia type: benign or pathogenic function getCriteriaType(entry) { const keys = Object.keys(evidenceCodes); let type; keys.map(key => { if (key === entry.criteria) { switch (evidenceCodes[key].class) { case 'stand-alone': case 'benign-strong': case 'benign-supporting': type = 'benign'; break; case 'pathogenic-supporting': case 'pathogenic-moderate': case 'pathogenic-strong' : case 'pathogenic-very-strong': type = 'pathogenic'; break; default: type = ''; } } }); return type; } // Method to get criteria class function getCriteriaClass(entry) { const keys = Object.keys(evidenceCodes); let classification = ''; keys.map(key => { if (key === entry.criteria) { classification = evidenceCodes[key].class; } }); return classification; } // Method to get short critetia description function getCriteriaDescription(entry) { const keys = Object.keys(evidenceCodes); let description = ''; keys.map(key => { if (key === entry.criteria) { description = evidenceCodes[key].definition; } }); return description; } // Method to get criteria strength function getCriteriaStrength(entry) { const keys = Object.keys(evidenceCodes); let strength = ''; keys.map(key => { if (key === entry.criteria) { switch (evidenceCodes[key].class) { case 'stand-alone': strength = 'stand-alone'; break; case 'pathogenic-very-strong': strength = 'very-strong'; break; case 'benign-strong': case 'pathogenic-strong': strength = 'strong'; break; case 'pathogenic-moderate': strength = 'moderate'; break; case 'benign-supporting': case 'pathogenic-supporting': strength = 'supporting'; break; default: strength = ''; } } }); return strength; } // Method to determine the levels a criteria is modified function getModifiedLevel(entry) { let modifiedLevel; if (entry.criteriaModifier && getCriteriaStrength(entry) === 'very-strong') { switch (entry.criteriaModifier) { case 'strong': modifiedLevel = '1-down'; break; case 'moderate': modifiedLevel = '2-down'; break; case 'supporting': modifiedLevel = '3-down'; break; } } if (entry.criteriaModifier && getCriteriaStrength(entry) === 'stand-alone') { switch (entry.criteriaModifier) { case 'strong': modifiedLevel = '1-down'; break; case 'supporting': modifiedLevel = '2-down'; break; } } if (entry.criteriaModifier && getCriteriaStrength(entry) === 'strong') { switch (entry.criteriaModifier) { case 'very-strong': case 'stand-alone': modifiedLevel = '1-up'; break; case 'moderate': modifiedLevel = '1-down'; break; case 'supporting': modifiedLevel = (getCriteriaType(entry) === 'pathogenic') ? '2-down' : '1-down'; break; } } if (entry.criteriaModifier && getCriteriaStrength(entry) === 'moderate') { switch (entry.criteriaModifier) { case 'very-strong': modifiedLevel = '2-up'; break; case 'strong': modifiedLevel = '1-up'; break; case 'supporting': modifiedLevel = '1-down'; break; } } if (entry.criteriaModifier && getCriteriaStrength(entry) === 'supporting') { switch (entry.criteriaModifier) { case 'very-strong': modifiedLevel = '3-up'; break; case 'stand-alone': modifiedLevel = '2-up'; break; case 'strong': modifiedLevel = (getCriteriaType(entry) === 'pathogenic') ? '2-up' : '1-up'; break; case 'moderate': modifiedLevel = '1-up'; break; } } return modifiedLevel; } // Function to sort evaluations by criteria strength level // Sort Order: very strong or stand alone >> strong >> moderate >> supporting // Input: array, interpretation.evaluations // output: object as // { // met: array of sorted met evaluations, // not_met: array of sorted not-met evaluations, // not_evaluated: array of sorted not-evaluated and untouched objects; // untouched obj has only one key:value element (criteria: code) // } function sortByStrength(evaluations) { // Get all criteria codes let criteriaCodes = Object.keys(evidenceCodes); let evaluationMet = []; let evaluationNotMet = []; let evaluationNotEvaluated = []; for (let evaluation of evaluations) { if (evaluation.criteriaStatus === 'met') { evaluationMet.push(evaluation); criteriaCodes.splice(criteriaCodes.indexOf(evaluation.criteria), 1); } else if (evaluation.criteriaStatus === 'not-met') { evaluationNotMet.push(evaluation); criteriaCodes.splice(criteriaCodes.indexOf(evaluation.criteria), 1); } else { evaluationNotEvaluated.push(evaluation); criteriaCodes.splice(criteriaCodes.indexOf(evaluation.criteria), 1); } } // Generate object for earch untouched criteria let untouchedCriteriaObjList = []; if (criteriaCodes.length) { for (let criterion of criteriaCodes) { untouchedCriteriaObjList.push({ criteria: criterion }); } } // merge not-evaluated and untouched together evaluationNotEvaluated = evaluationNotEvaluated.concat(untouchedCriteriaObjList); let sortedMetList = []; let sortedNotMetList = []; let sortedNotEvaluatedList = []; // sort Met if (evaluationMet.length) { // setup count strength values const MODIFIER_VS = 'very-strong'; const MODIFIER_SA = 'stand-alone'; const MODIFIER_S = 'strong'; const MODIFIER_M = 'moderate'; const MODIFIER_P = 'supporting'; // temp storage let vs_sa_level = []; let strong_level = []; let moderate_level = []; let supporting_level = []; for (let evaluation of evaluationMet) { let modified = evaluation.criteriaModifier ? evaluation.criteriaModifier : null; if (modified) { if (modified === MODIFIER_VS || modified === MODIFIER_SA) { vs_sa_level.push(evaluation); } else if (modified === MODIFIER_S) { strong_level.push(evaluation); } else if (modified === MODIFIER_M) { moderate_level.push(evaluation); } else if (modified === MODIFIER_P) { supporting_level.push(evaluation); } } else { if (evaluation.criteria === 'PVS1' || evaluation.criteria === 'BA1') { vs_sa_level.push(evaluation); } else if (evaluation.criteria[1] === 'S') { strong_level.push(evaluation); } else if (evaluation.criteria[1] === 'M') { moderate_level.push(evaluation); } else if (evaluation.criteria[1] === 'P') { supporting_level.push(evaluation); } } } if (vs_sa_level.length) { sortedMetList = sortedMetList .concat(vs_sa_level); } if (strong_level.length) { sortedMetList = sortedMetList.concat(strong_level); } if (moderate_level.length) { sortedMetList = sortedMetList.concat(moderate_level); } if (supporting_level.length) { sortedMetList = sortedMetList.concat(supporting_level); } } // sort Not-Met if (evaluationNotMet.length) { // temp storage let vs_sa_level = []; let strong_level = []; let moderate_level = []; let supporting_level = []; for (let evaluation of evaluationNotMet) { if (evaluation.criteria === 'PVS1' || evaluation.criteria === 'BA1') { vs_sa_level.push(evaluation); } else if (evaluation.criteria[1] === 'S') { strong_level.push(evaluation); } else if (evaluation.criteria[1] === 'M') { moderate_level.push(evaluation); } else if (evaluation.criteria[1] === 'P') { supporting_level.push(evaluation); } } if (vs_sa_level.length) { sortedNotMetList = sortedNotMetList .concat(vs_sa_level); } if (strong_level.length) { sortedNotMetList = sortedNotMetList.concat(strong_level); } if (moderate_level.length) { sortedNotMetList = sortedNotMetList.concat(moderate_level); } if (supporting_level.length) { sortedNotMetList = sortedNotMetList.concat(supporting_level); } } //sort Not-Evaluated and untouched if (evaluationNotEvaluated.length) { // temp storage let vs_sa_level = []; let strong_level = []; let moderate_level = []; let supporting_level = []; for (let evaluation of evaluationNotEvaluated) { if (evaluation.criteria === 'PVS1' || evaluation.criteria === 'BA1') { vs_sa_level.push(evaluation); } else if (evaluation.criteria[1] === 'S') { strong_level.push(evaluation); } else if (evaluation.criteria[1] === 'M') { moderate_level.push(evaluation); } else if (evaluation.criteria[1] === 'P') { supporting_level.push(evaluation); } } if (vs_sa_level.length) { sortedNotEvaluatedList = sortedNotEvaluatedList .concat(vs_sa_level); } if (strong_level.length) { sortedNotEvaluatedList = sortedNotEvaluatedList.concat(strong_level); } if (moderate_level.length) { sortedNotEvaluatedList = sortedNotEvaluatedList.concat(moderate_level); } if (supporting_level.length) { sortedNotEvaluatedList = sortedNotEvaluatedList.concat(supporting_level); } } return ({ met: sortedMetList, not_met: sortedNotMetList, not_evaluated: sortedNotEvaluatedList }); }
lib/ui/widgets/iframe.js
SignalK/instrumentpanel
import React from 'react'; import { render } from 'react-dom'; import util from 'util' import BaseWidget, {defaultComponentDidMount, defaultComponentWillUnmount} from './basewidget'; function Iframe(id, options, streamBundle, instrumentPanel) { BaseWidget.call(this, id, options, streamBundle, instrumentPanel); this.options.unit = ''; class IframeComponent extends React.Component { constructor(props) { super(props); this.finalUnit = ''; this.widgetLabel = ''; this.onOptionsUpdate = this.onOptionsUpdate.bind(this); this.onOptionsUpdate(this.props.optionsBundle.getOptions()); this.renderSVG = this.renderSVG.bind(this); this.renderIframe = this.renderIframe.bind(this); this.setDarkMode = this.setDarkMode.bind(this); this.state = { value: { src: '' }, darkModeOn: this.props.instrumentPanel.getDarkMode() }; } setDarkMode(darkMode) { this.setState({'darkModeOn': darkMode}); } componentDidMount() { defaultComponentDidMount(this, undefined, undefined); this.props.functions['setDarkMode'] = this.setDarkMode; this.setDarkMode(this.props.instrumentPanel.getDarkMode()); } componentWillUnmount() { this.props.functions['setDarkMode'] = undefined; defaultComponentWillUnmount(this); } onOptionsUpdate(options) { this.widgetLabel = options.label; } render() { return (this.props.instrumentPanel.model.get().settingsVisible) ? this.renderSVG() : this.renderIframe(); } renderSVG() { return ( <svg key={id} height="100%" width="100%" viewBox="0 0 20 33" stroke="none"> <text x="10" y="6" textAnchor="middle" fontSize="8" dominantBaseline="middle">{this.widgetLabel}</text> <text x="10" y="16" textAnchor="middle" fontSize="8" dominantBaseline="middle">{this.props.optionsBundle.getOptions().path}</text> <text x="10" y="26" textAnchor="middle" fontSize="8" dominantBaseline="middle">rendered disabled in setting mode</text> </svg> ) } renderIframe() { try { var fullSrc = this.state.value.src; var darkModeValue = (this.state.darkModeOn) ? this.state.value.darkValue : this.state.value.lightValue; var separator = (fullSrc.indexOf('?') !== -1) ? '&' : '?'; if (fullSrc !== '' && this.state.value.themeKey && this.state.value.themeKey !== '' && darkModeValue && darkModeValue !== '') { fullSrc += separator + this.state.value.themeKey + '=' + darkModeValue; } return ( <iframe src={fullSrc} sandbox='allow-scripts allow-same-origin allow-forms' width="100%" height="100%" frameBorder="0" scrolling="no" style={(!this.props.instrumentPanel.model.get().isLocked)?({pointerEvents: "none", padding: "5px"}):({})} /> ); } catch (ex) {console.log(ex)} return (<div>safety mode</div>) } } IframeComponent.defaultProps = { functions: {} } this.widget = React.createElement(IframeComponent,{ key: id, instrumentPanel: this.instrumentPanel, valueStream: this.valueStream, optionsBundle: this.optionsBundle }); } util.inherits(Iframe, BaseWidget); Iframe.prototype.getReactElement = function() { return this.widget; } Iframe.prototype.getSettingsElement = function(pushCellChange) { return this.getSettingsElementUnitOnly(pushCellChange); } Iframe.prototype.getType = function() { return "iframe"; } Iframe.prototype.getInitialDimensions = function() { return {h: 2}; } export default { constructor: Iframe, type: "iframe", paths: ['external.iframe.*'] }
app/javascript/mastodon/components/status.js
summoners-riftodon/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Avatar from './avatar'; import AvatarOverlay from './avatar_overlay'; import RelativeTimestamp from './relative_timestamp'; import DisplayName from './display_name'; import StatusContent from './status_content'; import StatusActionBar from './status_action_bar'; import AttachmentList from './attachment_list'; import { injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { MediaGallery, Video } from '../features/ui/util/async-components'; import { HotKeys } from 'react-hotkeys'; import classNames from 'classnames'; // We use the component (and not the container) since we do not want // to use the progress bar to show download progress import Bundle from '../features/ui/components/bundle'; export const textForScreenReader = (intl, status, rebloggedByText = false) => { const displayName = status.getIn(['account', 'display_name']); const values = [ displayName.length === 0 ? status.getIn(['account', 'acct']).split('@')[0] : displayName, status.get('spoiler_text') && status.get('hidden') ? status.get('spoiler_text') : status.get('search_index').slice(status.get('spoiler_text').length), intl.formatDate(status.get('created_at'), { hour: '2-digit', minute: '2-digit', month: 'short', day: 'numeric' }), status.getIn(['account', 'acct']), ]; if (rebloggedByText) { values.push(rebloggedByText); } return values.join(', '); }; @injectIntl export default class Status extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map, account: ImmutablePropTypes.map, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onDirect: PropTypes.func, onMention: PropTypes.func, onPin: PropTypes.func, onOpenMedia: PropTypes.func, onOpenVideo: PropTypes.func, onBlock: PropTypes.func, onEmbed: PropTypes.func, onHeightChange: PropTypes.func, onToggleHidden: PropTypes.func, muted: PropTypes.bool, hidden: PropTypes.bool, onMoveUp: PropTypes.func, onMoveDown: PropTypes.func, }; // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'account', 'muted', 'hidden', ] handleClick = () => { if (!this.context.router) { return; } const { status } = this.props; this.context.router.history.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`); } handleAccountClick = (e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { const id = e.currentTarget.getAttribute('data-id'); e.preventDefault(); this.context.router.history.push(`/accounts/${id}`); } } handleExpandedToggle = () => { this.props.onToggleHidden(this._properStatus()); }; renderLoadingMediaGallery () { return <div className='media_gallery' style={{ height: '110px' }} />; } renderLoadingVideoPlayer () { return <div className='media-spoiler-video' style={{ height: '110px' }} />; } handleOpenVideo = (media, startTime) => { this.props.onOpenVideo(media, startTime); } handleHotkeyReply = e => { e.preventDefault(); this.props.onReply(this._properStatus(), this.context.router.history); } handleHotkeyFavourite = () => { this.props.onFavourite(this._properStatus()); } handleHotkeyBoost = e => { this.props.onReblog(this._properStatus(), e); } handleHotkeyMention = e => { e.preventDefault(); this.props.onMention(this._properStatus().get('account'), this.context.router.history); } handleHotkeyOpen = () => { this.context.router.history.push(`/statuses/${this._properStatus().get('id')}`); } handleHotkeyOpenProfile = () => { this.context.router.history.push(`/accounts/${this._properStatus().getIn(['account', 'id'])}`); } handleHotkeyMoveUp = e => { this.props.onMoveUp(this.props.status.get('id'), e.target.getAttribute('data-featured')); } handleHotkeyMoveDown = e => { this.props.onMoveDown(this.props.status.get('id'), e.target.getAttribute('data-featured')); } handleHotkeyToggleHidden = () => { this.props.onToggleHidden(this._properStatus()); } _properStatus () { const { status } = this.props; if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { return status.get('reblog'); } else { return status; } } render () { let media = null; let statusAvatar, prepend, rebloggedByText; const { intl, hidden, featured } = this.props; let { status, account, ...other } = this.props; if (status === null) { return null; } if (hidden) { return ( <div> {status.getIn(['account', 'display_name']) || status.getIn(['account', 'username'])} {status.get('content')} </div> ); } if (status.get('filtered') || status.getIn(['reblog', 'filtered'])) { const minHandlers = this.props.muted ? {} : { moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, }; return ( <HotKeys handlers={minHandlers}> <div className='status__wrapper status__wrapper--filtered focusable' tabIndex='0'> <FormattedMessage id='status.filtered' defaultMessage='Filtered' /> </div> </HotKeys> ); } if (featured) { prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><i className='fa fa-fw fa-thumb-tack status__prepend-icon' /></div> <FormattedMessage id='status.pinned' defaultMessage='Pinned toot' /> </div> ); } else if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') { const display_name_html = { __html: status.getIn(['account', 'display_name_html']) }; prepend = ( <div className='status__prepend'> <div className='status__prepend-icon-wrapper'><i className='fa fa-fw fa-retweet status__prepend-icon' /></div> <FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handleAccountClick} data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} className='status__display-name muted'><bdi><strong dangerouslySetInnerHTML={display_name_html} /></bdi></a> }} /> </div> ); rebloggedByText = intl.formatMessage({ id: 'status.reblogged_by', defaultMessage: '{name} boosted' }, { name: status.getIn(['account', 'acct']) }); account = status.get('account'); status = status.get('reblog'); } if (status.get('media_attachments').size > 0) { if (this.props.muted || status.get('media_attachments').some(item => item.get('type') === 'unknown')) { media = ( <AttachmentList compact media={status.get('media_attachments')} /> ); } else if (status.getIn(['media_attachments', 0, 'type']) === 'video') { const video = status.getIn(['media_attachments', 0]); media = ( <Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} > {Component => ( <Component preview={video.get('preview_url')} src={video.get('url')} alt={video.get('description')} width={239} height={110} inline sensitive={status.get('sensitive')} onOpenVideo={this.handleOpenVideo} /> )} </Bundle> ); } else { media = ( <Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery}> {Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.props.onOpenMedia} />} </Bundle> ); } } if (account === undefined || account === null) { statusAvatar = <Avatar account={status.get('account')} size={48} />; }else{ statusAvatar = <AvatarOverlay account={status.get('account')} friend={account} />; } const handlers = this.props.muted ? {} : { reply: this.handleHotkeyReply, favourite: this.handleHotkeyFavourite, boost: this.handleHotkeyBoost, mention: this.handleHotkeyMention, open: this.handleHotkeyOpen, openProfile: this.handleHotkeyOpenProfile, moveUp: this.handleHotkeyMoveUp, moveDown: this.handleHotkeyMoveDown, toggleHidden: this.handleHotkeyToggleHidden, }; return ( <HotKeys handlers={handlers}> <div className={classNames('status__wrapper', `status__wrapper-${status.get('visibility')}`, { 'status__wrapper-reply': !!status.get('in_reply_to_id'), focusable: !this.props.muted })} tabIndex={this.props.muted ? null : 0} data-featured={featured ? 'true' : null} aria-label={textForScreenReader(intl, status, rebloggedByText, !status.get('hidden'))}> {prepend} <div className={classNames('status', `status-${status.get('visibility')}`, { 'status-reply': !!status.get('in_reply_to_id'), muted: this.props.muted })} data-id={status.get('id')}> <div className='status__info'> <a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a> <a onClick={this.handleAccountClick} target='_blank' data-id={status.getIn(['account', 'id'])} href={status.getIn(['account', 'url'])} title={status.getIn(['account', 'acct'])} className='status__display-name'> <div className='status__avatar'> {statusAvatar} </div> <DisplayName account={status.get('account')} /> </a> </div> <StatusContent status={status} onClick={this.handleClick} expanded={!status.get('hidden')} onExpandedToggle={this.handleExpandedToggle} /> {media} <StatusActionBar status={status} account={account} {...other} /> </div> </div> </HotKeys> ); } }
geonode/monitoring/frontend/src/containers/app/index.js
mcldev/geonode
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Style } from 'radium'; // Pages import Alerts from '../../pages/alerts'; import AlertConfig from '../../pages/alert-config'; import AlertsSettings from '../../pages/alerts-settings'; import ErrorDetails from '../../pages/error-details'; import Errors from '../../pages/errors'; import HWPerf from '../../pages/hardware-performance'; import Home from '../../pages/home'; import SWPerf from '../../pages/software-performance'; import reset from '../../reset.js'; import fonts from '../../fonts/fonts.js'; import actions from './actions'; import styles from './styles'; const mapStateToProps = (/* state */) => ({}); @connect(mapStateToProps, actions) class App extends React.Component { static propTypes = { children: PropTypes.node, get: PropTypes.func.isRequired, } static childContextTypes = { socket: PropTypes.object, } componentWillMount() { this.props.get(); } render() { return ( <div style={styles.root}> <Style rules={fonts} /> <Style rules={reset} /> {this.props.children} </div> ); } } export default { component: App, childRoutes: [ { path: '/', indexRoute: { component: Home }, childRoutes: [ { path: 'errors', indexRoute: { component: Errors }, childRoutes: [ { path: ':errorId', component: ErrorDetails, }, ], }, { path: 'alerts', indexRoute: { component: Alerts }, childRoutes: [ { path: 'settings', component: AlertsSettings, }, { path: ':alertId', component: AlertConfig, }, ], }, { path: 'performance/software', indexRoute: { component: SWPerf }, }, { path: 'performance/hardware', indexRoute: { component: HWPerf }, }, ], }, ], };
app/containers/AdminFournisseur/components/OffreFormContainer.js
Proxiweb/react-boilerplate
import React from 'react'; import PropTypes from 'prop-types'; import { createStructuredSelector } from 'reselect'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { isPristine } from 'redux-form'; import round from 'lodash/round'; import { saveOffre } from 'containers/Commande/actions'; import { makeSelectPending } from 'containers/App/selectors'; import OffreForm from './OffreForm'; const isProfilePristine = () => state => isPristine('offre')(state); const makeSelectValeurs = () => state => state.form; // import submit from './submit'; class OffreFormContainer extends React.Component { static propTypes = { quantiteUnite: PropTypes.string.isRequired, offre: PropTypes.object.isRequired, pristine: PropTypes.bool.isRequired, valeurs: PropTypes.object.isRequired, pending: PropTypes.bool.isRequired, handleToggeState: PropTypes.func.isRequired, save: PropTypes.func.isRequired, }; handleSubmit = values => { const { save, offre } = this.props; const tarifications = values.tarifications.map(t => ({ ...t, prix: parseInt(t.prix * 100, 10), recolteFond: parseInt(t.recolteFond * 100, 10), })); save({ ...offre, tarifications, poids: values.poids ? parseInt(values.poids, 10) : null, }); }; render() { const { pending, offre, pristine, handleToggeState, valeurs, quantiteUnite, } = this.props; const tarifications = offre.tarifications.map(t => ({ ...t, prix: round(t.prix / 100, 2), recolteFond: round(t.recolteFond / 1000, 2), })); return ( <OffreForm initialValues={{ ...offre, tarifications, quantiteUnite }} onSubmit={this.handleSubmit} pending={pending} quantiteUnite={quantiteUnite} pristine={pristine} valeurs={valeurs} handleToggeState={handleToggeState} /> ); } } const mapStateToProps = createStructuredSelector({ pending: makeSelectPending(), pristine: isProfilePristine(), valeurs: makeSelectValeurs(), }); const mapDispatchToProps = dispatch => bindActionCreators( { save: saveOffre, }, dispatch ); export default connect(mapStateToProps, mapDispatchToProps)(OffreFormContainer);
test/integration/css-features/fixtures/browsers-new/pages/_app.js
JeromeFitz/next.js
import App from 'next/app' import React from 'react' import './styles.css' class MyApp extends App { render() { const { Component, pageProps } = this.props return <Component {...pageProps} /> } } export default MyApp
examples/create-react-app/src/App.js
zeit/now-cli
import React from 'react'; import { useEffect, useState } from 'react'; import './App.css'; function App() { const [date, setDate] = useState(null); useEffect(() => { async function getDate() { const res = await fetch('/api/date'); const newDate = await res.text(); setDate(newDate); } getDate(); }, []); return ( <main> <h1>Create React App + Go API</h1> <h2> Deployed with{' '} <a href="https://vercel.com/docs" target="_blank" rel="noreferrer noopener" > Vercel </a> ! </h2> <p> <a href="https://github.com/vercel/vercel/tree/master/examples/create-react-app" target="_blank" rel="noreferrer noopener" > This project </a>{' '} was bootstrapped with{' '} <a href="https://facebook.github.io/create-react-app/"> Create React App </a>{' '} and contains three directories, <code>/public</code> for static assets,{' '} <code>/src</code> for components and content, and <code>/api</code>{' '} which contains a serverless <a href="https://golang.org/">Go</a>{' '} function. See{' '} <a href="/api/date"> <code>api/date</code> for the Date API with Go </a> . </p> <br /> <h2>The date according to Go is:</h2> <p>{date ? date : 'Loading date...'}</p> </main> ); } export default App;
docs/app/Examples/modules/Dropdown/Types/index.js
clemensw/stardust
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ContributionPrompt from 'docs/app/Components/ComponentDoc/ContributionPrompt' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const DropdownTypesExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='Dropdown' description='A dropdown.' examplePath='modules/Dropdown/Types/DropdownExampleDropdown' /> <ComponentExample title='Selection' description='A dropdown can be used to select between choices in a form.' examplePath='modules/Dropdown/Types/DropdownExampleSelection' /> <ComponentExample title='Search Selection' description='A selection dropdown can allow a user to search through a large list of choices.' examplePath='modules/Dropdown/Types/DropdownExampleSearchSelection' /> <ComponentExample examplePath='modules/Dropdown/Types/DropdownExampleSearchSelectionTwo' /> {/* Possibly add state selection example. */} <ComponentExample title='Multiple Selection' description='A selection dropdown can allow multiple selections.' examplePath='modules/Dropdown/Types/DropdownExampleMultipleSelection' /> <ComponentExample title='Multiple Search Selection' description='A selection dropdown can allow multiple search selections.' examplePath='modules/Dropdown/Types/DropdownExampleMultipleSearchSelection' /> <ComponentExample description='Dropdowns can support content that may not be allowed inside option tags.' examplePath='modules/Dropdown/Types/DropdownExampleMultipleSearchSelectionTwo' /> <ComponentExample title='Search Dropdown' description='A dropdown can be searchable.' examplePath='modules/Dropdown/Types/DropdownExampleSearchDropdown' /> <ComponentExample title='Search In-Menu' description='A dropdown can include a search prompt inside its menu.' examplePath='modules/Dropdown/Types/DropdownExampleSearchInMenu' > <ContributionPrompt> The example below shows the desired markup but is not functional. Needs to be defined via shorthand, which is not yet possible. </ContributionPrompt> </ComponentExample> <ComponentExample description='A dropdown with multiple selections can include a search prompt inside its menu.' examplePath='modules/Dropdown/Types/DropdownExampleMultipleSearchInMenu' > <ContributionPrompt> The example below shows the desired markup but is not functional. Needs to be defined via shorthand, which is not yet possible. </ContributionPrompt> </ComponentExample> <ComponentExample title='Inline' description='A dropdown can be formatted to appear inline in other content.' examplePath='modules/Dropdown/Types/DropdownExampleInline' /> <ComponentExample examplePath='modules/Dropdown/Types/DropdownExampleInlineTwo' /> <ComponentExample title='Pointing' description='A dropdown can be formatted so that its menu is pointing.' examplePath='modules/Dropdown/Types/DropdownExamplePointing' > <ContributionPrompt> The example below shows (roughly) the desired markup but is not functional since we don't currently support nested dropdowns. </ContributionPrompt> </ComponentExample> <ComponentExample examplePath='modules/Dropdown/Types/DropdownExamplePointingTwo' /> <ComponentExample title='Floating' description='A dropdown menu can appear to be floating below an element.' examplePath='modules/Dropdown/Types/DropdownExampleFloating' /> <ComponentExample title='Simple' description='A simple dropdown can open without Javascript.' examplePath='modules/Dropdown/Types/DropdownExampleSimple' /> </ExampleSection> ) export default DropdownTypesExamples
node_modules/lite-server/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
dope93x/emoplay-2
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
src/Components/Banner.js
Zangriev/Kentico
import React from 'react'; import BackgroundImage from '../Images/banner-default.jpg'; const Banner = (props) => { return ( <section className="banner-section" style={{ backgroundImage: "url(" + BackgroundImage + ")" }}> <h2 className="banner-heading">Roasting premium coffee</h2> <p className="banner-text"> Discover the fascinating world of Dancing Goat high-quality coffee and you will never miss a single coffee break again. </p> </section> ); } export default Banner;
node_modules/redux-form/es/Form.js
Starnes81/ReduxBlogTut
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React, { Component } from 'react'; import PropTypes from 'prop-types'; var Form = function (_Component) { _inherits(Form, _Component); function Form(props, context) { _classCallCheck(this, Form); var _this = _possibleConstructorReturn(this, (Form.__proto__ || Object.getPrototypeOf(Form)).call(this, props, context)); if (!context._reduxForm) { throw new Error('Form must be inside a component decorated with reduxForm()'); } return _this; } _createClass(Form, [{ key: 'componentWillMount', value: function componentWillMount() { this.context._reduxForm.registerInnerOnSubmit(this.props.onSubmit); } }, { key: 'render', value: function render() { return React.createElement('form', this.props); } }]); return Form; }(Component); Form.propTypes = { onSubmit: PropTypes.func.isRequired }; Form.contextTypes = { _reduxForm: PropTypes.object }; export default Form;
src/page/Auth/LoginRedirectPage.js
dovydasvenckus/time-tracker-web
import React from 'react'; import { AuthConsumer } from '../../utils/auth/authProvider'; const LoginRedirectPage = () => ( <AuthConsumer> {({ signInRedirect }) => { signInRedirect(); return <span>loading</span>; }} </AuthConsumer> ); export default LoginRedirectPage;
utilities/dom.js
salesforce/design-system-react
/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */ /* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */ /* eslint-disable consistent-return */ import React from 'react'; /** * Traverse all children */ function flatMapChildren(children, iterator) { const result = []; function go(xs) { return React.Children.map(xs, (child) => { // eslint-disable-next-line fp/no-mutating-methods result.push(iterator(child)); if (child.type) go(child.props.children); }); } go(children); return result; } /** * Perhaps there's a more pragmatic way to do this. Eventually, I suspect we'll have some utils to help find children. */ function hasChild(children, name) { let flag = false; flatMapChildren(children, (child) => { flag = flag || (child.type && child.type.name === name); }); return flag; } // findDOMNode complains so filter out strings from virtual dom function textContent(children) { return flatMapChildren(children, (child) => { // eslint-disable-line consistent-return if (typeof child === 'string') return child; }).join(' '); } const helpers = { textContent, hasChild }; export default helpers;
src/components/Panel.js
edauenhauer/google-drive-copy-folder
/** * Information message container */ 'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import Alert from './Alert'; export default function Panel(props) { return ( <Alert label={props.label} className="alert--neutral"> {props.children} </Alert> ); } Panel.propTypes = { label: PropTypes.string };
src/components/video_detail.js
gokulraj-ece/React-youtube
import React from 'react'; // ({ video }) or ({ props }) and then video=props.video const VideoDetail = ({ video }) => { if (!video) { return <div>Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`;//string interpolation //const url = "https://www.youtube.com/embed/" + videoId; //crafting your own youtube embed url return ( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe className="embed-responsive-item" src={url}></iframe> </div> <div className="details"> <div>{video.snippet.title}</div> <div>{video.snippet.description}</div> </div> </div> ); }; export default VideoDetail;
src/components/Main.js
yeWangye/gallery-by-react
require('normalize.css/normalize.css'); require('styles/App.scss'); import React from 'react'; import ReactDOM from 'react-dom' // 获取图片相关的数据 var imageDatas = require('../data/imageDatas.json'); // 利用自执行函数, 将图片名信息转成图片URL路径信息 imageDatas = (function (imageDatasArr) { for (var i = 0, j = imageDatasArr.length; i < j; i++) { var singleImageData = imageDatasArr[i]; singleImageData.imageURL = require('../images/' + singleImageData.fileName); imageDatasArr[i] = singleImageData; } return imageDatasArr; })(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({ class ImgFigure extends React.Component { /* * imgFigure 的点击处理函数 */ handleClick = (e) => { if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.stopPropagation(); e.preventDefault(); } render() { 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+'Aollo'} </p> </div> </figcaption> </figure> ); } } // 控制组件 // var ControllerUnit = React.createClass({ class ControllerUnit extends React.Component { handleClick = (e) => { // 如果点击的是当前正在选中态的按钮,则翻转图片,否则将对应的图片居中 if (this.props.arrange.isCenter) { this.props.inverse(); } else { this.props.center(); } e.preventDefault(); e.stopPropagation(); }; render() { let { arrange } = this.props; var controllerUnitClassName = 'controller-unit'; // 如果对应的是居中的图片,显示控制按钮的居中态 if (arrange.isCenter) { controllerUnitClassName += ' is-center'; // 如果同时对应的是翻转图片, 显示控制按钮的翻转态 if (arrange.isInverse) { controllerUnitClassName += ' is-inverse'; } } return ( <span className={controllerUnitClassName} onClick={this.handleClick}></span> ); } } class AppComponent extends React.Component { 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 (index) { return function () { var imgsArrangeArr = this.state.imgsArrangeArr; imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse; this.setState({ imgsArrangeArr: imgsArrangeArr }); }.bind(this); } /* * 重新布局所有图片 * @param centerIndex 指定居中排布哪个图片 */ rearrange (centerIndex) { var imgsArrangeArr = this.state.imgsArrangeArr, centerPos = this.Constant.centerPos, hPosRange = this.Constant.hPosRange, vPosRange = this.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; } var newTop = getRangeRandom(hPosRangeY[0], hPosRangeY[1]); var newLeft = getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1]); imgsArrangeArr[i] = { pos: { top: newTop, left: newLeft }, 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 (index) { return function () { this.rearrange(index); }.bind(this); } state = { imgsArrangeArr: [ { pos: { left: 0, top: 0 }, rotate: 0, // 旋转角度 isInverse: false, // 图片正反面 isCenter: false // 图片是否居中 } ]}; // 组件加载以后, 为每张图片计算其位置的范围 componentDidMount(){ // 首先拿到舞台的大小 var stageDOM = ReactDOM.findDOMNode(this.refs.stage), stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); // 拿到一个imageFigure的大小 var imgFigureDOM = ReactDOM.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 key={index} data={value} 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} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } } AppComponent.defaultProps = { }; export default AppComponent;
src/MessageContainer.js
FaridSafi/react-native-gifted-messenger
/* eslint no-console: 0, no-param-reassign: 0, no-use-before-define: ["error", { "variables": false }], no-return-assign: 0, react/no-string-refs: 0, react/sort-comp: 0 */ import PropTypes from 'prop-types'; import React from 'react'; import { FlatList, View, StyleSheet, Keyboard, TouchableOpacity, Text } from 'react-native'; import LoadEarlier from './LoadEarlier'; import Message from './Message'; import Color from './Color'; export default class MessageContainer extends React.PureComponent { state = { showScrollBottom: false, }; componentDidMount() { if (this.props.messages.length === 0) { this.attachKeyboardListeners(); } } componentWillUnmount() { this.detachKeyboardListeners(); } componentWillReceiveProps(nextProps) { if (this.props.messages.length === 0 && nextProps.messages.length > 0) { this.detachKeyboardListeners(); } else if (this.props.messages.length > 0 && nextProps.messages.length === 0) { this.attachKeyboardListeners(nextProps); } } attachKeyboardListeners = () => { const { invertibleScrollViewProps: invertibleProps } = this.props; Keyboard.addListener('keyboardWillShow', invertibleProps.onKeyboardWillShow); Keyboard.addListener('keyboardDidShow', invertibleProps.onKeyboardDidShow); Keyboard.addListener('keyboardWillHide', invertibleProps.onKeyboardWillHide); Keyboard.addListener('keyboardDidHide', invertibleProps.onKeyboardDidHide); }; detachKeyboardListeners = () => { const { invertibleScrollViewProps: invertibleProps } = this.props; Keyboard.removeListener('keyboardWillShow', invertibleProps.onKeyboardWillShow); Keyboard.removeListener('keyboardDidShow', invertibleProps.onKeyboardDidShow); Keyboard.removeListener('keyboardWillHide', invertibleProps.onKeyboardWillHide); Keyboard.removeListener('keyboardDidHide', invertibleProps.onKeyboardDidHide); }; renderFooter = () => { if (this.props.renderFooter) { const footerProps = { ...this.props, }; return this.props.renderFooter(footerProps); } return null; }; renderLoadEarlier = () => { if (this.props.loadEarlier === true) { const loadEarlierProps = { ...this.props, }; if (this.props.renderLoadEarlier) { return this.props.renderLoadEarlier(loadEarlierProps); } return <LoadEarlier {...loadEarlierProps} />; } return null; }; scrollTo(options) { if (this.flatListRef && options) { this.flatListRef.scrollToOffset(options); } } scrollToBottom = () => { this.scrollTo({ offset: 0, animated: 'true' }); }; handleOnScroll = (event) => { if (event.nativeEvent.contentOffset.y > this.props.scrollToBottomOffset) { this.setState({ showScrollBottom: true }); } else { this.setState({ showScrollBottom: false }); } }; renderRow = ({ item, index }) => { if (!item._id && item._id !== 0) { console.warn('GiftedChat: `_id` is missing for message', JSON.stringify(item)); } if (!item.user) { if (!item.system) { console.warn('GiftedChat: `user` is missing for message', JSON.stringify(item)); } item.user = {}; } const { messages, ...restProps } = this.props; const previousMessage = messages[index + 1] || {}; const nextMessage = messages[index - 1] || {}; const messageProps = { ...restProps, key: item._id, currentMessage: item, previousMessage, nextMessage, position: item.user._id === this.props.user._id ? 'right' : 'left', }; if (this.props.renderMessage) { return this.props.renderMessage(messageProps); } return <Message {...messageProps} />; }; renderHeaderWrapper = () => <View style={styles.headerWrapper}>{this.renderLoadEarlier()}</View>; renderScrollToBottomWrapper() { const scrollToBottomComponent = ( <View style={styles.scrollToBottomStyle}> <TouchableOpacity onPress={this.scrollToBottom} hitSlop={{ top: 5, left: 5, right: 5, bottom: 5 }}> <Text>V</Text> </TouchableOpacity> </View> ); if (this.props.scrollToBottomComponent) { return ( <TouchableOpacity onPress={this.scrollToBottom} hitSlop={{ top: 5, left: 5, right: 5, bottom: 5 }}> {this.props.scrollToBottomComponent} </TouchableOpacity> ); } return scrollToBottomComponent; } keyExtractor = (item) => `${item._id}`; render() { if (this.props.messages.length === 0) { return <View style={styles.container} />; } return ( <View style={this.props.alignTop ? styles.containerAlignTop : styles.container}> {this.state.showScrollBottom && this.props.scrollToBottom ? this.renderScrollToBottomWrapper() : null} <FlatList ref={(ref) => (this.flatListRef = ref)} extraData={this.props.extraData} keyExtractor={this.keyExtractor} enableEmptySections automaticallyAdjustContentInsets={false} inverted={this.props.inverted} data={this.props.messages} style={styles.listStyle} contentContainerStyle={styles.contentContainerStyle} renderItem={this.renderRow} {...this.props.invertibleScrollViewProps} ListFooterComponent={this.renderHeaderWrapper} ListHeaderComponent={this.renderFooter} onScroll={this.handleOnScroll} scrollEventThrottle={100} {...this.props.listViewProps} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, containerAlignTop: { flexDirection: 'row', alignItems: 'flex-start', }, contentContainerStyle: { justifyContent: 'flex-end', }, headerWrapper: { flex: 1, }, listStyle: { flex: 1, }, scrollToBottomStyle: { opacity: 0.8, position: 'absolute', paddingHorizontal: 15, paddingVertical: 8, right: 10, bottom: 30, zIndex: 999, height: 40, width: 40, borderRadius: 20, backgroundColor: Color.white, alignItems: 'center', justifyContent: 'center', shadowColor: Color.black, shadowOpacity: 0.5, shadowOffset: { width: 0, height: 0 }, shadowRadius: 1, }, }); MessageContainer.defaultProps = { messages: [], user: {}, renderFooter: null, renderMessage: null, onLoadEarlier: () => {}, inverted: true, loadEarlier: false, listViewProps: {}, invertibleScrollViewProps: {}, extraData: null, scrollToBottom: false, scrollToBottomOffset: 200, alignTop: false, }; MessageContainer.propTypes = { messages: PropTypes.arrayOf(PropTypes.object), user: PropTypes.object, renderFooter: PropTypes.func, renderMessage: PropTypes.func, renderLoadEarlier: PropTypes.func, onLoadEarlier: PropTypes.func, listViewProps: PropTypes.object, inverted: PropTypes.bool, loadEarlier: PropTypes.bool, invertibleScrollViewProps: PropTypes.object, extraData: PropTypes.object, scrollToBottom: PropTypes.bool, scrollToBottomOffset: PropTypes.number, scrollToBottomComponent: PropTypes.func, alignTop: PropTypes.bool, };
app/javascript/mastodon/features/picture_in_picture/components/header.js
Ryanaka/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from 'mastodon/components/icon_button'; import { Link } from 'react-router-dom'; import Avatar from 'mastodon/components/avatar'; import DisplayName from 'mastodon/components/display_name'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, }); const mapStateToProps = (state, { accountId }) => ({ account: state.getIn(['accounts', accountId]), }); export default @connect(mapStateToProps) @injectIntl class Header extends ImmutablePureComponent { static propTypes = { accountId: PropTypes.string.isRequired, statusId: PropTypes.string.isRequired, account: ImmutablePropTypes.map.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { account, statusId, onClose, intl } = this.props; return ( <div className='picture-in-picture__header'> <Link to={`/@${account.get('acct')}/${statusId}`} className='picture-in-picture__header__account'> <Avatar account={account} size={36} /> <DisplayName account={account} /> </Link> <IconButton icon='times' onClick={onClose} title={intl.formatMessage(messages.close)} /> </div> ); } }
src/components/QueueCancelConfirmDialog.js
branch-bookkeeper/pina
import React from 'react'; import PropTypes from 'prop-types'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogTitle from '@material-ui/core/DialogTitle'; import DialogActions from '@material-ui/core/DialogActions'; import Slide from '@material-ui/core/Slide'; import { queueItemShape, userShape } from '../constants/propTypes'; const propTypes = { open: PropTypes.bool, queueItemToRemove: queueItemShape.isRequired, currentUser: userShape.isRequired, onCancel: PropTypes.func.isRequired, onConfirm: PropTypes.func.isRequired, }; const QueueCancelConfirmDialog = ({ open, queueItemToRemove, currentUser, onCancel, onConfirm, }) => ( <Dialog open={open} TransitionComponent={Slide} onClose={onCancel}> {currentUser.login === queueItemToRemove.username ? <DialogTitle>Remove yourself from the queue?</DialogTitle> : <DialogTitle>Remove {queueItemToRemove.username} from the queue?</DialogTitle>} <DialogActions> <Button onClick={onCancel} color="primary"> No </Button> <Button onClick={onConfirm} color="primary"> Yes </Button> </DialogActions> </Dialog> ); QueueCancelConfirmDialog.propTypes = propTypes; export default QueueCancelConfirmDialog;
src/example.js
gcedo/component-sections-card
import React from 'react'; import SectionsCard from './index'; import sectionsCardData from './context'; sectionsCardData.media.map((mediaLink) => { mediaLink.icon = { useBackground: true, color: 'chicago', icon: mediaLink.meta, }; return mediaLink; }); export default ( <SectionsCard data={sectionsCardData} /> );
app/src/Gallery/components/Selectors.js
rmonnier/hypertube
import React, { Component } from 'react'; import { injectIntl } from 'react-intl'; class Selectors extends Component { handleSelect = (event) => { const name = event.target.name; const value = event.target.value; this.props.onSelect(name, value); } render() { const lang = this.props.intl.locale.split('-')[0]; const { filter } = this.props; const genreOptions = filter.genres .sort((a, b) => { if (a[lang] > b[lang]) return 1; return -1; }) .map((movieGenre) => { const value = movieGenre.en; const { _id: id } = movieGenre; return <option key={id} value={value}>{movieGenre[lang]}</option>; }); const oldest = this.props.intl.formatMessage({ id: 'gallery.oldest' }); const latest = this.props.intl.formatMessage({ id: 'gallery.latest' }); const seeds = this.props.intl.formatMessage({ id: 'gallery.seeds' }); const rating = this.props.intl.formatMessage({ id: 'gallery.rating' }); const name = this.props.intl.formatMessage({ id: 'profile.name' }); const all = this.props.intl.formatMessage({ id: 'gallery.all' }); const genres = this.props.intl.formatMessage({ id: 'gallery.genres' }); const orderBy = this.props.intl.formatMessage({ id: 'gallery.orderBy' }); return ( <div className="all-selectors"> <div className="one-selector"> <div>{genres}:</div> <select name="genre" className="selector-box" onChange={this.handleSelect} value={filter.genre} > <option value="">{all}</option> {genreOptions} </select> </div> <div className="one-selector"> <div>{rating}:</div> <select name="rating" className="selector-box" onChange={this.handleSelect} value={filter.rating} > <option value="0">{all}</option> <option value="9">9+</option> <option value="8">8+</option> <option value="7">7+</option> <option value="6">6+</option> <option value="5">5+</option> <option value="4">4+</option> <option value="3">3+</option> <option value="2">2+</option> <option value="1">1+</option> </select> </div> <div className="one-selector"> <div>{orderBy}:</div> <select name="sort" className="selector-box" onChange={this.handleSelect} value={filter.sort} > <option value="" /> <option value="latest">{latest}</option> <option value="oldest">{oldest}</option> <option value="seeds">{seeds}</option> <option value="rating">{rating}</option> <option value="name">{name}</option> </select> </div> </div> ); } } export default injectIntl(Selectors);
services/QuillLMS/client/app/bundles/Shared/components/draftJSCustomPlugins/addLinkPlugin.js
empirical-org/Empirical-Core
import React from 'react'; export const linkStrategy = (contentBlock, callback, contentState) => { contentBlock.findEntityRanges( (character) => { const entityKey = character.getEntity(); return ( entityKey !== null && contentState.getEntity(entityKey).getType() === 'LINK' ); }, callback ); }; export const Link = ({ contentState, entityKey, children }) => { const { url } = contentState.getEntity(entityKey).getData(); return ( <a aria-label={url} className="link" href={url} rel="noopener noreferrer" target="_blank" > {children} </a> ); }; const addLinkPlugin = { decorators: [ { strategy: linkStrategy, component: Link } ] }; export default addLinkPlugin;
src/deposit/DepositMobile.js
binary-com/binary-next-gen
import React from 'react'; import MobilePage from '../containers/MobilePage'; import DepositContainer from './DepositContainer'; export default (props) => ( <MobilePage toolbarShown={false} backBtnBarTitle="Deposit"> <DepositContainer {...props} /> </MobilePage> );
blueocean-material-icons/src/js/components/svg-icons/image/camera.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ImageCamera = (props) => ( <SvgIcon {...props}> <path d="M9.4 10.5l4.77-8.26C13.47 2.09 12.75 2 12 2c-2.4 0-4.6.85-6.32 2.25l3.66 6.35.06-.1zM21.54 9c-.92-2.92-3.15-5.26-6-6.34L11.88 9h9.66zm.26 1h-7.49l.29.5 4.76 8.25C21 16.97 22 14.61 22 12c0-.69-.07-1.35-.2-2zM8.54 12l-3.9-6.75C3.01 7.03 2 9.39 2 12c0 .69.07 1.35.2 2h7.49l-1.15-2zm-6.08 3c.92 2.92 3.15 5.26 6 6.34L12.12 15H2.46zm11.27 0l-3.9 6.76c.7.15 1.42.24 2.17.24 2.4 0 4.6-.85 6.32-2.25l-3.66-6.35-.93 1.6z"/> </SvgIcon> ); ImageCamera.displayName = 'ImageCamera'; ImageCamera.muiName = 'SvgIcon'; export default ImageCamera;
examples/transitions/app.js
schnerd/react-router
import React from 'react' import { createHistory, useBasename } from 'history' import { Router, Route, Link, History, Lifecycle } from 'react-router' const history = useBasename(createHistory)({ basename: '/transitions' }) const App = React.createClass({ render() { return ( <div> <ul> <li><Link to="/dashboard" activeClassName="active">Dashboard</Link></li> <li><Link to="/form" activeClassName="active">Form</Link></li> </ul> {this.props.children} </div> ) } }) const Dashboard = React.createClass({ render() { return <h1>Dashboard</h1> } }) const Form = React.createClass({ mixins: [ Lifecycle, History ], getInitialState() { return { textValue: 'ohai' } }, routerWillLeave() { if (this.state.textValue) return 'You have unsaved information, are you sure you want to leave this page?' }, handleChange(event) { this.setState({ textValue: event.target.value }) }, handleSubmit(event) { event.preventDefault() this.setState({ textValue: '' }, () => { this.history.pushState(null, '/') }) }, render() { return ( <div> <form onSubmit={this.handleSubmit}> <p>Click the dashboard link with text in the input.</p> <input type="text" ref="userInput" value={this.state.textValue} onChange={this.handleChange} /> <button type="submit">Go</button> </form> </div> ) } }) React.render(( <Router history={history}> <Route path="/" component={App}> <Route path="dashboard" component={Dashboard} /> <Route path="form" component={Form} /> </Route> </Router> ), document.getElementById('example'))
src/svg-icons/hardware/keyboard-arrow-left.js
mit-cml/iot-website-source
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardArrowLeft = (props) => ( <SvgIcon {...props}> <path d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"/> </SvgIcon> ); HardwareKeyboardArrowLeft = pure(HardwareKeyboardArrowLeft); HardwareKeyboardArrowLeft.displayName = 'HardwareKeyboardArrowLeft'; HardwareKeyboardArrowLeft.muiName = 'SvgIcon'; export default HardwareKeyboardArrowLeft;
floodwatch/src/js/components/profile_demographics/ProfileDemographics.js
O-C-R/floodwatch
// @flow import React, { Component } from 'react'; import { Col, Row, Button, ListGroup, ListGroupItem } from 'react-bootstrap'; import _ from 'lodash'; import scrollTo from 'scroll-to'; import log from 'loglevel'; import FWApiClient from '../../api/api'; import Age from './Age'; import Demographic from './Demographic'; import Location from './Location'; import type { DemographicCategoriesJSON } from '../../common/types'; const DEMOGRAPHIC_CATEGORIES: DemographicCategoriesJSON = require('../../../data/demographic_categories'); type Props = { onSuccess: ?() => void, }; type State = { birthYear: ?number, twofishesId: ?string, demographicIds: Array<number>, successMsg: ?string, errorMsg: ?string, curStatus: null | 'success' | 'error', }; export default class ProfileDemographics extends Component { props: Props; state: State; static defaultProps: { onSuccess: ?() => void, }; constructor(props: Props) { super(props); this.state = { birthYear: null, twofishesId: null, demographicIds: [], successMsg: null, errorMsg: null, curStatus: null, }; } componentDidMount() { const init = async () => { try { const userData = await FWApiClient.get().getCurrentPerson(); this.setState({ birthYear: userData.birth_year, twofishesId: userData.twofishes_id, demographicIds: userData.demographic_ids, }); } catch (e) { this.setState({ curStatus: 'error' }); log.error(e); } }; init(); } statusHandler(status: 'success' | 'error', message: string) { scrollTo(0, 0, { ease: 'linear', duration: 200, }); const successMsg = status === 'success' ? message : null; const errorMsg = status === 'error' ? message : null; this.setState({ curStatus: status, errorMsg, successMsg }); } async updateUserInfo() { const { onSuccess } = this.props; const { birthYear, twofishesId, demographicIds } = this.state; try { const userData = await FWApiClient.get().updatePersonDemographics({ birth_year: birthYear, twofishes_id: twofishesId, demographic_ids: demographicIds, }); this.setState({ birthYear: userData.birth_year, twofishesId: userData.twofishes_id, demographicIds: userData.demographic_ids, }); if (onSuccess) { onSuccess(); } this.statusHandler('success', 'Successfully saved changes!'); } catch (e) { this.statusHandler( 'error', 'Error while trying to save changes. Please check your connection.', ); } } updateYear(year: ?number): void { this.setState({ birthYear: year }); } updateDemographics(added: ?Array<number>, removed: ?Array<number>) { const { demographicIds } = this.state; if (added) { demographicIds.push(...added); } if (removed) { _.pull(demographicIds, ...removed); } this.setState({ demographicIds }); } updateLocation(twofishesId: ?string) { this.setState({ twofishesId }); } render() { const { categories } = DEMOGRAPHIC_CATEGORIES; const { successMsg, errorMsg, birthYear, twofishesId, demographicIds, } = this.state; return ( <div> {(successMsg || errorMsg) && <ListGroup> {successMsg && <ListGroupItem bsStyle="success"> {successMsg} </ListGroupItem>} {errorMsg && <ListGroupItem bsStyle="danger"> {errorMsg} </ListGroupItem>} </ListGroup>} <Row> <Col xs={12}> <Age onUpdate={this.updateYear.bind(this)} birthYear={birthYear} categoryInfo={categories.age} /> <Demographic onUpdate={this.updateDemographics.bind(this)} demographicIds={demographicIds} categoryInfo={categories.gender} /> <Demographic onUpdate={this.updateDemographics.bind(this)} demographicIds={demographicIds} categoryInfo={categories.race} /> <Demographic onUpdate={this.updateDemographics.bind(this)} demographicIds={demographicIds} categoryInfo={categories.religion} /> <Location onUpdate={this.updateLocation.bind(this)} twofishesId={twofishesId} categoryInfo={categories.location} /> </Col> <Col xs={12} className="profile-page_actions"> <Button className="profile-page_actions_submit" bsSize="large" bsStyle="primary" onClick={this.updateUserInfo.bind(this)} id="submit-button"> Save </Button> </Col> </Row> </div> ); } }
src/svg-icons/action/rowing.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionRowing = (props) => ( <SvgIcon {...props}> <path d="M8.5 14.5L4 19l1.5 1.5L9 17h2l-2.5-2.5zM15 1c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 20.01L18 24l-2.99-3.01V19.5l-7.1-7.09c-.31.05-.61.07-.91.07v-2.16c1.66.03 3.61-.87 4.67-2.04l1.4-1.55c.19-.21.43-.38.69-.5.29-.14.62-.23.96-.23h.03C15.99 6.01 17 7.02 17 8.26v5.75c0 .84-.35 1.61-.92 2.16l-3.58-3.58v-2.27c-.63.52-1.43 1.02-2.29 1.39L16.5 18H18l3 3.01z"/> </SvgIcon> ); ActionRowing = pure(ActionRowing); ActionRowing.displayName = 'ActionRowing'; ActionRowing.muiName = 'SvgIcon'; export default ActionRowing;
src/routes/index.js
hoop33/warnerxmas
import React from 'react'; import { Route, IndexRoute } from 'react-router'; // NOTE: here we're making use of the `resolve.root` configuration // option in webpack, which allows us to specify import paths as if // they were from the root of the ~/src directory. This makes it // very easy to navigate to files regardless of how deeply nested // your current file is. import CoreLayout from 'layouts/CoreLayout/CoreLayout'; import HomeView from 'views/HomeView/HomeView'; export default (store) => ( <Route path='/' component={CoreLayout}> <IndexRoute component={HomeView} /> </Route> );
src/scripts/components/LeaderBoard.js
drankadank/client
'use strict'; import React from 'react'; import LeaderItem from './LeaderItem'; import Firebase from 'firebase'; import moment from 'moment'; export default class LeaderBoard extends React.Component { constructor(props) { super(props); this.state = { leaders: [] }; this.fireRef = new Firebase('https://drank.firebaseio.com/'); } componentWillMount() { let chugsRef = this.fireRef.child('chugs'); chugsRef.orderByChild('totalTime').on('child_added', snapshot => { let leaders = this.state.leaders; leaders.unshift(snapshot.val()); this.setState({ leaders: leaders }); }); } render() { return ( <div id="leaderboard"> {this.orderedLeaders} </div> ); } get orderedLeaders() { return this.state.leaders.map(leader => { return ( <LeaderItem userId={leader.userId} time={leader.totalTime} /> ); }); } static PropTypes = { displayName: React.PropTypes.string, profileImageURL: React.PropTypes.string, id: React.PropTypes.string } static defaultProps = {} static contextTypes = {} }
examples/official-storybook/stories/addon-design-assets.stories.js
kadirahq/react-storybook
import React from 'react'; export default { title: 'Addons/Design assets', parameters: { options: { selectedPanel: 'storybook/design-assets/panel', }, }, }; export const SingleImage = () => <div>This story should a single image in the assets panel</div>; SingleImage.storyName = 'single image'; SingleImage.parameters = { assets: ['https://via.placeholder.com/300/09f/fff.png'], }; export const SingleWebpage = () => <div>This story should a single image in the assets panel</div>; SingleWebpage.storyName = 'single webpage'; SingleWebpage.parameters = { assets: ['https://www.example.com'], }; export const YoutubeVideo = () => <div>This story should a single image in the assets panel</div>; YoutubeVideo.storyName = 'youtube video'; YoutubeVideo.parameters = { assets: ['https://www.youtube.com/embed/p-LFh5Y89eM'], }; export const MultipleImages = () => ( <div>This story should a multiple images in the assets panel</div> ); MultipleImages.storyName = 'multiple images'; MultipleImages.parameters = { assets: [ 'https://via.placeholder.com/600/09f/fff.png', 'https://via.placeholder.com/600/f90/fff.png', ], }; export const NamedAssets = () => <div>This story should a single image in the assets panel</div>; NamedAssets.storyName = 'named assets'; NamedAssets.parameters = { assets: [ { name: 'blue', url: 'https://via.placeholder.com/300/09f/fff.png', }, { name: 'orange', url: 'https://via.placeholder.com/300/f90/fff.png', }, ], }; export const UrlReplacement = () => ( <div>This story should have a webpage, with within it's url the storyId</div> ); UrlReplacement.storyName = 'url replacement'; UrlReplacement.parameters = { assets: ['https://via.placeholder.com/600.png?text={id}'], };
server/sonar-web/src/main/js/apps/overview/qualityGate/EmptyQualityGate.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import { translate } from '../../../helpers/l10n'; const EmptyQualityGate = () => { return ( <div className="overview-quality-gate"> <h2 className="overview-title"> {translate('overview.quality_gate')} </h2> <p className="overview-quality-gate-warning"> {translate('overview.you_should_define_quality_gate')} </p> </div> ); }; export default EmptyQualityGate;
react/eventwizard/components/teamsTab/TeamList.js
bdaroz/the-blue-alliance
import React from 'react' import PropTypes from 'prop-types' import TeamItem from './TeamItem' import TEAM_SHAPE from '../../constants/ApiTeam' const TeamList = (props) => ( <div> {props.teams.length > 0 && <p> {props.teams.length} teams attending </p> } <ul> {props.teams.map((team) => <TeamItem key={team.key} team_number={team.team_number} nickname={team.nickname} /> )} </ul> </div> ) TeamList.propTypes = { teams: PropTypes.arrayOf(PropTypes.shape(TEAM_SHAPE)).isRequired, } export default TeamList
src/components/contemporary/TestimonialForm.js
bharney/YogaMarieMills
import React from 'react'; import { Link } from 'react-router'; import TextInput from '../common/TextInput'; import Admin from '../common/Admin'; import TestimonialDetailsForm from './TestimonialDetailsForm'; import Editor from 'draft-js-plugins-editor'; import createInlineToolbarPlugin from 'draft-js-inline-toolbar-plugin'; import { ItalicButton, BoldButton, UnderlineButton, HeadlineTwoButton, HeadlineThreeButton, UnorderedListButton, OrderedListButton, BlockquoteButton, } from 'draft-js-buttons'; const inlineToolbarPlugin = createInlineToolbarPlugin({ structure: [ BoldButton, ItalicButton, UnderlineButton, HeadlineTwoButton, HeadlineThreeButton, UnorderedListButton, OrderedListButton, BlockquoteButton, ] }); const plugins = [inlineToolbarPlugin]; const { InlineToolbar } = inlineToolbarPlugin; const TestimonialForm = ({ authorized, updateQuoteState, updateNameState, updateTestimonialState, saveTestimonial, addRow, removeRow, testimonial, errors, saving, onChange, editorState, ref, focus }) => { return ( <form> <div className="mdl-grid dark-color"> <div className="ribbon bg-image-landing"> <div className="container-fluid"> <div className="row m-t-1-em m-b-1-em"> <div className="col-xs-offset-12 col-sm-offset-1 col-sm-10 m-b-1-em"> <Admin saveAction={saveTestimonial} authorized={authorized} /> <h1 className="color-white text-center">{testimonial.header}</h1> <TextInput name="short" label="Title" value={testimonial.short} onChange={updateTestimonialState} /> <div className="col-xs-12 m-b-1-em"> <div className="mdl-card mdl-shadow--4dp p-1-em"> <div id="editor" className="editor" onClick={focus}> <p> <Editor editorState={editorState} onChange={onChange} ref={ref} plugins={plugins} /> <InlineToolbar /> </p> </div> </div> </div> <div className="col-2-masonry"> <TestimonialDetailsForm removeRow={removeRow} updateQuoteState={updateQuoteState} updateNameState={updateNameState} removeRow={removeRow} testimonial={testimonial} errors={errors} saving={saving} /> </div> <Link className="text-right" to="" onClick={addRow} > <button type="button" className="btn btn-success btn-circle-lg" title="Add Row"><i className="glyphicon glyphicon-plus"></i></button> </Link> </div> </div> </div> </div> </div> </form> ); }; TestimonialForm.propTypes = { testimonial: React.PropTypes.object.isRequired, updateTestimonialState: React.PropTypes.object.isRequired, saving: React.PropTypes.object.isRequired, saveTestimonial: React.PropTypes.func.isRequired, errors: React.PropTypes.object }; export default TestimonialForm;
src/charts/legend/Legend.js
jchen-eb/britecharts-react
import React from 'react'; import PropTypes from 'prop-types'; import legendChart from './legendChart'; export default class Legend extends React.Component { static defaultProps = { chart: legendChart, } static propTypes = { /** * Gets or Sets the colorSchema of the chart */ colorSchema: PropTypes.arrayOf(PropTypes.string), /** * Gets or Sets the height of the legend chart */ height: PropTypes.number, /** * Highlights a line entry by fading the rest of lines */ highlight: PropTypes.number, /** * Gets or Sets the horizontal mode on the legend */ isHorizontal: PropTypes.bool, /** * Gets or Sets the margin of the legend chart */ margin: PropTypes.shape({ top: PropTypes.number, bottom: PropTypes.number, left: PropTypes.number, right: PropTypes.number, }), /** * Gets or Sets the margin ratio of the legend chart. Used to determine spacing between legend elements. */ marginRatio: PropTypes.number, /** * Gets or Sets the markerSize of the legend chart. This markerSize will determine * the horizontal and vertical size of the colored marks added as color * identifiers for the chart's categories. */ markerSize: PropTypes.number, /** * Gets or Sets the number format of the legend chart */ numberFormat: PropTypes.string, /** * Gets or Sets the width of the chart */ width: PropTypes.number, /** * The data to be used by the chart */ data: PropTypes.arrayOf(PropTypes.any).isRequired, /** * Internally used, do not overwrite. * * @ignore */ chart: PropTypes.object, } componentDidMount() { this._chart = this.props.chart.create( this._rootNode, this.props.data, this._getChartConfiguration() ); } componentDidUpdate() { this.props.chart.update( this._rootNode, this.props.data, this._getChartConfiguration(), this._chart ); } componentWillUnmount() { this.props.chart.destroy(this._rootNode); } /** * We want to remove the chart and data from the props in order to have a configuration object * @return {Object} Configuration object for the chart */ _getChartConfiguration() { let configuration = { ...this.props }; delete configuration.data; delete configuration.chart; return configuration; } _setRef(componentNode) { this._rootNode = componentNode; } render() { return ( <div className="legend-container" ref={this._setRef.bind(this)} /> ); } }
app/components/ProjectSelector.js
azlyth/redub
import fs from 'fs-extra'; import path from 'path'; import { remote } from 'electron'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { Button } from 'react-bootstrap'; import * as u from '../utils'; import FileInput from './FileInput'; import styles from './ProjectSelector.css'; const ROOT_PROJECT_FOLDER = path.join(remote.app.getPath('documents'), 'redub'); const CONFIG_FILENAME = 'config.json'; function projectPath(name) { return path.join(ROOT_PROJECT_FOLDER, name); } export default class ProjectSelector extends Component { static propTypes = { onProjectChosen: PropTypes.func.isRequired, }; constructor(props) { super(props); u.makeDirectory(ROOT_PROJECT_FOLDER); this.getExistingProjects(); this.state = { newProjectName: '', nameAlreadyExists: false, existingProjects: [], videoFile: null, subFile: null, }; this.createNewProject = this.createNewProject.bind(this); this.chooseExistingProject = this.chooseExistingProject.bind(this); this.changeProjectName = this.changeProjectName.bind(this); } getExistingProjects() { fs.readdir(ROOT_PROJECT_FOLDER, (err, files) => { this.setState({ existingProjects: files }); }); } validateConfig(config) { // Make sure the video exists if (!u.fileExists(config.video)) { alert(`The video (${config.video}) seems to be missing.`); return false; } // Make sure the subtitles exist if (!u.fileExists(config.subtitles)) { alert(`The subtitles (${config.subtitles}) seem to be missing.`); return false; } return true; } loadProject(config) { if (this.validateConfig(config)) { this.props.onProjectChosen(config); } } createNewProject() { const projectDirectory = projectPath(this.state.newProjectName); const projectConfig = { video: this.state.videoFile.path, subtitles: this.state.subFile.path, projectDirectory, }; // Create the new project directory and save the configuration if (this.validateConfig(projectConfig)) { const configPath = path.join(projectDirectory, CONFIG_FILENAME); u.makeDirectory(projectDirectory); fs.writeFileSync(configPath, JSON.stringify(projectConfig), { encoding: 'utf8' }); this.loadProject(projectConfig); } } chooseExistingProject(projectName) { const configPath = path.join(projectPath(projectName), CONFIG_FILENAME); const config = JSON.parse(fs.readFileSync(configPath, { encoding: 'utf8' })); this.loadProject(config); } changeProjectName(event) { const newProjectName = event.target.value; const potentialProjectPath = projectPath(newProjectName); const nameAlreadyExists = newProjectName.length > 0 && u.fileExists(potentialProjectPath); this.setState({ newProjectName, nameAlreadyExists, }); } nameChosen() { return this.state.newProjectName.length > 0; } nameValid() { return !this.state.nameAlreadyExists; } canCreateNewProject() { const videoChosen = this.state.videoFile !== null; const subsChosen = this.state.subFile !== null; return this.nameChosen() && this.nameValid() && videoChosen && subsChosen; } nameClasses() { const classes = [styles.newProjectName]; if (this.nameChosen()) { const otherClass = this.nameValid() ? styles.validName : styles.invalidName; classes.push(otherClass); } return classNames(classes); } deleteProject(event, projectName) { // The project will be selected if you don't prevent the other click event event.stopPropagation(); if (confirm(`Are you sure you want to delete "${projectName}"?`)) { fs.removeSync(projectPath(projectName)); this.getExistingProjects(); } } renderProjects() { return ( <div> <h3>Existing projects:</h3> <div className={styles.projectListContainer}> {this.state.existingProjects.map((project, index) => (<div key={index} className={styles.project}> <Button bsSize="large" className={styles.chooseProject} onClick={() => { this.chooseExistingProject(project); }} > {project} </Button> <Button bsSize="large" className={styles.deleteProject} bsStyle="danger" onClick={(event) => { this.deleteProject(event, project); }} > <i className={classNames(['fa', 'fa-times'])} /> </Button> </div>) )} </div> </div> ); } render() { return ( <div className={styles.projectSelector}> {(this.state.existingProjects.length > 0) && <span> {this.renderProjects()} <br /> <hr /> </span> } <br /> <div> <input type="text" placeholder="Enter a new project name..." className={this.nameClasses()} value={this.state.newProjectName} onChange={this.changeProjectName} /> {this.state.nameAlreadyExists && <p className={styles.errorText}> A project with that name already exists! </p> } </div> <br /> <div> <FileInput className={styles.fileInput} placeholder="Choose video" onChange={(videoFile) => { this.setState({ videoFile }); }} /> &nbsp;&nbsp;&nbsp; <FileInput accept=".srt" className={styles.fileInput} placeholder="Choose subtitles (srt)" onChange={(subFile) => { this.setState({ subFile }); }} /> </div> <br /> <Button bsSize="large" bsStyle="success" disabled={!this.canCreateNewProject()} onClick={this.createNewProject} > CREATE NEW PROJECT </Button> </div> ); } }
local-cli/templates/HelloNavigation/views/chat/ChatScreen.js
htc2u/react-native
'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, Button, ListView, StyleSheet, Text, TextInput, View, } from 'react-native'; import KeyboardSpacer from '../../components/KeyboardSpacer'; import Backend from '../../lib/Backend'; export default class ChatScreen extends Component { static navigationOptions = { title: (navigation) => `Chat with ${navigation.state.params.name}`, } constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { messages: [], dataSource: ds, myMessage: '', isLoading: true, }; } async componentDidMount() { let chat; try { chat = await Backend.fetchChat(this.props.navigation.state.params.name); } catch (err) { // Here we would handle the fact the request failed, e.g. // set state to display "Messages could not be loaded". // We should also check network connection first before making any // network requests - maybe we're offline? See React Native's NetInfo // module. this.setState({ isLoading: false, }); return; } this.setState((prevState) => ({ messages: chat.messages, dataSource: prevState.dataSource.cloneWithRows(chat.messages), isLoading: false, })); } onAddMessage = async () => { // Optimistically update the UI this.addMessageLocal(); // Send the request try { await Backend.sendMessage({ name: this.props.navigation.state.params.name, // TODO Is reading state like this outside of setState OK? // Can it contain a stale value? message: this.state.myMessage, }); } catch (err) { // Here we would handle the request failure, e.g. call setState // to display a visual hint showing the message could not be sent. } } addMessageLocal = () => { this.setState((prevState) => { if (!prevState.myMessage) { return prevState; } const messages = [ ...prevState.messages, { name: 'Me', text: prevState.myMessage, } ]; return { messages: messages, dataSource: prevState.dataSource.cloneWithRows(messages), myMessage: '', } }); this.textInput.clear(); } onMyMessageChange = (event) => { this.setState({myMessage: event.nativeEvent.text}); } renderRow = (message) => ( <View style={styles.bubble}> <Text style={styles.name}>{message.name}</Text> <Text>{message.text}</Text> </View> ) render() { if (this.state.isLoading) { return ( <View style={styles.container}> <ActivityIndicator /> </View> ); } return ( <View style={styles.container}> <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} style={styles.listView} onLayout={this.scrollToBottom} /> <View style={styles.composer}> <TextInput ref={(textInput) => { this.textInput = textInput; }} style={styles.textInput} placeholder="Type a message..." text={this.state.myMessage} onSubmitEditing={this.onAddMessage} onChange={this.onMyMessageChange} /> {this.state.myMessage !== '' && ( <Button title="Send" onPress={this.onAddMessage} /> )} </View> <KeyboardSpacer /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 8, backgroundColor: 'white', }, listView: { flex: 1, alignSelf: 'stretch', }, bubble: { alignSelf: 'flex-end', backgroundColor: '#d6f3fc', padding: 12, borderRadius: 4, marginBottom: 4, }, name: { fontWeight: 'bold', }, composer: { flexDirection: 'row', alignItems: 'center', height: 36, }, textInput: { flex: 1, borderColor: '#ddd', borderWidth: 1, padding: 4, height: 30, fontSize: 13, marginRight: 8, } });
src/routes/Experiments/components/ExperimentsView.js
popaulina/grackle
import React from 'react'; import { connect } from 'react-redux' import { Field, change } from 'redux-form' import { Button, Grid, Col, Row } from 'react-bootstrap' import ReactAudioPlayer from 'react-audio-player' import './Experiments.scss' import { WithContext as ReactTags } from 'react-tag-input'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table' import { updateSelected } from '../../../helpers' //todo: loading, reset on cancel var ExperimentsView = ({ experiment, editing, setEditing, deleteExperiment, save, editedExperiment, dispatch, samples }) => ( <Grid className="content"> <div className="page viewText"> <div className="title"> Experiment: { editing ? <Field name="name" component="input" type="text"/> : <span className="entityName">{experiment ? experiment.name : ""}</span> } <Button className="edit btn btn-danger" onClick={() => deleteExperiment(experiment)}> Delete </Button> <Button className="edit" onClick={() => setEditing()}> {editing ? "Cancel" : "Edit"}</Button> {editing ? <Button className="edit" onClick={() => save(editedExperiment)}> Save </Button> : ""} <hr /> </div> <Row> <Col className="info"> <Row> <Col xs={3} className="viewLabel"> Repeats: </Col> <Col xs={7} className="rightViewLabel"> { editing ? <Field name="repeats" component="input" type="number"/> : <span>{experiment ? experiment.repeats : ""} </span> } </Col> </Row> <hr className="info-hr"/> <Row> <Col xs={3} className="viewLabel"> Active: </Col> <Col xs={7} className="rightViewLabel"> <Field name="active" component="input" type="checkbox" disabled={!editing} className="css-checkbox"/> </Col> </Row> <hr className="info-hr"/> <Row> <Col xs={3} className="viewLabel"> Tags: </Col> <Col xs={7} className="rightViewLabel"> <ReactTags tags={editedExperiment ? editedExperiment.tags : []} readOnly={!editing} handleDelete={(tag) => { dispatch(change('experimentsView', 'tags', editedExperiment.tags.filter((x) => x !== editedExperiment.tags[tag])))} } handleAddition={(tag) => dispatch(change('experimentsView'), 'tags', editedExperiment.tags.push({id: editedExperiment.tags.length + 1, text: tag }))} classNames={{ tags: 'tags', tagInput: 'tagInput', tagInputField: 'tagInputField', selected: 'tagsSelected', tag: 'tagSingle', remove: 'tagRemove' }}/> </Col> </Row> <hr className="create-hr" /> <div className="sample-list"> <Col xs={3}> Samples: </Col> { editing ? <BootstrapTable data={samples} selectRow={{ mode: 'checkbox', clickToSelect: true, selected: editedExperiment.sample_ids, onSelect: (row, selected) => dispatch(change('experimentsView', 'sample_ids', updateSelected(editedExperiment.sample_ids, row, selected))) }} striped hover pagination > <TableHeaderColumn dataField="id" isKey={true} hidden /> <TableHeaderColumn dataField="name" dataSort={true}>Name</TableHeaderColumn> </BootstrapTable> : <BootstrapTable data={samples} striped hover pagination > <TableHeaderColumn dataField="id" isKey={true} hidden /> <TableHeaderColumn dataField="name" dataSort={true}>Name</TableHeaderColumn> </BootstrapTable> } </div> </Col> </Row> </div> </Grid> ); export default ExperimentsView
src/svg-icons/places/child-care.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let PlacesChildCare = (props) => ( <SvgIcon {...props}> <circle cx="14.5" cy="10.5" r="1.25"/><circle cx="9.5" cy="10.5" r="1.25"/><path d="M22.94 12.66c.04-.21.06-.43.06-.66s-.02-.45-.06-.66c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66s.02.45.06.66c.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2zM7.5 14c.76 1.77 2.49 3 4.5 3s3.74-1.23 4.5-3h-9z"/> </SvgIcon> ); PlacesChildCare = pure(PlacesChildCare); PlacesChildCare.displayName = 'PlacesChildCare'; PlacesChildCare.muiName = 'SvgIcon'; export default PlacesChildCare;
src/index.js
globmont/espionage
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import Game from './Game' import './index.css'; import { Router, Route, hashHistory } from 'react-router' ReactDOM.render( <Router history={hashHistory}> <Route path="/" component={App}></Route> <Route path="game/:serverName" component={Game}></Route> </Router>, document.getElementById('root') );
src/index.js
shaunstanislaus/react-transform-boilerplate
import React from 'react'; import { App } from './App'; React.render(<App />, document.getElementById('root'));
src/forms/widgets/FileWidget.js
austinsc/react-gooey
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { dataURItoBlob, shouldRender, setState } from '../utils'; function addNameToDataURL(dataURL, name) { return dataURL.replace(';base64', `;name=${name};base64`); } function processFile(file) { const { name, size, type } = file; return new Promise((resolve, reject) => { const reader = new window.FileReader(); reader.onload = event => { resolve({ dataURL: addNameToDataURL(event.target.result, name), name, size, type }); }; reader.readAsDataURL(file); }); } function processFiles(files) { return Promise.all([].map.call(files, processFile)); } function FilesInfo(props) { const { filesInfo } = props; if (filesInfo.length === 0) { return null; } return ( <ul className="file-info"> {filesInfo.map((fileInfo, key) => { const { name, size, type } = fileInfo; return ( <li key={key}> <strong>{name}</strong> ({type}, {size} bytes) </li> ); })} </ul> ); } function extractFileInfo(dataURLs) { return dataURLs .filter(dataURL => typeof dataURL !== 'undefined') .map(dataURL => { const { blob, name } = dataURItoBlob(dataURL); return { name: name, size: blob.size, type: blob.type }; }); } class FileWidget extends Component { defaultProps = { multiple: false }; constructor(props) { super(props); const { value } = props; const values = Array.isArray(value) ? value : [value]; this.state = { values, filesInfo: extractFileInfo(values) }; } shouldComponentUpdate(nextProps, nextState) { return shouldRender(this, nextProps, nextState); } onChange = event => { const { multiple, onChange } = this.props; processFiles(event.target.files).then(filesInfo => { const state = { values: filesInfo.map(fileInfo => fileInfo.dataURL), filesInfo }; setState(this, state, () => { if (multiple) { onChange(state.values); } else { onChange(state.values[0]); } }); }); }; render() { const { multiple, id, readonly, disabled, autofocus } = this.props; const { filesInfo } = this.state; return ( <div> <p> <input ref={ref => (this.inputRef = ref)} id={id} type="file" disabled={readonly || disabled} onChange={this.onChange} defaultValue="" autoFocus={autofocus} multiple={multiple} /> </p> <FilesInfo filesInfo={filesInfo} /> </div> ); } } FileWidget.defaultProps = { autofocus: false }; if (process.env.NODE_ENV !== 'production') { FileWidget.propTypes = { multiple: PropTypes.bool, value: PropTypes.oneOfType([ PropTypes.string, PropTypes.arrayOf(PropTypes.string) ]), autofocus: PropTypes.bool }; } export default FileWidget;
examples/huge-apps/routes/Course/routes/Assignments/routes/Assignment/components/Assignment.js
jamiehill/react-router
import React from 'react'; class Assignment extends React.Component { render () { var { courseId, assignmentId } = this.props.params; var { title, body } = COURSES[courseId].assignments[assignmentId] return ( <div> <h4>{title}</h4> <p>{body}</p> </div> ); } } export default Assignment;
src/Parser/Rogue/Outlaw/Modules/RogueCore/Energy.js
hasseboulen/WoWAnalyzer
import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import resourceSuggest from 'Parser/Core/Modules/ResourceTracker/ResourceSuggest'; import EnergyTracker from '../../../Common/Resources/EnergyTracker'; class Energy extends Analyzer { static dependencies = { energyTracker: EnergyTracker, }; suggestions(when) { resourceSuggest(when, this.energyTracker, { spell: SPELLS.COMBAT_POTENCY, minor: 0.05, avg: 0.1, major: 0.15, extraSuggestion: <Wrapper> Try to keep energy below max to avoid waisting <SpellLink id={SPELLS.COMBAT_POTENCY.id} /> procs. </Wrapper>, }); } } export default Energy;
Libraries/CustomComponents/Navigator/Navigator.js
mrspeaker/react-native
/** * Copyright (c) 2013-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. * * Facebook, Inc. ("Facebook") owns all right, title and interest, including * all intellectual property and other proprietary rights, in and to the React * Native CustomComponents software (the "Software"). Subject to your * compliance with these terms, you are hereby granted a non-exclusive, * worldwide, royalty-free copyright license to (1) use and copy the Software; * and (2) reproduce and distribute the Software as part of your own software * ("Your Software"). Facebook reserves all rights not expressly granted to * you in this license agreement. * * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @providesModule Navigator */ /* eslint-disable no-extra-boolean-cast*/ 'use strict'; var AnimationsDebugModule = require('NativeModules').AnimationsDebugModule; var Dimensions = require('Dimensions'); var InteractionMixin = require('InteractionMixin'); var NavigationContext = require('NavigationContext'); var NavigatorBreadcrumbNavigationBar = require('NavigatorBreadcrumbNavigationBar'); var NavigatorNavigationBar = require('NavigatorNavigationBar'); var NavigatorSceneConfigs = require('NavigatorSceneConfigs'); var PanResponder = require('PanResponder'); var React = require('React'); var StyleSheet = require('StyleSheet'); var Subscribable = require('Subscribable'); var TimerMixin = require('react-timer-mixin'); var View = require('View'); var clamp = require('clamp'); var flattenStyle = require('flattenStyle'); var invariant = require('fbjs/lib/invariant'); var rebound = require('rebound'); var PropTypes = React.PropTypes; // TODO: this is not ideal because there is no guarantee that the navigator // is full screen, however we don't have a good way to measure the actual // size of the navigator right now, so this is the next best thing. var SCREEN_WIDTH = Dimensions.get('window').width; var SCREEN_HEIGHT = Dimensions.get('window').height; var SCENE_DISABLED_NATIVE_PROPS = { pointerEvents: 'none', style: { top: SCREEN_HEIGHT, bottom: -SCREEN_HEIGHT, opacity: 0, }, }; var __uid = 0; function getuid() { return __uid++; } function getRouteID(route) { if (route === null || typeof route !== 'object') { return String(route); } var key = '__navigatorRouteID'; if (!route.hasOwnProperty(key)) { Object.defineProperty(route, key, { enumerable: false, configurable: false, writable: false, value: getuid(), }); } return route[key]; } // styles moved to the top of the file so getDefaultProps can refer to it var styles = StyleSheet.create({ container: { flex: 1, overflow: 'hidden', }, defaultSceneStyle: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, }, baseScene: { position: 'absolute', overflow: 'hidden', left: 0, right: 0, bottom: 0, top: 0, }, disabledScene: { top: SCREEN_HEIGHT, bottom: -SCREEN_HEIGHT, }, transitioner: { flex: 1, backgroundColor: 'transparent', overflow: 'hidden', } }); var GESTURE_ACTIONS = [ 'pop', 'jumpBack', 'jumpForward', ]; /** * `Navigator` handles the transition between different scenes in your app. * It is implemented in JavaScript and is available on both iOS and Android. If * you are targeting iOS only, you may also want to consider using * [`NavigatorIOS`](docs/navigatorios.html) as it leverages native UIKit * navigation. * * To set up the `Navigator` you provide one or more objects called routes, * to identify each scene. You also provide a `renderScene` function that * renders the scene for each route object. * * ``` * import React, { Component } from 'react'; * import { Text, Navigator } from 'react-native'; * * export default class NavAllDay extends Component { * render() { * return ( * <Navigator * initialRoute={{ title: 'Awesome Scene', index: 0 }} * renderScene={(route, navigator) => * <Text>Hello {route.title}!</Text> * } * style={{padding: 100}} * /> * ); * } * } * ``` * * In the above example, `initialRoute` is used to specify the first route. It * contains a `title` property that identifies the route. The `renderScene` * prop returns a function that displays text based on the route's title. * * ### Additional Scenes * * The first example demonstrated one scene. To set up multiple scenes, you pass * the `initialRouteStack` prop to `Navigator`: * * ``` * render() { * const routes = [ * {title: 'First Scene', index: 0}, * {title: 'Second Scene', index: 1}, * ]; * return ( * <Navigator * initialRoute={routes[0]} * initialRouteStack={routes} * renderScene={(route, navigator) => * <TouchableHighlight onPress={() => { * if (route.index === 0) { * navigator.push(routes[1]); * } else { * navigator.pop(); * } * }}> * <Text>Hello {route.title}!</Text> * </TouchableHighlight> * } * style={{padding: 100}} * /> * ); * } * ``` * * In the above example, a `routes` variable is defined with two route objects * representing two scenes. Each route has an `index` property that is used to * manage the scene being rendered. The `renderScene` method is changed to * either push or pop the navigator depending on the current route's index. * Finally, the `Text` component in the scene is now wrapped in a * `TouchableHighlight` component to help trigger the navigator transitions. * * ### Navigation Bar * * You can optionally pass in your own navigation bar by returning a * `Navigator.NavigationBar` component to the `navigationBar` prop in * `Navigator`. You can configure the navigation bar properties, through * the `routeMapper` prop. There you set up the left, right, and title * properties of the navigation bar: * * ``` * <Navigator * renderScene={(route, navigator) => * // ... * } * navigationBar={ * <Navigator.NavigationBar * routeMapper={{ * LeftButton: (route, navigator, index, navState) => * { return (<Text>Cancel</Text>); }, * RightButton: (route, navigator, index, navState) => * { return (<Text>Done</Text>); }, * Title: (route, navigator, index, navState) => * { return (<Text>Awesome Nav Bar</Text>); }, * }} * style={{backgroundColor: 'gray'}} * /> * } * /> * ``` * * When configuring the left, right, and title items for the navigation bar, * you have access to info such as the current route object and navigation * state. This allows you to customize the title for each scene as well as * the buttons. For example, you can choose to hide the left button for one of * the scenes. * * Typically you want buttons to represent the left and right buttons. Building * on the previous example, you can set this up as follows: * * ``` * LeftButton: (route, navigator, index, navState) => * { * if (route.index === 0) { * return null; * } else { * return ( * <TouchableHighlight onPress={() => navigator.pop()}> * <Text>Back</Text> * </TouchableHighlight> * ); * } * }, * ``` * * This sets up a left navigator bar button that's visible on scenes after the * the first one. When the button is tapped the navigator is popped. * * Another type of navigation bar, with breadcrumbs, is provided by * `Navigator.BreadcrumbNavigationBar`. You can also provide your own navigation * bar by passing it through the `navigationBar` prop. See the * [UIExplorer](https://github.com/facebook/react-native/tree/master/Examples/UIExplorer) * demo to try out both built-in navigation bars out and see how to use them. * * ### Scene Transitions * * To change the animation or gesture properties of the scene, provide a * `configureScene` prop to get the config object for a given route: * * ``` * <Navigator * renderScene={(route, navigator) => * // ... * } * configureScene={(route, routeStack) => * Navigator.SceneConfigs.FloatFromBottom} * /> * ``` * In the above example, the newly pushed scene will float up from the bottom. * See `Navigator.SceneConfigs` for default animations and more info on * available [scene config options](/react-native/docs/navigator.html#configurescene). */ var Navigator = React.createClass({ propTypes: { /** * Optional function where you can configure scene animations and * gestures. Will be invoked with `route` and `routeStack` parameters, * where `route` corresponds to the current scene being rendered by the * `Navigator` and `routeStack` is the set of currently mounted routes * that the navigator could transition to. * * The function should return a scene configuration object. * * ``` * (route, routeStack) => Navigator.SceneConfigs.FloatFromRight * ``` * * Available scene configutation options are: * * - Navigator.SceneConfigs.PushFromRight (default) * - Navigator.SceneConfigs.FloatFromRight * - Navigator.SceneConfigs.FloatFromLeft * - Navigator.SceneConfigs.FloatFromBottom * - Navigator.SceneConfigs.FloatFromBottomAndroid * - Navigator.SceneConfigs.FadeAndroid * - Navigator.SceneConfigs.HorizontalSwipeJump * - Navigator.SceneConfigs.HorizontalSwipeJumpFromRight * - Navigator.SceneConfigs.VerticalUpSwipeJump * - Navigator.SceneConfigs.VerticalDownSwipeJump * */ configureScene: PropTypes.func, /** * Required function which renders the scene for a given route. Will be * invoked with the `route` and the `navigator` object. * * ``` * (route, navigator) => * <MySceneComponent title={route.title} navigator={navigator} /> * ``` */ renderScene: PropTypes.func.isRequired, /** * The initial route for navigation. A route is an object that the navigator * will use to identify each scene it renders. * * If both `initialRoute` and `initialRouteStack` props are passed to * `Navigator`, then `initialRoute` must be in a route in * `initialRouteStack`. If `initialRouteStack` is passed as a prop but * `initialRoute` is not, then `initialRoute` will default internally to * the last item in `initialRouteStack`. */ initialRoute: PropTypes.object, /** * Pass this in to provide a set of routes to initially mount. This prop * is required if `initialRoute` is not provided to the navigator. If this * prop is not passed in, it will default internally to an array * containing only `initialRoute`. */ initialRouteStack: PropTypes.arrayOf(PropTypes.object), /** * Pass in a function to get notified with the target route when * the navigator component is mounted and before each navigator transition. */ onWillFocus: PropTypes.func, /** * Will be called with the new route of each scene after the transition is * complete or after the initial mounting. */ onDidFocus: PropTypes.func, /** * Use this to provide an optional component representing a navigation bar * that is persisted across scene transitions. This component will receive * two props: `navigator` and `navState` representing the navigator * component and its state. The component is re-rendered when the route * changes. */ navigationBar: PropTypes.node, /** * Optionally pass in the navigator object from a parent `Navigator`. */ navigator: PropTypes.object, /** * Styles to apply to the container of each scene. */ sceneStyle: View.propTypes.style, }, statics: { BreadcrumbNavigationBar: NavigatorBreadcrumbNavigationBar, NavigationBar: NavigatorNavigationBar, SceneConfigs: NavigatorSceneConfigs, }, mixins: [TimerMixin, InteractionMixin, Subscribable.Mixin], getDefaultProps: function() { return { configureScene: () => NavigatorSceneConfigs.PushFromRight, sceneStyle: styles.defaultSceneStyle, }; }, getInitialState: function() { this._navigationBarNavigator = this.props.navigationBarNavigator || this; this._renderedSceneMap = new Map(); var routeStack = this.props.initialRouteStack || [this.props.initialRoute]; invariant( routeStack.length >= 1, 'Navigator requires props.initialRoute or props.initialRouteStack.' ); var initialRouteIndex = routeStack.length - 1; if (this.props.initialRoute) { initialRouteIndex = routeStack.indexOf(this.props.initialRoute); invariant( initialRouteIndex !== -1, 'initialRoute is not in initialRouteStack.' ); } return { sceneConfigStack: routeStack.map( (route) => this.props.configureScene(route, routeStack) ), routeStack, presentedIndex: initialRouteIndex, transitionFromIndex: null, activeGesture: null, pendingGestureProgress: null, transitionQueue: [], }; }, componentWillMount: function() { // TODO(t7489503): Don't need this once ES6 Class landed. this.__defineGetter__('navigationContext', this._getNavigationContext); this._subRouteFocus = []; this.parentNavigator = this.props.navigator; this._handlers = {}; this.springSystem = new rebound.SpringSystem(); this.spring = this.springSystem.createSpring(); this.spring.setRestSpeedThreshold(0.05); this.spring.setCurrentValue(0).setAtRest(); this.spring.addListener({ onSpringEndStateChange: () => { if (!this._interactionHandle) { this._interactionHandle = this.createInteractionHandle(); } }, onSpringUpdate: () => { this._handleSpringUpdate(); }, onSpringAtRest: () => { this._completeTransition(); }, }); this.panGesture = PanResponder.create({ onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder, onPanResponderRelease: this._handlePanResponderRelease, onPanResponderMove: this._handlePanResponderMove, onPanResponderTerminate: this._handlePanResponderTerminate, }); this._interactionHandle = null; this._emitWillFocus(this.state.routeStack[this.state.presentedIndex]); }, componentDidMount: function() { this._handleSpringUpdate(); this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]); }, componentWillUnmount: function() { if (this._navigationContext) { this._navigationContext.dispose(); this._navigationContext = null; } this.spring.destroy(); if (this._interactionHandle) { this.clearInteractionHandle(this._interactionHandle); } }, /** * Reset every scene with an array of routes. * * @param {RouteStack} nextRouteStack Next route stack to reinitialize. * All existing route stacks are destroyed an potentially recreated. There * is no accompanying animation and this method immediately replaces and * re-renders the navigation bar and the stack items. */ immediatelyResetRouteStack: function(nextRouteStack) { var destIndex = nextRouteStack.length - 1; this.setState({ routeStack: nextRouteStack, sceneConfigStack: nextRouteStack.map( route => this.props.configureScene(route, nextRouteStack) ), presentedIndex: destIndex, activeGesture: null, transitionFromIndex: null, transitionQueue: [], }, () => { this._handleSpringUpdate(); this._navBar && this._navBar.immediatelyRefresh(); this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]); }); }, _transitionTo: function(destIndex, velocity, jumpSpringTo, cb) { if (this.state.presentedIndex === destIndex) { cb && cb(); return; } if (this.state.transitionFromIndex !== null) { // Navigation is still transitioning, put the `destIndex` into queue. this.state.transitionQueue.push({ destIndex, velocity, cb, }); return; } this.state.transitionFromIndex = this.state.presentedIndex; this.state.presentedIndex = destIndex; this.state.transitionCb = cb; this._onAnimationStart(); if (AnimationsDebugModule) { AnimationsDebugModule.startRecordingFps(); } var sceneConfig = this.state.sceneConfigStack[this.state.transitionFromIndex] || this.state.sceneConfigStack[this.state.presentedIndex]; invariant( sceneConfig, 'Cannot configure scene at index ' + this.state.transitionFromIndex ); if (jumpSpringTo != null) { this.spring.setCurrentValue(jumpSpringTo); } this.spring.setOvershootClampingEnabled(true); this.spring.getSpringConfig().friction = sceneConfig.springFriction; this.spring.getSpringConfig().tension = sceneConfig.springTension; this.spring.setVelocity(velocity || sceneConfig.defaultTransitionVelocity); this.spring.setEndValue(1); }, /** * This happens for each frame of either a gesture or a transition. If both are * happening, we only set values for the transition and the gesture will catch up later */ _handleSpringUpdate: function() { if (!this.isMounted()) { return; } // Prioritize handling transition in progress over a gesture: if (this.state.transitionFromIndex != null) { this._transitionBetween( this.state.transitionFromIndex, this.state.presentedIndex, this.spring.getCurrentValue() ); } else if (this.state.activeGesture != null) { var presentedToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._transitionBetween( this.state.presentedIndex, presentedToIndex, this.spring.getCurrentValue() ); } }, /** * This happens at the end of a transition started by transitionTo, and when the spring catches up to a pending gesture */ _completeTransition: function() { if (!this.isMounted()) { return; } if (this.spring.getCurrentValue() !== 1 && this.spring.getCurrentValue() !== 0) { // The spring has finished catching up to a gesture in progress. Remove the pending progress // and we will be in a normal activeGesture state if (this.state.pendingGestureProgress) { this.state.pendingGestureProgress = null; } return; } this._onAnimationEnd(); var presentedIndex = this.state.presentedIndex; var didFocusRoute = this._subRouteFocus[presentedIndex] || this.state.routeStack[presentedIndex]; if (AnimationsDebugModule) { AnimationsDebugModule.stopRecordingFps(Date.now()); } this.state.transitionFromIndex = null; this.spring.setCurrentValue(0).setAtRest(); this._hideScenes(); if (this.state.transitionCb) { this.state.transitionCb(); this.state.transitionCb = null; } this._emitDidFocus(didFocusRoute); if (this._interactionHandle) { this.clearInteractionHandle(this._interactionHandle); this._interactionHandle = null; } if (this.state.pendingGestureProgress) { // A transition completed, but there is already another gesture happening. // Enable the scene and set the spring to catch up with the new gesture var gestureToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._enableScene(gestureToIndex); this.spring.setEndValue(this.state.pendingGestureProgress); return; } if (this.state.transitionQueue.length) { var queuedTransition = this.state.transitionQueue.shift(); this._enableScene(queuedTransition.destIndex); this._emitWillFocus(this.state.routeStack[queuedTransition.destIndex]); this._transitionTo( queuedTransition.destIndex, queuedTransition.velocity, null, queuedTransition.cb ); } }, _emitDidFocus: function(route) { this.navigationContext.emit('didfocus', {route: route}); if (this.props.onDidFocus) { this.props.onDidFocus(route); } }, _emitWillFocus: function(route) { this.navigationContext.emit('willfocus', {route: route}); var navBar = this._navBar; if (navBar && navBar.handleWillFocus) { navBar.handleWillFocus(route); } if (this.props.onWillFocus) { this.props.onWillFocus(route); } }, /** * Hides all scenes that we are not currently on, gesturing to, or transitioning from */ _hideScenes: function() { var gesturingToIndex = null; if (this.state.activeGesture) { gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); } for (var i = 0; i < this.state.routeStack.length; i++) { if (i === this.state.presentedIndex || i === this.state.transitionFromIndex || i === gesturingToIndex) { continue; } this._disableScene(i); } }, /** * Push a scene off the screen, so that opacity:0 scenes will not block touches sent to the presented scenes */ _disableScene: function(sceneIndex) { this.refs['scene_' + sceneIndex] && this.refs['scene_' + sceneIndex].setNativeProps(SCENE_DISABLED_NATIVE_PROPS); }, /** * Put the scene back into the state as defined by props.sceneStyle, so transitions can happen normally */ _enableScene: function(sceneIndex) { // First, determine what the defined styles are for scenes in this navigator var sceneStyle = flattenStyle([styles.baseScene, this.props.sceneStyle]); // Then restore the pointer events and top value for this scene var enabledSceneNativeProps = { pointerEvents: 'auto', style: { top: sceneStyle.top, bottom: sceneStyle.bottom, }, }; if (sceneIndex !== this.state.transitionFromIndex && sceneIndex !== this.state.presentedIndex) { // If we are not in a transition from this index, make sure opacity is 0 // to prevent the enabled scene from flashing over the presented scene enabledSceneNativeProps.style.opacity = 0; } this.refs['scene_' + sceneIndex] && this.refs['scene_' + sceneIndex].setNativeProps(enabledSceneNativeProps); }, _onAnimationStart: function() { var fromIndex = this.state.presentedIndex; var toIndex = this.state.presentedIndex; if (this.state.transitionFromIndex != null) { fromIndex = this.state.transitionFromIndex; } else if (this.state.activeGesture) { toIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); } this._setRenderSceneToHardwareTextureAndroid(fromIndex, true); this._setRenderSceneToHardwareTextureAndroid(toIndex, true); var navBar = this._navBar; if (navBar && navBar.onAnimationStart) { navBar.onAnimationStart(fromIndex, toIndex); } }, _onAnimationEnd: function() { var max = this.state.routeStack.length - 1; for (var index = 0; index <= max; index++) { this._setRenderSceneToHardwareTextureAndroid(index, false); } var navBar = this._navBar; if (navBar && navBar.onAnimationEnd) { navBar.onAnimationEnd(); } }, _setRenderSceneToHardwareTextureAndroid: function(sceneIndex, shouldRenderToHardwareTexture) { var viewAtIndex = this.refs['scene_' + sceneIndex]; if (viewAtIndex === null || viewAtIndex === undefined) { return; } viewAtIndex.setNativeProps({renderToHardwareTextureAndroid: shouldRenderToHardwareTexture}); }, _handleTouchStart: function() { this._eligibleGestures = GESTURE_ACTIONS; }, _handleMoveShouldSetPanResponder: function(e, gestureState) { var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex]; if (!sceneConfig) { return false; } this._expectingGestureGrant = this._matchGestureAction(this._eligibleGestures, sceneConfig.gestures, gestureState); return !!this._expectingGestureGrant; }, _doesGestureOverswipe: function(gestureName) { var wouldOverswipeBack = this.state.presentedIndex <= 0 && (gestureName === 'pop' || gestureName === 'jumpBack'); var wouldOverswipeForward = this.state.presentedIndex >= this.state.routeStack.length - 1 && gestureName === 'jumpForward'; return wouldOverswipeForward || wouldOverswipeBack; }, _deltaForGestureAction: function(gestureAction) { switch (gestureAction) { case 'pop': case 'jumpBack': return -1; case 'jumpForward': return 1; default: invariant(false, 'Unsupported gesture action ' + gestureAction); return; } }, _handlePanResponderRelease: function(e, gestureState) { var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex]; var releaseGestureAction = this.state.activeGesture; if (!releaseGestureAction) { // The gesture may have been detached while responder, so there is no action here return; } var releaseGesture = sceneConfig.gestures[releaseGestureAction]; var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); if (this.spring.getCurrentValue() === 0) { // The spring is at zero, so the gesture is already complete this.spring.setCurrentValue(0).setAtRest(); this._completeTransition(); return; } var isTravelVertical = releaseGesture.direction === 'top-to-bottom' || releaseGesture.direction === 'bottom-to-top'; var isTravelInverted = releaseGesture.direction === 'right-to-left' || releaseGesture.direction === 'bottom-to-top'; var velocity, gestureDistance; if (isTravelVertical) { velocity = isTravelInverted ? -gestureState.vy : gestureState.vy; gestureDistance = isTravelInverted ? -gestureState.dy : gestureState.dy; } else { velocity = isTravelInverted ? -gestureState.vx : gestureState.vx; gestureDistance = isTravelInverted ? -gestureState.dx : gestureState.dx; } var transitionVelocity = clamp(-10, velocity, 10); if (Math.abs(velocity) < releaseGesture.notMoving) { // The gesture velocity is so slow, is "not moving" var hasGesturedEnoughToComplete = gestureDistance > releaseGesture.fullDistance * releaseGesture.stillCompletionRatio; transitionVelocity = hasGesturedEnoughToComplete ? releaseGesture.snapVelocity : -releaseGesture.snapVelocity; } if (transitionVelocity < 0 || this._doesGestureOverswipe(releaseGestureAction)) { // This gesture is to an overswiped region or does not have enough velocity to complete // If we are currently mid-transition, then this gesture was a pending gesture. Because this gesture takes no action, we can stop here if (this.state.transitionFromIndex == null) { // There is no current transition, so we need to transition back to the presented index var transitionBackToPresentedIndex = this.state.presentedIndex; // slight hack: change the presented index for a moment in order to transitionTo correctly this.state.presentedIndex = destIndex; this._transitionTo( transitionBackToPresentedIndex, -transitionVelocity, 1 - this.spring.getCurrentValue() ); } } else { // The gesture has enough velocity to complete, so we transition to the gesture's destination this._emitWillFocus(this.state.routeStack[destIndex]); this._transitionTo( destIndex, transitionVelocity, null, () => { if (releaseGestureAction === 'pop') { this._cleanScenesPastIndex(destIndex); } } ); } this._detachGesture(); }, _handlePanResponderTerminate: function(e, gestureState) { if (this.state.activeGesture == null) { return; } var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._detachGesture(); var transitionBackToPresentedIndex = this.state.presentedIndex; // slight hack: change the presented index for a moment in order to transitionTo correctly this.state.presentedIndex = destIndex; this._transitionTo( transitionBackToPresentedIndex, null, 1 - this.spring.getCurrentValue() ); }, _attachGesture: function(gestureId) { this.state.activeGesture = gestureId; var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._enableScene(gesturingToIndex); }, _detachGesture: function() { this.state.activeGesture = null; this.state.pendingGestureProgress = null; this._hideScenes(); }, _handlePanResponderMove: function(e, gestureState) { if (this._isMoveGestureAttached !== undefined) { invariant( this._expectingGestureGrant, 'Responder granted unexpectedly.' ); this._attachGesture(this._expectingGestureGrant); this._onAnimationStart(); this._expectingGestureGrant = undefined; } var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex]; if (this.state.activeGesture) { var gesture = sceneConfig.gestures[this.state.activeGesture]; return this._moveAttachedGesture(gesture, gestureState); } var matchedGesture = this._matchGestureAction(GESTURE_ACTIONS, sceneConfig.gestures, gestureState); if (matchedGesture) { this._attachGesture(matchedGesture); } }, _moveAttachedGesture: function(gesture, gestureState) { var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top'; var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top'; var distance = isTravelVertical ? gestureState.dy : gestureState.dx; distance = isTravelInverted ? -distance : distance; var gestureDetectMovement = gesture.gestureDetectMovement; var nextProgress = (distance - gestureDetectMovement) / (gesture.fullDistance - gestureDetectMovement); if (nextProgress < 0 && gesture.isDetachable) { var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._transitionBetween(this.state.presentedIndex, gesturingToIndex, 0); this._detachGesture(); if (this.state.pendingGestureProgress != null) { this.spring.setCurrentValue(0); } return; } if (this._doesGestureOverswipe(this.state.activeGesture)) { var frictionConstant = gesture.overswipe.frictionConstant; var frictionByDistance = gesture.overswipe.frictionByDistance; var frictionRatio = 1 / ((frictionConstant) + (Math.abs(nextProgress) * frictionByDistance)); nextProgress *= frictionRatio; } nextProgress = clamp(0, nextProgress, 1); if (this.state.transitionFromIndex != null) { this.state.pendingGestureProgress = nextProgress; } else if (this.state.pendingGestureProgress) { this.spring.setEndValue(nextProgress); } else { this.spring.setCurrentValue(nextProgress); } }, _matchGestureAction: function(eligibleGestures, gestures, gestureState) { if (!gestures || !eligibleGestures || !eligibleGestures.some) { return null; } var matchedGesture = null; eligibleGestures.some((gestureName, gestureIndex) => { var gesture = gestures[gestureName]; if (!gesture) { return; } if (gesture.overswipe == null && this._doesGestureOverswipe(gestureName)) { // cannot swipe past first or last scene without overswiping return false; } var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top'; var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top'; var startedLoc = isTravelVertical ? gestureState.y0 : gestureState.x0; var currentLoc = isTravelVertical ? gestureState.moveY : gestureState.moveX; var travelDist = isTravelVertical ? gestureState.dy : gestureState.dx; var oppositeAxisTravelDist = isTravelVertical ? gestureState.dx : gestureState.dy; var edgeHitWidth = gesture.edgeHitWidth; if (isTravelInverted) { startedLoc = -startedLoc; currentLoc = -currentLoc; travelDist = -travelDist; oppositeAxisTravelDist = -oppositeAxisTravelDist; edgeHitWidth = isTravelVertical ? -(SCREEN_HEIGHT - edgeHitWidth) : -(SCREEN_WIDTH - edgeHitWidth); } if (startedLoc === 0) { startedLoc = currentLoc; } var moveStartedInRegion = gesture.edgeHitWidth == null || startedLoc < edgeHitWidth; if (!moveStartedInRegion) { return false; } var moveTravelledFarEnough = travelDist >= gesture.gestureDetectMovement; if (!moveTravelledFarEnough) { return false; } var directionIsCorrect = Math.abs(travelDist) > Math.abs(oppositeAxisTravelDist) * gesture.directionRatio; if (directionIsCorrect) { matchedGesture = gestureName; return true; } else { this._eligibleGestures = this._eligibleGestures.slice().splice(gestureIndex, 1); } }); return matchedGesture || null; }, _transitionSceneStyle: function(fromIndex, toIndex, progress, index) { var viewAtIndex = this.refs['scene_' + index]; if (viewAtIndex === null || viewAtIndex === undefined) { return; } // Use toIndex animation when we move forwards. Use fromIndex when we move back var sceneConfigIndex = fromIndex < toIndex ? toIndex : fromIndex; var sceneConfig = this.state.sceneConfigStack[sceneConfigIndex]; // this happens for overswiping when there is no scene at toIndex if (!sceneConfig) { sceneConfig = this.state.sceneConfigStack[sceneConfigIndex - 1]; } var styleToUse = {}; var useFn = index < fromIndex || index < toIndex ? sceneConfig.animationInterpolators.out : sceneConfig.animationInterpolators.into; var directionAdjustedProgress = fromIndex < toIndex ? progress : 1 - progress; var didChange = useFn(styleToUse, directionAdjustedProgress); if (didChange) { viewAtIndex.setNativeProps({style: styleToUse}); } }, _transitionBetween: function(fromIndex, toIndex, progress) { this._transitionSceneStyle(fromIndex, toIndex, progress, fromIndex); this._transitionSceneStyle(fromIndex, toIndex, progress, toIndex); var navBar = this._navBar; if (navBar && navBar.updateProgress && toIndex >= 0 && fromIndex >= 0) { navBar.updateProgress(progress, fromIndex, toIndex); } }, _handleResponderTerminationRequest: function() { return false; }, _getDestIndexWithinBounds: function(n) { var currentIndex = this.state.presentedIndex; var destIndex = currentIndex + n; invariant( destIndex >= 0, 'Cannot jump before the first route.' ); var maxIndex = this.state.routeStack.length - 1; invariant( maxIndex >= destIndex, 'Cannot jump past the last route.' ); return destIndex; }, _jumpN: function(n) { var destIndex = this._getDestIndexWithinBounds(n); this._enableScene(destIndex); this._emitWillFocus(this.state.routeStack[destIndex]); this._transitionTo(destIndex); }, /** * Transition to an existing scene without unmounting. * @param {object} route Route to transition to. The specified route must * be in the currently mounted set of routes defined in `routeStack`. */ jumpTo: function(route) { var destIndex = this.state.routeStack.indexOf(route); invariant( destIndex !== -1, 'Cannot jump to route that is not in the route stack' ); this._jumpN(destIndex - this.state.presentedIndex); }, /** * Jump forward to the next scene in the route stack. */ jumpForward: function() { this._jumpN(1); }, /** * Jump backward without unmounting the current scene. */ jumpBack: function() { this._jumpN(-1); }, /** * Navigate forward to a new scene, squashing any scenes that you could * jump forward to. * @param {object} route Route to push into the navigator stack. */ push: function(route) { invariant(!!route, 'Must supply route to push'); var activeLength = this.state.presentedIndex + 1; var activeStack = this.state.routeStack.slice(0, activeLength); var activeAnimationConfigStack = this.state.sceneConfigStack.slice(0, activeLength); var nextStack = activeStack.concat([route]); var destIndex = nextStack.length - 1; var nextSceneConfig = this.props.configureScene(route, nextStack); var nextAnimationConfigStack = activeAnimationConfigStack.concat([nextSceneConfig]); this._emitWillFocus(nextStack[destIndex]); this.setState({ routeStack: nextStack, sceneConfigStack: nextAnimationConfigStack, }, () => { this._enableScene(destIndex); this._transitionTo(destIndex, nextSceneConfig.defaultTransitionVelocity); }); }, _popN: function(n) { if (n === 0) { return; } invariant( this.state.presentedIndex - n >= 0, 'Cannot pop below zero' ); var popIndex = this.state.presentedIndex - n; var presentedRoute = this.state.routeStack[this.state.presentedIndex]; var popSceneConfig = this.props.configureScene(presentedRoute); // using the scene config of the currently presented view this._enableScene(popIndex); this._emitWillFocus(this.state.routeStack[popIndex]); this._transitionTo( popIndex, popSceneConfig.defaultTransitionVelocity, null, // no spring jumping () => { this._cleanScenesPastIndex(popIndex); } ); }, /** * Transition back and unmount the current scene. */ pop: function() { if (this.state.transitionQueue.length) { // This is the workaround to prevent user from firing multiple `pop()` // calls that may pop the routes beyond the limit. // Because `this.state.presentedIndex` does not update until the // transition starts, we can't reliably use `this.state.presentedIndex` // to know whether we can safely keep popping the routes or not at this // moment. return; } if (this.state.presentedIndex > 0) { this._popN(1); } }, /** * Replace a scene as specified by an index. * @param {object} route Route representing the new scene to render. * @param {number} index The route in the stack that should be replaced. * If negative, it counts from the back of the stack. * @param {Function} cb Callback function when the scene has been replaced. */ replaceAtIndex: function(route, index, cb) { invariant(!!route, 'Must supply route to replace'); if (index < 0) { index += this.state.routeStack.length; } if (this.state.routeStack.length <= index) { return; } var nextRouteStack = this.state.routeStack.slice(); var nextAnimationModeStack = this.state.sceneConfigStack.slice(); nextRouteStack[index] = route; nextAnimationModeStack[index] = this.props.configureScene(route, nextRouteStack); if (index === this.state.presentedIndex) { this._emitWillFocus(route); } this.setState({ routeStack: nextRouteStack, sceneConfigStack: nextAnimationModeStack, }, () => { if (index === this.state.presentedIndex) { this._emitDidFocus(route); } cb && cb(); }); }, /** * Replace the current scene with a new route. * @param {object} route Route that replaces the current scene. */ replace: function(route) { this.replaceAtIndex(route, this.state.presentedIndex); }, /** * Replace the previous scene. * @param {object} route Route that replaces the previous scene. */ replacePrevious: function(route) { this.replaceAtIndex(route, this.state.presentedIndex - 1); }, /** * Pop to the first scene in the stack, unmounting every other scene. */ popToTop: function() { this.popToRoute(this.state.routeStack[0]); }, /** * Pop to a particular scene, as specified by its route. * All scenes after it will be unmounted. * @param {object} route Route to pop to. */ popToRoute: function(route) { var indexOfRoute = this.state.routeStack.indexOf(route); invariant( indexOfRoute !== -1, 'Calling popToRoute for a route that doesn\'t exist!' ); var numToPop = this.state.presentedIndex - indexOfRoute; this._popN(numToPop); }, /** * Replace the previous scene and pop to it. * @param {object} route Route that replaces the previous scene. */ replacePreviousAndPop: function(route) { if (this.state.routeStack.length < 2) { return; } this.replacePrevious(route); this.pop(); }, /** * Navigate to a new scene and reset route stack. * @param {object} route Route to navigate to. */ resetTo: function(route) { invariant(!!route, 'Must supply route to push'); this.replaceAtIndex(route, 0, () => { // Do not use popToRoute here, because race conditions could prevent the // route from existing at this time. Instead, just go to index 0 if (this.state.presentedIndex > 0) { this._popN(this.state.presentedIndex); } }); }, /** * Returns the current list of routes. */ getCurrentRoutes: function() { // Clone before returning to avoid caller mutating the stack return this.state.routeStack.slice(); }, _cleanScenesPastIndex: function(index) { var newStackLength = index + 1; // Remove any unneeded rendered routes. if (newStackLength < this.state.routeStack.length) { this.setState({ sceneConfigStack: this.state.sceneConfigStack.slice(0, newStackLength), routeStack: this.state.routeStack.slice(0, newStackLength), }); } }, _renderScene: function(route, i) { var disabledSceneStyle = null; var disabledScenePointerEvents = 'auto'; if (i !== this.state.presentedIndex) { disabledSceneStyle = styles.disabledScene; disabledScenePointerEvents = 'none'; } return ( <View key={'scene_' + getRouteID(route)} ref={'scene_' + i} onStartShouldSetResponderCapture={() => { return (this.state.transitionFromIndex != null) || (this.state.transitionFromIndex != null); }} pointerEvents={disabledScenePointerEvents} style={[styles.baseScene, this.props.sceneStyle, disabledSceneStyle]}> {this.props.renderScene( route, this )} </View> ); }, _renderNavigationBar: function() { let { navigationBar } = this.props; if (!navigationBar) { return null; } return React.cloneElement(navigationBar, { ref: (navBar) => { this._navBar = navBar; if (navigationBar && typeof navigationBar.ref === 'function') { navigationBar.ref(navBar); } }, navigator: this._navigationBarNavigator, navState: this.state, }); }, render: function() { var newRenderedSceneMap = new Map(); var scenes = this.state.routeStack.map((route, index) => { var renderedScene; if (this._renderedSceneMap.has(route) && index !== this.state.presentedIndex) { renderedScene = this._renderedSceneMap.get(route); } else { renderedScene = this._renderScene(route, index); } newRenderedSceneMap.set(route, renderedScene); return renderedScene; }); this._renderedSceneMap = newRenderedSceneMap; return ( <View style={[styles.container, this.props.style]}> <View style={styles.transitioner} {...this.panGesture.panHandlers} onTouchStart={this._handleTouchStart} onResponderTerminationRequest={ this._handleResponderTerminationRequest }> {scenes} </View> {this._renderNavigationBar()} </View> ); }, _getNavigationContext: function() { if (!this._navigationContext) { this._navigationContext = new NavigationContext(); } return this._navigationContext; } }); module.exports = Navigator;
frontend/src/components/recipes/edit/components/Step2/Step2.js
jf248/scrape-the-plate
import React from 'react'; import { Compose } from 'lib/react-powerplug'; import * as Enhanced from 'lib/mui-components'; import { RecordForm } from 'controllers/record-form'; import validate from './validate'; import normalize from './normalize'; import Step2Pres from './Step2Pres'; function Step2(props) { const { id, goBack, isCreate, initialValues } = props; const renderFunc = (recordForm, modals) => { const { getInputProps, resetForm, getSubmitProps } = recordForm; const { getModalProps, onOpen: onOpenModal } = modals; return ( <Step2Pres {...{ getInputProps, getModalProps, getSubmitProps, goBack, isCreate, onOpenModal, resetForm, }} /> ); }; return ( /* eslint-disable react/jsx-key */ <Compose components={[ <RecordForm {...{ resource: 'recipes', id, validate, normalize, initialValues, meta: { onSuccess: { redirect: {}, snackbar: {} } }, }} />, <Enhanced.ModalController />, ]} render={renderFunc} /> /* eslint-enable react/jsx-key */ ); } export default Step2;
app/src/js/components/settings/general.js
tahnik/devRantron
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { SETTINGS } from '../../consts/types'; import Toggle from './toggle'; import Text from './text'; import Button from './button'; import Slider from './slider'; const { remote } = require('electron'); class General extends Component { handleChange(primaryKey, secondaryKey, value = null) { this.props.changeGeneral(primaryKey, secondaryKey, value); } getSettingComponent(setting, primaryKey, secondaryKey) { switch (setting.type) { case SETTINGS.TYPE.SLIDER: { return ( <Slider setting={setting} key={secondaryKey} handleChange={(value) => { this.handleChange(primaryKey, secondaryKey, value); }} theme={this.props.theme} /> ); } case SETTINGS.TYPE.TOGGLE: { return ( <Toggle setting={setting} key={secondaryKey} handleChange={() => { this.handleChange(primaryKey, secondaryKey, !setting.value); }} theme={this.props.theme} /> ); } case SETTINGS.TYPE.TEXT: { return ( <Text key={secondaryKey} setting={setting} theme={this.props.theme} handleChange={(value) => { this.handleChange(primaryKey, secondaryKey, value); }} /> ); } case SETTINGS.TYPE.BUTTON: { return ( <Button key={secondaryKey} setting={setting} handleChange={() => { this.handleChange(primaryKey, secondaryKey); }} theme={this.props.theme} /> ); } default: return <div />; } } getSettings() { const { general, theme } = this.props; const settings = []; Object.keys(general).forEach((key) => { const setting = general[key]; if (setting.options) { const subSettings = []; const Header = <div className="header">{setting.title}</div>; Object.keys(setting.options).forEach((optionKey) => { const settingComponent = this.getSettingComponent( setting.options[optionKey], key, optionKey, ); subSettings.push(settingComponent); }); /* eslint-disable */ settings.push( <div className="multi_settings" style={{ backgroundColor: theme.item_card.backgroundColor, color: theme.item_card.color, }} key={key} > { Header } <div className="options"> { subSettings.map(s => s) } </div> </div>, ); } else { const component = this.getSettingComponent(setting, key); settings.push(<div className="single_settings" key={key} style={{ backgroundColor: theme.item_card.backgroundColor, color: theme.item_card.color, }} > { component } </div>); /* eslint-enable */ } }); return settings; } render() { return ( <div className="general_container"> { this.getSettings().map(s => s) } <div className="version_number" style={{ color: this.props.theme.item_card.color }} > v{remote.app.getVersion()} </div> </div> ); } } General.propTypes = { general: PropTypes.object.isRequired, changeGeneral: PropTypes.func.isRequired, theme: PropTypes.object.isRequired, }; export default General;
src/containers/Activation.js
hanyulo/twreporter-react
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup' import LoadingSpinner from '../components/Spinner' import React from 'react' import get from 'lodash/get' import styled from 'styled-components' import withLayout from '../helpers/with-layout' import withRouter from 'react-router/lib/withRouter' import { ActivePage, PageContainer } from '@twreporter/registration' const _ = { get } const StyledCSSTransitionGroup = styled(CSSTransitionGroup)` .spinner-leave { opacity: 1; } .spinner-leave.spinner-leave-active { opacity: 0; transition: opacity 400ms linear 1600ms; } ` const LoadingCover = styled.div` position: fixed; height: 100vh; width: 100%; top: 0; left: 0; z-index: 1999; background-color: white; div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } ` class Activation extends React.PureComponent { constructor(props) { super(props) this.state = { authError: false } this.handleError = this._handleError.bind(this) } _handleError() { this.setState({ authError: true }) } render() { const { location } = this.props const destination = _.get(location, 'query.destination', '/') return ( <PageContainer> <div> { this.state.authError ? null : <StyledCSSTransitionGroup transitionName="spinner" transitionEnter={false} transitionLeaveTimeout={2000} > <LoadingCover key="loader"> <LoadingSpinner alt="首頁載入中" /> </LoadingCover> </StyledCSSTransitionGroup> } <ActivePage destination={destination} errorOccurs={this.handleError} {...this.props} /> </div> </PageContainer> ) } } export default withRouter(withLayout(Activation))
src/rsg-components/Styled/Styled.js
bluetidepro/react-styleguidist
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import createStyleSheet from '../../styles/createStyleSheet'; export default styles => WrappedComponent => { const componentName = WrappedComponent.name.replace(/Renderer$/, ''); return class extends Component { static displayName = `Styled(${componentName})`; static contextTypes = { config: PropTypes.object, }; constructor(props, context) { super(props, context); this.sheet = createStyleSheet(styles, context.config || {}, componentName); this.sheet.update(props).attach(); } componentDidUpdate(nextProps) { this.sheet.update(nextProps); } render() { return <WrappedComponent {...this.props} classes={this.sheet.classes} />; } }; };
fields/types/geopoint/GeoPointColumn.js
snowkeeper/keystone
import React from 'react'; import ItemsTableCell from '../../components/ItemsTableCell'; import ItemsTableValue from '../../components/ItemsTableValue'; var GeoPointColumn = React.createClass({ displayName: 'GeoPointColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, }, renderValue () { const value = this.props.data.fields[this.props.col.path]; if (!value || !value.length) return null; const formattedValue = `${value[1]}, ${value[0]}`; const formattedTitle = `Lat: ${value[1]} Lng: ${value[0]}`; return ( <ItemsTableValue title={formattedTitle} field={this.props.col.type}> {formattedValue} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = GeoPointColumn;
js/components/fab/multiple.js
bengaara/simbapp
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Platform, View } from 'react-native'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Fab, Button, IconNB, Left, Right, Body, Icon } from 'native-base'; import { Actions } from 'react-native-router-flux'; import { openDrawer } from '../../actions/drawer'; import styles from './styles'; const { popRoute, } = actions; class MultipleFab extends Component { static propTypes = { popRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } constructor(props) { super(props); this.state = { active: false, active1: false, active2: false, active3: false, }; } popRoute() { this.props.popRoute(this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={() => Actions.pop()}> <Icon name="arrow-back" /> </Button> </Left> <Body> <Title>Multiple FABs</Title> </Body> <Right /> </Header> <View style={{ flex: 1 }}> <Fab active={this.state.active} direction="up" containerStyle={{ }} style={{ backgroundColor: '#5067FF' }} position="bottomRight" onPress={() => this.setState({ active: !this.state.active })} > <IconNB name="md-share" /> <Button style={{ backgroundColor: '#34A34F' }}> <IconNB name="logo-whatsapp" /> </Button> <Button style={{ backgroundColor: '#3B5998' }}> <IconNB name="logo-facebook" /> </Button> <Button disabled style={{ backgroundColor: '#DD5144' }}> <IconNB name="ios-mail" /> </Button> </Fab> <Fab active={this.state.active1} direction="left" containerStyle={{ }} style={{ backgroundColor: '#5067FF' }} position="topRight" onPress={() => this.setState({ active1: !this.state.active1 })} > <IconNB name="md-share" /> <Button style={{ backgroundColor: '#34A34F' }}> <IconNB name="logo-whatsapp" /> </Button> <Button style={{ backgroundColor: '#3B5998' }}> <IconNB name="logo-facebook" /> </Button> <Button disabled style={{ backgroundColor: '#DD5144' }}> <IconNB name="ios-mail" /> </Button> </Fab> <Fab active={this.state.active2} direction="down" containerStyle={{ }} style={{ backgroundColor: '#5067FF' }} position="topLeft" onPress={() => this.setState({ active2: !this.state.active2 })} > <IconNB name="md-share" /> <Button style={{ backgroundColor: '#34A34F' }}> <IconNB name="logo-whatsapp" /> </Button> <Button style={{ backgroundColor: '#3B5998' }}> <IconNB name="logo-facebook" /> </Button> <Button disabled style={{ backgroundColor: '#DD5144' }}> <IconNB name="ios-mail" /> </Button> </Fab> <Fab active={this.state.active3} direction="right" containerStyle={{ }} style={{ backgroundColor: '#5067FF' }} position="bottomLeft" onPress={() => this.setState({ active3: !this.state.active3 })} > <IconNB name="md-share" /> <Button style={{ backgroundColor: '#34A34F' }}> <IconNB name="logo-whatsapp" /> </Button> <Button style={{ backgroundColor: '#3B5998' }}> <IconNB name="logo-facebook" /> </Button> <Button disabled style={{ backgroundColor: '#DD5144' }}> <IconNB name="ios-mail" /> </Button> </Fab> </View> </Container> ); } } function bindAction(dispatch) { return { popRoute: key => dispatch(popRoute(key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(MultipleFab);
services/ui/.storybook/decorators/AnonymousUser.js
amazeeio/lagoon
import React from 'react'; import { AuthContext } from 'lib/Authenticator'; const noUser = { apiToken: 'dummy-value-not-used-but-evals-to-true', authenticated: false, provider: 'local-auth', providerData: {}, user: {}, }; export default storyFn => ( <AuthContext.Provider value={noUser}> {storyFn()} </AuthContext.Provider> );
apps/marketplace/components/BuyerDashboard/BuyerDashboardHelp.js
AusDTO/dto-digitalmarketplace-frontend
import React from 'react' const BuyerDashboardHelp = () => ( <div className="row"> <div className="col-xs-12"> <span /> <h2 className="au-display-lg">Need a hand?</h2> <p> <a href="/buyers-guide" target="_blank" rel="noopener noreferrer"> Read the buyers guide </a>{' '} or <a href="/contact-us">contact us</a> - we can help you write your opportunity. </p> </div> </div> ) export default BuyerDashboardHelp
jenkins-design-language/src/js/components/material-ui/svg-icons/action/chrome-reader-mode.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionChromeReaderMode = (props) => ( <SvgIcon {...props}> <path d="M13 12h7v1.5h-7zm0-2.5h7V11h-7zm0 5h7V16h-7zM21 4H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 15h-9V6h9v13z"/> </SvgIcon> ); ActionChromeReaderMode.displayName = 'ActionChromeReaderMode'; ActionChromeReaderMode.muiName = 'SvgIcon'; export default ActionChromeReaderMode;
src/Tabs.js
mmarcant/react-bootstrap
import React from 'react'; import requiredForA11y from 'react-prop-types/lib/isRequiredForA11y'; import uncontrollable from 'uncontrollable'; import Nav from './Nav'; import NavItem from './NavItem'; import UncontrolledTabContainer from './TabContainer'; import TabContent from './TabContent'; import { bsClass as setBsClass } from './utils/bootstrapUtils'; import ValidComponentChildren from './utils/ValidComponentChildren'; const TabContainer = UncontrolledTabContainer.ControlledComponent; const propTypes = { /** * Mark the Tab with a matching `eventKey` as active. * * @controllable onSelect */ activeKey: React.PropTypes.any, /** * Navigation style */ bsStyle: React.PropTypes.oneOf(['tabs', 'pills']), animation: React.PropTypes.bool, id: requiredForA11y(React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number, ])), /** * Callback fired when a Tab is selected. * * ```js * function ( * Any eventKey, * SyntheticEvent event? * ) * ``` * * @controllable activeKey */ onSelect: React.PropTypes.func, /** * Unmount tabs (remove it from the DOM) when it is no longer visible */ unmountOnExit: React.PropTypes.bool, }; const defaultProps = { bsStyle: 'tabs', animation: true, unmountOnExit: false }; function getDefaultActiveKey(children) { let defaultActiveKey; ValidComponentChildren.forEach(children, child => { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } class Tabs extends React.Component { renderTab(child) { const { title, eventKey, disabled, tabClassName } = child.props; if (title == null) { return null; } return ( <NavItem eventKey={eventKey} disabled={disabled} className={tabClassName} > {title} </NavItem> ); } render() { const { id, onSelect, animation, unmountOnExit, bsClass, className, style, children, activeKey = getDefaultActiveKey(children), ...props } = this.props; return ( <TabContainer id={id} activeKey={activeKey} onSelect={onSelect} className={className} style={style} > <div> <Nav {...props} role="tablist" > {ValidComponentChildren.map(children, this.renderTab)} </Nav> <TabContent bsClass={bsClass} animation={animation} unmountOnExit={unmountOnExit} > {children} </TabContent> </div> </TabContainer> ); } } Tabs.propTypes = propTypes; Tabs.defaultProps = defaultProps; setBsClass('tab', Tabs); export default uncontrollable(Tabs, { activeKey: 'onSelect' });
src/index.js
rawild/healthcare4allNY
import React from 'react'; import ReactDOM from 'react-dom'; import App from './js/components/App'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; import { AppContainer } from 'react-hot-loader' import { Provider } from 'react-redux' import { createStore } from 'redux' import todoApp from './js/redux' let store = createStore(todoApp) const render = () => { ReactDOM.render( <AppContainer> <Provider store={store}> <App /> </Provider> </AppContainer>, document.getElementById('root')) } render() registerServiceWorker();
yycomponent/modal/Modal.js
77ircloud/yycomponent
import React from 'react'; import { Modal as _Modal } from 'antd'; class Modal extends React.Component{ constructor(props){ super(props); } render(){ return (<_Modal {...this.props}/>); } } Modal.info = _Modal.info; Modal.success = _Modal.success; Modal.error = _Modal.error; Modal.warning = _Modal.warning; Modal.confirm = _Modal.confirm; export default Modal
src/containers/DevTools.js
abkfenris/inferno-react
import React from 'react' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' > <LogMonitor /> </DockMonitor> )
pollard/components/SearchSongConnector.js
spencerliechty/pollard
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { addSong, artistChange, clearSearchSongInputs, searchSong, titleChange, setError, clearError, } from '../actions/Actions.js'; import SearchSongDisplay from './SearchSongDisplay'; class SearchSongConnector extends Component { render() { return ( <SearchSongDisplay {...this.props} /> ); } } function mapStateToProps({state}) { return { lastSearchedSong: state.getIn(['view', 'search']), }; } function mapDispatchToProps(dispatch) { return { addSong: bindActionCreators(addSong, dispatch), artistChange: bindActionCreators(artistChange, dispatch), clearSearchSongInputs: bindActionCreators(clearSearchSongInputs, dispatch), searchSong: bindActionCreators(searchSong, dispatch), titleChange: bindActionCreators(titleChange, dispatch), setError: bindActionCreators(setError, dispatch), clearError: bindActionCreators(clearError, dispatch), }; } // Wrap the component to inject dispatch and state into it export default connect(mapStateToProps, mapDispatchToProps)(SearchSongConnector);
components/carousel/carouselPage.js
Travix-International/travix-ui-kit
import PropTypes from 'prop-types'; import React from 'react'; export default function CarouselPage({ images, current }) { return ( <div className="ui-carousel-page"> {current + 1} / {images.length} </div> ); } CarouselPage.propTypes = { images: PropTypes.array.isRequired, current: PropTypes.number.isRequired, };
src/components/Grid/Grid.js
HichamBenjelloun/react-examples
import React from 'react'; import Square from './Square'; import './Grid.css'; const Grid = ({ size, }) => { const [height, width] = size.split('x').map(el => Number(el)); if (!Number.isInteger(height) || !Number.isInteger(width)) { return ( <span className="error"> <span role="img" aria-label="warning">⚠</span>️ Try again with positive integers. </span> ); } if (height <= 0 || width <= 0) { return ( <span className="error"> <span role="img" aria-label="warning">⚠</span>️ Elements have been painted in another dimension. Try again with positive integers. </span> ); } if (height * width > 10_000) { return ( <span className="error"> ⚠️ Sorry, there are too many elements to paint. Try again with a smaller size. </span> ); } const squareNodes = [...new Array(height * width)].map( (_, index) => { const rowIndex = ~~(index / width); const columnIndex = index % width; return ( <Square key={`${rowIndex},${columnIndex}`} rowIndex={rowIndex} columnIndex={columnIndex} /> ) } ); const gridStyle = { display: 'grid', gridTemplateColumns: `repeat(${width}, 50px)`, gridTemplateRows: `repeat(${height}, 50px)`, gridGap: '5px', }; return ( <div className="Grid" style={gridStyle} > {squareNodes} </div> ); }; export default Grid;
src/_wlk/icons/Instagram.js
welovekpop/uwave-web-welovekpop.club
import React from 'react'; import SvgIcon from '@material-ui/core/SvgIcon'; // Instagram icon from the Font-Awesome icon font by Dave Gandy: // http://fontawesome.io/icon/instagram/ // https://github.com/FortAwesome/Font-Awesome /* eslint-disable max-len */ const InstagramIcon = props => ( <SvgIcon viewBox="0 0 1792 1792" {...props}> <path d="M1490 1426v-648h-135q20 63 20 131 0 126-64 232.5t-174 168.5-240 62q-197 0-337-135.5t-140-327.5q0-68 20-131h-141v648q0 26 17.5 43.5t43.5 17.5h1069q25 0 43-17.5t18-43.5zm-284-533q0-124-90.5-211.5t-218.5-87.5q-127 0-217.5 87.5t-90.5 211.5 90.5 211.5 217.5 87.5q128 0 218.5-87.5t90.5-211.5zm284-360v-165q0-28-20-48.5t-49-20.5h-174q-29 0-49 20.5t-20 48.5v165q0 29 20 49t49 20h174q29 0 49-20t20-49zm174-208v1142q0 81-58 139t-139 58h-1142q-81 0-139-58t-58-139v-1142q0-81 58-139t139-58h1142q81 0 139 58t58 139z" /> </SvgIcon> ); /* eslint-enable max-len */ export default InstagramIcon;
src/svg-icons/content/reply.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentReply = (props) => ( <SvgIcon {...props}> <path d="M10 9V5l-7 7 7 7v-4.1c5 0 8.5 1.6 11 5.1-1-5-4-10-11-11z"/> </SvgIcon> ); ContentReply = pure(ContentReply); ContentReply.displayName = 'ContentReply'; ContentReply.muiName = 'SvgIcon'; export default ContentReply;
app/javascript/mastodon/features/compose/components/upload_form.js
ambition-vietnam/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import UploadProgressContainer from '../containers/upload_progress_container'; import ImmutablePureComponent from 'react-immutable-pure-component'; import UploadContainer from '../containers/upload_container'; export default class UploadForm extends ImmutablePureComponent { static propTypes = { mediaIds: ImmutablePropTypes.list.isRequired, }; render () { const { mediaIds } = this.props; return ( <div className='compose-form__upload-wrapper'> <UploadProgressContainer /> <div className='compose-form__uploads-wrapper'> {mediaIds.map(id => ( <UploadContainer id={id} key={id} /> ))} </div> </div> ); } }
src/helpers/universalRouter.js
clkao/react-redux-universal-hot-example
import qs from 'query-string'; import React from 'react'; import {match, RoutingContext} from 'react-router'; import createRoutes from '../routes'; import {Provider} from 'react-redux'; const getFetchData = (component = {}) => { return component.WrappedComponent ? getFetchData(component.WrappedComponent) : component.fetchData; }; const fetchDataForContainers = (containers, store, params, query) => { const promises = containers .filter((component) => getFetchData(component)) // only look at ones with a static fetchData() .map(getFetchData) // pull out fetch data methods .map(fetchData => fetchData(store, params, query || {})); // call fetch data methods and save promises return Promise.all(promises); }; export default function universalRouter(location, history, store, preload) { const routes = createRoutes(); return new Promise((resolve, reject) => { match({routes, history, location}, (error, redirectLocation, renderProps) => { if (error) { return reject(error); } if (redirectLocation) { return resolve({ redirectLocation }); } if (history) { // only on client side renderProps.history = history; } function resolveWithComponent() { const component = ( <Provider store={store} key="provider"> <RoutingContext {...renderProps}/> </Provider> ); resolve({ component }); } if (preload) { fetchDataForContainers( renderProps.components, store, renderProps.params, qs.parse(renderProps.location.search) ) .then(() => resolveWithComponent(), err => reject(err)); } else { resolveWithComponent(); } }); }); }
packages/material-ui-icons/src/Folder.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Folder = props => <SvgIcon {...props}> <path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z" /> </SvgIcon>; Folder = pure(Folder); Folder.muiName = 'SvgIcon'; export default Folder;
packages/react-error-overlay/src/containers/StackTrace.js
brysgo/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { Component } from 'react'; import StackFrame from './StackFrame'; import Collapsible from '../components/Collapsible'; import { isInternalFile } from '../utils/isInternalFile'; import { isBultinErrorName } from '../utils/isBultinErrorName'; import type { StackFrame as StackFrameType } from '../utils/stack-frame'; import type { ErrorLocation } from '../utils/parseCompileError'; const traceStyle = { fontSize: '1em', flex: '0 1 auto', minHeight: '0px', overflow: 'auto', }; type Props = {| stackFrames: StackFrameType[], errorName: string, contextSize: number, editorHandler: (errorLoc: ErrorLocation) => void, |}; class StackTrace extends Component<Props> { renderFrames() { const { stackFrames, errorName, contextSize, editorHandler } = this.props; const renderedFrames = []; let hasReachedAppCode = false, currentBundle = [], bundleCount = 0; stackFrames.forEach((frame, index) => { const { fileName, _originalFileName: sourceFileName } = frame; const isInternalUrl = isInternalFile(sourceFileName, fileName); const isThrownIntentionally = !isBultinErrorName(errorName); const shouldCollapse = isInternalUrl && (isThrownIntentionally || hasReachedAppCode); if (!isInternalUrl) { hasReachedAppCode = true; } const frameEle = ( <StackFrame key={'frame-' + index} frame={frame} contextSize={contextSize} critical={index === 0} showCode={!shouldCollapse} editorHandler={editorHandler} /> ); const lastElement = index === stackFrames.length - 1; if (shouldCollapse) { currentBundle.push(frameEle); } if (!shouldCollapse || lastElement) { if (currentBundle.length === 1) { renderedFrames.push(currentBundle[0]); } else if (currentBundle.length > 1) { bundleCount++; renderedFrames.push( <Collapsible key={'bundle-' + bundleCount}> {currentBundle} </Collapsible> ); } currentBundle = []; } if (!shouldCollapse) { renderedFrames.push(frameEle); } }); return renderedFrames; } render() { return <div style={traceStyle}>{this.renderFrames()}</div>; } } export default StackTrace;
app/javascript/mastodon/features/ui/components/column_subheading.js
alarky/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;
app/javascript/mastodon/components/video_player.js
Toootim/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { isIOS } from '../is_mobile'; const messages = defineMessages({ toggle_sound: { id: 'video_player.toggle_sound', defaultMessage: 'Toggle sound' }, toggle_visible: { id: 'video_player.toggle_visible', defaultMessage: 'Toggle visibility' }, expand_video: { id: 'video_player.expand', defaultMessage: 'Expand video' }, }); @injectIntl export default class VideoPlayer extends React.PureComponent { static propTypes = { media: ImmutablePropTypes.map.isRequired, width: PropTypes.number, height: PropTypes.number, sensitive: PropTypes.bool, intl: PropTypes.object.isRequired, autoplay: PropTypes.bool, onOpenVideo: PropTypes.func.isRequired, }; static defaultProps = { width: 239, height: 110, }; state = { visible: !this.props.sensitive, preview: true, muted: true, hasAudio: true, videoError: false, }; handleClick = () => { this.setState({ muted: !this.state.muted }); } handleVideoClick = (e) => { e.stopPropagation(); const node = this.video; if (node.paused) { node.play(); } else { node.pause(); } } handleOpen = () => { this.setState({ preview: !this.state.preview }); } handleVisibility = () => { this.setState({ visible: !this.state.visible, preview: true, }); } handleExpand = () => { this.video.pause(); this.props.onOpenVideo(this.props.media, this.video.currentTime); } setRef = (c) => { this.video = c; } handleLoadedData = () => { if (('WebkitAppearance' in document.documentElement.style && this.video.audioTracks.length === 0) || this.video.mozHasAudio === false) { this.setState({ hasAudio: false }); } } handleVideoError = () => { this.setState({ videoError: true }); } componentDidMount () { if (!this.video) { return; } this.video.addEventListener('loadeddata', this.handleLoadedData); this.video.addEventListener('error', this.handleVideoError); } componentDidUpdate () { if (!this.video) { return; } this.video.addEventListener('loadeddata', this.handleLoadedData); this.video.addEventListener('error', this.handleVideoError); } componentWillUnmount () { if (!this.video) { return; } this.video.removeEventListener('loadeddata', this.handleLoadedData); this.video.removeEventListener('error', this.handleVideoError); } render () { const { media, intl, width, height, sensitive, autoplay } = this.props; let spoilerButton = ( <div className={`status__video-player-spoiler ${this.state.visible ? 'status__video-player-spoiler--visible' : ''}`}> <IconButton overlay title={intl.formatMessage(messages.toggle_visible)} icon={this.state.visible ? 'eye' : 'eye-slash'} onClick={this.handleVisibility} /> </div> ); let expandButton = ( <div className='status__video-player-expand'> <IconButton overlay title={intl.formatMessage(messages.expand_video)} icon='expand' onClick={this.handleExpand} /> </div> ); let muteButton = ''; if (this.state.hasAudio) { muteButton = ( <div className='status__video-player-mute'> <IconButton overlay title={intl.formatMessage(messages.toggle_sound)} icon={this.state.muted ? 'volume-off' : 'volume-up'} onClick={this.handleClick} /> </div> ); } if (!this.state.visible) { if (sensitive) { return ( <div role='button' tabIndex='0' style={{ width: `${width}px`, height: `${height}px` }} className='media-spoiler' onClick={this.handleVisibility}> {spoilerButton} <span className='media-spoiler__warning'><FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /></span> <span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </div> ); } else { return ( <div role='button' tabIndex='0' style={{ width: `${width}px`, height: `${height}px` }} className='media-spoiler' onClick={this.handleVisibility}> {spoilerButton} <span className='media-spoiler__warning'><FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' /></span> <span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span> </div> ); } } if (this.state.preview && !autoplay) { return ( <div role='button' tabIndex='0' className='media-spoiler-video' style={{ width: `${width}px`, height: `${height}px`, backgroundImage: `url(${media.get('preview_url')})` }} onClick={this.handleOpen}> {spoilerButton} <div className='media-spoiler-video-play-icon'><i className='fa fa-play' /></div> </div> ); } if (this.state.videoError) { return ( <div style={{ width: `${width}px`, height: `${height}px` }} className='video-error-cover' > <span className='media-spoiler__warning'><FormattedMessage id='video_player.video_error' defaultMessage='Video could not be played' /></span> </div> ); } return ( <div className='status__video-player' style={{ width: `${width}px`, height: `${height}px` }}> {spoilerButton} {muteButton} {expandButton} <video className='status__video-player-video' role='button' tabIndex='0' ref={this.setRef} src={media.get('url')} autoPlay={!isIOS()} loop muted={this.state.muted} onClick={this.handleVideoClick} /> </div> ); } }
src/components/Lobby/Tournament/Match/index.js
socialgorithm/ultimate-ttt-web
import React from 'react'; import classNames from 'classnames'; import { Grid, Progress } from 'semantic-ui-react'; import './index.scss'; export default (props) => { const { match, totalGames } = props; const stats = match.stats; const colorA = stats.wins[0] > stats.wins[1] ? 'green' : null; const colorB = stats.wins[1] > stats.wins[0] ? 'green' : null; let progress = null; let gridStyle = null; if (props.displayProgress) { gridStyle = { borderBottom: '1px solid #efefef', }; progress = ( <Progress value={ match.stats.gamesCompleted } total={ totalGames } progress='ratio' indicating /> ); } return ( <div className={ classNames('match', { 'small': props.small }) }> <Grid columns={ 2 } textAlign='center' verticalAlign='middle' style={ gridStyle }> <Grid.Column color={ colorA }> <h2>{ match.players[0].token }</h2> <h3>{ stats.wins[0] }</h3> </Grid.Column> <Grid.Column color={ colorB }> <h2>{ match.players[1].token }</h2> <h3>{ stats.wins[1] }</h3> </Grid.Column> </Grid> { progress } </div> ); };
src/@ui/DashboardSubheader/index.js
NewSpring/Apollos
import React from 'react'; import { View } from 'react-native'; import { compose } from 'recompose'; import PropTypes from 'prop-types'; import { H6, H7 } from '@ui/typography'; import styled from '@ui/styled'; import Button from '@ui/Button'; import { enhancer as mediaQuery } from '@ui/MediaQuery'; const Row = compose( mediaQuery(({ md }) => ({ minWidth: md }), styled(({ theme }) => ({ paddingHorizontal: theme.sizing.baseUnit, }))), styled(({ theme }) => ({ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: theme.sizing.baseUnit / 2, marginTop: theme.sizing.baseUnit * 2, marginBottom: theme.sizing.baseUnit / 2, })), )(View); const StyledH6 = styled(({ theme }) => ({ color: theme.colors.darkTertiary, }))(H6); const StyledH7 = styled(({ theme }) => ({ color: theme.colors.darkTertiary, }))(H7); const StyledButton = styled(({ theme }) => ({ borderColor: theme.colors.darkTertiary, height: theme.sizing.baseUnit * 1.5, paddingHorizontal: theme.sizing.baseUnit * 0.75, borderWidth: 1, }))(Button); function DashboardSubheader(props) { return ( <Row> <StyledH6>{props.text}</StyledH6> <StyledButton bordered pill onPress={props.onPress} > <StyledH7>{props.buttonText}</StyledH7> </StyledButton> </Row> ); } DashboardSubheader.propTypes = { text: PropTypes.string, buttonText: PropTypes.string, onPress: PropTypes.func, }; DashboardSubheader.defaultProps = { text: '', buttonText: '', onPress() {}, }; export default DashboardSubheader;
src/routes/login/Login.js
takahashik/todo-app
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Login.css'; class Login 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 className={s.lead}>Log in with your username or company email address.</p> <div className={s.formGroup}> <a className={s.facebook} href="/login/facebook"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d="M22 16l1-5h-5V7c0-1.544.784-2 3-2h2V0h-4c-4.072 0-7 2.435-7 7v4H7v5h5v14h6V16h4z" /> </svg> <span>Log in with Facebook</span> </a> </div> <div className={s.formGroup}> <a className={s.google} href="/login/google"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d={'M30 13h-4V9h-2v4h-4v2h4v4h2v-4h4m-15 2s-2-1.15-2-2c0 0-.5-1.828 1-3 ' + '1.537-1.2 3-3.035 3-5 0-2.336-1.046-5-3-6h3l2.387-1H10C5.835 0 2 3.345 2 7c0 ' + '3.735 2.85 6.56 7.086 6.56.295 0 .58-.006.86-.025-.273.526-.47 1.12-.47 1.735 ' + '0 1.037.817 2.042 1.523 2.73H9c-5.16 0-9 2.593-9 6 0 3.355 4.87 6 10.03 6 5.882 ' + '0 9.97-3 9.97-7 0-2.69-2.545-4.264-5-6zm-4-4c-2.395 0-5.587-2.857-6-6C4.587 ' + '3.856 6.607.93 9 1c2.394.07 4.603 2.908 5.017 6.052C14.43 10.195 13 13 11 ' + '13zm-1 15c-3.566 0-7-1.29-7-4 0-2.658 3.434-5.038 7-5 .832.01 2 0 2 0 1 0 ' + '2.88.88 4 2 1 1 1 2.674 1 3 0 3-1.986 4-7 4z'} /> </svg> <span>Log in with Google</span> </a> </div> <div className={s.formGroup}> <a className={s.twitter} href="/login/twitter"> <svg className={s.icon} width="30" height="30" viewBox="0 0 30 30" xmlns="http://www.w3.org/2000/svg" > <path d={'M30 6.708c-1.105.49-2.756 1.143-4 1.292 1.273-.762 2.54-2.56 ' + '3-4-.97.577-2.087 1.355-3.227 1.773L25 5c-1.12-1.197-2.23-2-4-2-3.398 0-6 ' + '2.602-6 6 0 .4.047.7.11.956L15 10C9 10 5.034 8.724 2 5c-.53.908-1 1.872-1 ' + '3 0 2.136 1.348 3.894 3 5-1.01-.033-2.17-.542-3-1 0 2.98 4.186 6.432 7 7-1 ' + '1-4.623.074-5 0 .784 2.447 3.31 3.95 6 4-2.105 1.648-4.647 2.51-7.53 2.51-.5 ' + '0-.988-.03-1.47-.084C2.723 27.17 6.523 28 10 28c11.322 0 17-8.867 17-17 ' + '0-.268.008-.736 0-1 1.2-.868 2.172-2.058 3-3.292z'} /> </svg> <span>Log in with Twitter</span> </a> </div> <strong className={s.lineThrough}>OR</strong> <form method="post"> <div className={s.formGroup}> <label className={s.label} htmlFor="usernameOrEmail"> Username or email address: </label> <input className={s.input} id="usernameOrEmail" type="text" name="usernameOrEmail" autoFocus // eslint-disable-line jsx-a11y/no-autofocus /> </div> <div className={s.formGroup}> <label className={s.label} htmlFor="password"> Password: </label> <input className={s.input} id="password" type="password" name="password" /> </div> <div className={s.formGroup}> <button className={s.button} type="submit"> Log in </button> </div> </form> </div> </div> ); } } export default withStyles(s)(Login);
thinking-in-react/step-2-part-3.js
hackerrdave/nodeschool
import React from 'react'; export const ProductCategoryRow = React.createClass({ render() { return ( <tr> <th colSpan={2}>{this.props.category}</th> </tr> ); } }); export const ProductRow = React.createClass({ render() { const product = this.props.product; const style = { color: product.stocked ? null : 'red' }; return ( <tr> <td style={style}>{product.name}</td> <td>{product.price}</td> </tr> ); } }); export const ProductTable = React.createClass({ render() { const products = this.props.products; const rows = []; let currentCategory; products.forEach((product) => { if (product.category !== currentCategory) { currentCategory = product.category; rows.push(( <ProductCategoryRow key={currentCategory} category={currentCategory}/> )); } rows.push(( <ProductRow key={product.name} product={product}/> )); }); return ( <table> <thead> <tr> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> {rows} </tbody> </table> ); } }); export const SearchBar = React.createClass({ render() { return ( <form> <input type="search" placeholder="Search..."/> <label> <input type="checkbox"/> Only show products in stock </label> </form> ); } }); export const FilterableProductTable = React.createClass({ render() { const products = this.props.products; return ( <div> <SearchBar/> <ProductTable products={products}/> </div> ); } });
src/title/TitlePrivate.js
saketkumar95/zulip-mobile
/* @flow */ import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { Avatar } from '../common'; const styles = StyleSheet.create({ wrapper: { flexDirection: 'row', alignItems: 'center', }, title: { fontSize: 16, paddingLeft: 4, }, }); export default class TitlePrivate extends React.PureComponent { render() { const { narrow, realm, users, color } = this.props; const { fullName, avatarUrl } = users.find(x => x.email === narrow[0].operand) || {}; return ( <View style={styles.wrapper}> <Avatar size={24} name={fullName} avatarUrl={avatarUrl} realm={realm} /> <Text style={[styles.title, { color }]}> {fullName} </Text> </View> ); } }
client.js
jhen0409/isomorphic-react-flux-boilerplate
'use strict'; require('!style!raw!sass!./sass/style.scss'); import React from 'react'; import Router from 'react-router'; import app from './scripts/app'; import navigateAction from './scripts/actions/navigate'; const HistoryLocation = Router.HistoryLocation; const dehydratedState = window.App; window.React = React; function RenderApp(context, Handler){ var mountNode = document.getElementById('app'); var Component = React.createFactory(Handler); React.render(Component({context:context.getComponentContext()}), mountNode); } app.rehydrate(dehydratedState, function(err, context) { if (err) { throw err; } window.context = context; var firstRender = true; Router.run(app.getComponent(), HistoryLocation, function(Handler, state) { if (firstRender) { RenderApp(context, Handler); firstRender = false; } else { context.executeAction(navigateAction, state, function() { RenderApp(context, Handler); }); } }); });
packages/lore-react-forms-bootstrap/src/schemas/actions.js
lore/lore-forms
import React from 'react'; import { FormSection, PropBarrier } from 'lore-react-forms'; export default function(form) { return (actions) => { return ( <FormSection style={{ padding: '0 20px 20px 20px', marginTop: '20px', position: 'relative', textAlign: 'right' }}> <PropBarrier> {actions} </PropBarrier> </FormSection> ); }; }
pages/start.js
zapier/formatic
import React from 'react'; import 'isomorphic-unfetch'; import Formatic from '@/src/formatic'; import Page from '@/docs/components/Page'; import Section from '@/docs/components/Section'; import SubSection from '@/docs/components/SubSection'; import CodeBlock from '@/docs/components/CodeBlock'; import Example from '@/docs/components/Example'; import Sections from '@/docs/components/Sections'; import { loadSnippets } from '@/docs/utils'; const basicExampleFields = [ { type: 'single-line-string', key: 'firstName', label: 'First Name', }, { type: 'single-line-string', key: 'lastName', label: 'Last Name', }, ]; const basicExampleValue = { firstName: 'Joe', lastName: 'Foo', }; const Start = props => ( <Page pageKey="start"> <Sections> <Section title="Install"> <SubSection title="npm"> <CodeBlock language="bash">{`npm install formatic --save`}</CodeBlock> </SubSection> <SubSection title="yarn"> <CodeBlock language="bash">{`yarn add formatic`}</CodeBlock> </SubSection> </Section> <Section title="Basic Usage"> <p> Basic usage of Formatic is pretty simple. Formatic is just a React component. Pass in the fields as props to render your fields. </p> <CodeBlock language="javascript"> {props.snippets['basic-example']} </CodeBlock> <p>That example gives us this form:</p> <Example> <Formatic fields={basicExampleFields} /> </Example> <p>You can also pass a value for the fields.</p> <CodeBlock language="javascript"> {props.snippets['basic-example-with-value']} </CodeBlock> <p> Used this way, Formatic is a controlled component. So if you try to edit the values in this form, you'll notice you can't. </p> <Example> <Formatic fields={basicExampleFields} value={basicExampleValue} /> </Example> <p> That's because we're always setting it to a fixed value. We need to use the `onChange` handler to keep the value in sync with the changes, just like with an `input` element. </p> <CodeBlock language="javascript"> {props.snippets['basic-example-with-on-change']} </CodeBlock> <p> Now above, when we didn't supply a value, we were using Formatic as an uncontrolled component. You can also pass a `defaultValue` and use Formatic as an uncontrolled component. </p> <CodeBlock language="javascript"> {props.snippets['basic-example-uncontrolled']} </CodeBlock> </Section> </Sections> </Page> ); const snippetKeys = [ 'basic-example', 'basic-example-with-value', 'basic-example-with-on-change', 'basic-example-uncontrolled', ]; Start.getInitialProps = async () => { return { snippets: loadSnippets(snippetKeys) }; }; export default Start;
app/javascript/mastodon/features/keyboard_shortcuts/index.js
anon5r/mastonon
import React from 'react'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ heading: { id: 'keyboard_shortcuts.heading', defaultMessage: 'Keyboard Shortcuts' }, }); @injectIntl export default class KeyboardShortcuts extends ImmutablePureComponent { static propTypes = { intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; render () { const { intl } = this.props; return ( <Column icon='question' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <div className='keyboard-shortcuts scrollable optionally-scrollable'> <table> <thead> <tr> <th><FormattedMessage id='keyboard_shortcuts.hotkey' defaultMessage='Hotkey' /></th> <th><FormattedMessage id='keyboard_shortcuts.description' defaultMessage='Description' /></th> </tr> </thead> <tbody> <tr> <td><kbd>r</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.reply' defaultMessage='to reply' /></td> </tr> <tr> <td><kbd>m</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.mention' defaultMessage='to mention author' /></td> </tr> <tr> <td><kbd>f</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.favourite' defaultMessage='to favourite' /></td> </tr> <tr> <td><kbd>b</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.boost' defaultMessage='to boost' /></td> </tr> <tr> <td><kbd>enter</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.enter' defaultMessage='to open status' /></td> </tr> <tr> <td><kbd>x</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.toggle_hidden' defaultMessage='to show/hide text behind CW' /></td> </tr> <tr> <td><kbd>up</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.up' defaultMessage='to move up in the list' /></td> </tr> <tr> <td><kbd>down</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.down' defaultMessage='to move down in the list' /></td> </tr> <tr> <td><kbd>1</kbd>-<kbd>9</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.column' defaultMessage='to focus a status in one of the columns' /></td> </tr> <tr> <td><kbd>n</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.compose' defaultMessage='to focus the compose textarea' /></td> </tr> <tr> <td><kbd>alt</kbd>+<kbd>n</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.toot' defaultMessage='to start a brand new toot' /></td> </tr> <tr> <td><kbd>backspace</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.back' defaultMessage='to navigate back' /></td> </tr> <tr> <td><kbd>s</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.search' defaultMessage='to focus search' /></td> </tr> <tr> <td><kbd>esc</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.unfocus' defaultMessage='to un-focus compose textarea/search' /></td> </tr> <tr> <td><kbd>?</kbd></td> <td><FormattedMessage id='keyboard_shortcuts.legend' defaultMessage='to display this legend' /></td> </tr> </tbody> </table> </div> </Column> ); } }
src/svg-icons/navigation/close.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationClose = (props) => ( <SvgIcon {...props}> <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/> </SvgIcon> ); NavigationClose = pure(NavigationClose); NavigationClose.displayName = 'NavigationClose'; NavigationClose.muiName = 'SvgIcon'; export default NavigationClose;