path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/svg-icons/notification/live-tv.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationLiveTv = (props) => ( <SvgIcon {...props}> <path d="M21 6h-7.59l3.29-3.29L16 2l-4 4-4-4-.71.71L10.59 6H3c-1.1 0-2 .89-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.11-.9-2-2-2zm0 14H3V8h18v12zM9 10v8l7-4z"/> </SvgIcon> ); NotificationLiveTv = pure(NotificationLiveTv); NotificationLiveTv.displayName = 'NotificationLiveTv'; NotificationLiveTv.muiName = 'SvgIcon'; export default NotificationLiveTv;
server/sonar-web/src/main/js/apps/background-tasks/components/Search.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. */ /* @flow */ import React from 'react'; import StatusFilter from './StatusFilter'; import TypesFilter from './TypesFilter'; import CurrentsFilter from './CurrentsFilter'; import DateFilter from './DateFilter'; import { DEFAULT_FILTERS } from './../constants'; import { translate } from '../../../helpers/l10n'; export default class Search extends React.Component { static propTypes = { loading: React.PropTypes.bool.isRequired, status: React.PropTypes.any.isRequired, taskType: React.PropTypes.any.isRequired, currents: React.PropTypes.any.isRequired, query: React.PropTypes.string.isRequired, onFilterUpdate: React.PropTypes.func.isRequired, onReload: React.PropTypes.func.isRequired }; handleStatusChange(status: string) { this.props.onFilterUpdate({ status }); } handleTypeChange(taskType: string) { this.props.onFilterUpdate({ taskType }); } handleCurrentsChange(currents: string) { this.props.onFilterUpdate({ currents }); } handleDateChange(date: string) { this.props.onFilterUpdate(date); } handleQueryChange(query: string) { this.props.onFilterUpdate({ query }); } handleReload(e: Object) { e.target.blur(); this.props.onReload(); } handleReset(e: Object) { e.preventDefault(); e.target.blur(); this.props.onFilterUpdate(DEFAULT_FILTERS); } renderSearchBox() { const { component, query } = this.props; if (component) { // do not render search form on the project-level page return null; } return ( <li> <h6 className="bt-search-form-label"> Search by Task or Component </h6> <input onChange={e => this.handleQueryChange(e.target.value)} value={query} ref="searchInput" className="js-search input-large" type="search" placeholder="Search" /> </li> ); } render() { const { loading, component, types, status, taskType, currents, minSubmittedAt, maxExecutedAt } = this.props; return ( <section className="big-spacer-top big-spacer-bottom"> <ul className="bt-search-form"> <li> <h6 className="bt-search-form-label"> Status </h6> <StatusFilter value={status} onChange={this.handleStatusChange.bind(this)} /> </li> {types.length > 1 && <li> <h6 className="bt-search-form-label"> Type </h6> <TypesFilter value={taskType} types={types} onChange={this.handleTypeChange.bind(this)} /> </li>} {!component && <li> <h6 className="bt-search-form-label"> Only Latest Analysis </h6> <CurrentsFilter value={currents} onChange={this.handleCurrentsChange.bind(this)} /> </li>} <li> <h6 className="bt-search-form-label"> Date </h6> <DateFilter minSubmittedAt={minSubmittedAt} maxExecutedAt={maxExecutedAt} onChange={this.handleDateChange.bind(this)} /> </li> {this.renderSearchBox()} <li className="bt-search-form-right"> <button className="js-reload" onClick={this.handleReload.bind(this)} disabled={loading}> {translate('reload')} </button> {' '} <button ref="resetButton" onClick={this.handleReset.bind(this)} disabled={loading}> {translate('reset_verb')} </button> </li> </ul> </section> ); } }
react-router-tutorial/lessons/02-rendering-a-route/index.js
zerotung/practices-and-notes
import React from 'react' import { render } from 'react-dom' import App from './modules/App' render(<App/>, document.getElementById('app'))
src/routes/home/Home.js
Maryanushka/masterskaya
/** * 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 './Home.css'; import Header from '../../components/Header'; import Catalog from '../../components/Catalog'; import About from '../../components/About'; import Works from '../../components/Works'; import Form from '../../components/Form'; import Footer from '../../components/Footer'; class Home extends React.Component { render() { return ( <div> <Header /> <Catalog /> <About /> <Works /> <Form /> <Footer /> </div> ); } } export default withStyles(s)(Home);
source/components/Modals/ConfirmModal.js
mikey1384/twin-kle
import PropTypes from 'prop-types'; import React from 'react'; import Modal from 'components/Modal'; import Button from 'components/Button'; ConfirmModal.propTypes = { onHide: PropTypes.func.isRequired, title: PropTypes.string.isRequired, onConfirm: PropTypes.func.isRequired }; export default function ConfirmModal({ onHide, title, onConfirm }) { return ( <Modal onHide={onHide}> <header>{title}</header> <main style={{ fontSize: '3rem', paddingTop: 0 }}>Are you sure?</main> <footer> <Button transparent style={{ marginRight: '0.7rem' }} onClick={onHide}> Cancel </Button> <Button color="blue" onClick={() => onConfirm()}> Confirm </Button> </footer> </Modal> ); }
src/views/TweetSlices/TweetSlicesContainer.js
btamayo/tweetstormer
import React, { Component } from 'react'; import Clipboard from 'clipboard/dist/clipboard.js'; import TweetSlice from './TweetSlice'; import cx from 'classnames'; class TweetSlicesContainer extends Component { constructor(props) { super(props); this.state = { lastCopiedIndex: -1, empty: false }; } componentDidMount() { this.clip = new Clipboard('.copy'); this.clip.on('success', (e) => { // console.log(`Copied: ${e.text}`); }); } componentWillReceiveProps(props) { if (props.slices.length === 1 && props.slices[0].length === 0) { this.setState({ empty: true }) } else { this.setState({ empty: false }) } } componentWillUnmount() { this.clip.destroy(); } updateActive(key) { this.setState({ lastCopiedIndex: key }); } render() { let overflowClassNames = (index, max) => { let sliceClasses = cx({ 'overflow': max > 0 && ((index + 1) > max), 'active-copy': this.state.lastCopiedIndex === index }); return sliceClasses; }; return ( <div> <div className='ui teal message'> <h3>Your tweet part(s): { this.state.empty ? 'None yet' : `${this.props.slices.length} total!` }</h3> </div> <div className='ui one column grid stackable padded'> {/* Key has to be item and not index so that it can differentiate */} { this.props.slices.length > 0 && this.props.slices.map((item, key) => { return <TweetSlice key={ item } text={ item } partNumber={ key } isActiveCopy={ this.state.lastCopiedIndex === key } onClick={ this.updateActive.bind(this, key) } className={ overflowClassNames(key, this.props.maxPartsIndicator) } />; } )} </div> </div> ); } } export default TweetSlicesContainer;
geonode/contrib/monitoring/frontend/src/pages/alerts/index.js
simod/geonode
import React, { Component } from 'react'; import Header from '../../components/organisms/header'; import AlertList from '../../components/organisms/alert-list'; import styles from './styles'; class Alerts extends Component { render() { return ( <div style={styles.root}> <Header back="/" /> <AlertList /> </div> ); } } export default Alerts;
client/src/components/Order.js
yhyecho/aa-journey
import React from 'react' import { connect } from 'react-redux' import { checkout } from '../redux/actions/cartActions' import '../css/order.css' class Order extends React.Component { constructor(props) { super(props) this.pay = this.pay.bind(this) } pay() { this.props.checkout(this.props.cart) } render() { let currentCourse let cartItems = this.props.cart.map(item => { currentCourse = this.props.courses.filter(value => value._id == item)[0] return ( <li className="course" key={item}> <div className="card"> <img src={currentCourse.poster}/> <p className="title">{currentCourse.name}</p> </div> </li> ) }) return ( <div> <h1 className="page-title"> 欲购买课程 </h1> <ul className="course-list container"> {cartItems} </ul> <div className="submit-order"> <div className="container"> <div className="total-fee"> ¥ 66.6 元 </div> <div className='pay' onClick={this.pay}>结算</div> </div> </div> </div> ) } } const mapStateToProps = (state) => ({ cart: state.cart, courses: state.courses }) export default connect(mapStateToProps, {checkout})(Order)
app/components/ToggleOption/index.js
singaporesamara/SOAS-DASHBOARD
/** * * ToggleOption * */ import React from 'react'; import { injectIntl, intlShape } from 'react-intl'; const ToggleOption = ({ value, message, intl }) => ( <option value={value}> {message ? intl.formatMessage(message) : value} </option> ); ToggleOption.propTypes = { value: React.PropTypes.string.isRequired, message: React.PropTypes.object, intl: intlShape.isRequired, }; export default injectIntl(ToggleOption);
src/common/containers/App.js
ThinkingInReact/ThinkingInReact.xyz
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Header from 'components//reduxed/Header'; import TOC from 'components//static/TOC'; import Features from 'components//dumb/Features'; import Examples from 'components//dumb/Examples'; import AboutBook from 'components//static/AboutBook'; import Footer from 'components//dumb/Footer'; class App extends Component { render() { return ( <div className="App"> <Header /> <TOC /> <Features /> <Examples /> <AboutBook /> <Footer /> </div> ); } } function mapStateToProps(state) { return { loginFormOpen: state.loginFormOpen, buyFormOpen: state.buyForm.open } } export default connect(mapStateToProps)(App);
src/MyChild.js
juliofornode/testing-react-with-enzyme-mocha-chai
import React from 'react'; const MyChild = () => { return( <div> <h5>This is MyChild component</h5> </div> ); }; export default MyChild;
src/components/StartAuction/StartAuctionInfo.js
ens-bid/ens-bid-dapp
import React from 'react'; import {shortFormatHash, momentFromNow} from '../../lib/util'; import Button from 'material-ui/Button'; import Card from 'material-ui/Card'; import Divider from 'material-ui/Divider'; import './StartAuctionInfo.css'; const RevealAuctionOn = (props) => <div className="RevealAuctionOn"> <h4>Reveal Auction On:</h4> <p>{props.unsealStartsAt}</p> <p>{props.endsMomentFromNow}</p> <Divider /> </div>; const InfoItem = (props) => { let classes = ''; if (props.title === 'ENS') classes = 'eth-item'; if (props.title === 'TxHash') classes = 'eth-txhash'; if (props.title === 'JSON') classes = 'eth-json'; return ( <div className="StartAuctionInfo-info-item"> <p> <span>{props.title}:</span> <span className={classes}>{props.children}</span> </p> <Divider /> </div> ); }; export const StartAuctionInfo = (props) => { const endsMomentFromNow = momentFromNow(props.unsealStartsAt); const hidden = (props.registratesAt.year() - 1970) <= 0 ; const ethersacnUrl = process.env.REACT_APP_ETHERSCAN_URL || 'https://ropsten.etherscan.io/tx/'; const txHashUrl = ethersacnUrl + props.auctionTXHash; const revealAuctionOn = !hidden && <RevealAuctionOn unsealStartsAt={props.unsealStartsAt.toString()} endsMomentFromNow={endsMomentFromNow.toString()} />; const {ethBid, ethMask, secret} = props.formResult; const shorterTxHash = shortFormatHash(props.auctionTXHash); const itemTitleValue = [ {title: 'ENS', value: `${props.searchResult.searchName}.eth`}, {title: 'ETH Bid', value: ethBid}, {title: 'ETH Mask', value: ethMask}, {title: 'Secret', value: secret}, {title: 'TxHash', value: <a target='_blank' href={txHashUrl}>{shorterTxHash}</a>}, {title: 'JSON', value: JSON.parse(props.exportJson)} ]; const infoItems = itemTitleValue.map(({title, value}, index) => <InfoItem key={`infoItem-${index}`} title={title}>{value}</InfoItem> ); return ( <Card raised > <div className="StartAuctionInfo"> {revealAuctionOn} {infoItems} <div className="StartAuctionInfo-actions"> <Button raised onClick={() => props.backToSearch()}>BACK TO SEARCH</Button> {/*<Button raised>MY ENS LIST</Button>*/} </div> </div> </Card> ); }
app/addons/permissions/layout.js
apache/couchdb-fauxton
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import React from 'react'; import {TabsSidebarHeader} from '../documents/layouts'; import PermissionsContainer from './container/PermissionsContainer'; import SidebarControllerContainer from "../documents/sidebar/SidebarControllerContainer"; import {SidebarItemSelection} from '../documents/sidebar/helpers'; export const PermissionsLayout = ({docURL, database, endpoint, dbName, dropDownLinks, partitionKey}) => { const selectedNavItem = new SidebarItemSelection('permissions'); return ( <div id="dashboard" className="with-sidebar"> <TabsSidebarHeader hideQueryOptions={true} hideJumpToDoc={true} docURL={docURL} endpoint={endpoint} dbName={dbName} dropDownLinks={dropDownLinks} database={database} /> <div className="with-sidebar tabs-with-sidebar content-area"> <aside id="sidebar-content" className="scrollable"> <SidebarControllerContainer selectedNavItem={selectedNavItem} selectedPartitionKey={partitionKey}/> </aside> <section id="dashboard-content" className="flex-layout flex-col"> <PermissionsContainer url={endpoint} /> </section> </div> </div> ); }; export default PermissionsLayout;
app/javascript/mastodon/components/icon_with_badge.js
Nyoho/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'mastodon/components/icon'; const formatNumber = num => num > 40 ? '40+' : num; const IconWithBadge = ({ id, count, issueBadge, className }) => ( <i className='icon-with-badge'> <Icon id={id} fixedWidth className={className} /> {count > 0 && <i className='icon-with-badge__badge'>{formatNumber(count)}</i>} {issueBadge && <i className='icon-with-badge__issue-badge' />} </i> ); IconWithBadge.propTypes = { id: PropTypes.string.isRequired, count: PropTypes.number.isRequired, issueBadge: PropTypes.bool, className: PropTypes.string, }; export default IconWithBadge;
src/svg-icons/device/screen-lock-portrait.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceScreenLockPortrait = (props) => ( <SvgIcon {...props}> <path d="M10 16h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2v1h-2.4v-1zM17 1H7c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 18H7V5h10v14z"/> </SvgIcon> ); DeviceScreenLockPortrait = pure(DeviceScreenLockPortrait); DeviceScreenLockPortrait.displayName = 'DeviceScreenLockPortrait'; DeviceScreenLockPortrait.muiName = 'SvgIcon'; export default DeviceScreenLockPortrait;
src/components/BaseComponent/Overlay/Overlay.js
dreambo8563/RSK
import React, { Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Overlay.css'; class Overlay extends Component { render() { return ( <div className={s.overlay}> </div > ); } } export default withStyles(s)(Overlay);
src/components/alert/index.js
buttercomponents/butter-base-components
import React from 'react' import { translate } from 'react-i18next' import style from './style.styl' const Alert = ({t, message}) => ( <div className={style['success']}> <span>{t(message)}</span> <i className='material-icons'>check</i> </div> ) export default translate(['alert'])(Alert)
app/components/Tasks/index.js
theterra/newsb
import React from 'react'; import Feed from '../Feed'; import TripCard from '../TripCard'; import Search from '../Search'; import classNames from 'classnames'; import Flatpickr from 'react-flatpickr'; import moment from 'moment'; import OrderStyle from './OrderStyle'; export default class Tasks extends React.Component { //eslint-disable-line constructor() { super(); this.state = { expand: false, data: [], intervalId: '', }; this.taskExpand = this.taskExpand.bind(this); this.detailedInfo = this.detailedInfo.bind(this); this.closeOrders = this.closeOrders.bind(this); this.searchText = this.searchText.bind(this); this.emitSearch = this.emitSearch.bind(this); this.pickDate = this.pickDate.bind(this); } componentDidUpdate(prevProps) { if(this.props.closeOrderExpand !== prevProps.closeOrderExpand) { this.closeOrders(); } } taskExpand() { const taskDiv = document.querySelector('.taskExpand'); const listShow = document.querySelector('.listShow'); const closeTag = document.querySelector('.closeTag'); if (!this.props.orderBlock && this.props.isAdmin()) { taskDiv.style.height = '92vh'; listShow.style.opacity = '1'; listShow.style.display = 'block'; closeTag.style.top = '-2px'; this.props.orderClose(true); this.props.divTask(); } } detailedInfo(data) { this.props.orderDetails(); this.props.getOrderDetail(data); } closeOrders() { const taskDiv = document.querySelector('.taskExpand'); const listShow = document.querySelector('.listShow'); const closeTag = document.querySelector('.closeTag'); if (this.props.orderBlock && this.props.isAdmin()) { taskDiv.style.height = '24vh'; listShow.style.opacity = '0'; listShow.style.display = 'none'; closeTag.style.top = '-20px'; this.props.orderExpand(false); this.props.divTask(); this.props.closeOrderDetails(); this.props.clearOrderDetails(); } } searchText(e) { this.emitSearch(e.target.value); } emitSearch(newSearch) { this.props.onSearchOrderAttr(newSearch); } pickDate(date) { const selectedDate = moment(date[0]).format('YYYYMMDD'); this.props.setDateRange({ fromDate: selectedDate, toDate: null }); this.props.getOrder({ isDateSelected: true }); } render() { const { expand, data } = this.state; const { stats, stateOrders, isAdmin, orderStats, orderId } = this.props; const orderUser = { marginTop: '2.65em', display: isAdmin() ? 'none': 'block', opacity: isAdmin() ? '0' : '1', transition: 'all 500ms cubic-bezier(0.250, 0.250, 0.750, 0.750)', } return ( <div className={ isAdmin() ? 'all-65 marginTop' : 'all-100 marginTop'} style={{ height: '24vh' }}> <OrderStyle className={classNames('boxShadow liner taskExpand block-background', { progressLiner: stats.request })} manager={isAdmin()} > <div className={classNames('orders-block', 'ink-flex', { indeterminate: stats.request })}> <div className="all-100" style={{ padding: '0.5em 0.8em' }}> <div className="ink-flex"> <div className="all-70"> <div className="team-search" style={{ width: '100%' }}> <Search placeHolder={'Search Orders'} searchText={this.searchText} /> </div> </div> <div className="all-30" style={{ textAlign: 'right' }}> <Flatpickr options={{ defaultDate: new Date() }} style={{ width: '92px', color: '#333' }} onChange={this.pickDate} /> </div> </div> </div> </div> <hr/> <div style={{ padding: '0.6em 0.8em' }}> <div className="ink-flex" style={{ position: 'relative' }}> <div className="all-100 block-stats-background" style={{ position: 'relative', zIndex: '1' }}> <Feed tasksExpand={this.taskExpand} stats={stats} orderStats={orderStats}/> </div> <div className="all-100 closeTag"> <a className="ink-flex push-right closeFeed" onClick={this.closeOrders}>Close</a> </div> </div> {/* <div className="search" style={{ marginTop: '14px', width: '20.90em' }}> <div className="wrapper"> <i className="fa fa-search" aria-hidden="true"></i> <input type="text" placeholder="Search" style={{ width: '100%', outline: 'none' }} /> </div> </div> */} <div className="listShow" style={orderUser}> { stateOrders.map((order) => { const date = moment(order.createdAt).format('YYYY-MM-DD HH:mm'); return ( <TripCard orderId={orderId} id={order._id} key={order._id} detailedInfo={() => {this.detailedInfo(order._id)}} customerName={order.id} orderStatus={order.status} orderAddress={order.to_address} orderPilot={order.pilot ? order.pilot.user.firstName : '-'} orderTime={date} /> ); })} </div> </div> </OrderStyle> </div> ); } }
src/components/icons/SalesforceIcon.js
InsideSalesOfficial/insidesales-components
import React from 'react'; const SalesforceIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 4 28 12"> {props.title && <title>{props.title}</title>} <path d="M21.9593578,2.72659767 C25.2924879,2.72659767 27.9948018,5.46201583 27.9948018,8.83614765 C27.9948018,12.2107205 25.2924879,14.9461387 21.9593578,14.9461387 C21.5524789,14.9461387 21.155017,14.9048724 20.7702996,14.827254 C20.0144879,16.1802836 18.5736179,17.0948198 16.9196717,17.0948198 C16.2275821,17.0948198 15.573035,16.9346688 14.9896179,16.648892 C14.2235103,18.4582447 12.4374117,19.7270408 10.3563713,19.7270408 C8.18888251,19.7270408 6.34151031,18.3508894 5.63259552,16.420573 C5.32277489,16.486221 5.00146547,16.5209351 4.67230852,16.5209351 C2.09178834,16.5209351 1.25560528e-05,14.3999118 1.25560528e-05,11.7833783 C1.25560528e-05,10.0294044 0.939330942,8.49839426 2.33612915,7.67924306 C2.04853274,7.01488761 1.88894529,6.28242708 1.88894529,5.51197637 C1.88894529,2.50281478 4.32343857,0.0630017098 7.32609327,0.0630017098 C9.08915157,0.0630017098 10.655896,0.904077589 11.6495193,2.2075877 C12.5522368,1.26369265 13.8091605,0.678215639 15.1994296,0.678215639 C17.0476179,0.678215639 18.6596269,1.71214045 19.5183354,3.24724569 C20.2646673,2.91276839 21.0904161,2.72659767 21.9593578,2.72659767 Z M5.99446099,9.81715084 L5.99446099,9.80770055 C5.99446099,9.35144051 5.59166278,9.1854304 5.21441614,9.06572672 L5.16500807,9.05003923 C4.88029955,8.95711137 4.63464036,8.87703591 4.63464036,8.68872312 L4.63464036,8.67920982 C4.63464036,8.51817687 4.77828161,8.39973322 5.00083767,8.39973322 C5.24812915,8.39973322 5.54150135,8.48226576 5.73034439,8.58716399 C5.73034439,8.58716399 5.78628161,8.6230751 5.80643408,8.56901943 C5.81754619,8.53966053 5.91303498,8.28160459 5.92333094,8.25350573 C5.93400359,8.2233908 5.91504395,8.2007101 5.89533094,8.18873973 C5.67930404,8.05700268 5.38103498,7.96697291 5.07246996,7.96697291 L5.01527713,7.96741392 C4.4894296,7.96741392 4.12241614,8.28614073 4.12241614,8.74284178 L4.12241614,8.75229207 C4.12241614,9.23331187 4.5272861,9.38980869 4.90660448,9.49842403 L4.96750135,9.51738761 C5.24398565,9.60244023 5.48223677,9.67596349 5.48223677,9.87082849 L5.48223677,9.8807828 C5.48223677,10.0590783 5.32710673,10.1920754 5.07780628,10.1920754 C4.9806852,10.1920754 4.67168072,10.1904373 4.33800359,9.97862481 C4.29769865,9.95462107 4.2746583,9.93773655 4.24339372,9.91870996 C4.22694529,9.90837764 4.18576143,9.8906741 4.16768072,9.94472976 L4.05455067,10.2601805 C4.03684664,10.3064869 4.06070314,10.3159372 4.06647892,10.3238124 C4.11915157,10.3621806 4.1722009,10.3898385 4.22612915,10.4208354 C4.51165381,10.5727331 4.78154619,10.6169604 5.06336682,10.6169604 C5.6377435,10.6169604 5.99446099,10.310582 5.99446099,9.81715084 Z M8.3454565,10.4584476 C8.38576143,10.4481153 8.38249686,10.4052109 8.38249686,10.4052109 L8.38168072,8.91628612 C8.38168072,8.58930606 8.29485561,8.34731561 8.12409327,8.19705599 C7.9537704,8.04761539 7.70277489,7.97201306 7.37857758,7.97201306 C7.25678386,7.97201306 7.06134888,7.98851957 6.94369865,8.0120823 C6.94369865,8.0120823 6.5894296,8.08100642 6.44377937,8.19579595 C6.44377937,8.19579595 6.41169865,8.21564156 6.42896323,8.26062494 L6.54372556,8.57034247 C6.55816502,8.61034871 6.59721435,8.59674029 6.59721435,8.59674029 C6.59721435,8.59674029 6.60958206,8.59176313 6.62395874,8.58313187 C6.93585112,8.41296363 7.33086457,8.41794078 7.33086457,8.41794078 C7.5060843,8.41794078 7.64106188,8.45385189 7.73196771,8.52321702 C7.82042511,8.59176313 7.865313,8.69420429 7.865313,8.91137197 L7.865313,8.98029609 C7.72625471,8.96007247 7.59786906,8.94848011 7.59786906,8.94848011 C7.53201256,8.94356596 7.44688251,8.94110888 7.34480179,8.94110888 C7.2057435,8.94110888 7.07120538,8.95843442 6.94489148,8.99270747 C6.8182009,9.02698052 6.70419193,9.07983915 6.60631749,9.15002331 C6.50756413,9.2210265 6.42852377,9.31143428 6.37095426,9.41878958 C6.31332197,9.52614488 6.28412915,9.65246377 6.28412915,9.79371412 C6.28412915,9.93824056 6.30880179,10.0632994 6.35858655,10.1657406 C6.40799462,10.2685597 6.47912466,10.3544314 6.57009327,10.4204574 C6.66018296,10.4865464 6.77168072,10.5348689 6.90044305,10.5641648 C7.02801256,10.5934607 7.17240717,10.6083292 7.33042511,10.6083292 C7.49704395,10.6083292 7.66246996,10.5942797 7.823313,10.5670629 C7.98258655,10.5397831 8.17758206,10.5001549 8.231887,10.4873655 C8.28581525,10.4749541 8.3454565,10.4584476 8.3454565,10.4584476 Z M9.43481973,10.505447 L9.43481973,7.03013408 C9.43481973,7.00285424 9.41548341,6.98099257 9.38829955,6.98099257 L8.95794081,6.98099257 C8.93081973,6.98099257 8.91148341,7.00285424 8.91148341,7.03013408 L8.91148341,10.505447 C8.91148341,10.5327269 8.93081973,10.5550295 8.95794081,10.5550295 L9.38829955,10.5550295 C9.41548341,10.5550295 9.43481973,10.5327269 9.43481973,10.505447 Z M12.1218152,9.38722561 C12.1234475,9.36990008 12.1773758,9.05281132 12.0732861,8.68614004 C12.0325417,8.53172229 11.9317166,8.3760445 11.8659229,8.30504131 C11.7613937,8.19188983 11.6593758,8.1130114 11.5577345,8.06928806 C11.4252682,8.0122713 11.2668108,7.97472215 11.0932233,7.97472215 C10.8903803,7.97472215 10.7064341,8.0089952 10.5570798,8.07917936 C10.4077256,8.14936352 10.2822278,8.24556748 10.1835372,8.36533417 C10.0851605,8.48465984 10.0111426,8.62666621 9.96380628,8.78814018 C9.91646996,8.94835411 9.89261345,9.12299548 9.89261345,9.30752816 C9.89261345,9.49539994 9.9172861,9.67048232 9.96625471,9.82735715 C10.0156628,9.98631104 10.0946404,10.1254823 10.2011785,10.2415319 C10.3081561,10.3579595 10.4452054,10.4487453 10.6093758,10.5127552 C10.7726673,10.5759462 10.9709901,10.6089592 11.1985686,10.6081402 C11.6671605,10.6068801 11.9140126,10.5020449 12.0156538,10.4454692 C12.0337345,10.4351369 12.0506224,10.4178113 12.0296538,10.3674728 L11.9230529,10.0692846 C11.9070439,10.0251202 11.8622188,10.0412487 11.8622188,10.0412487 C11.7457614,10.0845941 11.5811516,10.1622125 11.1960574,10.1613934 C10.9446852,10.1610154 10.7579139,10.0866731 10.641017,9.96980453 C10.5212951,9.85091988 10.4620305,9.67583749 10.452174,9.42855488 L12.0744789,9.42975192 C12.0744789,9.42975192 12.1172951,9.4293109 12.1218152,9.38722561 Z M13.4701471,10.6169604 C14.0445238,10.6169604 14.4012413,10.310582 14.4012413,9.81715084 L14.4012413,9.80770055 C14.4012413,9.35144051 13.998443,9.1854304 13.6211964,9.06572672 L13.5717883,9.05003923 C13.2870798,8.95711137 13.0414834,8.87703591 13.0414834,8.68872312 L13.0414834,8.67920982 C13.0414834,8.51817687 13.1850619,8.39973322 13.4076179,8.39973322 C13.6549094,8.39973322 13.9482816,8.48226576 14.1371247,8.58716399 C14.1371247,8.58716399 14.1930619,8.6230751 14.2132143,8.56901943 C14.2243265,8.53966053 14.3198152,8.28160459 14.3301112,8.25350573 C14.3407839,8.2233908 14.321887,8.2007101 14.3021112,8.18873973 C14.0860843,8.05700268 13.7881919,7.96697291 13.4792502,7.96697291 L13.4220574,7.96741392 C12.8962099,7.96741392 12.5291964,8.28614073 12.5291964,8.74284178 L12.5291964,8.75229207 C12.5291964,9.23331187 12.9345058,9.38980869 13.3134475,9.49842403 L13.3743444,9.51738761 C13.6508287,9.60244023 13.8894565,9.67596349 13.8894565,9.87082849 L13.8894565,9.8807828 C13.8894565,10.0590783 13.7343265,10.1920754 13.4845865,10.1920754 C13.3874655,10.1920754 13.0789004,10.1904373 12.7447839,9.97862481 C12.7044789,9.95462107 12.6806224,9.93855557 12.650174,9.91870996 C12.639878,9.91215776 12.5913489,9.89313118 12.5749004,9.94472976 L12.4613309,10.2601805 C12.4436269,10.3064869 12.4674834,10.3159372 12.4732592,10.3238124 C12.5259318,10.3621806 12.5789812,10.3898385 12.6329094,10.4208354 C12.9184341,10.5727331 13.1883265,10.6169604 13.4701471,10.6169604 Z M16.3044879,8.41567272 L16.3650081,8.0771003 C16.3690888,8.04490631 16.3555283,8.02468268 16.3123354,8.02468268 L15.7935193,8.02468268 C15.7959677,8.01309033 15.8194475,7.82975469 15.8790888,7.65763339 C15.9045776,7.58366911 15.9522906,7.5246993 15.993035,7.48381104 C16.0325238,7.44374181 16.0786045,7.41526493 16.1288287,7.39869542 C16.1802457,7.38218892 16.2386942,7.37393566 16.3028556,7.37393566 C16.3518242,7.37393566 16.3995372,7.37973184 16.4362009,7.38716607 C16.4863623,7.3979394 16.5061381,7.40367258 16.5192592,7.40738969 C16.5719318,7.4238962 16.5789632,7.40820872 16.5896359,7.38262993 L16.7135013,7.04071841 C16.7262457,7.00398828 16.6953578,6.9883008 16.6838691,6.98376466 C16.6320126,6.96769916 16.5851157,6.95692583 16.5234027,6.94577449 C16.4608735,6.93424513 16.3867928,6.92844895 16.3028556,6.92844895 C16.0094834,6.92844895 15.7782637,7.01186352 15.6157883,7.17617258 C15.454443,7.3392846 15.3446404,7.58782724 15.2894565,7.91442929 L15.2697435,8.02468268 L14.9014744,8.02468268 C14.9014744,8.02468268 14.8562099,8.02304463 14.8471695,8.07218615 L14.7867121,8.41075856 C14.7821919,8.44295255 14.7961919,8.46317618 14.8393848,8.46317618 L15.198174,8.46317618 L14.8340484,10.5012259 C14.805609,10.6650939 14.7731516,10.8001701 14.7369274,10.9025482 C14.7015193,11.0036663 14.6665507,11.0792687 14.6237973,11.1341434 C14.5822368,11.187002 14.5431247,11.2266302 14.4752592,11.2493739 C14.4192592,11.2679595 14.3547211,11.2765907 14.2843444,11.2765907 C14.2452323,11.2765907 14.1929991,11.2700385 14.1543265,11.2621633 C14.1156538,11.2547291 14.0955013,11.2460978 14.0666852,11.2340644 C14.0666852,11.2340644 14.024748,11.2179989 14.0078601,11.2600842 C13.9946762,11.2947983 13.8992502,11.5586504 13.8876987,11.5912854 C13.8762099,11.6234794 13.8922188,11.6486172 13.9128108,11.6560514 C13.9605238,11.6729989 13.9959318,11.6841503 14.0609094,11.6993968 C14.1514386,11.7208804 14.227591,11.7221405 14.2987211,11.7221405 C14.4480753,11.7221405 14.5843085,11.7010978 14.6969991,11.6602095 C14.8105686,11.6188803 14.909322,11.5470581 14.9969632,11.4504761 C15.0911964,11.3455779 15.1508377,11.2357655 15.207591,11.0858839 C15.2639677,10.9376403 15.3116807,10.7534856 15.3503534,10.538775 L15.7157345,8.46317618 L16.250183,8.46317618 C16.250183,8.46317618 16.2954475,8.46481423 16.3044879,8.41567272 Z M18.6797794,9.81047263 C18.7266762,9.65151874 18.7505327,9.47769639 18.7505327,9.29354173 C18.7505327,9.10938706 18.7266762,8.93562771 18.6797794,8.77661082 C18.6328197,8.6168379 18.5591785,8.47602857 18.4616807,8.35878196 C18.364183,8.24109434 18.2403175,8.14652843 18.0934744,8.07798232 C17.9470081,8.00943622 17.774174,7.97440714 17.5799946,7.97440714 C17.3853758,7.97440714 17.212165,8.00943622 17.0656987,8.07798232 C16.9191695,8.14652843 16.7953668,8.24109434 16.6978691,8.35922298 C16.5999318,8.47646959 16.5266673,8.61727892 16.4797704,8.77661082 C16.4328735,8.93562771 16.409017,9.10938706 16.409017,9.29354173 C16.409017,9.47769639 16.4328735,9.65195975 16.4797704,9.81047263 C16.5266673,9.96986754 16.5999318,10.1106769 16.6978691,10.2283645 C16.7953668,10.3460521 16.919609,10.440177 17.0660753,10.5070851 C17.2125417,10.5739301 17.3853758,10.6078252 17.5799946,10.6078252 C17.774174,10.6078252 17.9465686,10.5739301 18.0934744,10.5070851 C18.2399408,10.440177 18.3637435,10.3460521 18.4616807,10.2283645 C18.5591785,10.1111179 18.6328197,9.97030855 18.6797794,9.81047263 Z M20.6852951,8.10942029 C20.6976628,8.07269016 20.6717345,8.05492362 20.6610619,8.05082849 C20.6335013,8.04049617 20.4952592,8.01120027 20.3890978,8.00414405 C20.1849991,7.99179567 20.0718691,8.02606873 19.9706673,8.07187114 C19.8698422,8.11729553 19.7583444,8.19119681 19.6966314,8.27498939 L19.6961919,8.07640728 C19.6961919,8.04912744 19.6768556,8.02726576 19.6497345,8.02726576 L19.2337525,8.02726576 C19.2066314,8.02726576 19.1872323,8.04912744 19.1872323,8.07640728 L19.1872323,10.505447 C19.1872323,10.5327269 19.2090798,10.5545885 19.2366404,10.5545885 L19.6629184,10.5545885 C19.6900395,10.5545885 19.7118242,10.5327269 19.7118242,10.505447 L19.7118242,9.29196668 C19.7118242,9.12891766 19.7299677,8.96662467 19.7657525,8.86462453 C19.8007211,8.76350642 19.8484341,8.68298994 19.9076987,8.62515416 C19.9669632,8.56731838 20.034452,8.52687114 20.10847,8.50419044 C20.1837435,8.48106873 20.267304,8.47319348 20.3257525,8.47319348 C20.4108825,8.47319348 20.5038601,8.49549617 20.5038601,8.49549617 C20.5355641,8.49883527 20.5528287,8.47943068 20.5635013,8.45133181 C20.5911247,8.37698952 20.6704789,8.15364765 20.6852951,8.10942029 Z M22.7144161,10.4850974 C22.7144161,10.4850974 22.7490081,10.4681499 22.7337525,10.4277026 L22.6161022,10.1015416 C22.60047,10.0548572 22.5547659,10.0726237 22.5547659,10.0726237 C22.4852682,10.0994625 22.4111874,10.1238443 22.3317704,10.1361927 C22.2519767,10.149045 22.163896,10.1552192 22.0692861,10.1552192 C21.8376269,10.1552192 21.6529274,10.0858541 21.5208377,9.9492029 C21.388748,9.81211068 21.3142906,9.59078487 21.3151067,9.29146266 C21.3159229,9.01935729 21.3813399,8.81453799 21.4989901,8.65804117 C21.615887,8.5028044 21.7939946,8.42316995 22.0309901,8.42316995 C22.2284969,8.42316995 22.3794834,8.44622866 22.5375013,8.49581118 C22.5375013,8.49581118 22.5753578,8.51231769 22.5930619,8.46273516 C22.6354386,8.34548856 22.6662637,8.262515 22.7110888,8.13411705 C22.723896,8.09738692 22.6926314,8.08207745 22.6810798,8.07754131 C22.6189901,8.05315956 22.472461,8.01309033 22.3614027,7.99620581 C22.2581291,7.98051833 22.1367749,7.97226507 22.0017973,7.97226507 C21.8005865,7.97226507 21.6212233,8.00691614 21.4677256,8.07546225 C21.3142906,8.14363034 21.1847121,8.23813325 21.0814386,8.35582087 C20.9785417,8.47350849 20.9003803,8.61431783 20.8485238,8.77371273 C20.7962906,8.93260362 20.7703623,9.10686698 20.7703623,9.29184067 C20.7703623,9.69070595 20.8773399,10.0131499 21.0892233,10.2489661 C21.3015462,10.4863574 21.6199677,10.6065021 22.0355103,10.6065021 C22.2811695,10.6065021 22.5329812,10.5565416 22.7144161,10.4850974 Z M25.117017,9.38722561 C25.1186493,9.36990008 25.1725776,9.05281132 25.0684879,8.68614004 C25.0277435,8.53172229 24.9269184,8.3760445 24.8611247,8.30504131 C24.7565955,8.19188983 24.6541381,8.1130114 24.5529363,8.06928806 C24.4208466,8.0122713 24.2620753,7.97472215 24.0879857,7.97472215 C23.8855821,7.97472215 23.7016359,8.0089952 23.5523444,8.07917936 C23.4029901,8.14936352 23.2774924,8.24556748 23.178739,8.36533417 C23.0803623,8.48465984 23.0063444,8.62666621 22.9590081,8.78814018 C22.9116717,8.94835411 22.8878152,9.12299548 22.8878152,9.30752816 C22.8878152,9.49539994 22.9125507,9.67048232 22.9614565,9.82735715 C23.0108646,9.98631104 23.0898422,10.1254823 23.196443,10.2415319 C23.3034206,10.3579595 23.4404072,10.4487453 23.6045776,10.5127552 C23.7679318,10.5759462 23.9661919,10.6089592 24.1937704,10.6081402 C24.6623623,10.6068801 24.9092143,10.5020449 25.0108556,10.4454692 C25.0289991,10.4351369 25.0458242,10.4178113 25.0248556,10.3674728 L24.9183175,10.0692846 C24.9022457,10.0251202 24.8574206,10.0412487 24.8574206,10.0412487 C24.7409632,10.0845941 24.5764161,10.1622125 24.1912592,10.1613934 C23.9394475,10.1610154 23.7531157,10.0866731 23.6362188,9.96980453 C23.5164969,9.85091988 23.4572951,9.67583749 23.4473758,9.42855488 L25.0696807,9.42975192 C25.0696807,9.42975192 25.1124969,9.4293109 25.117017,9.38722561 Z" id="Combined-Shape"></path> <path d="M11.0545318,8.40577534 C10.8413928,8.40577534 10.6904063,8.49000893 10.5903973,8.64234762 C10.5249803,8.74270971 10.4826036,8.87148567 10.4595632,9.02634443 L11.6169803,9.02678545 C11.6054287,8.87690384 11.5762359,8.74308772 11.5095632,8.64234762 C11.4083614,8.49000893 11.2676709,8.40577534 11.0545318,8.40577534" id="Fill-1" fillRule="nonzero"></path> <path d="M6.95477937,9.46918506 C6.85728161,9.53810918 6.80994529,9.64136936 6.80994529,9.78419475 C6.80994529,9.87504355 6.82639372,9.94604673 6.8589139,9.99600727 C6.87988251,10.0290203 6.88854619,10.0418727 6.95233094,10.0926522 C6.95107534,10.0922112 7.09798117,10.2078198 7.42795426,10.1875962 C7.65999013,10.1735467 7.86609776,10.1293824 7.86609776,10.1293824 L7.86609776,9.38904659 C7.86609776,9.38904659 7.65791839,9.35439553 7.42544305,9.35149744 C7.09465381,9.3469613 6.95396323,9.46918506 6.95477937,9.46918506" id="Fill-3" fillRule="nonzero"></path> <path d="M17.5799695,8.41615806 C17.3668305,8.41615806 17.2150278,8.49005933 17.1150188,8.64202001 C17.0146332,8.79561873 16.9636556,9.01530649 16.9636556,9.29358606 C16.9636556,9.57230663 17.0146332,9.7923094 17.1154583,9.94760918 C17.2150278,10.1012079 17.3668305,10.1763062 17.5799695,10.1763062 C17.7926691,10.1763062 17.9453507,10.1012079 18.0465525,9.94760918 C18.1485704,9.7923094 18.2004269,9.57230663 18.2004269,9.29358606 C18.2004269,9.01530649 18.1485704,8.79561873 18.0465525,8.64202001 C17.9453507,8.49005933 17.7926691,8.41615806 17.5799695,8.41615806" id="Fill-5" fillRule="nonzero"></path> <path d="M24.0497462,8.40577534 C23.8366072,8.40577534 23.6851812,8.49000893 23.5860511,8.64234762 C23.5201946,8.74270971 23.4778179,8.87148567 23.4547776,9.02634443 L24.6121946,9.02678545 C24.600643,8.87690384 24.5714502,8.74308772 24.5044009,8.64234762 C24.4031991,8.49000893 24.2628852,8.40577534 24.0497462,8.40577534" id="Fill-7-path"></path> </svg> ); export default SalesforceIcon;
app/javascript/mastodon/features/getting_started/index.js
imomix/mastodon
import React from 'react'; import Column from '../ui/components/column'; import ColumnLink from '../ui/components/column_link'; import ColumnSubheading from '../ui/components/column_subheading'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ heading: { id: 'getting_started.heading', defaultMessage: 'Getting started' }, home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' }, notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' }, public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' }, navigation_subheading: { id: 'column_subheading.navigation', defaultMessage: 'Navigation' }, settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' }, community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, sign_out: { id: 'navigation_bar.logout', defaultMessage: 'Logout' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, info: { id: 'navigation_bar.info', defaultMessage: 'Extended information' }, }); const mapStateToProps = state => ({ me: state.getIn(['accounts', state.getIn(['meta', 'me'])]), columns: state.getIn(['settings', 'columns']), }); class GettingStarted extends ImmutablePureComponent { static propTypes = { intl: PropTypes.object.isRequired, me: ImmutablePropTypes.map.isRequired, columns: ImmutablePropTypes.list, multiColumn: PropTypes.bool, }; render () { const { intl, me, columns, multiColumn } = this.props; let navItems = []; if (multiColumn) { if (!columns.find(item => item.get('id') === 'HOME')) { navItems.push(<ColumnLink key='0' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/timelines/home' />); } if (!columns.find(item => item.get('id') === 'NOTIFICATIONS')) { navItems.push(<ColumnLink key='1' icon='bell' text={intl.formatMessage(messages.notifications)} to='/notifications' />); } if (!columns.find(item => item.get('id') === 'COMMUNITY')) { navItems.push(<ColumnLink key='2' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />); } if (!columns.find(item => item.get('id') === 'PUBLIC')) { navItems.push(<ColumnLink key='3' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />); } } navItems = navItems.concat([ <ColumnLink key='4' icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />, ]); if (me.get('locked')) { navItems.push(<ColumnLink key='5' icon='users' text={intl.formatMessage(messages.follow_requests)} to='/follow_requests' />); } navItems = navItems.concat([ <ColumnLink key='6' icon='volume-off' text={intl.formatMessage(messages.mutes)} to='/mutes' />, <ColumnLink key='7' icon='ban' text={intl.formatMessage(messages.blocks)} to='/blocks' />, ]); return ( <Column icon='asterisk' heading={intl.formatMessage(messages.heading)} hideHeadingOnMobile> <div className='getting-started__wrapper'> <ColumnSubheading text={intl.formatMessage(messages.navigation_subheading)} /> {navItems} <ColumnSubheading text={intl.formatMessage(messages.settings_subheading)} /> <ColumnLink icon='book' text={intl.formatMessage(messages.info)} href='/about/more' /> <ColumnLink icon='cog' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' /> <ColumnLink icon='sign-out' text={intl.formatMessage(messages.sign_out)} href='/auth/sign_out' method='delete' /> </div> <div className='getting-started__footer scrollable optionally-scrollable'> <div className='static-content getting-started'> <p> <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/FAQ.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.faq' defaultMessage='FAQ' /></a> • <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/User-guide.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.userguide' defaultMessage='User Guide' /></a> • <a href='https://github.com/tootsuite/documentation/blob/master/Using-Mastodon/Apps.md' rel='noopener' target='_blank'><FormattedMessage id='getting_started.appsshort' defaultMessage='Apps' /></a> </p> <p> <FormattedMessage id='getting_started.open_source_notice' defaultMessage='Mastodon is open source software. You can contribute or report issues on GitHub at {github}.' values={{ github: <a href='https://github.com/tootsuite/mastodon' rel='noopener' target='_blank'>tootsuite/mastodon</a> }} /> </p> </div> </div> </Column> ); } } export default connect(mapStateToProps)(injectIntl(GettingStarted));
src/client.js
ueno-llc/starter-kit
/* eslint no-underscore-dangle: 0 */ import React from 'react'; import ReactDOM from 'react-dom'; import Router from 'react-router/lib/Router'; import browserHistory from 'react-router/lib/browserHistory'; import applyRouterMiddleware from 'react-router/lib/applyRouterMiddleware'; import useScroll from 'react-router-scroll/lib/useScroll'; import match from 'react-router/lib/match'; import stringify from 'json-stringify-safe'; import { toJS } from 'mobx'; import { Provider } from 'mobx-react'; import routes from './routes'; import Store from './store'; const state = JSON.parse(document.getElementById('__INITIAL_STATE__').innerText || '{}'); let store = window.store = new Store(state); // Render the application const render = (Root, target = 'root') => { match({ routes: (<Router>{routes}</Router>), location: window.location, }, (err, location, props) => { // Make sure that all System.imports are loaded before rendering const imports = props.routes .filter(route => route.getComponent) .map(route => new Promise(resolve => route.getComponent(location, resolve))); // Run the chain Promise.all(imports) .then(() => { ReactDOM.render( <Root {...store}> <Router history={browserHistory} render={applyRouterMiddleware(useScroll())} > {props.routes} </Router> </Root>, document.getElementById(target) ); }); }); }; // Render for the first time render(Provider); if (module.hot) { // Remove some warnings and errors related to // hot reloading and System.import conflicts. require('utils/hmr'); // eslint-disable-line if (module.hot.data && module.hot.data.store) { store = new Store(JSON.parse(module.hot.data.store)); } module.hot.dispose((data) => { data.store = stringify(toJS(store)); // eslint-disable-line }); module.hot.accept('./client.js'); module.hot.accept(() => { render( require('mobx-react').Provider // eslint-disable-line ); }); }
packages/react/src/components/SelectItemGroup/SelectItemGroup.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React from 'react'; import classnames from 'classnames'; import { settings } from 'carbon-components'; const { prefix } = settings; const SelectItemGroup = ({ children, className, disabled, label, ...other }) => { const classNames = classnames(`${prefix}--select-optgroup`, className); return ( <optgroup className={classNames} label={label} disabled={disabled} {...other}> {children} </optgroup> ); }; SelectItemGroup.propTypes = { /** * Provide the contents of your <SelectItemGroup> */ children: PropTypes.node, /** * Specify an optional className to be applied to the node */ className: PropTypes.string, /** * Specify whether the <SelectItemGroup> should be disabled */ disabled: PropTypes.bool, /** * Specify the label to be displayed */ label: PropTypes.string.isRequired, }; SelectItemGroup.defaultProps = { disabled: false, label: 'Provide label', }; export default SelectItemGroup;
web-app/src/shared/components/SquareSelect/index.js
crypticism/FF
import React from 'react'; import classNames from 'classnames'; import stylesheet from './SquareSelect.scss'; export default function SquareSelect({ selected, hasItemsSelected = false }) { return ( <span className={classNames(stylesheet.squareIcon, { [stylesheet.selected]: selected, 'is-selected': selected, // necessary for parent access })} > {hasItemsSelected && '-'} </span> ); }
showcase/examples/dragable-chart/dragable-chart-example.js
Apercu/react-vis
// Copyright (c) 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import PropTypes from 'prop-types'; import DragMarker from './drag-marker'; import {scaleLinear} from 'd3-scale'; import { XYPlot, XAxis, YAxis, makeWidthFlexible, Voronoi, LineSeries, VerticalGridLines } from 'index'; function getRandomSeriesData(xMax, yMax) { return Array(xMax) .fill() .map((e, x) => ({x, y: Math.floor(Math.random() * yMax) + 1})); } const PLOT_MARGIN = { top: 50, left: 50, right: 10 }; const PLOT_HEIGHT = 300; const PLOT_DOMAIN = { x: [0, 100], y: [0, 10] }; const seriesData = getRandomSeriesData(PLOT_DOMAIN.x[1], PLOT_DOMAIN.y[1]); class DragableChartExample extends React.Component { state = { isDrawing: false, selectionStart: null, selectionEnd: null, hoveredX: null }; onMouseLeave = () => this.setState({isDrawing: false}) onMouseDown = node => this.setState({isDrawing: true, selectionStart: node.x, selectionEnd: null}); onMouseUp = node => this.setState({isDrawing: false}); onHover = node => this.setState(nextState => ({selectionEnd: nextState.isDrawing ? node.x : nextState.selectionEnd, hoveredX: node.x})); render() { const PLOT_WIDTH = this.props.width; const x = scaleLinear().domain(PLOT_DOMAIN.x).range([PLOT_MARGIN.left, PLOT_WIDTH - PLOT_MARGIN.right]); const y = scaleLinear().domain(PLOT_DOMAIN.y).range([PLOT_HEIGHT, 0]); return ( <div> <XYPlot onMouseLeave={this.onMouseLeave} width={PLOT_WIDTH} height={PLOT_HEIGHT} margin={PLOT_MARGIN} xDomain={x.domain()} yDomain={y.domain()} > <XAxis /> <YAxis /> <LineSeries curve={'curveMonotoneX'} data={seriesData} /> {this.state.hoveredX !== null && <VerticalGridLines tickValues={[this.state.hoveredX]} />} <Voronoi extent={[[PLOT_MARGIN.left, PLOT_MARGIN.top], [PLOT_WIDTH, PLOT_HEIGHT]]} nodes={seriesData} onHover={this.onHover} onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} x={d => x(d.x)} y={d => 0} /> {this.state.isDrawing && this.state.selectionEnd !== null && <DragMarker selectionStart={x(this.state.selectionStart)} selectionEnd={x(this.state.selectionEnd)} />} </XYPlot> <div style={{marginLeft: '50px'}}> <p><strong>selectionStart:</strong> {this.state.selectionStart}</p> <p><strong>selectionEnd:</strong> {this.state.selectionEnd}</p> <p><strong>isDrawing:</strong> {this.state.isDrawing.toString()}</p> </div> </div> ); } } DragableChartExample.propTypes = { width: PropTypes.number }; export default makeWidthFlexible(DragableChartExample);
actor-apps/app-web/src/app/components/modals/create-group/ContactItem.react.js
TimurTarasenko/actor-platform
import React from 'react'; import AvatarItem from 'components/common/AvatarItem.react'; class ContactItem extends React.Component { static propTypes = { contact: React.PropTypes.object, onToggle: React.PropTypes.func } constructor(props) { super(props); this.onToggle = this.onToggle.bind(this); this.state = { isSelected: false }; } onToggle() { const isSelected = !this.state.isSelected; this.setState({ isSelected: isSelected }); this.props.onToggle(this.props.contact, isSelected); } render() { let contact = this.props.contact; let icon; if (this.state.isSelected) { icon = 'check_box'; } else { icon = 'check_box_outline_blank'; } return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this.onToggle}>{icon}</a> </div> </li> ); } } export default ContactItem;
src/encoded/static/components/browse/components/FacetCharts.js
hms-dbmi/fourfront
'use strict'; import React from 'react'; import _ from 'underscore'; import url from 'url'; import { unhighlightTerms } from '@hms-dbmi-bgm/shared-portal-components/es/components/viz/utilities'; import { FlexibleDescriptionBox } from '@hms-dbmi-bgm/shared-portal-components/es/components/ui/FlexibleDescriptionBox'; import { object, layout, ajax, console, isServerSide, analytics, searchFilters, memoizedUrlParse } from '@hms-dbmi-bgm/shared-portal-components/es/components/util'; import { navigate } from './../../util'; import { ChartDataController } from './../../viz/chart-data-controller'; import * as BarPlot from './../../viz/BarPlot'; /** * @callback showFunc * @param {string} path - Path of current page or view, derived from 'href' prop on FacetCharts component. * @return {string|boolean} - The type of view to display ('full', 'small') or bool. */ /** * Area for displaying Charts rel to browsing. * Originally designed as space for 2 charts, a bigger barplot and a smaller/square/circle pie-like chart, to take up 3/4 and 1/4 width of header respectively (where 1/4 of width ~== height). * Now the 1/4 area for smaller chart is used for legend & ui controls. */ export class FacetCharts extends React.PureComponent { /** * @type {Object} defaultProps * @static * @public * @member * @constant * @property {string} [href='/'] Current page/view URL, used to filter charts and pass 'path' arg to props.show, if provided. * @property {boolean|string|showFunc} [show] - Type of view to show or whether to display or not; if function supplied, as well as props.href, path is passed as argument. * @property {string[]} initialFields - Array with 2 items representing the x-axis field and the group by field. */ static defaultProps = { 'href' : '/', 'show' : function(path, search, hash){ if (path === '/' || path === '/home') return 'large'; if (path.indexOf('/browse/') > -1) return true; return false; }, 'views' : ['small', 'large'], 'initialFields' : [ 'experiments_in_set.experiment_type.display_title', 'experiments_in_set.biosample.biosource.individual.organism.name' ] }; /** * Binds functions and initiates a state object. * * @member * @ignore * @public * @constructor */ constructor(props){ super(props); this.show = this.show.bind(this); this.state = { 'mounted' : false }; } /** * Updates `state.mounted`. * Initializes ChartDataController if not yet initialized, which fetches data used for charts. */ componentDidMount(){ var { debug, browseBaseState, initialFields } = this.props; if (!ChartDataController.isInitialized()){ ChartDataController.initialize( browseBaseState, initialFields, ()=>{ if (debug) console.log("Mounted FacetCharts after initializing ChartDataController:", ChartDataController.getState()); setTimeout(() => this.setState({ 'mounted' : true }), 100); } ); } else { if (debug) console.log('Mounted FacetCharts'); setTimeout(() => this.setState({ 'mounted' : true }), 100); } } /** * @ignore */ componentDidUpdate(pastProps, pastState){ if (this.props.debug){ var propKeys = _.keys(this.props), stateKeys = _.keys(this.state), i; for (i = 0; i < propKeys.length; i++){ if (this.props[propKeys[i]] !== pastProps[propKeys[i]]){ console.log('DIFFERENT PROP:', propKeys[i], pastProps[propKeys[i]], this.props[propKeys[i]]); } } for (i = 0; i < stateKeys.length; i++){ if (this.state[stateKeys[i]] !== pastState[stateKeys[i]]){ console.log('DIFFERENT STATE:', stateKeys[i], pastState[stateKeys[i]], this.state[stateKeys[i]]); } } } } /** * Given `this.props`, determines if element is currently meant to be invisible (false) or a certain layout ({string}). * * @instance * @private * @param {Object} [props=this.props] - Representation of current or next props for this component. * @returns {string|boolean} What layout should currently be rendered. */ show(props = this.props){ if (props.show === false) return false; if (typeof props.show === 'string' && props.views.indexOf(props.show) > -1) return props.show; if (typeof props.show === 'function') { var show; if (typeof props.href === 'string') { const urlParts = memoizedUrlParse(props.href); show = props.show(urlParts.pathname, urlParts.search, urlParts.hash); } else { show = props.show(); } if (show === false) return false; // If true, continue to use default ('small') if (props.views.indexOf(show) > -1) return show; } return props.views[0]; // Default } /** Defines buttons/actions to be shown in onHover popover. */ cursorDetailActions(){ const { href, browseBaseState, context } = this.props; const isBrowseHref = navigate.isBrowseHref(href); const currExpSetFilters = searchFilters.contextFiltersToExpSetFilters(context && context.filters); return [ { 'title' : isBrowseHref ? 'Explore' : 'Browse', 'function' : function(cursorProps, mouseEvt){ var baseParams = navigate.getBrowseBaseParams(browseBaseState), browseBaseHref = navigate.getBrowseBaseHref(baseParams); // Reset existing filters if selecting from 'all' view. Preserve if from filtered view. var currentExpSetFilters = browseBaseState === 'all' ? {} : currExpSetFilters; var newExpSetFilters = _.reduce(cursorProps.path, function(expSetFilters, node){ // Do not change filter IF SET ALREADY because we want to strictly enable filters, not disable any. if (expSetFilters && expSetFilters[node.field] && expSetFilters[node.field].has(node.term)){ return expSetFilters; } return searchFilters.changeFilter(node.field, node.term, expSetFilters, null, true);// Existing expSetFilters, if null they're retrieved from Redux store, only return new expSetFilters vs saving them == set to TRUE }, currentExpSetFilters); // Register 'Set Filter' event for each field:term pair (node) of selected Bar Section. _.forEach(cursorProps.path, function(node){ analytics.event('BarPlot', 'Set Filter', { 'eventLabel' : analytics.eventLabelFromChartNode(node, false), // 'New' filter logged here. 'field' : node.field, 'term' : node.term, 'currentFilters' : analytics.getStringifiedCurrentFilters(currExpSetFilters), // 'Existing' filters, or filters at time of action, go here. }); }); searchFilters.saveChangedFilters(newExpSetFilters, browseBaseHref, () => { // Scroll to top of browse page container after navigation is complete. setTimeout(layout.animateScrollTo, 200, "content", Math.abs(layout.getPageVerticalScrollPosition() - 510) * 2, 79); }); }, 'disabled' : function(cursorProps){ if (currExpSetFilters && typeof currExpSetFilters === 'object'){ if ( Array.isArray(cursorProps.path) && (cursorProps.path[0] && cursorProps.path[0].field) && currExpSetFilters[cursorProps.path[0].field] instanceof Set && currExpSetFilters[cursorProps.path[0].field].has(cursorProps.path[0].term) && ( !cursorProps.path[1] || ( cursorProps.path[1].field && currExpSetFilters[cursorProps.path[1].field] instanceof Set && currExpSetFilters[cursorProps.path[1].field].has(cursorProps.path[1].term) ) ) ) return true; } return false; } } ]; } /** * @private * @returns {JSX.Element} Area with BarPlot chart, wrapped by `ChartDataController.Provider` instance. */ render(){ const show = this.show(); if (!show) return null; // We don't show section at all. const { context, debug, windowWidth, colWidthPerScreenSize, schemas, href, isFullscreen } = this.props; const { mounted } = this.state; if (context && context.total === 0) return null; if (debug) console.log('WILL SHOW FACETCHARTS', show, href); const gridState = layout.responsiveGridState(windowWidth || null); const cursorDetailActions = this.cursorDetailActions(); const browseBaseParams = navigate.getBrowseBaseParams(); const expSetFilters = searchFilters.contextFiltersToExpSetFilters(context && context.filters, browseBaseParams); let height = show === 'small' ? 300 : 450; let width; if (gridState === 'xs'){ width = windowWidth - 20; } else if (gridState === 'sm'){ width = layout.gridContainerWidth(windowWidth); } else if (isFullscreen){ width = parseInt((windowWidth - 40) * 0.75) - 20; } else { width = parseInt(layout.gridContainerWidth(windowWidth) * 0.75); } if (mounted && gridState === 'xs') height = Math.min(height, 240); //vizUtil.unhighlightTerms(); if (!mounted){ return ( // + 30 == breadcrumbs (26) + breadcrumbs-margin-bottom (10) + description (30) <div className={"facet-charts loading " + show} key="facet-charts" style={{ 'height' : height }}> <i className="icon icon-spin icon-circle-notch fas" style={{ 'top' : (height / 2 - 30) + 'px' }} /> </div> ); } if (debug) console.log('FacetCharts SCHEMAS AT RENDER', schemas); return ( <div className={"facet-charts show-" + show} key="facet-charts"> <ChartDataController.Provider id="barplot1"> <BarPlot.UIControlsWrapper legend chartHeight={height} {...{ href, windowWidth, cursorDetailActions, expSetFilters }}> <BarPlot.Chart {...{ width, height, schemas, windowWidth, href, cursorDetailActions, context }} /> </BarPlot.UIControlsWrapper> </ChartDataController.Provider> </div> ); } }
actor-apps/app-web/src/app/utils/require-auth.js
changjiashuai/actor-platform
import React from 'react'; import LoginStore from 'stores/LoginStore'; export default (Component) => { return class Authenticated extends React.Component { static willTransitionTo(transition) { if (!LoginStore.isLoggedIn()) { transition.redirect('/auth', {}, {'nextPath': transition.path}); } } render() { return <Component {...this.props}/>; } }; };
src/components/Main.js
joshsalom/quarrelofcuties
import React from 'react'; import {Switch, Route} from 'react-router-dom'; import Scrim from './Scrim'; import Leaderboard from './Leaderboard'; class Main extends React.Component { render() { return ( <main> <Switch> <Route exact path='/' component={Scrim}/> <Route path='/leaderboard' component={Leaderboard}/> </Switch> </main> ); } } export default Main;
app/components/ResumeEducationSection/index.js
yagneshmodh/personalApplication
import React from 'react'; import Title from '../Title/index'; import baseStyle from '../../common/Style/baseStyle.css'; // import Paper from 'material-ui/Paper'; import SwipeWrapper from '../../containers/SwipeWrapper/index'; import ProjectCard from '../ProjectCard/index'; const PortfolioSection = (() => <div className={baseStyle.wrapper}> <Title caption="Here are Some of" title="My Projects" /> <SwipeWrapper minWidth={300} navigation> <ProjectCard /> <ProjectCard /> <ProjectCard /> </SwipeWrapper> </div> ); export default PortfolioSection;
src/svg-icons/image/switch-video.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageSwitchVideo = (props) => ( <SvgIcon {...props}> <path d="M18 9.5V6c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-3.5l4 4v-13l-4 4zm-5 6V13H7v2.5L3.5 12 7 8.5V11h6V8.5l3.5 3.5-3.5 3.5z"/> </SvgIcon> ); ImageSwitchVideo = pure(ImageSwitchVideo); ImageSwitchVideo.displayName = 'ImageSwitchVideo'; ImageSwitchVideo.muiName = 'SvgIcon'; export default ImageSwitchVideo;
app/javascript/mastodon/containers/status_container.js
dunn/mastodon
import React from 'react'; import { connect } from 'react-redux'; import Status from '../components/status'; import { makeGetStatus } from '../selectors'; import { replyCompose, mentionCompose, directCompose, } from '../actions/compose'; import { reblog, favourite, bookmark, unreblog, unfavourite, unbookmark, pin, unpin, } from '../actions/interactions'; import { muteStatus, unmuteStatus, deleteStatus, hideStatus, revealStatus, toggleStatusCollapse, } from '../actions/statuses'; import { unmuteAccount, unblockAccount, } from '../actions/accounts'; import { blockDomain, unblockDomain, } from '../actions/domain_blocks'; import { initMuteModal } from '../actions/mutes'; import { initBlockModal } from '../actions/blocks'; import { initReport } from '../actions/reports'; import { openModal } from '../actions/modal'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { boostModal, deleteModal } from '../initial_state'; import { showAlertForError } from '../actions/alerts'; const messages = defineMessages({ deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' }, deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' }, redraftConfirm: { id: 'confirmations.redraft.confirm', defaultMessage: 'Delete & redraft' }, redraftMessage: { id: 'confirmations.redraft.message', defaultMessage: 'Are you sure you want to delete this status and re-draft it? Favourites and boosts will be lost, and replies to the original post will be orphaned.' }, replyConfirm: { id: 'confirmations.reply.confirm', defaultMessage: 'Reply' }, replyMessage: { id: 'confirmations.reply.message', defaultMessage: 'Replying now will overwrite the message you are currently composing. Are you sure you want to proceed?' }, blockDomainConfirm: { id: 'confirmations.domain_block.confirm', defaultMessage: 'Hide entire domain' }, }); const makeMapStateToProps = () => { const getStatus = makeGetStatus(); const mapStateToProps = (state, props) => ({ status: getStatus(state, props), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { intl }) => ({ onReply (status, router) { dispatch((_, getState) => { let state = getState(); if (state.getIn(['compose', 'text']).trim().length !== 0) { dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.replyMessage), confirm: intl.formatMessage(messages.replyConfirm), onConfirm: () => dispatch(replyCompose(status, router)), })); } else { dispatch(replyCompose(status, router)); } }); }, onModalReblog (status) { if (status.get('reblogged')) { dispatch(unreblog(status)); } else { dispatch(reblog(status)); } }, onReblog (status, e) { if ((e && e.shiftKey) || !boostModal) { this.onModalReblog(status); } else { dispatch(openModal('BOOST', { status, onReblog: this.onModalReblog })); } }, onFavourite (status) { if (status.get('favourited')) { dispatch(unfavourite(status)); } else { dispatch(favourite(status)); } }, onBookmark (status) { if (status.get('bookmarked')) { dispatch(unbookmark(status)); } else { dispatch(bookmark(status)); } }, onPin (status) { if (status.get('pinned')) { dispatch(unpin(status)); } else { dispatch(pin(status)); } }, onEmbed (status) { dispatch(openModal('EMBED', { url: status.get('url'), onError: error => dispatch(showAlertForError(error)), })); }, onDelete (status, history, withRedraft = false) { if (!deleteModal) { dispatch(deleteStatus(status.get('id'), history, withRedraft)); } else { dispatch(openModal('CONFIRM', { message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage), confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm), onConfirm: () => dispatch(deleteStatus(status.get('id'), history, withRedraft)), })); } }, onDirect (account, router) { dispatch(directCompose(account, router)); }, onMention (account, router) { dispatch(mentionCompose(account, router)); }, onOpenMedia (media, index) { dispatch(openModal('MEDIA', { media, index })); }, onOpenVideo (media, time) { dispatch(openModal('VIDEO', { media, time })); }, onBlock (status) { const account = status.get('account'); dispatch(initBlockModal(account)); }, onUnblock (account) { dispatch(unblockAccount(account.get('id'))); }, onReport (status) { dispatch(initReport(status.get('account'), status)); }, onMute (account) { dispatch(initMuteModal(account)); }, onUnmute (account) { dispatch(unmuteAccount(account.get('id'))); }, onMuteConversation (status) { if (status.get('muted')) { dispatch(unmuteStatus(status.get('id'))); } else { dispatch(muteStatus(status.get('id'))); } }, onToggleHidden (status) { if (status.get('hidden')) { dispatch(revealStatus(status.get('id'))); } else { dispatch(hideStatus(status.get('id'))); } }, onToggleCollapsed (status, isCollapsed) { dispatch(toggleStatusCollapse(status.get('id'), isCollapsed)); }, onBlockDomain (domain) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.domain_block.message' defaultMessage='Are you really, really sure you want to block the entire {domain}? In most cases a few targeted blocks or mutes are sufficient and preferable. You will not see content from that domain in any public timelines or your notifications. Your followers from that domain will be removed.' values={{ domain: <strong>{domain}</strong> }} />, confirm: intl.formatMessage(messages.blockDomainConfirm), onConfirm: () => dispatch(blockDomain(domain)), })); }, onUnblockDomain (domain) { dispatch(unblockDomain(domain)); }, }); export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Status));
lib/components/notifications.js
chabou/hyper
import React from 'react'; import {decorate} from '../utils/plugins'; import Notification_ from './notification'; const Notification = decorate(Notification_, 'Notification'); export default class Notifications extends React.PureComponent { render() { return ( <div className="notifications_view"> {this.props.customChildrenBefore} {this.props.fontShowing && ( <Notification key="font" backgroundColor="rgba(255, 255, 255, .2)" text={`${this.props.fontSize}px`} userDismissable={false} onDismiss={this.props.onDismissFont} dismissAfter={1000} /> )} {this.props.resizeShowing && ( <Notification key="resize" backgroundColor="rgba(255, 255, 255, .2)" text={`${this.props.cols}x${this.props.rows}`} userDismissable={false} onDismiss={this.props.onDismissResize} dismissAfter={1000} /> )} {this.props.messageShowing && ( <Notification key="message" backgroundColor="#FE354E" text={this.props.messageText} onDismiss={this.props.onDismissMessage} userDismissable={this.props.messageDismissable} userDismissColor="#AA2D3C" > {this.props.messageURL ? [ this.props.messageText, ' (', <a key="link" style={{color: '#fff'}} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={this.props.messageURL} > more </a>, ')' ] : null} </Notification> )} {this.props.updateShowing && ( <Notification key="update" backgroundColor="#18E179" color="#000" text={`Version ${this.props.updateVersion} ready`} onDismiss={this.props.onDismissUpdate} userDismissable > Version <b>{this.props.updateVersion}</b> ready. {this.props.updateNote && ` ${this.props.updateNote.trim().replace(/\.$/, '')}`} (<a style={{color: '#000'}} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={`https://github.com/zeit/hyper/releases/tag/${this.props.updateVersion}`} > notes </a>).{' '} {this.props.updateCanInstall ? ( <a style={{ cursor: 'pointer', textDecoration: 'underline', fontWeight: 'bold' }} onClick={this.props.onUpdateInstall} > Restart </a> ) : ( <a style={{ color: '#000', cursor: 'pointer', textDecoration: 'underline', fontWeight: 'bold' }} onClick={ev => { window.require('electron').shell.openExternal(ev.target.href); ev.preventDefault(); }} href={this.props.updateReleaseUrl} > Download </a> )}.{' '} </Notification> )} {this.props.customChildren} <style jsx>{` .notifications_view { position: fixed; bottom: 20px; right: 20px; } `}</style> </div> ); } }
assets/js/components/home.js
joshgagnon/sailjs-webpack-base
"use strict"; import React from 'react'; import { pureRender } from '../utils'; import AuthenticatedComponent from './authenticated'; @AuthenticatedComponent @pureRender export default class Home extends React.Component { render() { return <div/> } }
blueocean-material-icons/src/js/components/svg-icons/content/send.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ContentSend = (props) => ( <SvgIcon {...props}> <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/> </SvgIcon> ); ContentSend.displayName = 'ContentSend'; ContentSend.muiName = 'SvgIcon'; export default ContentSend;
app/jsx/blueprint_courses/apps/BlueprintCourse.js
venturehive/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { ConnectedCourseSidebar } from '../components/CourseSidebar' import FlashNotifications from '../flashNotifications' import createStore from '../store' import Router from '../router' export default class BlueprintCourse { constructor (root, data, debug) { this.root = root this.store = createStore(data, debug) this.router = new Router() } routes = [{ path: Router.PATHS.singleMigration, onEnter: ({ params }) => this.app.showChangeLog(params), onExit: () => this.app.hideChangeLog(), }] setupRouter () { this.router.registerRoutes(this.routes) this.router.start() } unmount () { ReactDOM.unmountComponentAtNode(this.root) } render () { ReactDOM.render( <Provider store={this.store}> <ConnectedCourseSidebar routeTo={this.router.page} realRef={(c) => { this.app = c }} /> </Provider>, this.root ) } start () { FlashNotifications.subscribe(this.store) this.render() if (window.location.hash.indexOf('#!/blueprint') === 0) { this.setupRouter() } } }
src/components/Menu/TopMenu.js
joopand/presensi
import React from 'react' import { Link } from 'react-router' class TopMenu extends React.Component { constructor (props) { super(props) this.state = {openMenu: false} } openMenu () { console.log('hi') console.log(this.state.openMenu) if (this.state.openMenu) { this.setState({openMenu: false}) } else { this.setState({openMenu: true}) } } componentDidMount () { $(function() { $('.nav-open' ).removeClass() var $toggle = $('.navbar-toggle') $toggle.click(function() { setTimeout(function(){ $('.navbar-toggle').addClass('toggled'); }, 430) var $layer = $('<div class="close-layer"></div>') $layer.appendTo(".main-panel") setTimeout(function(){ $layer.addClass('visible') }, 100) $layer.click(function() { $('html').removeClass('nav-open') // mobile_menu_visible = 0 $layer.removeClass('visible') setTimeout(function(){ $layer.remove() $toggle.removeClass('toggled') }, 400) }) $('html').addClass('nav-open') }) }) } render () { return ( <nav className='navbar navbar-default'> <div className='container-fluid'> <div className='navbar-header'> <button type='button' className='navbar-toggle' data-toggle='collapse'> <span className='sr-only'>Toggle navigation</span> <span className='icon-bar'></span> <span className='icon-bar'></span> <span className='icon-bar'></span> </button> </div> <div className='collapse navbar-collapse'> <ul className='nav navbar-nav navbar-right'> <li className={'dropdown dropdown-with-icons' + (this.state.openMenu ? ' open' : '')}> <Link to='/logout' className='btn btn-fill btn-warning btn-wd text-danger'> <i className='pe-7s-close-circle'></i> Log out </Link> </li> </ul> </div> </div> </nav> // <div className='ui stackable menu'> // <div className='ui container'> // <a className='item'> // <i className='home icon'></i> Home // </a> // // <div className='right item'> // Logged in as // <div className='ui simple inline dropdown item'> // <div className='text'> // Nama // </div> // <i className='dropdown icon'></i> // <div className='menu'> // <a className='item'> // <i className='sign out icon'> // </i>Logout // </a> // </div> // </div> // </div> // </div> // </div> ) } } export default TopMenu
docs/app/Examples/collections/Grid/Variations/GridExampleVerticalAlignmentRow.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Grid, Image } from 'semantic-ui-react' const GridExampleVerticalAlignmentRow = () => ( <Grid columns={4} centered> <Grid.Row verticalAlign='top'> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> <br /> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> <Grid.Row verticalAlign='middle'> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> <br /> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> <Grid.Row verticalAlign='bottom'> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> <br /> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> </Grid> ) export default GridExampleVerticalAlignmentRow
src/containers/organizations/components/OrganizationDetailsComponent.js
kryptnostic/gallery
import React from 'react'; import DocumentTitle from 'react-document-title'; import Immutable from 'immutable'; import styled from 'styled-components'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import LoadingSpinner from '../../../components/asynccontent/LoadingSpinner'; import Button from '../../../components/buttons/Button'; import StyledFlexContainerStacked from '../../../components/flex/StyledFlexContainerStacked'; import OrganizationAddMembersSectionComponent from './OrganizationAddMembersSectionComponent'; import OrganizationDescriptionSectionComponent from './OrganizationDescriptionSectionComponent'; import OrganizationEntitySetsSectionComponent from './OrganizationEntitySetsSectionComponent'; import OrganizationNameSectionComponent from './OrganizationNameSectionComponent'; import OrganizationDomainsSectionComponent from './OrganizationDomainsSectionComponent'; import OrganizationIntegrationDetailsSectionComponent from './OrganizationIntegrationDetailsSectionComponent'; import OrganizationMembersSectionComponent from './OrganizationMembersSectionComponent'; import OrganizationRolesSectionComponent from './OrganizationRolesSectionComponent'; import OrganizationTitleSectionComponent from './OrganizationTitleSectionComponent'; import OrganizationTrustedOrgsSectionComponent from './OrganizationTrustedOrgsSectionComponent'; import OrganizationDeleteConfirmationModal from './OrganizationDeleteConfirmationModal'; import { isDefined, isNonEmptyString } from '../../../utils/LangUtils'; import { deleteOrganizationRequest, getOrganizationIntegrationAccount, fetchMembersRequest, loadTrustedOrganizationsRequest, loadOrganizationEntitySets, showDeleteModal, hideDeleteModal } from '../actions/OrganizationActionFactory'; import { fetchOrganizationRequest, fetchOrganizationsRequest } from '../actions/OrganizationsActionFactory'; const LoadingSpinnerWrapper = styled.div` width: 100%; `; const DeleteButtonSection = styled.div` width: 100%; display: flex; justify-content: center; margin-top: 50px; `; const MODES = { CREATE: 'CREATE', EDIT: 'EDIT', VIEW: 'VIEW' }; function mapStateToProps(state, ownProps) { const isCreatingOrg = state.getIn(['organizations', 'isCreatingOrg']); const isFetchingOrg = state.getIn(['organizations', 'isFetchingOrg']); const isConfirmingDeletion = state.getIn(['organizations', 'isConfirmingDeletion']); const ownedRoles = state.getIn(['organizations', 'ownedRoles']); // TODO: checking if orgId === 'new' feels wrong. there's probably a better pattern for this use case. if (isDefined(ownProps.params) && ownProps.params.orgId === 'new') { return { isCreatingOrg, isFetchingOrg: false, isConfirmingDeletion, mode: MODES.CREATE, organization: Immutable.fromJS({ isOwner: true }), organizationId: '', ownedRoles, members: Immutable.List() }; } let mode = MODES.VIEW; let organizationId; if (isDefined(ownProps.params) && isNonEmptyString(ownProps.params.orgId)) { organizationId = ownProps.params.orgId; } const organization = state.getIn(['organizations', 'organizations', organizationId], Immutable.Map()); if (organization.get('isOwner') === true) { mode = MODES.EDIT; } const members = state.getIn(['organizations', 'members'], Immutable.List()); return { isCreatingOrg, isFetchingOrg, isConfirmingDeletion, mode, organization, organizationId, ownedRoles, members }; } function mapDispatchToProps(dispatch) { const actions = { deleteOrganizationRequest, fetchMembersRequest, getOrganizationIntegrationAccount, loadTrustedOrganizationsRequest, fetchOrganizationRequest, fetchOrganizationsRequest, loadOrganizationEntitySets, showDeleteModal, hideDeleteModal }; return { actions: bindActionCreators(actions, dispatch) }; } class OrganizationDetailsComponent extends React.Component { static propTypes = { actions: React.PropTypes.shape({ deleteOrganizationRequest: React.PropTypes.func.isRequired, fetchMembersRequest: React.PropTypes.func.isRequired, fetchOrganizationRequest: React.PropTypes.func.isRequired, loadTrustedOrganizationsRequest: React.PropTypes.func.isRequired, loadOrganizationEntitySets: React.PropTypes.func.isRequired, showDeleteModal: React.PropTypes.func.isRequired, hideDeleteModal: React.PropTypes.func.isRequired }).isRequired, isCreatingOrg: React.PropTypes.bool.isRequired, isFetchingOrg: React.PropTypes.bool.isRequired, isConfirmingDeletion: React.PropTypes.bool.isRequired, mode: React.PropTypes.string.isRequired, organization: React.PropTypes.instanceOf(Immutable.Map).isRequired, organizationId: React.PropTypes.string.isRequired, ownedRoles: React.PropTypes.instanceOf(Immutable.Set).isRequired } componentDidMount() { const { actions, mode, organization, organizationId } = this.props; if (mode === MODES.VIEW || mode === MODES.EDIT) { actions.fetchOrganizationRequest(organizationId); actions.fetchMembersRequest(organizationId); actions.fetchOrganizationsRequest(); actions.loadOrganizationEntitySets(organizationId); if (organization.get('isOwner')) { actions.loadTrustedOrganizationsRequest(organizationId); actions.getOrganizationIntegrationAccount(organizationId); } } } componentWillReceiveProps(nextProps :Object) { const { actions, organizationId, organization } = this.props; if (nextProps.mode === MODES.VIEW || nextProps.mode === MODES.EDIT) { if (organizationId !== nextProps.organizationId) { actions.fetchOrganizationRequest(nextProps.organizationId); actions.fetchMembersRequest(nextProps.organizationId); actions.loadOrganizationEntitySets(nextProps.organizationId); } if (organization !== nextProps.organization && nextProps.organization.get('isOwner')) { actions.loadTrustedOrganizationsRequest(organizationId); actions.getOrganizationIntegrationAccount(organizationId); } } } renderOrganizationTitleSection = () => { const { organization, ownedRoles } = this.props; return ( <OrganizationTitleSectionComponent organization={organization} ownedRoles={ownedRoles} /> ); } renderOrganizationDescriptionSection = () => { // hide in create mode if (this.props.mode === MODES.CREATE) { return null; } return ( <OrganizationDescriptionSectionComponent organization={this.props.organization} /> ); } renderOrganizationNameSection = () => { // hide in create mode if (this.props.mode === MODES.CREATE) { return null; } return ( <OrganizationNameSectionComponent organization={this.props.organization} /> ); } renderOrganizationIntegrationAccountSection = () => { // hide in create mode or if user is not an organization owner if (this.props.mode === MODES.CREATE || !this.props.organization.get('isOwner')) { return null; } return ( <OrganizationIntegrationDetailsSectionComponent organization={this.props.organization} /> ); } renderOrganizationDomainsSection = () => { if (this.props.mode === MODES.CREATE) { return null; } return ( <OrganizationDomainsSectionComponent organization={this.props.organization} /> ); } renderOrganizationRolesSection = () => { if (this.props.mode === MODES.CREATE) { return null; } return ( <OrganizationRolesSectionComponent organization={this.props.organization} /> ); } renderOrganizationTrustedOrgsSection = () => { if (this.props.mode === MODES.CREATE) { return null; } if (this.props.organization.get('isOwner')) { return <OrganizationTrustedOrgsSectionComponent organization={this.props.organization} /> } return null; } renderOrganizationMembersSection = () => { if (this.props.mode === MODES.CREATE) { return null; } return ( <OrganizationMembersSectionComponent organization={this.props.organization} users={this.props.members} /> ); } renderOrganizationAddMembersSection = () => { if (this.props.mode === MODES.CREATE) { return null; } return ( <OrganizationAddMembersSectionComponent organization={this.props.organization} /> ); } renderOrganizationEntitySetsSection = () => { if (this.props.mode === MODES.CREATE) { return null; } return ( <OrganizationEntitySetsSectionComponent organization={this.props.organization} /> ); } handleOnClickDeleteButton = () => { this.props.actions.showDeleteModal(); } handleCancelDelete = () => { this.props.actions.hideDeleteModal(); } handleConfirmDelete = () => { this.props.actions.deleteOrganizationRequest(this.props.organizationId); } renderOrganizationDeleteButton = () => { const isOwner = this.props.organization.get('isOwner', false); if (this.props.mode === MODES.CREATE || !isOwner) { return null; } return ( <DeleteButtonSection> <Button scStyle="red" onClick={this.handleOnClickDeleteButton}> Delete Organization </Button> </DeleteButtonSection> ); } renderLoadingSpinner = () => { return ( <LoadingSpinnerWrapper> <LoadingSpinner /> </LoadingSpinnerWrapper> ); } render() { const title = this.props.organization.get('title', 'Organizations'); const { isConfirmingDeletion } = this.props; if (this.props.isCreatingOrg) { return ( <DocumentTitle title={title}> <StyledFlexContainerStacked> { this.renderOrganizationTitleSection() } { this.renderLoadingSpinner() } </StyledFlexContainerStacked> </DocumentTitle> ); } if (this.props.isFetchingOrg) { return ( <DocumentTitle title={title}> <StyledFlexContainerStacked> { this.renderLoadingSpinner() } </StyledFlexContainerStacked> </DocumentTitle> ); } return ( <DocumentTitle title={title}> <StyledFlexContainerStacked> { this.renderOrganizationTitleSection() } { this.renderOrganizationDescriptionSection() } { this.renderOrganizationNameSection() } { this.renderOrganizationIntegrationAccountSection() } { this.renderOrganizationDomainsSection() } { this.renderOrganizationRolesSection() } { this.renderOrganizationTrustedOrgsSection() } { this.renderOrganizationMembersSection() } { this.renderOrganizationAddMembersSection() } { this.renderOrganizationEntitySetsSection() } { this.renderOrganizationDeleteButton() } <OrganizationDeleteConfirmationModal isConfirmingDeletion={isConfirmingDeletion} handleCancelDelete={this.handleCancelDelete} handleConfirmDelete={this.handleConfirmDelete} /> </StyledFlexContainerStacked> </DocumentTitle> ); } } export default connect(mapStateToProps, mapDispatchToProps)(OrganizationDetailsComponent);
classic/src/scenes/wbfa/generated/FASMagic.free.js
wavebox/waveboxapp
import React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faMagic } from '@fortawesome/free-solid-svg-icons/faMagic' export default class FASMagic extends React.Component { render () { return (<FontAwesomeIcon {...this.props} icon={faMagic} />) } }
react-native/Manager/src/components/EmployeeForm.js
vanyaland/react-demos
import React, { Component } from 'react'; import { View, Text, Picker } from 'react-native'; import { connect } from 'react-redux'; import { CardSection, Input } from './common'; import { employeeUpdate } from '../actions'; class EmployeeForm extends Component { render() { const { name, phone, shift, employeeUpdate } = this.props; return ( <View> <CardSection> <Input label="Name" placeholder="Enter your name" value={name} onChangeText={value => employeeUpdate({ prop: 'name', value })} //onChangeText={text => employeeUpdate({ prop: 'name', value: text })} /> </CardSection> <CardSection> <Input label="Phone" placeholder="555-555-5555" value={phone} onChangeText={value => employeeUpdate({ prop: 'phone', value })} /> </CardSection> <CardSection style={{ flexDirection: 'column' }}> <Text style={styles.pickerTextStyle}>Shift</Text> <Picker selectedValue={shift} onValueChange={value => this.props.employeeUpdate({ prop: 'shift', value })} > <Picker.Item label="Monday" value="Monday" /> <Picker.Item label="Tuesday" value="Tuesday" /> <Picker.Item label="Wednesday" value="Wednesday" /> <Picker.Item label="Thursday" value="Thursday" /> <Picker.Item label="Friday" value="Friday" /> <Picker.Item label="Saturday" value="Saturday" /> <Picker.Item label="Sunday" value="Sunday" /> </Picker> </CardSection> </View> ); } } const styles = { pickerTextStyle: { fontSize: 18, paddingLeft: 20 } }; const mapStateToProps = (state) => { const { name, phone, shift } = state.employeeForm; return { name, phone, shift }; }; export default connect(mapStateToProps, { employeeUpdate })(EmployeeForm);
src/components/Card.js
pieroit/cheshire-cat
import React from 'react' import utils from './../utils' class Card extends React.Component { state = { 'filters' : {}, 'data' : [] } onFiltersChange = (filtersStatus) => { console.warn('CARD FILTER CHANGE', filtersStatus) this.setState({ 'filters': filtersStatus }) } // Executed when data arrives, to transofrm data before passing them to sub-components onData = (res) => { console.warn('CARD HAS NEW DATA', res) if(res) { this.setState({ 'data': res }) } } render() { let component = this let children = React.Children.map( this.props.children, child => { //console.log(child.type.name) // Give every sub-component additional pertaining props let augmentedProps = Object.assign({}, child.props) if(child.type.name === 'Filters'){ augmentedProps.notifyCardThatfiltersChanged = component.onFiltersChange augmentedProps.filtersStatus = component.state.filters } if(child.type.name === 'DataSource'){ augmentedProps.notifyCardThatDataArrived = component.onData } if(child.type.name === 'LookingGlass'){ augmentedProps.data = component.state.data } return ( <child.type {...augmentedProps} /> ) } ) return ( <div className="cheshire-card"> {utils.jsonPrettyPrint(this.state.filters)} {children} </div> ) } } export default Card
src/containers/Navigation/Navigation.js
prashanth-cpaul/ReactReduxSample
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import styles from './Navigation.css'; import { menuClicked } from 'state/navigation'; const headerIcon = require('../../images/header_icon.jpg'); var menuStylesClass = styles.menuStyles; class Navigation extends Component{ constructor(props){ super(props); this.handleNavClick = this.handleNavClick.bind(this); this.handleMenuItemClick = this.handleMenuItemClick.bind(this); this.updateNavigationStyle = this.updateNavigationStyle.bind(this); } updateNavigationStyle() { // to handle the case where the menu(viewport width < 400px) is open and // the viewport width is increased var width = window.innerWidth; if(this.props.isPressed && width > 400){ menuStylesClass = styles.menuStyles; this.props.menuClicked(false); } } componentDidMount() { window.addEventListener("resize", this.updateNavigationStyle); } componentWillUnmount() { window.removeEventListener("resize", this.updateNavigationStyle); } handleNavClick(){ if (this.props.isPressed){ menuStylesClass = styles.menuStyles; this.props.menuClicked(false); }else{ menuStylesClass = styles.menuStylesOpen; this.props.menuClicked(true); } } handleMenuItemClick(){ menuStylesClass = styles.menuStyles; this.props.menuClicked(false); } render() { return ( <div className={styles.wrapper}> <div className={styles.headerIconWrapper}> <img src={headerIcon} className={styles.headerIcon} /> </div> <nav> <a className={styles.burgerNav} onClick={this.handleNavClick}></a> <ul className={menuStylesClass} onClick={this.handleMenuItemClick}> <li><Link to="/">Home</Link></li> <li><Link to="stats">Stats</Link></li> <li><Link to="videos">Videos</Link></li> <li><Link to="">Gallery</Link></li> </ul> </nav> </div> ); } } const mapStateToProps = (state) => ({ isPressed: state.navigation.isPressed }); export default connect(mapStateToProps, { menuClicked })(Navigation);
actor-apps/app-web/src/app/components/Login.react.js
bensonX/actor-platform
import _ from 'lodash'; import React from 'react'; import classNames from 'classnames'; import { Styles, RaisedButton, TextField } from 'material-ui'; import { AuthSteps } from 'constants/ActorAppConstants'; import Banner from 'components/common/Banner.react'; import LoginActionCreators from 'actions/LoginActionCreators'; import LoginStore from 'stores/LoginStore'; import ActorTheme from 'constants/ActorTheme'; const ThemeManager = new Styles.ThemeManager(); let getStateFromStores = function () { return ({ step: LoginStore.getStep(), errors: LoginStore.getErrors(), smsRequested: LoginStore.isSmsRequested(), signupStarted: LoginStore.isSignupStarted(), codeSent: false }); }; class Login extends React.Component { static contextTypes = { router: React.PropTypes.func }; static childContextTypes = { muiTheme: React.PropTypes.object }; getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } componentWillUnmount() { LoginStore.removeChangeListener(this.onChange); } componentDidMount() { this.handleFocus(); } componentDidUpdate() { this.handleFocus(); } constructor(props) { super(props); this.state = _.assign({ phone: '', name: '', code: '' }, getStateFromStores()); ThemeManager.setTheme(ActorTheme); if (LoginStore.isLoggedIn()) { window.setTimeout(() => this.context.router.replaceWith('/'), 0); } else { LoginStore.addChangeListener(this.onChange); } } onChange = () => { this.setState(getStateFromStores()); } onPhoneChange = event => { this.setState({phone: event.target.value}); } onCodeChange = event => { this.setState({code: event.target.value}); } onNameChange = event => { this.setState({name: event.target.value}); } onRequestSms = event => { event.preventDefault(); LoginActionCreators.requestSms(this.state.phone); } onSendCode = event => { event.preventDefault(); LoginActionCreators.sendCode(this.context.router, this.state.code); } onSignupRequested = event => { event.preventDefault(); LoginActionCreators.sendSignup(this.context.router, this.state.name); } onWrongNumberClick = event => { event.preventDefault(); LoginActionCreators.wrongNumberClick(); } handleFocus = () => { switch (this.state.step) { case AuthSteps.PHONE_WAIT: this.refs.phone.focus(); break; case AuthSteps.CODE_WAIT: this.refs.code.focus(); break; case AuthSteps.SIGNUP_NAME_WAIT: this.refs.name.focus(); break; default: return; } } render() { let requestFormClassName = classNames('login__form', 'login__form--request', { 'login__form--done': this.state.step > AuthSteps.PHONE_WAIT, 'login__form--active': this.state.step === AuthSteps.PHONE_WAIT }); let checkFormClassName = classNames('login__form', 'login__form--check', { 'login__form--done': this.state.step > AuthSteps.CODE_WAIT, 'login__form--active': this.state.step === AuthSteps.CODE_WAIT }); let signupFormClassName = classNames('login__form', 'login__form--signup', { 'login__form--active': this.state.step === AuthSteps.SIGNUP_NAME_WAIT }); return ( <section className="login-new row center-xs middle-xs"> <Banner/> <div className="login-new__welcome col-xs row center-xs middle-xs"> <img alt="Actor messenger" className="logo" src="assets/img/logo.png" srcSet="assets/img/logo@2x.png 2x"/> <article> <h1 className="login-new__heading">Welcome to <strong>Actor</strong></h1> <p> Actor Messenger brings all your business network connections into one place, makes it easily accessible wherever you go. </p> <p> Our aim is to make your work easier, reduce your email amount, make the business world closer by reducing time to find right contacts. </p> </article> <footer> <div className="pull-left"> Actor Messenger © 2015 </div> <div className="pull-right"> <a href="//actor.im/ios">iPhone</a> <a href="//actor.im/android">Android</a> </div> </footer> </div> <div className="login-new__form col-xs-6 col-md-4 row center-xs middle-xs"> <div> <h1 className="login-new__heading">Sign in</h1> <form className={requestFormClassName} onSubmit={this.onRequestSms}> <TextField className="login__form__input" disabled={this.state.step > AuthSteps.PHONE_WAIT} errorText={this.state.errors.phone} floatingLabelText="Phone number" onChange={this.onPhoneChange} ref="phone" type="text" value={this.state.phone}/> <footer className="text-center"> <RaisedButton label="Request code" type="submit"/> </footer> </form> <form className={checkFormClassName} onSubmit={this.onSendCode}> <TextField className="login__form__input" disabled={this.state.step > AuthSteps.CODE_WAIT} errorText={this.state.errors.code} floatingLabelText="Auth code" onChange={this.onCodeChange} ref="code" type="text" value={this.state.code}/> <footer className="text-center"> <RaisedButton label="Check code" type="submit"/> </footer> </form> <form className={signupFormClassName} onSubmit={this.onSignupRequested}> <TextField className="login__form__input" errorText={this.state.errors.signup} floatingLabelText="Your name" onChange={this.onNameChange} ref="name" type="text" value={this.state.name}/> <footer className="text-center"> <RaisedButton label="Sign up" type="submit"/> </footer> </form> </div> </div> </section> ); } } export default Login;
src/routes/Home/components/HomeView.js
38Slava/redux-webrtc
import React from 'react' import DuckImage from '../assets/Duck.jpg' import classes from './HomeView.scss' export const HomeView = () => ( <div> <h4>Welcome!</h4> <img alt='This is a duck, because Redux!' className={classes.duck} src={DuckImage} /> </div> ) export default HomeView
src/components/Html.js
willchertoff/Ben-Kinde
/** * 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 serialize from 'serialize-javascript'; import config from '../config'; /* eslint-disable react/no-danger */ class Html extends React.Component { static propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, styles: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, cssText: PropTypes.string.isRequired, }).isRequired), scripts: PropTypes.arrayOf(PropTypes.string.isRequired), app: PropTypes.object, // eslint-disable-line children: PropTypes.string.isRequired, }; static defaultProps = { styles: [], scripts: [], }; render() { const { title, description, styles, scripts, app, children } = this.props; return ( <html className="no-js" lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <title>{title}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {scripts.map(script => <link key={script} rel="preload" href={script} as="script" />)} <link rel="apple-touch-icon" href="apple-touch-icon.png" /> {styles.map(style => ( <style key={style.id} id={style.id} dangerouslySetInnerHTML={{ __html: style.cssText }} /> ))} </head> <body> <div id="app" dangerouslySetInnerHTML={{ __html: children }} /> <script dangerouslySetInnerHTML={{ __html: `window.App=${serialize(app)}` }} /> {scripts.map(script => <script key={script} src={script} />)} {config.analytics.googleTrackingId && <script dangerouslySetInnerHTML={{ __html: 'window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;' + `ga('create','${config.analytics.googleTrackingId}','auto');ga('send','pageview')` }} /> } {config.analytics.googleTrackingId && <script src="https://www.google-analytics.com/analytics.js" async defer /> } </body> </html> ); } } export default Html;
src/components/RitualsForType.js
TrueWill/embracer
import React from 'react'; import PropTypes from 'prop-types'; export default function RitualsForType({ ritualType, displayName, permutations, selected, updateRituals }) { const handleChange = e => { const rituals = JSON.parse(e.target.value); updateRituals(ritualType, rituals); }; const options = permutations.map(p => { const valueAsString = JSON.stringify(p.value); return ( <option value={valueAsString} key={valueAsString}> {p.description} </option> ); }); return ( <div className="row"> <div className="col-sm-12"> <div className="row"> <div className="col-sm-12">{displayName}</div> </div> <div className="row"> <div className="col-sm-12"> <select value={JSON.stringify(selected)} onChange={handleChange}> {options} </select> </div> </div> </div> </div> ); } RitualsForType.propTypes = { ritualType: PropTypes.string.isRequired, displayName: PropTypes.string.isRequired, permutations: PropTypes.arrayOf( PropTypes.shape({ description: PropTypes.string.isRequired, value: PropTypes.arrayOf(PropTypes.number).isRequired }) ).isRequired, selected: PropTypes.arrayOf(PropTypes.number).isRequired, updateRituals: PropTypes.func.isRequired };
BackUp FIrebase/IQApp/src/components/HomeInit.js
victorditadi/IQApp
import React, { Component } from 'react'; import { View, Text, Image, Dimensions, TouchableOpacity } from 'react-native'; import { Container, Content, Icon } from 'native-base'; import InfoCarousel from './InfoCarousel'; import { ButtonHome, CardSection } from './common'; var width = Dimensions.get('window').width; var height = Dimensions.get('window').height; const styles = { fundoLogo: { flex: 0.5, justifyContent: 'center', alignItems: 'center', marginTop: height * .1 }, fundoScreen: { flex: 3, backgroundColor: '#715696' }, fundoButton: { flex: 0.4, backgroundColor: '#603C8F', flexDirection: 'row' } }; const { fundoLogo, fundoScreen, fundoButton } = styles; class HomeInit extends Component { constructor(props) { super(props); carousel = <InfoCarousel /> this.state = { carousel: carousel } ; } render(){ return ( <View style = {{flex: 1, backgroundColor: '#715696'}}> <View style = {fundoLogo}> <Image source={require('../assets/img/logo-iqmail.png')} /> </View> <View style = {fundoScreen}> {this.state.carousel} </View> <View style = {fundoButton}> {/* <ButtonHome color='#3D3C3C'> Cadastrar </ButtonHome> */} <ButtonHome color='#3D3C3C'> Login </ButtonHome> </View> </View> ); } }; export default HomeInit
src/backend/middleware/ssr.js
opentechinstitute/piecewise
import fs from 'fs'; import { Readable } from 'stream'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { HelmetProvider } from 'react-helmet-async'; import { StaticRouter } from 'react-router-dom'; import { ServerStyleSheets, StylesProvider, ThemeProvider, } from '@material-ui/core/styles'; import CssBaseline from '@material-ui/core/CssBaseline'; import { printDrainHydrateMarks } from 'react-imported-component/server'; import MultiStream from 'multistream'; import App from '../../frontend/components/App.jsx'; import theme from '../../frontend/theme.js'; import { getLogger } from '../log.js'; const log = getLogger('backend:middleware:ssr'); const appString = '<div id="app">'; const stylesString = '<style id="jss-server-side">'; const splitter = '###SPLIT###'; const getHTMLFragments = ({ drainHydrateMarks, rawHTML }) => { log.debug('Getting HTML fragments.'); const [startingRawHTMLFragment, endingRawHTMLFragment] = rawHTML .replace(appString, `${appString}${splitter}`) .split(splitter); const startingHTMLFragment = `${startingRawHTMLFragment}${drainHydrateMarks}`; return [startingHTMLFragment, endingRawHTMLFragment]; }; const getApplicationStream = async (originalUrl, context) => { log.debug('Getting application stream.'); const helmetContext = {}; const app = ( <HelmetProvider context={helmetContext}> <StylesProvider injectFirst> <ThemeProvider theme={theme}> <CssBaseline /> <StaticRouter location={originalUrl} context={context}> <div>SERVER RENDERED</div> <App /> </StaticRouter> </ThemeProvider> </StylesProvider> </HelmetProvider> ); const sheets = new ServerStyleSheets(); const collected = sheets.collect(app); return [collected, sheets]; }; const injectStyles = (htmlFragment, stylesFragment) => { log.debug('Injecting styles.'); return htmlFragment.replace(stylesString, `${stylesString}${stylesFragment}`); }; /** * Installs server-side rendering middleware into the koa app. * * @param {Object} ctx - the koa context object * @param {funtion} next - continue to next middleware */ const ssr = async (ctx, next) => { const context = {}; const [appStream, stylesFragment] = await getApplicationStream( ctx.originalUrl, context, ); log.debug('About to server-side render page.'); let rendered; try { rendered = renderToString(appStream); } catch (err) { ctx.throw(500, `Error while rendering page: ${err}`); } log.debug('Just server-side rendered page.'); if (context.url) { ctx.status = 301; return ctx.redirect(context.url); } if (!ctx.state.htmlEntrypoint) ctx.throw(500, 'No HTML entrypoint specified for SSR.'); let rawHTML; try { rawHTML = fs.readFileSync(ctx.state.htmlEntrypoint).toString(); } catch (e) { ctx.throw(500, `Invalid HTML entrypoint specified: ${e}`); } const [startingHTMLFragment, endingHTMLFragment] = getHTMLFragments({ drainHydrateMarks: printDrainHydrateMarks(), rawHTML: rawHTML, }); const injectedStartingFragment = injectStyles( startingHTMLFragment, stylesFragment.toString(), ); log.debug('Crossing the streams.'); const htmlStream = new MultiStream([ Readable.from(injectedStartingFragment), Readable.from(rendered), Readable.from(endingHTMLFragment), ]); ctx.body = htmlStream; ctx.type = 'html'; await next(); }; export default ssr;
docs/app/Examples/elements/Segment/Variations/SegmentExampleGroupSizes.js
aabustamante/Semantic-UI-React
import React from 'react' import { Segment } from 'semantic-ui-react' const SegmentGroupSizesExample = () => { const sizes = ['mini', 'tiny', 'small', 'large', 'big', 'huge', 'massive'] return ( <div> {sizes.map(size => ( <Segment.Group key={size} size={size}> <Segment> It's a {size} segment </Segment> <Segment> And it's a {size} segment, too </Segment> </Segment.Group> ))} </div> ) } export default SegmentGroupSizesExample
src/svg-icons/action/shop-two.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionShopTwo = (props) => ( <SvgIcon {...props}> <path d="M3 9H1v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2H3V9zm15-4V3c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H5v11c0 1.11.89 2 2 2h14c1.11 0 2-.89 2-2V5h-5zm-6-2h4v2h-4V3zm0 12V8l5.5 3-5.5 4z"/> </SvgIcon> ); ActionShopTwo = pure(ActionShopTwo); ActionShopTwo.displayName = 'ActionShopTwo'; ActionShopTwo.muiName = 'SvgIcon'; export default ActionShopTwo;
src/js/components/List/stories/RenderedList.js
HewlettPackard/grommet
import React from 'react'; import { Box, List, Text } from 'grommet'; const locations = [ 'Boise', 'Fort Collins', 'Los Gatos', 'Palo Alto', 'San Francisco', ]; const data = []; for (let i = 0; i < 40; i += 1) { data.push({ entry: `entry-${i + 1}`, location: locations[i % locations.length], }); } export const RenderedList = () => ( <Box align="center" pad="large"> <List data={data.slice(0, 10)} primaryKey={(item) => ( <Text key={item.entry} size="large" weight="bold"> {item.entry} </Text> )} secondaryKey={(item) => ( <Text key={item.location} size="small" color="dark-4"> {item.location} </Text> )} /> </Box> ); RenderedList.storyName = 'Key render'; export default { title: 'Visualizations/List/Key render', };
app/javascript/mastodon/features/list_editor/index.js
kibousoft/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { injectIntl } from 'react-intl'; import { setupListEditor, clearListSuggestions, resetListEditor } from '../../actions/lists'; import Account from './components/account'; import Search from './components/search'; import Motion from '../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; const mapStateToProps = state => ({ title: state.getIn(['listEditor', 'title']), accountIds: state.getIn(['listEditor', 'accounts', 'items']), searchAccountIds: state.getIn(['listEditor', 'suggestions', 'items']), }); const mapDispatchToProps = dispatch => ({ onInitialize: listId => dispatch(setupListEditor(listId)), onClear: () => dispatch(clearListSuggestions()), onReset: () => dispatch(resetListEditor()), }); @connect(mapStateToProps, mapDispatchToProps) @injectIntl export default class ListEditor extends ImmutablePureComponent { static propTypes = { listId: PropTypes.string.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, onInitialize: PropTypes.func.isRequired, onClear: PropTypes.func.isRequired, onReset: PropTypes.func.isRequired, title: PropTypes.string.isRequired, accountIds: ImmutablePropTypes.list.isRequired, searchAccountIds: ImmutablePropTypes.list.isRequired, }; componentDidMount () { const { onInitialize, listId } = this.props; onInitialize(listId); } componentWillUnmount () { const { onReset } = this.props; onReset(); } render () { const { title, accountIds, searchAccountIds, onClear } = this.props; const showSearch = searchAccountIds.size > 0; return ( <div className='modal-root__modal list-editor'> <h4>{title}</h4> <Search /> <div className='drawer__pager'> <div className='drawer__inner list-editor__accounts'> {accountIds.map(accountId => <Account key={accountId} accountId={accountId} added />)} </div> {showSearch && <div role='button' tabIndex='-1' className='drawer__backdrop' onClick={onClear} />} <Motion defaultStyle={{ x: -100 }} style={{ x: spring(showSearch ? 0 : -100, { stiffness: 210, damping: 20 }) }}> {({ x }) => ( <div className='drawer__inner backdrop' style={{ transform: x === 0 ? null : `translateX(${x}%)`, visibility: x === -100 ? 'hidden' : 'visible' }}> {searchAccountIds.map(accountId => <Account key={accountId} accountId={accountId} />)} </div> )} </Motion> </div> </div> ); } }
src/BootstrapMixin.js
sheep902/react-bootstrap
import React from 'react'; import styleMaps from './styleMaps'; import CustomPropTypes from './utils/CustomPropTypes'; const BootstrapMixin = { propTypes: { /** * bootstrap className * @private */ bsClass: CustomPropTypes.keyOf(styleMaps.CLASSES), /** * Style variants * @type {("default"|"primary"|"success"|"info"|"warning"|"danger"|"link")} */ bsStyle: React.PropTypes.oneOf(styleMaps.STYLES), /** * Size variants * @type {("xsmall"|"small"|"medium"|"large"|"xs"|"sm"|"md"|"lg")} */ bsSize: CustomPropTypes.keyOf(styleMaps.SIZES) }, getBsClassSet() { let classes = {}; let bsClass = this.props.bsClass && styleMaps.CLASSES[this.props.bsClass]; if (bsClass) { classes[bsClass] = true; let prefix = bsClass + '-'; let bsSize = this.props.bsSize && styleMaps.SIZES[this.props.bsSize]; if (bsSize) { classes[prefix + bsSize] = true; } if (this.props.bsStyle) { if (styleMaps.STYLES.indexOf(this.props.bsStyle) >= 0) { classes[prefix + this.props.bsStyle] = true; } else { classes[this.props.bsStyle] = true; } } } return classes; }, prefixClass(subClass) { return styleMaps.CLASSES[this.props.bsClass] + '-' + subClass; } }; export default BootstrapMixin;
src/svg-icons/action/invert-colors.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionInvertColors = (props) => ( <SvgIcon {...props}> <path d="M17.66 7.93L12 2.27 6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58c2.05 0 4.1-.78 5.66-2.34 3.12-3.12 3.12-8.19 0-11.31zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/> </SvgIcon> ); ActionInvertColors = pure(ActionInvertColors); ActionInvertColors.displayName = 'ActionInvertColors'; export default ActionInvertColors;
src/Well.js
BespokeInsights/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Well = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'well' }; }, render() { let classes = this.getBsClassSet(); return ( <div {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </div> ); } }); export default Well;
src/components/SearchBox.js
afonsobarros/reactnd-project-readable
import React from 'react'; import TextField from 'material-ui/TextField'; import IconButton from 'material-ui/IconButton'; const SearchBox = () => { const styles = { iconButton: { float: 'left', paddingTop: 17 }, textField: { color: white, backgroundColor: blue500, borderRadius: 2, height: 35 }, inputStyle: { color: white, paddingLeft: 5 }, hintStyle: { height: 16, paddingLeft: 5, color: white } }; return ( <div> <IconButton style={styles.iconButton} > <i className="material-icons" color={white}>search</i> </IconButton> <TextField hintText="Search..." underlineShow={false} fullWidth={true} style={styles.textField} inputStyle={styles.inputStyle} hintStyle={styles.hintStyle} /> </div> ); }; export default SearchBox;
src/components/Journal.js
evertisland/emmet
import React from 'react' import Link from 'gatsby-link' import styled from 'styled-components' import ui from '../layouts/theme' import HorizontalScrollContainer from '../components/HorizontalScrollContainer' const Container = styled.div` width: 100%; flex: 1; display: flex; flex-direction: row; flex-wrap: wrap; break-inside: avoid; ` const Preview = styled.div` width: 100%; .blog-post-preview { background: rgba(14,17,17,0.4); margin: 0 ${ui.component.body.margin}; padding: ${ui.size.s}; padding-bottom: 20px; transition: background ease-in-out .2s; height: 100%; &:hover { background: rgba(0,0,0,0.7); } } h1 { color: ${ui.color.accent}; font-size: ${ui.size.m}; } h2 { font-size: ${ui.size.ms}; line-height: 0.2; color: ${ui.color.contentDark}; margin-top: ${ui.size.xs}; } p { color: ${ui.color.white}; font-weight: 200; font-size: ${ui.size.ms} } @media (min-width: 768px) { width: 50%; .blog-post-preview { margin: 0; } h1 { font-size: ${ui.size.ml}; } } ` export default function Journal ({ posts }) { return ( <Container> {posts .filter(post => post.node.frontmatter.title.length > 0) .map(({ node: post }) => { return ( <Preview key={post.id}> <Link to={post.frontmatter.path}> <div className="blog-post-preview"> <h1>{post.frontmatter.title}</h1> <h2>{post.frontmatter.date}</h2> {/* <p>{post.excerpt}</p> */} </div> </Link> </Preview> ); })} </Container> ); }
src/index.js
sunyuis/galler-by-reat
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
src/js/react/presentational/Scroll.js
koluch/db-scheme
// @flow import React from 'react' import cn from 'bem-cn' const bem = cn('scroll') class Scroll extends React.Component { props: { children?: *, } render() { return ( <div className={bem()}> <div className={bem('body')}> {this.props.children} </div> </div> ) } } export default Scroll
modules/UI/videolayout/LocalVideo.js
bgrozev/jitsi-meet
/* global $, config, interfaceConfig, APP */ /* eslint-disable no-unused-vars */ import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { JitsiTrackEvents } from '../../../react/features/base/lib-jitsi-meet'; import { VideoTrack } from '../../../react/features/base/media'; import { updateSettings } from '../../../react/features/base/settings'; import { getLocalVideoTrack } from '../../../react/features/base/tracks'; import { shouldDisplayTileView } from '../../../react/features/video-layout'; /* eslint-enable no-unused-vars */ const logger = require('jitsi-meet-logger').getLogger(__filename); import UIEvents from '../../../service/UI/UIEvents'; import SmallVideo from './SmallVideo'; /** * */ export default class LocalVideo extends SmallVideo { /** * * @param {*} VideoLayout * @param {*} emitter * @param {*} streamEndedCallback */ constructor(VideoLayout, emitter, streamEndedCallback) { super(VideoLayout); this.videoSpanId = 'localVideoContainer'; this.streamEndedCallback = streamEndedCallback; this.container = this.createContainer(); this.$container = $(this.container); this.isLocal = true; this._setThumbnailSize(); this.updateDOMLocation(); this.localVideoId = null; this.bindHoverHandler(); if (!config.disableLocalVideoFlip) { this._buildContextMenu(); } this.emitter = emitter; this.statsPopoverLocation = interfaceConfig.VERTICAL_FILMSTRIP ? 'left top' : 'top center'; Object.defineProperty(this, 'id', { get() { return APP.conference.getMyUserId(); } }); this.initBrowserSpecificProperties(); // Set default display name. this.updateDisplayName(); // Initialize the avatar display with an avatar url selected from the redux // state. Redux stores the local user with a hardcoded participant id of // 'local' if no id has been assigned yet. this.initializeAvatar(); this.addAudioLevelIndicator(); this.updateIndicators(); this.container.onclick = this._onContainerClick; } /** * */ createContainer() { const containerSpan = document.createElement('span'); containerSpan.classList.add('videocontainer'); containerSpan.id = this.videoSpanId; containerSpan.innerHTML = ` <div class = 'videocontainer__background'></div> <span id = 'localVideoWrapper'></span> <div class = 'videocontainer__toolbar'></div> <div class = 'videocontainer__toptoolbar'></div> <div class = 'videocontainer__hoverOverlay'></div> <div class = 'displayNameContainer'></div> <div class = 'avatar-container'></div>`; return containerSpan; } /** * Triggers re-rendering of the display name using current instance state. * * @returns {void} */ updateDisplayName() { if (!this.container) { logger.warn( `Unable to set displayName - ${this.videoSpanId } does not exist`); return; } this._renderDisplayName({ allowEditing: APP.store.getState()['features/base/jwt'].isGuest, displayNameSuffix: interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME, elementID: 'localDisplayName', participantID: this.id }); } /** * * @param {*} stream */ changeVideo(stream) { this.videoStream = stream; this.localVideoId = `localVideo_${stream.getId()}`; this._updateVideoElement(); // eslint-disable-next-line eqeqeq const isVideo = stream.videoType != 'desktop'; const settings = APP.store.getState()['features/base/settings']; this._enableDisableContextMenu(isVideo); this.setFlipX(isVideo ? settings.localFlipX : false); const endedHandler = () => { const localVideoContainer = document.getElementById('localVideoWrapper'); // Only remove if there is no video and not a transition state. // Previous non-react logic created a new video element with each track // removal whereas react reuses the video component so it could be the // stream ended but a new one is being used. if (localVideoContainer && this.videoStream.isEnded()) { ReactDOM.unmountComponentAtNode(localVideoContainer); } this._notifyOfStreamEnded(); stream.off(JitsiTrackEvents.LOCAL_TRACK_STOPPED, endedHandler); }; stream.on(JitsiTrackEvents.LOCAL_TRACK_STOPPED, endedHandler); } /** * Notify any subscribers of the local video stream ending. * * @private * @returns {void} */ _notifyOfStreamEnded() { if (this.streamEndedCallback) { this.streamEndedCallback(this.id); } } /** * Shows or hides the local video container. * @param {boolean} true to make the local video container visible, false * otherwise */ setVisible(visible) { // We toggle the hidden class as an indication to other interested parties // that this container has been hidden on purpose. this.$container.toggleClass('hidden'); // We still show/hide it as we need to overwrite the style property if we // want our action to take effect. Toggling the display property through // the above css class didn't succeed in overwriting the style. if (visible) { this.$container.show(); } else { this.$container.hide(); } } /** * Sets the flipX state of the video. * @param val {boolean} true for flipped otherwise false; */ setFlipX(val) { this.emitter.emit(UIEvents.LOCAL_FLIPX_CHANGED, val); if (!this.localVideoId) { return; } if (val) { this.selectVideoElement().addClass('flipVideoX'); } else { this.selectVideoElement().removeClass('flipVideoX'); } } /** * Builds the context menu for the local video. */ _buildContextMenu() { $.contextMenu({ selector: `#${this.videoSpanId}`, zIndex: 10000, items: { flip: { name: 'Flip', callback: () => { const { store } = APP; const val = !store.getState()['features/base/settings'] .localFlipX; this.setFlipX(val); store.dispatch(updateSettings({ localFlipX: val })); } } }, events: { show(options) { options.items.flip.name = APP.translation.generateTranslationHTML( 'videothumbnail.flip'); } } }); } /** * Enables or disables the context menu for the local video. * @param enable {boolean} true for enable, false for disable */ _enableDisableContextMenu(enable) { if (this.$container.contextMenu) { this.$container.contextMenu(enable); } } /** * Places the {@code LocalVideo} in the DOM based on the current video layout. * * @returns {void} */ updateDOMLocation() { if (!this.container) { return; } if (this.container.parentElement) { this.container.parentElement.removeChild(this.container); } const appendTarget = shouldDisplayTileView(APP.store.getState()) ? document.getElementById('localVideoTileViewContainer') : document.getElementById('filmstripLocalVideoThumbnail'); appendTarget && appendTarget.appendChild(this.container); this._updateVideoElement(); } /** * Renders the React Element for displaying video in {@code LocalVideo}. * */ _updateVideoElement() { const localVideoContainer = document.getElementById('localVideoWrapper'); const videoTrack = getLocalVideoTrack(APP.store.getState()['features/base/tracks']); ReactDOM.render( <Provider store = { APP.store }> <VideoTrack id = 'localVideo_container' videoTrack = { videoTrack } /> </Provider>, localVideoContainer ); // Ensure the video gets play() called on it. This may be necessary in the // case where the local video container was moved and re-attached, in which // case video does not autoplay. const video = this.container.querySelector('video'); video && !config.testing?.noAutoPlayVideo && video.play(); } }
src/svg-icons/hardware/keyboard-arrow-up.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboardArrowUp = (props) => ( <SvgIcon {...props}> <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"/> </SvgIcon> ); HardwareKeyboardArrowUp = pure(HardwareKeyboardArrowUp); HardwareKeyboardArrowUp.displayName = 'HardwareKeyboardArrowUp'; HardwareKeyboardArrowUp.muiName = 'SvgIcon'; export default HardwareKeyboardArrowUp;
lib/ItemWrapper.js
xadn/react-infinite-scroll
import React from 'react'; class ItemWrapper extends React.Component { constructor(props) { super(props); this.state = {renderedOnce: false}; } shouldComponentUpdate(nextProps, nextState) { return ( this.props.top !== nextProps.top || this.state.renderedOnce !== nextState.renderedOnce ); } componentDidMount() { this.setState({renderedOnce: true}); } render() { const style = { backfaceVisibility: 'hidden', display: 'flex', opacity: this.state.renderedOnce ? 1 : 0, position: 'absolute', transform: `translate3d(0px, ${this.props.top}px, 0px)`, }; const { model, cid, } = this.props; return ( <div style={style} onWheel={() => model.updateLastScrolled(cid)}> {this.props.children} </div> ); } } export default ItemWrapper;
fields/types/select/SelectFilter.js
stosorio/keystone
import React from 'react'; import { Checkbox, FormField, SegmentedControl } from 'elemental'; import PopoutList from '../../../admin/src/components/PopoutList'; const TOGGLE_OPTIONS = [ { label: 'Matches', value: false }, { label: 'Does NOT Match', value: true } ]; var SelectFilter = React.createClass({ getInitialState () { return { inverted: TOGGLE_OPTIONS[0].value, selectedOptions: {}, allSelected: false, indeterminate: false }; }, toggleAllOptions () { this.props.field.ops.map(opt => this.toggleOption(opt.value, !this.state.allSelected)); }, toggleOption (option, value) { let newOptions = this.state.selectedOptions; if (value) { newOptions[option] = value; } else { delete newOptions[option]; } let optionCount = Object.keys(newOptions).length; this.setState({ selectedOptions: newOptions, indeterminate: !!optionCount && optionCount !== this.props.field.ops.length, allSelected: optionCount === this.props.field.ops.length }); }, renderToggle () { return ( <FormField> <SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={() => this.setState({ inverted: !this.state.inverted })} /> </FormField> ); }, renderOptions () { let options = this.props.field.ops.map((opt) => { let optionKey = opt.value; let optionValue = this.state.selectedOptions[optionKey]; return ( <PopoutList.Item key={'item_' + opt.value} icon={optionValue ? 'check' : 'dash'} isSelected={optionValue} label={opt.label} onClick={this.toggleOption.bind(this, optionKey, !optionValue)} /> ); }); return options; }, render () { return ( <div> {this.renderToggle()} <FormField style={{ borderBottom: '1px dashed rgba(0,0,0,0.1)', paddingBottom: '1em' }}> <Checkbox focusOnMount onChange={this.toggleAllOptions} label="Select all options" value={true} checked={this.state.allSelected} indeterminate={this.state.indeterminate} /> </FormField> {this.renderOptions()} </div> ); } }); module.exports = SelectFilter;
client/modules/App/components/Footer/Footer.js
Dokvel/outfit_ua
import React from 'react'; import { FormattedMessage } from 'react-intl'; // Import Style import styles from './Footer.css'; // Import Images import bg from '../../header-bk.png'; export function Footer() { return ( <div style={{ background: `#FFF url(${bg}) center` }} className={styles.footer}> <p>&copy; 2016 &middot; Hashnode &middot; LinearBytes Inc.</p> <p><FormattedMessage id="twitterMessage" /> : <a href="https://twitter.com/@mern_io" target="_Blank">@mern_io</a></p> </div> ); } export default Footer;
server/server.js
vibhas77/Student-Wallet
import Express from 'express'; import compression from 'compression'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import path from 'path'; import IntlWrapper from '../client/modules/Intl/IntlWrapper'; // Webpack Requirements import webpack from 'webpack'; import config from '../webpack.config.dev'; import webpackDevMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; // Initialize the Express App const app = new Express(); // Run Webpack dev server in development mode if (process.env.NODE_ENV === 'development') { const compiler = webpack(config); app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); app.use(webpackHotMiddleware(compiler)); } // React And Redux Setup import { configureStore } from '../client/store'; import { Provider } from 'react-redux'; import React from 'react'; import { renderToString } from 'react-dom/server'; import { match, RouterContext } from 'react-router'; import Helmet from 'react-helmet'; // Import required modules import routes from '../client/routes'; import { fetchComponentData } from './util/fetchData'; import posts from './routes/post.routes'; import dummyData from './dummyData'; import serverConfig from './config'; // Set native promises as mongoose promise mongoose.Promise = global.Promise; // MongoDB Connection mongoose.connect(serverConfig.mongoURL, (error) => { if (error) { console.error('Please make sure Mongodb is installed and running!'); // eslint-disable-line no-console throw error; } // feed some dummy data in DB. dummyData(); }); // Apply body Parser and server public assets and routes app.use(compression()); app.use(bodyParser.json({ limit: '20mb' })); app.use(bodyParser.urlencoded({ limit: '20mb', extended: false })); app.use(Express.static(path.resolve(__dirname, '../dist'))); app.use('/api', posts); // Render Initial HTML const renderFullPage = (html, initialState) => { const head = Helmet.rewind(); // Import Manifests const assetsManifest = process.env.webpackAssets && JSON.parse(process.env.webpackAssets); const chunkManifest = process.env.webpackChunkAssets && JSON.parse(process.env.webpackChunkAssets); return ` <!doctype html> <html> <head> ${head.base.toString()} ${head.title.toString()} ${head.meta.toString()} ${head.link.toString()} ${head.script.toString()} ${process.env.NODE_ENV === 'production' ? `<link rel='stylesheet' href='${assetsManifest['/app.css']}' />` : ''} <link href='https://fonts.googleapis.com/css?family=Lato:400,300,700' rel='stylesheet' type='text/css'/> <link rel="shortcut icon" href="http://res.cloudinary.com/hashnode/image/upload/v1455629445/static_imgs/mern/mern-favicon-circle-fill.png" type="image/png" /> </head> <body> <div id="root">${html}</div> <script> window.__INITIAL_STATE__ = ${JSON.stringify(initialState)}; ${process.env.NODE_ENV === 'production' ? `//<![CDATA[ window.webpackManifest = ${JSON.stringify(chunkManifest)}; //]]>` : ''} </script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/vendor.js'] : '/vendor.js'}'></script> <script src='${process.env.NODE_ENV === 'production' ? assetsManifest['/app.js'] : '/app.js'}'></script> </body> </html> `; }; const renderError = err => { const softTab = '&#32;&#32;&#32;&#32;'; const errTrace = process.env.NODE_ENV !== 'production' ? `:<br><br><pre style="color:red">${softTab}${err.stack.replace(/\n/g, `<br>${softTab}`)}</pre>` : ''; return renderFullPage(`Server Error${errTrace}`, {}); }; // Server Side Rendering based on routes matched by React-router. app.use((req, res, next) => { match({ routes, location: req.url }, (err, redirectLocation, renderProps) => { if (err) { return res.status(500).end(renderError(err)); } if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search); } if (!renderProps) { return next(); } const store = configureStore(); return fetchComponentData(store, renderProps.components, renderProps.params) .then(() => { const initialView = renderToString( <Provider store={store}> <IntlWrapper> <RouterContext {...renderProps} /> </IntlWrapper> </Provider> ); const finalState = store.getState(); res .set('Content-Type', 'text/html') .status(200) .end(renderFullPage(initialView, finalState)); }) .catch((error) => next(error)); }); }); // start app app.listen(serverConfig.port, (error) => { if (!error) { console.log(`MERN is running on port: ${serverConfig.port}! Build something amazing!`); // eslint-disable-line } }); export default app;
src/components/SegmentedControl/index.js
r1cebank/react-native-boilerplate
import React from 'react'; import { View, ScrollView } from 'react-native'; import Styles from './resources/styles'; import { Components } from '../../global/globalIncludes'; class F8SegmentedControl extends React.Component { static propTypes = { values: React.PropTypes.array, selectedIndex: React.PropTypes.number, selectionColor: React.PropTypes.string, style: View.propTypes.style, onChange: React.PropTypes.func }; render() { const segments = this.props.values.map( (value, index) => ( <Components.Segment key={value} value={value} isSelected={index === this.props.selectedIndex} selectionColor={this.props.selectionColor || 'white'} onPress={() => this.props.onChange(index)} /> ) ); return ( <View style={[Styles.container, this.props.style]}> <ScrollView style={Styles.scrollview} ref="scrollview" horizontal={true} pagingEnabled={true} scrollsToTop={false} scrollEventThrottle={10} automaticallyAdjustContentInsets={false} directionalLockEnabled={true} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false}> {segments} </ScrollView> </View> ); } } module.exports = F8SegmentedControl;
src/components/antd/transfer/list.js
hyd378008136/olymComponents
import React from 'react'; import { findDOMNode } from 'react-dom'; import classNames from 'classnames'; import Animate from 'rc-animate'; import PureRenderMixin from 'rc-util/lib/PureRenderMixin'; import Checkbox from '../checkbox'; import Search from './search'; import Item from './item'; import triggerEvent from '../_util/triggerEvent'; function noop() { } function isRenderResultPlainObject(result) { return result && !React.isValidElement(result) && Object.prototype.toString.call(result) === '[object Object]'; } export default class TransferList extends React.Component { constructor(props) { super(props); this.handleSelect = (selectedItem) => { const { checkedKeys } = this.props; const result = checkedKeys.some((key) => key === selectedItem.key); this.props.handleSelect(selectedItem, !result); }; this.handleFilter = (e) => { this.props.handleFilter(e); if (!e.target.value) { return; } // Manually trigger scroll event for lazy search bug // https://github.com/ant-design/ant-design/issues/5631 this.triggerScrollTimer = setTimeout(() => { const listNode = findDOMNode(this).querySelectorAll('.ant-transfer-list-content')[0]; if (listNode) { triggerEvent(listNode, 'scroll'); } }, 0); }; this.handleClear = () => { this.props.handleClear(); }; this.matchFilter = (text, item) => { const { filter, filterOption } = this.props; if (filterOption) { return filterOption(filter, item); } return text.indexOf(filter) >= 0; }; this.renderItem = (item) => { const { render = noop } = this.props; const renderResult = render(item); const isRenderResultPlain = isRenderResultPlainObject(renderResult); return { renderedText: isRenderResultPlain ? renderResult.value : renderResult, renderedEl: isRenderResultPlain ? renderResult.label : renderResult, }; }; this.state = { mounted: false, }; } componentDidMount() { this.timer = setTimeout(() => { this.setState({ mounted: true, }); }, 0); } componentWillUnmount() { clearTimeout(this.timer); clearTimeout(this.triggerScrollTimer); } shouldComponentUpdate(...args) { return PureRenderMixin.shouldComponentUpdate.apply(this, args); } getCheckStatus(filteredDataSource) { const { checkedKeys } = this.props; if (checkedKeys.length === 0) { return 'none'; } else if (filteredDataSource.every(item => checkedKeys.indexOf(item.key) >= 0)) { return 'all'; } return 'part'; } render() { const { prefixCls, dataSource, titleText, checkedKeys, lazy, body = noop, footer = noop, showSearch, style, filter, searchPlaceholder, notFoundContent, itemUnit, itemsUnit, onScroll, } = this.props; // Custom Layout const footerDom = footer(Object.assign({}, this.props)); const bodyDom = body(Object.assign({}, this.props)); const listCls = classNames(prefixCls, { [`${prefixCls}-with-footer`]: !!footerDom, }); const filteredDataSource = []; const totalDataSource = []; const showItems = dataSource.map((item) => { const { renderedText, renderedEl } = this.renderItem(item); if (filter && filter.trim() && !this.matchFilter(renderedText, item)) { return null; } // all show items totalDataSource.push(item); if (!item.disabled) { // response to checkAll items filteredDataSource.push(item); } const checked = checkedKeys.indexOf(item.key) >= 0; return (React.createElement(Item, { key: item.key, item: item, lazy: lazy, renderedText: renderedText, renderedEl: renderedEl, checked: checked, prefixCls: prefixCls, onClick: this.handleSelect })); }); const unit = dataSource.length > 1 ? itemsUnit : itemUnit; const search = showSearch ? (React.createElement("div", { className: `${prefixCls}-body-search-wrapper` }, React.createElement(Search, { prefixCls: `${prefixCls}-search`, onChange: this.handleFilter, handleClear: this.handleClear, placeholder: searchPlaceholder, value: filter }))) : null; const listBody = bodyDom || (React.createElement("div", { className: showSearch ? `${prefixCls}-body ${prefixCls}-body-with-search` : `${prefixCls}-body` }, search, React.createElement(Animate, { component: "ul", componentProps: { onScroll }, className: `${prefixCls}-content`, transitionName: this.state.mounted ? `${prefixCls}-content-item-highlight` : '', transitionLeave: false }, showItems), React.createElement("div", { className: `${prefixCls}-body-not-found` }, notFoundContent))); const listFooter = footerDom ? (React.createElement("div", { className: `${prefixCls}-footer` }, footerDom)) : null; const checkStatus = this.getCheckStatus(filteredDataSource); const checkedAll = checkStatus === 'all'; const checkAllCheckbox = (React.createElement(Checkbox, { ref: "checkbox", checked: checkedAll, indeterminate: checkStatus === 'part', onChange: () => this.props.handleSelectAll(filteredDataSource, checkedAll) })); return (React.createElement("div", { className: listCls, style: style }, React.createElement("div", { className: `${prefixCls}-header` }, checkAllCheckbox, React.createElement("span", { className: `${prefixCls}-header-selected` }, React.createElement("span", null, (checkedKeys.length > 0 ? `${checkedKeys.length}/` : '') + totalDataSource.length, " ", unit), React.createElement("span", { className: `${prefixCls}-header-title` }, titleText))), listBody, listFooter)); } } TransferList.defaultProps = { dataSource: [], titleText: '', showSearch: false, render: noop, lazy: {}, };
nailgun/static/views/cluster_page_tabs/network_tab.js
huntxu/fuel-web
/* * Copyright 2015 Mirantis, Inc. * * Licensed under the Apache License, Version 2.0 (the 'License'); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ import $ from 'jquery'; import _ from 'underscore'; import i18n from 'i18n'; import Backbone from 'backbone'; import React from 'react'; import ReactDOM from 'react-dom'; import utils from 'utils'; import models from 'models'; import dispatcher from 'dispatcher'; import {CreateNodeNetworkGroupDialog, RemoveNodeNetworkGroupDialog} from 'views/dialogs'; import {backboneMixin, dispatcherMixin, unsavedChangesMixin, renamingMixin} from 'component_mixins'; import {Input, RadioGroup, Table} from 'views/controls'; import SettingSection from 'views/cluster_page_tabs/setting_section'; import CSSTransitionGroup from 'react-addons-transition-group'; var parametersNS = 'cluster_page.network_tab.networking_parameters.'; var networkTabNS = 'cluster_page.network_tab.'; var defaultNetworkSubtabs = ['neutron_l2', 'neutron_l3', 'network_settings', 'network_verification', 'nova_configuration']; var NetworkModelManipulationMixin = { setValue(attribute, value, options) { function convertToStringIfNaN(value) { var convertedValue = parseInt(value, 10); return _.isNaN(convertedValue) ? '' : convertedValue; } if (options && options.isInteger && !_.isNull(value)) { // for ranges values if (_.isArray(value)) { value = _.map(value, convertToStringIfNaN); } else { value = convertToStringIfNaN(value); } } var networkConfiguration = this.props.cluster.get('networkConfiguration'); this.getModel().set(attribute, value); dispatcher.trigger('hideNetworkVerificationResult'); networkConfiguration.isValid(); }, getModel() { return this.props.network || this.props.cluster.get('networkConfiguration').get('networking_parameters'); } }; var NetworkInputsMixin = { composeProps(attribute, isRange, isInteger) { var network = this.props.network; var ns = network ? networkTabNS + 'network.' : parametersNS; var error = this.getError(attribute) || null; // in case of verification error we need to pass an empty string to highlight the field only // but not overwriting validation error if (!error && _.contains(this.props.verificationErrorField, attribute)) { error = ''; } return { key: attribute, onChange: _.partialRight(this.setValue, {isInteger: isInteger}), disabled: this.props.disabled, name: attribute, label: i18n(ns + attribute), value: this.getModel().get(attribute), network: network, cluster: this.props.cluster, wrapperClassName: isRange ? attribute : false, error: error }; }, renderInput(attribute, isInteger, additionalProps = {}) { return ( <Input {...additionalProps} {...this.composeProps(attribute, false, isInteger)} type='text' wrapperClassName={attribute} /> ); }, getError(attribute) { var validationError = this.props.cluster.get('networkConfiguration').validationError; if (!validationError) return null; var error; if (this.props.network) { try { error = validationError.networks[this.props.currentNodeNetworkGroup.id][this.props.network.id][attribute]; } catch (e) {} return error || null; } error = (validationError.networking_parameters || {})[attribute]; if (!error) return null; // specific format needed for vlan_start error if (attribute == 'fixed_networks_vlan_start') return [error]; return error; } }; var Range = React.createClass({ mixins: [ NetworkModelManipulationMixin ], getDefaultProps() { return { extendable: true, placeholder: '127.0.0.1', hiddenControls: false }; }, propTypes: { wrapperClassName: React.PropTypes.node, extendable: React.PropTypes.bool, name: React.PropTypes.string, autoIncreaseWith: React.PropTypes.number, integerValue: React.PropTypes.bool, placeholder: React.PropTypes.string, hiddenControls: React.PropTypes.bool, mini: React.PropTypes.bool }, getInitialState() { return {elementToFocus: null}; }, componentDidUpdate() { // this glitch is needed to fix // when pressing '+' or '-' buttons button remains focused if (this.props.extendable && this.state.elementToFocus && this.getModel().get(this.props.name).length) { $(this.refs[this.state.elementToFocus].getInputDOMNode()).focus(); this.setState({elementToFocus: null}); } }, autoCompleteIPRange(error, rangeStart, event) { var input = event.target; if (input.value) return; if (_.isUndefined(error)) input.value = rangeStart; if (input.setSelectionRange) { var startPos = _.lastIndexOf(rangeStart, '.') + 1; var endPos = rangeStart.length; input.setSelectionRange(startPos, endPos); } }, onRangeChange(name, newValue, attribute, rowIndex) { var model = this.getModel(); var valuesToSet = _.cloneDeep(model.get(attribute)); var valuesToModify = this.props.extendable ? valuesToSet[rowIndex] : valuesToSet; if (this.props.autoIncreaseWith) { valuesToSet = newValue; } else if (_.contains(name, 'range-start')) { // if first range field valuesToModify[0] = newValue; } else if (_.contains(name, 'range-end')) { // if end field valuesToModify[1] = newValue; } this.setValue(attribute, valuesToSet, {isInteger: this.props.integerValue}); }, addRange(attribute, rowIndex) { var newValue = _.clone(this.getModel().get(attribute)); newValue.splice(rowIndex + 1, 0, ['', '']); this.setValue(attribute, newValue); this.setState({ elementToFocus: 'start' + (rowIndex + 1) }); }, removeRange(attribute, rowIndex) { var newValue = _.clone(this.getModel().get(attribute)); newValue.splice(rowIndex, 1); this.setValue(attribute, newValue); this.setState({ elementToFocus: 'start' + _.min([newValue.length - 1, rowIndex]) }); }, getRangeProps(isRangeEnd) { var error = this.props.error || null; var attributeName = this.props.name; return { type: 'text', placeholder: error ? '' : this.props.placeholder, className: 'form-control', disabled: this.props.disabled, onChange: _.partialRight(this.onRangeChange, attributeName), name: (isRangeEnd ? 'range-end_' : 'range-start_') + attributeName }; }, renderRangeControls(attributeName, index, length) { return ( <div className='ip-ranges-control'> <button className='btn btn-link ip-ranges-add' disabled={this.props.disabled} onClick={_.partial(this.addRange, attributeName, index)} > <i className='glyphicon glyphicon-plus-sign'></i> </button> {(length > 1) && <button className='btn btn-link ip-ranges-delete' disabled={this.props.disabled} onClick={_.partial(this.removeRange, attributeName, index)} > <i className='glyphicon glyphicon-minus-sign'></i> </button> } </div> ); }, render() { var error = this.props.error || null; var attributeName = this.props.name; var attribute = this.getModel().get(attributeName); var ranges = this.props.autoIncreaseWith ? [attribute || 0, (attribute + this.props.autoIncreaseWith - 1 || 0)] : attribute; var wrapperClasses = { 'form-group range row': true, mini: this.props.mini, [this.props.wrapperClassName]: this.props.wrapperClassName }; var verificationError = this.props.verificationError || null; var [startInputError, endInputError] = error || []; wrapperClasses[this.props.wrapperClassName] = this.props.wrapperClassName; return ( <div className={utils.classNames(wrapperClasses)}> {!this.props.hiddenHeader && <div className='range-row-header col-xs-12'> <div>{i18n(networkTabNS + 'range_start')}</div> <div>{i18n(networkTabNS + 'range_end')}</div> </div> } <div className='col-xs-12'> <label>{this.props.label}</label> {this.props.extendable ? _.map(ranges, (range, index) => { var rangeError = _.findWhere(error, {index: index}) || {}; return ( <div className='range-row clearfix' key={index}> <Input {...this.getRangeProps()} error={(rangeError.start || verificationError) ? '' : null} value={range[0]} onChange={_.partialRight(this.onRangeChange, attributeName, index)} ref={'start' + index} inputClassName='start' placeholder={rangeError.start ? '' : this.props.placeholder} /> <Input {...this.getRangeProps(true)} error={rangeError.end ? '' : null} value={range[1]} onChange={_.partialRight(this.onRangeChange, attributeName, index)} onFocus={_.partial(this.autoCompleteIPRange, rangeError && rangeError.start, range[0])} disabled={this.props.disabled || !!this.props.autoIncreaseWith} placeholder={rangeError.end ? '' : this.props.placeholder} extraContent={!this.props.hiddenControls && this.renderRangeControls(attributeName, index, ranges.length)} /> <div className='validation-error text-danger pull-left'> <span className='help-inline'> {rangeError.start || rangeError.end} </span> </div> </div> ); }) : <div className='range-row clearfix'> <Input {...this.getRangeProps()} value={ranges[0]} error={startInputError ? '' : null} inputClassName='start' /> <Input {...this.getRangeProps(true)} disabled={this.props.disabled || !!this.props.autoIncreaseWith} value={ranges[1]} error={endInputError ? '' : null} /> {error && (startInputError || endInputError) && <div className='validation-error text-danger pull-left'> <span className='help-inline'>{startInputError || endInputError}</span> </div> } </div> } </div> </div> ); } }); var VlanTagInput = React.createClass({ mixins: [NetworkModelManipulationMixin], getInitialState() { return {pendingFocus: false}; }, componentDidUpdate() { var value = this.props.value; if (!_.isNull(value) && this.state.pendingFocus) { $(this.refs[this.props.name].getInputDOMNode()).focus(); this.setState({pendingFocus: false}); } }, onTaggingChange(attribute, value) { this.setValue(attribute, value ? '' : null); this.setState({pendingFocus: true}); }, onInputChange(attribute, value) { this.setValue(attribute, value, {isInteger: true}); }, render() { return ( <div className={'vlan-tagging form-group ' + this.props.name}> <label className='vlan-tag-label'>{this.props.label}</label> <Input {...this.props} onChange={this.onTaggingChange} type='checkbox' checked={!_.isNull(this.props.value)} error={null} label={null} /> {!_.isNull(this.props.value) && <Input {...this.props} ref={this.props.name} onChange={this.onInputChange} type='text' label={null} /> } </div> ); } }); var CidrControl = React.createClass({ mixins: [NetworkModelManipulationMixin], onCidrChange(name, cidr) { this.props.onChange(name, cidr); if (this.props.network.get('meta').notation == 'cidr') { this.props.autoUpdateParameters(cidr); } }, render() { return ( <div className='form-group cidr'> <label>{i18n(networkTabNS + 'network.cidr')}</label> <Input {...this.props} type='text' label={null} onChange={this.onCidrChange} wrapperClassName='pull-left' /> <Input type='checkbox' checked={this.props.network.get('meta').notation == 'cidr'} label={i18n(networkTabNS + 'network.use_whole_cidr')} disabled={this.props.disabled} onChange={this.props.changeNetworkNotation} wrapperClassName='pull-left' /> </div> ); } }); // FIXME(morale): this component is a lot of copy-paste from Range component // and should be rewritten either as a mixin or as separate component for // multiplying other components (eg accepting Range, Input etc) var MultipleValuesInput = React.createClass({ mixins: [ NetworkModelManipulationMixin ], propTypes: { name: React.PropTypes.string, placeholder: React.PropTypes.string, label: React.PropTypes.string, value: React.PropTypes.array }, getInitialState() { return {elementToFocus: null}; }, componentDidUpdate() { // this glitch is needed to fix // when pressing '+' or '-' buttons button remains focused if (this.state.elementToFocus && this.getModel().get(this.props.name).length) { $(this.refs[this.state.elementToFocus].getInputDOMNode()).focus(); this.setState({elementToFocus: null}); } }, onChange(attribute, value, index) { var model = this.getModel(); var valueToSet = _.cloneDeep(model.get(attribute)); valueToSet[index] = value; this.setValue(attribute, valueToSet); }, addValue(attribute, index) { var newValue = _.clone(this.getModel().get(attribute)); newValue.splice(index + 1, 0, ''); this.setValue(attribute, newValue); this.setState({ elementToFocus: 'row' + (index + 1) }); }, removeValue(attribute, index) { var newValue = _.clone(this.getModel().get(attribute)); newValue.splice(index, 1); this.setValue(attribute, newValue); this.setState({ elementToFocus: 'row' + _.min([newValue.length - 1, index]) }); }, renderControls(attributeName, index, length) { return ( <div className='ip-ranges-control'> <button className='btn btn-link ip-ranges-add' disabled={this.props.disabled} onClick={_.partial(this.addValue, attributeName, index)} > <i className='glyphicon glyphicon-plus-sign' /> </button> {length > 1 && <button className='btn btn-link ip-ranges-delete' disabled={this.props.disabled} onClick={_.partial(this.removeValue, attributeName, index)} > <i className='glyphicon glyphicon-minus-sign' /> </button> } </div> ); }, render() { var attributeName = this.props.name; var values = this.props.value; return ( <div className={'form-group row multiple-values ' + attributeName}> <div className='col-xs-12'> <label>{this.props.label}</label> {_.map(values, (value, index) => { var inputError = (this.props.error || {})[index]; return ( <div className='range-row clearfix' key={attributeName + index}> <Input type='text' disabled={this.props.disabled} name={attributeName} error={(inputError || this.props.verificationError) && ''} value={value} onChange={_.partialRight(this.onChange, index)} ref={'row' + index} placeholder={inputError ? '' : this.props.placeholder} extraContent={this.renderControls(attributeName, index, values.length)} /> <div className='validation-error text-danger pull-left'>{inputError}</div> </div> ); })} </div> </div> ); } }); var NetworkTab = React.createClass({ mixins: [ NetworkInputsMixin, NetworkModelManipulationMixin, backboneMixin('cluster', 'change:status'), backboneMixin('nodeNetworkGroups', 'change update'), backboneMixin({ modelOrCollection(props) { return props.cluster.get('networkConfiguration').get('networking_parameters'); }, renderOn: 'change' }), backboneMixin({ modelOrCollection(props) { return props.cluster.get('networkConfiguration').get('networks'); }, renderOn: 'change reset update' }), backboneMixin({ modelOrCollection(props) { return props.cluster.get('tasks'); }, renderOn: 'update change:status' }), dispatcherMixin('hideNetworkVerificationResult', function() { this.setState({hideVerificationResult: true}); }), dispatcherMixin('networkConfigurationUpdated', function() { this.setState({hideVerificationResult: false}); }), backboneMixin({ modelOrCollection(props) { return props.cluster.get('settings'); }, renderOn: 'change invalid' }), unsavedChangesMixin ], statics: { fetchData(options) { var cluster = options.cluster; return $.when( cluster.get('settings').fetch({cache: true}), cluster.get('networkConfiguration').fetch({cache: true}) ).then(() => ({})); } }, getInitialState() { var settings = this.props.cluster.get('settings'); return { configModels: { cluster: this.props.cluster, settings: settings, networking_parameters: this.props.cluster.get('networkConfiguration').get('networking_parameters'), version: app.version, release: this.props.cluster.get('release'), default: settings }, initialSettingsAttributes: _.cloneDeep(settings.attributes), settingsForChecks: new models.Settings(_.cloneDeep(settings.attributes)), initialConfiguration: _.cloneDeep(this.props.cluster.get('networkConfiguration').toJSON()), hideVerificationResult: false }; }, componentDidMount() { this.props.cluster.get('networkConfiguration').isValid(); this.props.cluster.get('settings').isValid({models: this.state.configModels}); this.props.cluster.get('tasks').on('change:status change:unsaved', this.destroyUnsavedNetworkVerificationTask, this); }, componentWillUnmount() { this.loadInitialConfiguration(); this.props.cluster.get('tasks').off(null, this.destroyUnsavedNetworkVerificationTask, this); this.removeUnsavedTasks(); }, destroyUnsavedNetworkVerificationTask(task) { // FIXME(vkramskikh): remove tasks which we marked as "unsaved" hacky flag // immediately after completion, so they won't be taken into account when // we determine cluster verification status. They need to be removed silently // and kept in the collection to show verification result to the user if (task.match({group: 'network', active: false}) && task.get('unsaved')) { task.destroy({silent: true}); task.unset('id'); // hack to prevent issuing another DELETE requests after actual removal this.props.cluster.get('tasks').add(task, {silent: true}); } }, removeUnsavedTasks() { var clusterTasks = this.props.cluster.get('tasks'); clusterTasks.each((task) => task.get('unsaved') && clusterTasks.remove(task)); }, isNetworkConfigurationChanged() { return !_.isEqual(this.state.initialConfiguration, this.props.cluster.get('networkConfiguration').toJSON()); }, isNetworkSettingsChanged() { return this.props.cluster.get('settings').hasChanges(this.state.initialSettingsAttributes, this.state.configModels); }, hasChanges() { return this.isNetworkConfigurationChanged() || this.isNetworkSettingsChanged(); }, revertChanges() { this.loadInitialConfiguration(); this.loadInitialSettings(); this.setState({ hideVerificationResult: true, key: _.now() }); }, loadInitialConfiguration() { var networkConfiguration = this.props.cluster.get('networkConfiguration'); networkConfiguration.get('networks').reset(_.cloneDeep(this.state.initialConfiguration.networks)); networkConfiguration.get('networking_parameters').set(_.cloneDeep(this.state.initialConfiguration.networking_parameters)); }, loadInitialSettings() { var settings = this.props.cluster.get('settings'); settings.set(_.cloneDeep(this.state.initialSettingsAttributes), {silent: true, validate: false}); settings.mergePluginSettings(); settings.isValid({models: this.state.configModels}); }, updateInitialConfiguration() { this.setState({initialConfiguration: _.cloneDeep(this.props.cluster.get('networkConfiguration').toJSON())}); }, isLocked() { return !!this.props.cluster.task({group: ['deployment', 'network'], active: true}) || !this.props.cluster.isAvailableForSettingsChanges() || this.state.actionInProgress; }, prepareIpRanges() { var removeEmptyRanges = (ranges) => { return _.filter(ranges, (range) => _.compact(range).length); }; var networkConfiguration = this.props.cluster.get('networkConfiguration'); networkConfiguration.get('networks').each((network) => { if (network.get('meta').notation == 'ip_ranges') { network.set({ip_ranges: removeEmptyRanges(network.get('ip_ranges'))}); } }); var floatingRanges = networkConfiguration.get('networking_parameters').get('floating_ranges'); if (floatingRanges) { networkConfiguration.get('networking_parameters').set({floating_ranges: removeEmptyRanges(floatingRanges)}); } }, onManagerChange(name, value) { var networkConfiguration = this.props.cluster.get('networkConfiguration'); var networkingParameters = networkConfiguration.get('networking_parameters'); var fixedAmount = networkConfiguration.get('networking_parameters').get('fixed_networks_amount') || 1; networkingParameters.set({ net_manager: value, fixed_networks_amount: value == 'FlatDHCPManager' ? 1 : fixedAmount }); networkConfiguration.isValid(); this.setState({hideVerificationResult: true}); }, verifyNetworks() { this.setState({actionInProgress: true}); this.prepareIpRanges(); dispatcher.trigger('networkConfigurationUpdated', this.startVerification); }, startVerification() { var networkConfiguration = this.props.cluster.get('networkConfiguration'); var task = new models.Task(); var options = { method: 'PUT', url: _.result(networkConfiguration, 'url') + '/verify', data: JSON.stringify(networkConfiguration) }; var ns = networkTabNS + 'verify_networks.verification_error.'; task.save({}, options) .fail((response) => { utils.showErrorDialog({ title: i18n(ns + 'title'), message: i18n(ns + 'start_verification_warning'), response: response }); }) .then(() => { return this.props.cluster.fetchRelated('tasks'); }) .then(() => { // FIXME(vkramskikh): this ugly hack is needed to distinguish // verification tasks for saved config from verification tasks // for unsaved config (which appear after clicking "Verify" // button without clicking "Save Changes" button first). // For proper implementation, this should be managed by backend this.props.cluster.get('tasks').get(task.id).set('unsaved', this.hasChanges()); dispatcher.trigger('networkVerificationTaskStarted'); return $.Deferred().resolve(); }) .always(() => { this.setState({actionInProgress: false}); }); }, isDiscardingPossible() { return !this.props.cluster.task({group: 'network', active: true}); }, applyChanges() { if (!this.isSavingPossible()) return $.Deferred().reject(); this.setState({actionInProgress: true}); this.prepareIpRanges(); var requests = []; var result = $.Deferred(); dispatcher.trigger('networkConfigurationUpdated', () => { return Backbone.sync('update', this.props.cluster.get('networkConfiguration')) .then((response) => { this.updateInitialConfiguration(); result.resolve(response); }, (response) => { result.reject(); return this.props.cluster.fetchRelated('tasks') .done(() => { // FIXME (morale): this hack is needed until backend response // format is unified https://bugs.launchpad.net/fuel/+bug/1521661 var checkNetworksTask = this.props.cluster.task('check_networks'); if (!(checkNetworksTask && checkNetworksTask.get('message'))) { var fakeTask = new models.Task({ cluster: this.props.cluster.id, message: utils.getResponseText(response), status: 'error', name: 'check_networks', result: {} }); this.props.cluster.get('tasks').remove(checkNetworksTask); this.props.cluster.get('tasks').add(fakeTask); } // FIXME(vkramskikh): the same hack for check_networks task: // remove failed tasks immediately, so they won't be taken into account this.props.cluster.task('check_networks').set('unsaved', true); }); }) .always(() => { this.setState({actionInProgress: false}); }); }); requests.push(result); if (this.isNetworkSettingsChanged()) { // collecting data to save var settings = this.props.cluster.get('settings'); var dataToSave = this.props.cluster.isAvailableForSettingsChanges() ? settings.attributes : _.pick(settings.attributes, (group) => (group.metadata || {}).always_editable); var options = {url: settings.url, patch: true, wait: true, validate: false}; var deferred = new models.Settings(_.cloneDeep(dataToSave)).save(null, options); if (deferred) { this.setState({actionInProgress: true}); deferred .done(() => this.setState({initialSettingsAttributes: _.cloneDeep(settings.attributes)})) .always(() => { this.setState({ actionInProgress: false, key: _.now() }); this.props.cluster.fetch(); }) .fail((response) => { utils.showErrorDialog({ title: i18n('cluster_page.settings_tab.settings_error.title'), message: i18n('cluster_page.settings_tab.settings_error.saving_warning'), response: response }); }); requests.push(deferred); } } return $.when(...requests); }, isSavingPossible() { return !this.state.actionInProgress && this.props.cluster.isAvailableForSettingsChanges() && this.hasChanges() && _.isNull(this.props.cluster.get('networkConfiguration').validationError) && _.isNull(this.props.cluster.get('settings').validationError); }, renderButtons() { var isCancelChangesDisabled = this.state.actionInProgress || !!this.props.cluster.task({group: 'deployment', active: true}) || !this.hasChanges(); return ( <div className='well clearfix'> <div className='btn-group pull-right'> <button key='revert_changes' className='btn btn-default btn-revert-changes' onClick={this.revertChanges} disabled={isCancelChangesDisabled} > {i18n('common.cancel_changes_button')} </button> <button key='apply_changes' className='btn btn-success apply-btn' onClick={this.applyChanges} disabled={!this.isSavingPossible()} > {i18n('common.save_settings_button')} </button> </div> </div> ); }, getVerificationErrors() { var task = this.state.hideVerificationResult ? null : this.props.cluster.task({group: 'network', status: 'error'}); var fieldsWithVerificationErrors = []; // @TODO(morale): soon response format will be changed and this part should be rewritten if (task && task.get('result').length) { _.each(task.get('result'), (verificationError) => { _.each(verificationError.ids, (networkId) => { _.each(verificationError.errors, (field) => { fieldsWithVerificationErrors.push({network: networkId, field: field}); }); }); }); } return fieldsWithVerificationErrors; }, removeNodeNetworkGroup() { var nodeNetworkGroup = this.nodeNetworkGroups.find({name: this.props.activeNetworkSectionName}); RemoveNodeNetworkGroupDialog .show({ showUnsavedChangesWarning: this.hasChanges() }) .done(() => { this.props.setActiveNetworkSectionName(this.nodeNetworkGroups.find({is_default: true}).get('name')); return nodeNetworkGroup .destroy({wait: true}) .then( () => this.props.cluster.get('networkConfiguration').fetch(), (response) => utils.showErrorDialog({ title: i18n(networkTabNS + 'node_network_group_deletion_error'), response: response }) ) .then(this.updateInitialConfiguration); }); }, addNodeNetworkGroup(hasChanges) { if (hasChanges) { utils.showErrorDialog({ title: i18n(networkTabNS + 'node_network_group_creation_error'), message: <div><i className='glyphicon glyphicon-danger-sign' /> {i18n(networkTabNS + 'save_changes_warning')}</div> }); return; } CreateNodeNetworkGroupDialog .show({ clusterId: this.props.cluster.id, nodeNetworkGroups: this.nodeNetworkGroups }) .done(() => { this.setState({hideVerificationResult: true}); return this.nodeNetworkGroups.fetch() .then(() => { var newNodeNetworkGroup = this.nodeNetworkGroups.last(); this.props.nodeNetworkGroups.add(newNodeNetworkGroup); this.props.setActiveNetworkSectionName(newNodeNetworkGroup.get('name')); return this.props.cluster.get('networkConfiguration').fetch(); }) .then(this.updateInitialConfiguration); }); }, render() { var isLocked = this.isLocked(); var hasChanges = this.hasChanges(); var {activeNetworkSectionName, cluster} = this.props; var networkConfiguration = this.props.cluster.get('networkConfiguration'); var networkingParameters = networkConfiguration.get('networking_parameters'); var manager = networkingParameters.get('net_manager'); var managers = [ { label: i18n(networkTabNS + 'flatdhcp_manager'), data: 'FlatDHCPManager', checked: manager == 'FlatDHCPManager', disabled: isLocked }, { label: i18n(networkTabNS + 'vlan_manager'), data: 'VlanManager', checked: manager == 'VlanManager', disabled: isLocked } ]; var classes = { row: true, 'changes-locked': isLocked }; var nodeNetworkGroups = this.nodeNetworkGroups = new models.NodeNetworkGroups(this.props.nodeNetworkGroups.where({cluster_id: cluster.id})); var isNovaEnvironment = cluster.get('net_provider') == 'nova_network'; var networks = networkConfiguration.get('networks'); var isMultiRack = nodeNetworkGroups.length > 1; var networkVerifyTask = cluster.task('verify_networks'); var networkCheckTask = cluster.task('check_networks'); var {validationError} = networkConfiguration; var notEnoughOnlineNodesForVerification = cluster.get('nodes').where({online: true}).length < 2; var isVerificationDisabled = validationError || this.state.actionInProgress || !!cluster.task({group: ['deployment', 'network'], active: true}) || isMultiRack || notEnoughOnlineNodesForVerification; var currentNodeNetworkGroup = nodeNetworkGroups.findWhere({name: activeNetworkSectionName}); var nodeNetworkGroupProps = { cluster: cluster, locked: isLocked, actionInProgress: this.state.actionInProgress, verificationErrors: this.getVerificationErrors(), validationError: validationError }; return ( <div className={utils.classNames(classes)}> <div className='col-xs-12'> <div className='row'> <div className='title col-xs-7'> {i18n(networkTabNS + 'title')} {!isNovaEnvironment && <div className='forms-box segmentation-type'> {'(' + i18n('common.network.neutron_' + networkingParameters.get('segmentation_type')) + ')'} </div> } </div> <div className='col-xs-5 node-network-groups-controls'> {!isNovaEnvironment && <button key='add_node_group' className='btn btn-default add-nodegroup-btn pull-right' onClick={_.partial(this.addNodeNetworkGroup, hasChanges)} disabled={!!cluster.task({group: ['deployment', 'network'], active: true}) || this.state.actionInProgress} > {hasChanges && <i className='glyphicon glyphicon-danger-sign'/>} {i18n(networkTabNS + 'add_node_network_group')} </button> } </div> </div> </div> {isNovaEnvironment && <div className='col-xs-12 forms-box nova-managers'> <RadioGroup key='net_provider' name='net_provider' values={managers} onChange={this.onManagerChange} wrapperClassName='pull-left' /> </div> } <div className='network-tab-content col-xs-12'> <div className='row'> <NetworkSubtabs cluster={cluster} validationError={validationError} setActiveNetworkSectionName={this.props.setActiveNetworkSectionName} nodeNetworkGroups={nodeNetworkGroups} activeGroupName={activeNetworkSectionName} isMultiRack={isMultiRack} hasChanges={hasChanges} showVerificationResult={!this.state.hideVerificationResult} /> <div className='col-xs-10'> {!_.contains(defaultNetworkSubtabs, activeNetworkSectionName) && <NodeNetworkGroup {...nodeNetworkGroupProps} nodeNetworkGroups={nodeNetworkGroups} nodeNetworkGroup={currentNodeNetworkGroup} networks={networks.where({group_id: currentNodeNetworkGroup.id})} removeNodeNetworkGroup={this.removeNodeNetworkGroup} setActiveNetworkSectionName={this.props.setActiveNetworkSectionName} /> } {activeNetworkSectionName == 'network_settings' && <NetworkSettings {... _.pick(this.state, 'key', 'configModels', 'settingsForChecks')} cluster={this.props.cluster} locked={this.state.actionInProgress} initialAttributes={this.state.initialSettingsAttributes} /> } {activeNetworkSectionName == 'network_verification' && <NetworkVerificationResult key='network_verification' task={networkVerifyTask} networks={networks} hideVerificationResult={this.state.hideVerificationResult} isMultirack={isMultiRack} isVerificationDisabled={isVerificationDisabled} notEnoughNodes={notEnoughOnlineNodesForVerification} verifyNetworks={this.verifyNetworks} /> } {activeNetworkSectionName == 'nova_configuration' && <NovaParameters cluster={cluster} validationError={validationError} /> } {activeNetworkSectionName == 'neutron_l2' && <NetworkingL2Parameters cluster={cluster} validationError={validationError} disabled={this.isLocked()} /> } {activeNetworkSectionName == 'neutron_l3' && <NetworkingL3Parameters cluster={cluster} validationError={validationError} disabled={this.isLocked()} /> } </div> </div> </div> {!this.state.hideVerificationResult && networkCheckTask && networkCheckTask.match({status: 'error'}) && <div className='col-xs-12'> <div className='alert alert-danger enable-selection col-xs-12 network-alert'> {utils.renderMultilineText(networkCheckTask.get('message'))} </div> </div> } <div className='col-xs-12 page-buttons content-elements'> {this.renderButtons()} </div> </div> ); } }); var NodeNetworkGroup = React.createClass({ render() { var {cluster, networks, nodeNetworkGroup, nodeNetworkGroups, verificationErrors, validationError} = this.props; return ( <div> <NodeNetworkGroupTitle nodeNetworkGroups={nodeNetworkGroups} currentNodeNetworkGroup={nodeNetworkGroup} removeNodeNetworkGroup={this.props.removeNodeNetworkGroup} setActiveNetworkSectionName={this.props.setActiveNetworkSectionName} isRenamingPossible={cluster.isAvailableForSettingsChanges()} isDeletionPossible={!cluster.task({group: ['deployment', 'network'], active: true})} /> {networks.map((network) => { return ( <Network key={network.id} network={network} cluster={cluster} validationError={(validationError || {}).networks} disabled={this.props.locked} verificationErrorField={_.pluck(_.where(verificationErrors, {network: network.id}), 'field')} currentNodeNetworkGroup={nodeNetworkGroup} /> ); })} </div> ); } }); var NetworkSubtabs = React.createClass({ renderClickablePills(sections, isNetworkGroupPill) { var {cluster, nodeNetworkGroups, validationError} = this.props; var isNovaEnvironment = cluster.get('net_provider') == 'nova_network'; var networkParametersErrors = (validationError || {}).networking_parameters; var networksErrors = (validationError || {}).networks; return (sections.map((groupName) => { var tabLabel = groupName; var isActive = groupName == this.props.activeGroupName; var isInvalid; // is one of predefined sections selected (networking_parameters) if (groupName == 'neutron_l2') { isInvalid = !!_.intersection(NetworkingL2Parameters.renderedParameters, _.keys(networkParametersErrors)).length; } else if (groupName == 'neutron_l3') { isInvalid = !!_.intersection(NetworkingL3Parameters.renderedParameters, _.keys(networkParametersErrors)).length; } else if (groupName == 'nova_configuration') { isInvalid = !!_.intersection(NovaParameters.renderedParameters, _.keys(networkParametersErrors)).length; } else if (groupName == 'network_settings') { var settings = cluster.get('settings'); isInvalid = _.any(_.keys(settings.validationError), (settingPath) => { var settingSection = settingPath.split('.')[0]; return settings.get(settingSection).metadata.group == 'network' || settings.get(settingPath).group == 'network'; }); } if (isNetworkGroupPill) { isInvalid = networksErrors && (isNovaEnvironment || !!networksErrors[nodeNetworkGroups.findWhere({name: groupName}).id]); } else { tabLabel = i18n(networkTabNS + 'tabs.' + groupName); } if (groupName == 'network_verification') { tabLabel = i18n(networkTabNS + 'tabs.connectivity_check'); isInvalid = this.props.showVerificationResult && cluster.task({ name: 'verify_networks', status: 'error' }); } return ( <li key={groupName} role='presentation' className={utils.classNames({ active: isActive, warning: this.props.isMultiRack && groupName == 'network_verification' })} onClick={_.partial(this.props.setActiveNetworkSectionName, groupName)} > <a className={'subtab-link-' + groupName}> {isInvalid && <i className='subtab-icon glyphicon-danger-sign' />} {tabLabel} </a> </li> ); })); }, render() { var {nodeNetworkGroups} = this.props; var settingsSections = []; var nodeGroupSections = nodeNetworkGroups.pluck('name'); if (this.props.cluster.get('net_provider') == 'nova_network') { settingsSections.push('nova_configuration'); } else { settingsSections = settingsSections.concat(['neutron_l2', 'neutron_l3']); } settingsSections.push('network_settings'); return ( <div className='col-xs-2'> <CSSTransitionGroup component='ul' transitionName='subtab-item' className='nav nav-pills nav-stacked node-network-groups-list' transitionEnter={false} transitionLeave={false} key='node-group-list' id='node-group-list' > <li className='group-title' key='group1'> {i18n(networkTabNS + 'tabs.node_network_groups')} </li> {this.renderClickablePills(nodeGroupSections, true)} <li className='group-title' key='group2'> {i18n(networkTabNS + 'tabs.settings')} </li> {this.renderClickablePills(settingsSections)} <li className='group-title' key='group3'> {i18n(networkTabNS + 'tabs.network_verification')} </li> {this.renderClickablePills(['network_verification'])} </CSSTransitionGroup> </div> ); } }); var NodeNetworkGroupTitle = React.createClass({ mixins: [ renamingMixin('node-group-title-input') ], onNodeNetworkGroupNameKeyDown(e) { this.setState({nodeNetworkGroupNameChangingError: null}); if (e.key == 'Enter') { this.setState({actionInProgress: true}); var element = this.refs['node-group-title-input'].getInputDOMNode(); var newName = _.trim(element.value); var currentNodeNetworkGroup = this.props.currentNodeNetworkGroup; if (newName != currentNodeNetworkGroup.get('name')) { var validationError = currentNodeNetworkGroup.validate({name: newName}); if (validationError) { this.setState({ nodeNetworkGroupNameChangingError: validationError, actionInProgress: false }); element.focus(); } else { currentNodeNetworkGroup .save({name: newName}, {validate: false}) .fail((response) => { this.setState({ nodeNetworkGroupNameChangingError: utils.getResponseText(response) }); element.focus(); }) .done(() => { this.endRenaming(); this.props.setActiveNetworkSectionName(newName, true); }); } } else { this.endRenaming(); } } else if (e.key == 'Escape') { this.endRenaming(); e.stopPropagation(); ReactDOM.findDOMNode(this).focus(); } }, startNodeNetworkGroupRenaming(e) { this.setState({nodeNetworkGroupNameChangingError: null}); this.startRenaming(e); }, render() { var {currentNodeNetworkGroup, isRenamingPossible, isDeletionPossible} = this.props; var classes = { 'network-group-name': true, 'no-rename': !isRenamingPossible }; return ( <div className={utils.classNames(classes)} key={currentNodeNetworkGroup.id}> {this.state.isRenaming ? <Input type='text' ref='node-group-title-input' name='new-name' defaultValue={currentNodeNetworkGroup.get('name')} error={this.state.nodeNetworkGroupNameChangingError} disabled={this.state.actionInProgress} onKeyDown={this.onNodeNetworkGroupNameKeyDown} wrapperClassName='node-group-renaming clearfix' maxLength='50' selectOnFocus autoFocus /> : <div className='name' onClick={isRenamingPossible && this.startNodeNetworkGroupRenaming}> <button className='btn-link'>{currentNodeNetworkGroup.get('name')}</button> {isRenamingPossible && <i className='glyphicon glyphicon-pencil' />} </div> } {isDeletionPossible && ( currentNodeNetworkGroup.get('is_default') ? <span className='explanation'>{i18n(networkTabNS + 'default_node_network_group_info')}</span> : !this.state.isRenaming && <i className='glyphicon glyphicon-remove' onClick={this.props.removeNodeNetworkGroup} /> )} </div> ); } }); var Network = React.createClass({ mixins: [ NetworkInputsMixin, NetworkModelManipulationMixin ], autoUpdateParameters(cidr) { var useGateway = this.props.network.get('meta').use_gateway; if (useGateway) this.setValue('gateway', utils.getDefaultGatewayForCidr(cidr)); this.setValue('ip_ranges', utils.getDefaultIPRangeForCidr(cidr, useGateway)); }, changeNetworkNotation(name, value) { var meta = _.clone(this.props.network.get('meta')); meta.notation = value ? 'cidr' : 'ip_ranges'; this.setValue('meta', meta); if (value) this.autoUpdateParameters(this.props.network.get('cidr')); }, render() { var meta = this.props.network.get('meta'); if (!meta.configurable) return null; var networkName = this.props.network.get('name'); var ipRangeProps = this.composeProps('ip_ranges', true); var gatewayProps = this.composeProps('gateway'); return ( <div className={'forms-box ' + networkName}> <h3 className='networks'>{i18n('network.' + networkName)}</h3> <div className='network-description'>{i18n('network.descriptions.' + networkName)}</div> <CidrControl {... this.composeProps('cidr')} changeNetworkNotation={this.changeNetworkNotation} autoUpdateParameters={this.autoUpdateParameters} /> <Range {...ipRangeProps} disabled={ipRangeProps.disabled || meta.notation == 'cidr'} rowsClassName='ip-ranges-rows' verificationError={_.contains(this.props.verificationErrorField, 'ip_ranges')} /> {meta.use_gateway && <Input {...gatewayProps} type='text' disabled={gatewayProps.disabled || meta.notation == 'cidr'} /> } <VlanTagInput {...this.composeProps('vlan_start')} label={i18n(networkTabNS + 'network.use_vlan_tagging')} value={this.props.network.get('vlan_start')} /> </div> ); } }); var NovaParameters = React.createClass({ mixins: [ NetworkInputsMixin, NetworkModelManipulationMixin ], statics: { renderedParameters: [ 'floating_ranges', 'fixed_networks_cidr', 'fixed_network_size', 'fixed_networks_amount', 'fixed_networks_vlan_start', 'dns_nameservers' ] }, render() { var networkConfiguration = this.props.cluster.get('networkConfiguration'); var networkingParameters = networkConfiguration.get('networking_parameters'); var manager = networkingParameters.get('net_manager'); var fixedNetworkSizeValues = _.map(_.range(3, 12), _.partial(Math.pow, 2)); return ( <div className='forms-box nova-config' key='nova-config'> <h3 className='networks'>{i18n(parametersNS + 'nova_configuration')}</h3> <Range {...this.composeProps('floating_ranges', true)} rowsClassName='floating-ranges-rows' /> {this.renderInput('fixed_networks_cidr')} {(manager == 'VlanManager') ? <div> <Input {...this.composeProps('fixed_network_size', false, true)} type='select' children={_.map(fixedNetworkSizeValues, (value) => { return <option key={value} value={value}>{value}</option>; })} inputClassName='pull-left' /> {this.renderInput('fixed_networks_amount', true)} <Range {...this.composeProps('fixed_networks_vlan_start', true)} wrapperClassName='clearfix vlan-id-range' label={i18n(parametersNS + 'fixed_vlan_range')} extendable={false} autoIncreaseWith={parseInt(networkingParameters.get('fixed_networks_amount'), 10) || 0} integerValue placeholder='' mini /> </div> : <VlanTagInput {...this.composeProps('fixed_networks_vlan_start')} label={i18n(parametersNS + 'use_vlan_tagging_fixed')} /> } <MultipleValuesInput {...this.composeProps('dns_nameservers', true)} /> </div> ); } }); var NetworkingL2Parameters = React.createClass({ mixins: [ NetworkInputsMixin, NetworkModelManipulationMixin ], statics: { renderedParameters: [ 'vlan_range', 'gre_id_range', 'base_mac' ] }, render() { var networkParameters = this.props.cluster.get('networkConfiguration').get('networking_parameters'); var idRangePrefix = networkParameters.get('segmentation_type') == 'vlan' ? 'vlan' : 'gre_id'; return ( <div className='forms-box' key='neutron-l2'> <h3 className='networks'>{i18n(parametersNS + 'l2_configuration')}</h3> <div className='network-description'>{i18n(networkTabNS + 'networking_parameters.l2_' + networkParameters.get('segmentation_type') + '_description')}</div> <div> <Range {...this.composeProps(idRangePrefix + '_range', true)} extendable={false} placeholder='' integerValue mini /> {this.renderInput('base_mac')} </div> </div> ); } }); var NetworkingL3Parameters = React.createClass({ mixins: [ NetworkInputsMixin, NetworkModelManipulationMixin ], statics: { renderedParameters: [ 'floating_ranges', 'internal_cidr', 'internal_gateway', 'internal_name', 'floating_name', 'baremetal_range', 'baremetal_gateway', 'dns_nameservers' ] }, render() { var networks = this.props.cluster.get('networkConfiguration').get('networks'); return ( <div key='neutron-l3'> <div className='forms-box' key='floating-net'> <h3> <span className='subtab-group-floating-net'>{i18n(networkTabNS + 'floating_net')}</span> </h3> <div className='network-description'>{i18n('network.descriptions.floating')}</div> <Range {...this.composeProps('floating_ranges', true)} rowsClassName='floating-ranges-rows' hiddenControls /> {this.renderInput('floating_name', false, {maxLength: '65'})} </div> <div className='forms-box' key='internal-net'> <h3> <span className='subtab-group-internal-net'>{i18n(networkTabNS + 'internal_net')}</span> </h3> <div className='network-description'>{i18n('network.descriptions.internal')}</div> {this.renderInput('internal_cidr')} {this.renderInput('internal_gateway')} {this.renderInput('internal_name', false, {maxLength: '65'})} </div> {networks.findWhere({name: 'baremetal'}) && <div className='forms-box' key='baremetal-net'> <h3> <span className='subtab-group-baremetal-net'>{i18n(networkTabNS + 'baremetal_net')}</span> </h3> <div className='network-description'>{i18n(networkTabNS + 'networking_parameters.baremetal_parameters_description')}</div> <Range key='baremetal_range' {...this.composeProps('baremetal_range', true)} extendable={false} hiddenControls /> {this.renderInput('baremetal_gateway')} </div> } <div className='forms-box' key='dns-nameservers'> <h3> <span className='subtab-group-dns-nameservers'>{i18n(networkTabNS + 'dns_nameservers')}</span> </h3> <div className='network-description'>{i18n(networkTabNS + 'networking_parameters.dns_servers_description')}</div> <MultipleValuesInput {...this.composeProps('dns_nameservers', true)} /> </div> </div> ); } }); var NetworkSettings = React.createClass({ onChange(groupName, settingName, value) { var settings = this.props.cluster.get('settings'); var name = settings.makePath(groupName, settingName, settings.getValueAttribute(settingName)); this.props.settingsForChecks.set(name, value); // FIXME: the following hacks cause we can't pass {validate: true} option to set method // this form of validation isn't supported in Backbone DeepModel settings.validationError = null; settings.set(name, value); settings.isValid({models: this.props.configModels}); }, checkRestrictions(action, setting) { return this.props.cluster.get('settings').checkRestrictions(this.props.configModels, action, setting); }, render() { var cluster = this.props.cluster; var settings = cluster.get('settings'); var locked = this.props.locked || !!cluster.task({group: ['deployment', 'network'], active: true}); var lockedCluster = !cluster.isAvailableForSettingsChanges(); var allocatedRoles = _.uniq(_.flatten(_.union(cluster.get('nodes').pluck('roles'), cluster.get('nodes').pluck('pending_roles')))); return ( <div className='forms-box network'> { _.chain(settings.attributes) .keys() .filter( (sectionName) => { var section = settings.get(sectionName); return (section.metadata.group == 'network' || _.any(section, {group: 'network'})) && !this.checkRestrictions('hide', section.metadata).result; } ) .sortBy( (sectionName) => settings.get(sectionName + '.metadata.weight') ) .map( (sectionName) => { var section = settings.get(sectionName); var settingsToDisplay = _.compact(_.map(section, (setting, settingName) => { if ( (section.metadata.group || setting.group == 'network') && settingName != 'metadata' && setting.type != 'hidden' && !this.checkRestrictions('hide', setting).result ) return settingName; })); if (_.isEmpty(settingsToDisplay) && !settings.isPlugin(section)) return null; return <SettingSection {... _.pick(this.props, 'cluster', 'initialAttributes', 'settingsForChecks', 'configModels')} key={sectionName} sectionName={sectionName} settingsToDisplay={settingsToDisplay} onChange={_.bind(this.onChange, this, sectionName)} allocatedRoles={allocatedRoles} settings={settings} makePath={settings.makePath} getValueAttribute={settings.getValueAttribute} locked={locked} lockedCluster={lockedCluster} checkRestrictions={this.checkRestrictions} />; } ) .value() } </div> ); } }); var NetworkVerificationResult = React.createClass({ getConnectionStatus(task, isFirstConnectionLine) { if (!task || task.match({status: 'ready'})) return 'stop'; if (task && task.match({status: 'error'}) && !(isFirstConnectionLine && !task.get('result').length)) return 'error'; return 'success'; }, render() { var task = this.props.task; var ns = networkTabNS + 'verify_networks.'; if (this.props.hideVerificationResult) task = null; return ( <div className='verification-control'> <div className='forms-box'> <h3>{i18n(networkTabNS + 'tabs.connectivity_check')}</h3> {this.props.isMultirack && <div className='alert alert-warning'> <p>{i18n(networkTabNS + 'verification_multirack_warning')}</p> </div> } {!this.props.isMultirack && this.props.notEnoughNodes && <div className='alert alert-warning'> <p>{i18n(networkTabNS + 'not_enough_nodes')}</p> </div> } <div className='page-control-box'> <div className='verification-box row'> <div className='verification-network-placeholder col-xs-10 col-xs-offset-2'> <div className='router-box'> <div className='verification-router'></div> </div> <div className='animation-box'> {_.times(3, (index) => { ++index; return <div key={index} className={this.getConnectionStatus(task, index == 1) + ' connect-' + index}></div>; })} </div> <div className='nodes-box'> {_.times(3, (index) => { ++index; return <div key={index} className={'verification-node-' + index}></div>; })} </div> </div> </div> </div> <div className='row'> <div className='verification-text-placeholder col-xs-12'> <ol className='verification-description'> {_.times(5, (index) => { return <li key={index}>{i18n(ns + 'step_' + index)}</li>; })} </ol> </div> </div> <button key='verify_networks' className='btn btn-default verify-networks-btn' onClick={this.props.verifyNetworks} disabled={this.props.isVerificationDisabled} > {i18n(networkTabNS + 'verify_networks_button')} </button> </div> {(task && task.match({status: 'ready'})) && <div className='col-xs-12'> <div className='alert alert-success enable-selection'> {i18n(ns + 'success_alert')} </div> {task.get('message') && <div className='alert alert-warning enable-selection'> {task.get('message')} </div> } </div> } {task && task.match({status: 'error'}) && <div className='col-xs-12'> <div className='alert alert-danger enable-selection network-alert'> {i18n(ns + 'fail_alert')} {utils.renderMultilineText(task.get('message'))} </div> </div> } {(task && !!task.get('result').length) && <div className='verification-result-table col-xs-12'> <Table tableClassName='table table-condensed enable-selection' noStripes head={_.map(['node_name', 'node_mac_address', 'node_interface', 'expected_vlan'], (attr) => ({label: i18n(ns + attr)}))} body={ _.map(task.get('result'), (node) => { var absentVlans = _.map(node.absent_vlans, (vlan) => { return vlan || i18n(networkTabNS + 'untagged'); }); return [node.name || 'N/A', node.mac || 'N/A', node.interface, absentVlans.join(', ')]; }) } /> </div> } </div> ); } }); export default NetworkTab;
src/svg-icons/action/gif.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionGif = (props) => ( <SvgIcon {...props}> <path d="M11.5 9H13v6h-1.5zM9 9H6c-.6 0-1 .5-1 1v4c0 .5.4 1 1 1h3c.6 0 1-.5 1-1v-2H8.5v1.5h-2v-3H10V10c0-.5-.4-1-1-1zm10 1.5V9h-4.5v6H16v-2h2v-1.5h-2v-1z"/> </SvgIcon> ); ActionGif = pure(ActionGif); ActionGif.displayName = 'ActionGif'; ActionGif.muiName = 'SvgIcon'; export default ActionGif;
src/routes/Questionnaire/components/Counter.js
tkshi/q
import React from 'react' import QuestionnaireList from './QuestionnaireList' export const Counter = (props) => ( <div style={{ margin: '0 auto' }} > <QuestionnaireList {...props}/> <button className='btn btn-default' onClick={props.fetchQuestionnaires}> fetchQuestionnaires (Async) </button> </div> ) Counter.propTypes = { questionnaire : React.PropTypes.object.isRequired, fetchQuestionnaires : React.PropTypes.func.isRequired, } export default Counter
client/app/components/mobile_cloud_services.js
poddarh/nectarine
import React from 'react'; import {getUserCloudServices} from '../server'; import {Link} from 'react-router'; export default class MobileCloudServices extends React.Component { constructor(props){ super(props); this.port = location.port ? parseInt(location.port) : (location.protocol == "https:" ? 443 : 80); this.host = location.hostname; this.state = { "cloud_services": { } } getUserCloudServices('1', (data) => {this.setState({cloud_services: data});}) } send(url) { // var peer = new Peer({host: this.host, port: this.port, path: '/api'}); // peer.on('open', function() { // var conn = peer.connect(prompt("Enter Peer ID:")); // conn.on('open', function(){ // conn.send({url: url}); // }); // }); } render(){ return( <div className="container"> <div className="col-xs-12"> <div className="row text-center title"> Select a Cloud Service </div> <div className="row text-center"> {(function(bool) { if(bool) return <Link to={"/files_and_folders/google_drive"}><img src="img/googledrive_logo.png"/></Link> })(this.state.cloud_services.google_drive !== undefined)} {(function(bool) { if(bool) return <Link to="/files_and_folders/dropbox"><img src="img/dropbox_logo.png"/></Link> })(this.state.cloud_services.dropbox !== undefined)} </div> <div className="row text-center title"> Alternatively, enter the URL for the file you wish to share </div> <div className="row search"> <input type="text" className="form-control" placeholder="File URL" id="url-input"></input> </div> <div className="row text-center"> <button className=".btn-primary .btn-lg share" onClick={() => this.send(document.getElementById("url-input").value)}>Share!</button> </div> </div> </div> ) } }
src/js/components/SkipLinkAnchor.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import CSSClassnames from '../utils/CSSClassnames'; const CLASS_ROOT = CSSClassnames.SKIP_LINK_ANCHOR; export default class SkipLinkAnchor extends Component { render () { let id = 'skip-link-' + this.props.label.toLowerCase().replace(/ /g, '_'); return ( <a tabIndex="-1" aria-hidden="true" id={id} className={CLASS_ROOT}> {this.props.label} </a> ); } } SkipLinkAnchor.propTypes = { label: PropTypes.node.isRequired };
src/svg-icons/maps/local-parking.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalParking = (props) => ( <SvgIcon {...props}> <path d="M13 3H6v18h4v-6h3c3.31 0 6-2.69 6-6s-2.69-6-6-6zm.2 8H10V7h3.2c1.1 0 2 .9 2 2s-.9 2-2 2z"/> </SvgIcon> ); MapsLocalParking = pure(MapsLocalParking); MapsLocalParking.displayName = 'MapsLocalParking'; MapsLocalParking.muiName = 'SvgIcon'; export default MapsLocalParking;
src/views/pages/DevPage.js
Domiii/project-empire
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { dataBind } from 'dbdi/react'; import { Alert, Button, Jumbotron, Well, Panel } from 'react-bootstrap'; import { LinkContainer } from 'react-router-bootstrap'; import { LoadOverlay } from 'src/views/components/overlays'; import DynamicForm from 'src/views/tools/DynamicForm'; import FAIcon from 'src/views/components/util/FAIcon'; import LoadIndicator from 'src/views/components/util/LoadIndicator'; import { NOT_LOADED } from 'dbdi/util'; export const schemaTemplate = { type: 'object', properties: [ { id: 'cycleId', type: 'number', title: 'Cycle', isOptional: false }, { id: 'scheduleId', type: 'string' } ] }; const uiSchema = { 'ui:options': { inline: true }, cycleId: { 'ui:placeholder': '很棒的新目標~', 'ui:options': { inline: true } }, scheduleId: { 'ui:widget': 'hidden', } }; @dataBind({ updateCycleId( args, { }, { learnerScheduleAdjustOffsetForCycleId } ) { return learnerScheduleAdjustOffsetForCycleId(args); } }) class LearnerScheduleCycleForm extends Component { static propTypes = { updateCycleId: PropTypes.func.isRequired }; onChange = ({ formData }) => { return this.props.updateCycleId(formData); } render( { }, { learnerScheduleSettings }, { currentLearnerScheduleId } ) { const scheduleId = currentLearnerScheduleId; if (scheduleId === NOT_LOADED) { return <LoadIndicator />; } if (!scheduleId) { return (<Alert className="no-margin no-padding" bsStyle="warning"> no schedule </Alert>); } const { updateCycleId } = this.props; // supply scheduleId for updateCycleId const idArgs = { scheduleId }; // supply scheduleId for updateCycleId // const formArgs = { // scheduleId // }; const props = { schemaTemplate, uiSchema, idArgs, reader: learnerScheduleSettings, writer: updateCycleId, onChange: this.onChange //formArgs }; return (<DynamicForm {...props} > {/* no buttons! */} <span /> </DynamicForm>); } } // @dataBind() // class SessionManipulator extends Component { // render() { // } // } @dataBind({ clickDeleteFileIds(evt, { }, { deleteAllVideoIdsInSession }, { livePresentationSessionId } ) { const sessionArgs = { sessionId: livePresentationSessionId }; deleteAllVideoIdsInSession(sessionArgs); }, clickDeleteSession(evt, { }, { deletePresentationSession }, { livePresentationSessionId } ) { const sessionArgs = { sessionId: livePresentationSessionId }; deletePresentationSession(sessionArgs); } }) class SessionsManipulator extends Component { render( { }, { clickDeleteFileIds, clickDeleteSession }, { livePresentationSessionId } ) { return (<div> <Button bsStyle="danger" disabled={!livePresentationSessionId} onClick={clickDeleteFileIds}> Delete all fileIds of active session </Button> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <Button bsStyle="danger" disabled={!livePresentationSessionId} onClick={clickDeleteSession}> ️⚠️ Delete live presentation session ⚠️ </Button> </div>); } } @dataBind({ }) export default class DevPage extends Component { constructor(...args) { super(...args); } render({ }, { }, { isCurrentUserDev, currentUser_isLoaded }) { if (!currentUser_isLoaded) { return (<LoadOverlay />); } if (!isCurrentUserDev) { return (<Alert bsStyle="warning">Devs only :/</Alert>); } return (<div className="container no-padding"> <Panel bsStyle="primary"> <Panel.Heading> Schedule Settings </Panel.Heading> <Panel.Body> <LearnerScheduleCycleForm /> </Panel.Body> </Panel> <Panel bsStyle="primary"> <Panel.Heading> Presentation Sessions </Panel.Heading> <Panel.Body> <SessionsManipulator /> </Panel.Body> </Panel> </div>); } }
js/jqwidgets/demos/react/app/listbox/textwithicons/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxListBox from '../../../jqwidgets-react/react_jqxlistbox.js'; class App extends React.Component { render() { let source = [ { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/numberinput.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxNumberInput</span></div>', title: 'jqxNumberInput' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/progressbar.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxProgressBar</span></div>', title: 'jqxProgressBar' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/calendar.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxCalendar</span></div>', title: 'jqxCalendar' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/button.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxButton</span></div>', title: 'jqxButton' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/dropdownlist.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxDropDownList</span></div>', title: 'jqxDropDownList' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/listbox.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxListBox</span></div>', title: 'jqxListBox' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/tooltip.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxTooltip</span></div>', title: 'jqxTooltip' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/scrollbar.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxScrollBar</span></div>', title: 'jqxScrollBar' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/datetimeinput.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxDateTimeInput</span></div>', title: 'jqxDateTimeInput' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/expander.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxExpander</span></div>', title: 'jqxExpander' }, { html: '<div style="height: 20px; float: left"><img width="16" height="16" style="float: left; margin-top: 2px; margin-right: 5px" src="../../images/menu.png"/><span style="float: left; font-size: 13px; font-family: Verdana Arial">jqxMenu</span></div>', title: 'jqxMenu' } ]; return ( <JqxListBox width={200} height={250} source={source} /> ) } } ReactDOM.render(<App />, document.getElementById('app'));
wwwroot/app/src/components/base/form/Label.js
AlinCiocan/PlanEatSave
import React from 'react'; const InputGroup = (props) => { return ( <label className="pes-form-label"> {props.text} </label> ); }; export default InputGroup;
packages/reactor-kitchensink/src/examples/Calendar/CalendarPanel/CalendarPanel.js
sencha/extjs-reactor
import React, { Component } from 'react'; import { Calendar } from '@extjs/ext-react-calendar'; import '../data'; export default class CalendarExample extends Component { store = Ext.create('Ext.calendar.store.Calendars', { autoLoad: true, proxy: { type: 'ajax', url: '/KitchenSink/CalendarFull' } }); titleTpl = ({start, end}) => <div>{formatDate(start)} - {formatDate(end)}</div> render() { return ( <Calendar shadow views={{ day: { startTime: 6, endTime: 22 }, workweek: { xtype: 'calendar-week', controlStoreRange: false, titleTpl: this.titleTpl, label: 'Work Week', weight: 15, dayHeaderFormat: 'D d', firstDayOfWeek: 1, visibleDays: 5 } }} timezoneOffset={0} store={this.store} /> ); } } function formatDate(date) { return Ext.util.Format.date(date, 'j M'); }
source/test/title/index.js
cloverfield-tools/universal-react-boilerplate
import React from 'react'; import reactDom from 'react-dom/server'; import test from 'tape'; import dom from 'cheerio'; import createTitle from 'shared/components/title'; const Title = createTitle(React); const render = reactDom.renderToStaticMarkup; test('Title', assert => { const titleText = 'Hello!'; const props = { title: titleText, className: 'title' }; const re = new RegExp(titleText, 'g'); const el = <Title { ...props } />; const $ = dom.load(render(el)); const output = $('.title').html(); const actual = re.test(output); const expected = true; assert.equal(actual, expected, 'should output the correct title text'); assert.end(); });
components/CustomUrl.js
sdumetz/sam
import React from 'react'; import ReactDOM from 'react-dom'; export default class CustomUrl extends React.Component{ constructor(props){ super(props) this.state = {url:""} } componentDidUpdate(){ this.setFocus(); } componentDidMount(){ this.setFocus(); } setFocus(){ } handleChange(event){ this.setState({url: event.target.value}); } onSubmit(e){ e.preventDefault(); e.stopPropagation(); console.log(this.state.url); this.props.handleSend(this.state.url); return false; } render(){ return(<form method="" action="" onSubmit={this.onSubmit.bind(this)}><input ref="input" placeholder="http://example.com" value={this.state.url} onChange={this.handleChange.bind(this)} type="text"/><button type="submit">Submit</button></form>) } }
src/routes/not-found/index.js
foxleigh81/foxweb
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import NotFound from './NotFound'; const title = 'Page Not Found'; function action() { return { chunks: ['not-found'], title, component: ( <Layout> <NotFound title={title} /> </Layout> ), status: 404, }; } export default action;
docs/app/Examples/addons/TextArea/Types/index.js
shengnian/shengnian-ui-react
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const TextAreaTypesExamples = () => ( <ExampleSection title='Types'> <ComponentExample title='TextArea' description='A default TextArea.' examplePath='addons/TextArea/Types/TextAreaExampleTextArea' /> </ExampleSection> ) export default TextAreaTypesExamples
node_modules/@material-ui/core/esm/Breadcrumbs/BreadcrumbCollapsed.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import withStyles from '../styles/withStyles'; import { emphasize } from '../styles/colorManipulator'; import MoreHorizIcon from '../internal/svg-icons/MoreHoriz'; var styles = function styles(theme) { return { root: { display: 'flex' }, icon: { width: 24, height: 16, backgroundColor: theme.palette.grey[100], color: theme.palette.grey[700], borderRadius: 2, marginLeft: theme.spacing(0.5), marginRight: theme.spacing(0.5), cursor: 'pointer', '&:hover, &:focus': { backgroundColor: theme.palette.grey[200] }, '&:active': { boxShadow: theme.shadows[0], backgroundColor: emphasize(theme.palette.grey[200], 0.12) } } }; }; /** * @ignore - internal component. */ function BreadcrumbCollapsed(props) { var classes = props.classes, other = _objectWithoutProperties(props, ["classes"]); return React.createElement("li", _extends({ className: classes.root }, other), React.createElement(MoreHorizIcon, { className: classes.icon })); } process.env.NODE_ENV !== "production" ? BreadcrumbCollapsed.propTypes = { /** * @ignore */ classes: PropTypes.object.isRequired } : void 0; export default withStyles(styles, { name: 'PrivateBreadcrumbCollapsed' })(BreadcrumbCollapsed);
packages/slate-html-serializer/test/serialize/block-with-is-void.js
ashutoshrishi/slate
/** @jsx h */ import React from 'react' import h from '../helpers/h' export const rules = [ { serialize(obj, children) { if (obj.object == 'block' && obj.type == 'image') { return React.createElement('img') } }, }, ] export const input = ( <value> <document> <image /> </document> </value> ) export const output = ` <img/> `.trim()
src/components/fieldComponents/ArrayContainer.js
gearz-lab/react-metaform
import React from 'react'; import metadataProvider from '../../lib/metadataProvider.js'; import MetaFormGroup from '../groupComponents/MetaFormGroup.js'; import Alert from 'react-bootstrap/lib/Alert.js'; import GlyphButton from '../GlyphButton.js'; import Glyphicon from 'react-bootstrap/lib/Glyphicon.js'; import DropdownButton from 'react-bootstrap/lib/DropdownButton.js'; import MenuItem from 'react-bootstrap/lib/MenuItem.js'; import Dropdown from 'react-bootstrap/lib/Dropdown.js'; import arrayHelper from'../../lib/helpers/arrayHelper.js'; import _ from 'underscore'; const ArrayContainerItem = React.createClass({ propTypes: { index: React.PropTypes.number.isRequired, onAction: React.PropTypes.func }, handleAction: function (e, eventKey) { if (this.props.onAction) { this.props.onAction(this.props.index, eventKey) } }, render: function () { return <div className="array-container-item"> <div className="row"> <div className="col-md-11"> <div className="array-container-item-content"> {this.props.children} </div> </div> <div className="col-md-1"> <Dropdown pullRight onSelect={this.handleAction}> <Dropdown.Toggle noCaret bsSize="small"> <Glyphicon glyph="cog"/> </Dropdown.Toggle> <Dropdown.Menu > <MenuItem eventKey="remove"><Glyphicon glyph="remove" className="text-danger"/><span className="glyphicon-text text-danger">Remove</span></MenuItem> <MenuItem divider/> <MenuItem eventKey="moveUp"><Glyphicon glyph="chevron-up"/><span className="glyphicon-text">Move up</span></MenuItem> <MenuItem eventKey="moveDown"><Glyphicon glyph="chevron-down"/><span className="glyphicon-text">Move down</span></MenuItem> <MenuItem divider/> <MenuItem eventKey="moveFirst"><Glyphicon glyph="chevron-up"/><span className="glyphicon-text">Move first</span></MenuItem> <MenuItem eventKey="moveLast"><Glyphicon glyph="chevron-down"/><span className="glyphicon-text">Move last</span></MenuItem> </Dropdown.Menu> </Dropdown> </div> </div> </div>; } }); const ArrayContainer = React.createClass({ propTypes: { name: React.PropTypes.string.isRequired, addText: React.PropTypes.string }, handleAdd: function () { if (this.props.onChange) { let value = this.props.value; value.push({}); this.props.onChange({id: this.props.id, value: value}); } // This "return false" is so a "#" doesn't get added to the URL when this method is triggered from a "a" element. return false; }, handleItemAction: function (index, eventKey) { let value = this.props.value; switch (eventKey) { case "remove": value.splice(index, 1); break; case 'moveUp': arrayHelper.move(value, index, index - 1); break; case 'moveDown': arrayHelper.move(value, index, index + 1); break; case 'moveFirst': arrayHelper.move(value, index, 0); break; case 'moveLast': arrayHelper.move(value, index, value.length - 1); break; } if (this.props.onChange) { this.props.onChange({id: this.props.id, value: value}); } }, render: function () { var header = this.props.displayName ? <header className="metaform-group-header no-lateral-margin"> <span>{this.props.displayName}</span> </header> : null; let components = this.props.fields.map((fields, index) => { return <ArrayContainerItem index={index} onAction={this.handleItemAction}> { this.props.componentFactory.buildGroupComponent({ component: this.props.layout.component, layout: this.props.layout, fields: fields, componentFactory: this.props.componentFactory }) } </ArrayContainerItem>; }); return ( <div className="array-container"> {header} <div className="array-container-content"> {components.length ? components : <Alert bsStyle="warning"> This array is empty. Consider <a href="#" onClick={this.handleAdd}>adding a new item</a>. </Alert>} </div> <div className=""> <span className="pull-right"> <GlyphButton glyph="plus" text={this.props.addText ? this.props.addText : "Add" } onClick={this.handleAdd}/> </span> </div> </div> ); } }); export default ArrayContainer;
traveller/App/Containers/LoginScreen.js
Alabaster-Aardvarks/traveller
// @flow import React from 'react' import { View, ScrollView, Text, TextInput, TouchableOpacity, Image, Keyboard, LayoutAnimation } from 'react-native' import { connect } from 'react-redux' import Styles from './Styles/LoginScreenStyle' import {Images, Metrics} from '../Themes' import LoginActions from '../Redux/LoginRedux' import { Actions as NavigationActions } from 'react-native-router-flux' import I18n from 'react-native-i18n' type LoginScreenProps = { dispatch: () => any, fetching: boolean, attemptLogin: () => void } class LoginScreen extends React.Component { props: LoginScreenProps state: { username: string, password: string, visibleHeight: number, topLogo: { width: number } } isAttempting: boolean keyboardDidShowListener: Object keyboardDidHideListener: Object constructor (props: LoginScreenProps) { super(props) this.state = { username: 'reactnative@infinite.red', password: 'password', visibleHeight: Metrics.screenHeight, topLogo: { width: Metrics.screenWidth } } this.isAttempting = false } componentWillReceiveProps (newProps) { this.forceUpdate() // Did the login attempt complete? if (this.isAttempting && !newProps.fetching) { NavigationActions.pop() } } componentWillMount () { // Using keyboardWillShow/Hide looks 1,000 times better, but doesn't work on Android // TODO: Revisit this if Android begins to support - https://github.com/facebook/react-native/issues/3468 this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow) this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide) } componentWillUnmount () { this.keyboardDidShowListener.remove() this.keyboardDidHideListener.remove() } keyboardDidShow = (e) => { // Animation types easeInEaseOut/linear/spring LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) let newSize = Metrics.screenHeight - e.endCoordinates.height this.setState({ visibleHeight: newSize, topLogo: {width: 100, height: 70} }) } keyboardDidHide = (e) => { // Animation types easeInEaseOut/linear/spring LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut) this.setState({ visibleHeight: Metrics.screenHeight, topLogo: {width: Metrics.screenWidth} }) } handlePressLogin = () => { const { username, password } = this.state this.isAttempting = true // attempt a login - a saga is listening to pick it up from here. this.props.attemptLogin(username, password) } handleChangeUsername = (text) => { this.setState({ username: text }) } handleChangePassword = (text) => { this.setState({ password: text }) } render () { const { username, password } = this.state const { fetching } = this.props const editable = !fetching const textInputStyle = editable ? Styles.textInput : Styles.textInputReadonly return ( <ScrollView contentContainerStyle={{justifyContent: 'center'}} style={[Styles.container, {height: this.state.visibleHeight}]} keyboardShouldPersistTaps> <Image source={Images.logo} style={[Styles.topLogo, this.state.topLogo]} /> <View style={Styles.form}> <View style={Styles.row}> <Text style={Styles.rowLabel}>{I18n.t('username')}</Text> <TextInput ref='username' style={textInputStyle} value={username} editable={editable} keyboardType='default' returnKeyType='next' autoCapitalize='none' autoCorrect={false} onChangeText={this.handleChangeUsername} underlineColorAndroid='transparent' onSubmitEditing={() => this.refs.password.focus()} placeholder={I18n.t('username')} /> </View> <View style={Styles.row}> <Text style={Styles.rowLabel}>{I18n.t('password')}</Text> <TextInput ref='password' style={textInputStyle} value={password} editable={editable} keyboardType='default' returnKeyType='go' autoCapitalize='none' autoCorrect={false} secureTextEntry onChangeText={this.handleChangePassword} underlineColorAndroid='transparent' onSubmitEditing={this.handlePressLogin} placeholder={I18n.t('password')} /> </View> <View style={[Styles.loginRow]}> <TouchableOpacity style={Styles.loginButtonWrapper} onPress={this.handlePressLogin}> <View style={Styles.loginButton}> <Text style={Styles.loginText}>{I18n.t('signIn')}</Text> </View> </TouchableOpacity> <TouchableOpacity style={Styles.loginButtonWrapper} onPress={NavigationActions.pop}> <View style={Styles.loginButton}> <Text style={Styles.loginText}>{I18n.t('cancel')}</Text> </View> </TouchableOpacity> </View> </View> </ScrollView> ) } } const mapStateToProps = (state) => { return { fetching: state.login.fetching } } const mapDispatchToProps = (dispatch) => { return { attemptLogin: (username, password) => dispatch(LoginActions.loginRequest(username, password)) } } export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen)
src/components/Content.js
nchathu2014/reactApp
import React from 'react'; export default class Content extends React.Component{ render(){ var i=6; var myStyle={ fontSize:100, color:"#d31145" } return( <div> <h3>Another content {8+9}</h3> <p data-myattribute="I am a attribute value">paragraph</p> <div> {(i==6)? <h4 style={myStyle}>True</h4>: <h4>False</h4> } </div> <label htmlFor="name">I am label</label> </div> ); } }
app/javascript/mastodon/components/modal_root.js
cobodo/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import 'wicg-inert'; import { createBrowserHistory } from 'history'; import { multiply } from 'color-blend'; export default class ModalRoot extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { children: PropTypes.node, onClose: PropTypes.func.isRequired, backgroundColor: PropTypes.shape({ r: PropTypes.number, g: PropTypes.number, b: PropTypes.number, }), ignoreFocus: PropTypes.bool, }; activeElement = this.props.children ? document.activeElement : null; handleKeyUp = (e) => { if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27) && !!this.props.children) { this.props.onClose(); } } handleKeyDown = (e) => { if (e.key === 'Tab') { const focusable = Array.from(this.node.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter((x) => window.getComputedStyle(x).display !== 'none'); const index = focusable.indexOf(e.target); let element; if (e.shiftKey) { element = focusable[index - 1] || focusable[focusable.length - 1]; } else { element = focusable[index + 1] || focusable[0]; } if (element) { element.focus(); e.stopPropagation(); e.preventDefault(); } } } componentDidMount () { window.addEventListener('keyup', this.handleKeyUp, false); window.addEventListener('keydown', this.handleKeyDown, false); this.history = this.context.router ? this.context.router.history : createBrowserHistory(); } componentWillReceiveProps (nextProps) { if (!!nextProps.children && !this.props.children) { this.activeElement = document.activeElement; this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true)); } } componentDidUpdate (prevProps) { if (!this.props.children && !!prevProps.children) { this.getSiblings().forEach(sibling => sibling.removeAttribute('inert')); // Because of the wicg-inert polyfill, the activeElement may not be // immediately selectable, we have to wait for observers to run, as // described in https://github.com/WICG/inert#performance-and-gotchas Promise.resolve().then(() => { if (!this.props.ignoreFocus) { this.activeElement.focus({ preventScroll: true }); } this.activeElement = null; }).catch(console.error); this._handleModalClose(); } if (this.props.children && !prevProps.children) { this._handleModalOpen(); } if (this.props.children) { this._ensureHistoryBuffer(); } } componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp); window.removeEventListener('keydown', this.handleKeyDown); } _handleModalOpen () { this._modalHistoryKey = Date.now(); this.unlistenHistory = this.history.listen((_, action) => { if (action === 'POP') { this.props.onClose(); } }); } _handleModalClose () { if (this.unlistenHistory) { this.unlistenHistory(); } const { state } = this.history.location; if (state && state.mastodonModalKey === this._modalHistoryKey) { this.history.goBack(); } } _ensureHistoryBuffer () { const { pathname, state } = this.history.location; if (!state || state.mastodonModalKey !== this._modalHistoryKey) { this.history.push(pathname, { ...state, mastodonModalKey: this._modalHistoryKey }); } } getSiblings = () => { return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node); } setRef = ref => { this.node = ref; } render () { const { children, onClose } = this.props; const visible = !!children; if (!visible) { return ( <div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} /> ); } let backgroundColor = null; if (this.props.backgroundColor) { backgroundColor = multiply({ ...this.props.backgroundColor, a: 1 }, { r: 0, g: 0, b: 0, a: 0.7 }); } return ( <div className='modal-root' ref={this.setRef}> <div style={{ pointerEvents: visible ? 'auto' : 'none' }}> <div role='presentation' className='modal-root__overlay' onClick={onClose} style={{ backgroundColor: backgroundColor ? `rgba(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b}, 0.7)` : null }} /> <div role='dialog' className='modal-root__container'>{children}</div> </div> </div> ); } }
imports/ui/components/Loading/Loading.js
jamiebones/Journal_Publication
import React from 'react'; import './Loading.scss' const Loading = () => ( <div className="loader"> Loading... </div> ); export default Loading;
src/wallet/Wallet.js
ryanbaer/busy
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { injectIntl } from 'react-intl'; import { openTransfer } from '../wallet/walletActions'; import Affix from '../components/Utils/Affix'; import LeftSidebar from '../app/Sidebar/LeftSidebar'; import Action from '../components/Button/Action'; import SteemTrendingCharts from '../components/Sidebar/SteemTrendingCharts'; import UserWallet from '../user/UserWallet'; const Wallet = props => ( <div className="shifted"> <div className="feed-layout container"> <Affix className="leftContainer" stickPosition={77}> <div className="left"> <LeftSidebar /> </div> </Affix> <Affix className="rightContainer" stickPosition={77}> <div className="right"> <SteemTrendingCharts /> <Action style={{ margin: '10px 0' }} text={props.intl.formatMessage({ id: 'transfer', defaultMessage: 'Transfer', })} onClick={() => props.openTransfer('')} /> </div> </Affix> <div className="center"> <UserWallet isCurrentUser /> </div> </div> </div> ); Wallet.propTypes = { openTransfer: PropTypes.func.isRequired, intl: PropTypes.shape().isRequired, }; export default connect(null, { openTransfer, })(injectIntl(Wallet));
src/client/components/search/Table.js
gearz-lab/hypersonic
import React from 'react'; import clone from 'clone'; import Loading from 'react-loading'; import {Table, Alert} from 'react-bootstrap'; import { getDetailsUrl } from '../../lib/routingHelper'; export default React.createClass({ propTypes: { selection: React.PropTypes.object, rows: React.PropTypes.array, handleSelectionChange: React.PropTypes.func, loading: React.PropTypes.bool, entityName: React.PropTypes.string.isRequired }, handleCheck: function (e) { let { selection, handleSelectionChange } = this.props; let id = e.target.getAttributeNode('data-id').value; if (!id) { throw Error('Every row should have a non-null data-id attribute'); } let checked = e.target.checked; let newSelection = clone(selection); if (checked) { newSelection[id.toString()] = true; } else { delete newSelection[id.toString()]; } handleSelectionChange(newSelection); }, render: function () { let { rows, layout, selection, loading, entityName } = this.props; if (!rows.length) { return <Alert bsStyle="warning"> The search returned no results. </Alert>; } let loadingBox = loading ? <div className="grid-loading"> <Loading type='spin' color='black' delay={0} height={12} width={12}/> </div> : null; let mainField = layout.fields[0]; // the main field is the field that contains the link to the actuall object let otherFields = layout.fields.slice(1); return <Table bordered condensed> <colgroup> <col span="1" style={{ width: 30 }}/> </colgroup> <thead> <tr> <th>{loadingBox}</th> { layout.fields.map((f, i) => { return <th key={`th-${i}`}>{f.displayName ? f.displayName : f.name}</th> }) } </tr> </thead> <tbody> { rows.map((r, i) => { return <tr key={`tr-${i}`}> <td className="check-column"> <input type="checkbox" onChange={this.handleCheck} data-id={r['id']} checked={Boolean(selection[r['id']]) }/> </td> <td> <a href={getDetailsUrl(entityName, r['id'])}>{r[mainField.name]}</a> </td> { otherFields.map((f, j) => { return <td key={`td-${i}${j}`}> {r[f.name]} </td> }) } </tr> }) } </tbody> </Table>; } })
src/component/BarChart.js
dnadrshin/dashboard
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Bar } from 'react-chartjs-2'; class LineChart extends Component { render() { let chartData = { labels: ['1', '2', '3', '4', '5', '6', '7'], datasets: [ { label: 'Weather Amount', backgroundColor: 'rgba(255,99,132,0.2)', borderColor: 'rgba(255,99,132,1)', borderWidth: 1, hoverBackgroundColor: 'rgba(255,99,132,0.4)', hoverBorderColor: 'rgba(255,99,132,1)', data: this.props.store.data_bar } ] }; return <Bar data={chartData} /> } } const mapStateToProps = (state) => { return { store: state } } const LineChartC = connect(mapStateToProps)(LineChart) export default LineChartC;
src/containers/PlaylistEdit.js
kellhellia/vkReduxLast
import React, { Component } from 'react'; import { connect } from 'react-redux'; import store from '../store'; import { getSearchTerm, search, getCurrentPlaylist, addTrackToPlaylist, removeTrackFromPlaylist, handleFriendsModalOpen, handleFriendsModalClose } from '../actions'; import Modal from 'react-modal'; import CheckedFriend from './CheckedFriend'; class PlaylistEdit extends Component { componentDidMount() { let playlistId = this.props.params.playlistId; this.props.dispatch(getCurrentPlaylist(playlistId)); } handleInputChange(e) { this.props.dispatch(getSearchTerm(e.target.value)); } handleSearch(e) { e.preventDefault(); let searchTerm = this.props.search.value.searchTerm; if (searchTerm.length !== 0) { this.props.dispatch(search(searchTerm)); } } handleAddSong(track) { let playlistId = this.props.params.playlistId; this.props.dispatch(addTrackToPlaylist(playlistId, track)); } handleRemoveTrack(trackId) { let playlistId = this.props.params.playlistId; this.props.dispatch(removeTrackFromPlaylist(playlistId, trackId)); } handleFriendsModalOpen() { this.props.dispatch(handleFriendsModalOpen()); } handleFriendsModalClose() { this.props.dispatch(handleFriendsModalClose()); } render() { const customStyles = { overlay : { position: 'fixed', backgroundColor: 'rgba(0, 0, 0, .8)' }, content : { top: '70px', left: '30%', right: 'auto', bottom: 'auto', backgroundColor: '#fff', border: 0, borderRadius: 0, width: '40%', height: '500px', color: 'black', paddingTop: '20px', paddingLeft: '20px', paddingRight: '20px', paddingBottom: '0px' } }; let searchResults = this.props.search.value.searchResults; let searchResultsSongs = searchResults ? searchResults.map((track, index) => { if (track.title) { return ( <div className="row form-group" key={index}> <div className="col-xs-9"> <p>{track.artist} - {track.title}</p> </div> <div className="col-xs-2"> <button className="btn btn-primary inline-block" onClick={this.handleAddSong.bind(this, track)} >Add song</button> </div> </div> ) } }) : ''; let searchResultsBlock = searchResults && searchResults.length ? (<div className="col-sm-12">Search results: {searchResultsSongs} </div>) : <span />; let fetchStatus = this.props.currentPlaylist.fetchStatus.value; let fetchStatusFriends = this.props.user.fetchStatusFriends.value; let fetchStatusPlaylist = this.props.currentPlaylist.fetchStatus.value; let friendsModalOpen = this.props.app.friendsModalOpen; let friendsFromVk = this.props.user.friends; let friendsFromPlaylist = this.props.currentPlaylist.value.friends; let lol = (fetchStatusFriends === 'LOADED' && fetchStatusPlaylist === 'LOADED') ? friendsFromVk.map((friend, index) => { return ( <CheckedFriend key={index} friend={friend} checked={friendsFromPlaylist.length && friendsFromPlaylist.indexOf(friend.uid) != -1} /> ) }) : <span />; return ( <div className="playlist-edit"> <i className="playlist-edit-cog glyphicon glyphicon-cog" onClick={::this.handleFriendsModalOpen}></i> <Modal isOpen={friendsModalOpen} onRequestClose={::this.handleFriendsModalClose} style={customStyles} > <h5>Кто может слушать плейлист: </h5> <div className="container-fluid"> <div className="row mb50"> { fetchStatusFriends === 'LOADING' && ( <div>Loading friends...</div> ) } { fetchStatusFriends === 'FAILED' && ( <div>Loading friends failed</div> ) } {lol} </div> </div> </Modal> <div className="row"> <div className="col-sm-10"> <form onSubmit={::this.handleSearch}> <input className="search__input form-control" placeholder="Введите исполнителя/название трека" onChange={::this.handleInputChange} /> </form> </div> <div className="col-sm-2"> <button type="submit" className="btn btn-primary text-uppercase" onClick={::this.handleSearch} >Search</button> </div> </div> <div className="row"> <div className="col-xs-6"> <div className="mb50 row"> <h4>Search results:</h4> {searchResultsBlock} </div> </div> <div className="col-xs-6"> <h4>Playlist songs:</h4> { fetchStatus === 'LOADING' && ( <div>Loading songs...</div> ) } { fetchStatus === 'FAILED' && ( <div>Loading songs failed</div> ) } { fetchStatus === 'LOADED' && ( this.props.currentPlaylist.value.songs.map((track, index) => { let trackId = track.trackId; return ( <div className="row form-group" key={index}> <div className="col-xs-10"> <span>{track.artist} - {track.title}</span> </div> <div className="col-xs-2"> <button className="btn btn-danger" onClick={this.handleRemoveTrack.bind(this, {trackId})} >Remove track</button> </div> </div> ) }) ) } </div> </div> </div> ) } } PlaylistEdit = connect(state => state)(PlaylistEdit); export default PlaylistEdit;
docs/lib/examples/BigPlayButton.js
video-react/video-react
import React from 'react'; import { Player, BigPlayButton } from 'video-react'; export default props => { return ( <Player src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4"> <BigPlayButton position="center" /> </Player> ); };
core/src/plugins/access.ajxp_conf/res/js/AdminWorkspaces/editor/FeaturesListWizard.js
pydio/pydio-core
/* * Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io> * This file is part of Pydio. * * Pydio is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pydio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <https://pydio.com>. */ import React from 'react' import {RaisedButton} from 'material-ui' import Workspace from '../model/Workspace' export default React.createClass({ mixins:[AdminComponents.MessagesConsumerMixin], propTypes:{ onSelectionChange:React.PropTypes.func.isRequired, driverLabel:React.PropTypes.string, driverDescription:React.PropTypes.string, currentSelection:React.PropTypes.string, wizardType:React.PropTypes.string, driversLoaded:React.PropTypes.bool, additionalComponents:React.PropTypes.object, disableCreateButton:React.PropTypes.bool }, getInitialState:function(){ return { edit:this.props.wizardType == 'workspace'?'template':'general', step:1, subStep1:'template' }; }, componentWillReceiveProps:function(newProps){ if(newProps.currentSelection){ this.setState({edit:newProps.currentSelection}); } }, setEditState:function(key){ this.props.onSelectionChange(key); this.setState({edit:key}); }, closeCurrent:function(event){ event.stopPropagation(); }, dropDownChange: function(item){ if(item.payload.name){ this.setState({step:3}); } this.setState({edit:'driver', selectedDriver:item.payload.name}); this.props.onSelectionChange('driver', item.payload.name); }, dropChangeDriverOrTemplate:function(event, item){ if(item == 'template'){ this.setState({step:1,subStep1:item}); }else{ this.setState({step:2, subStep1:'driver'}); this.setEditState('general'); } }, dropDownChangeTpl: function(item){ if(item.payload != -1){ var tpl = item.payload == "0" ? "0" : item.payload.name; this.setState({ edit:'general', selectedTemplate:tpl == "0"? null: tpl, step:2 }); this.props.onSelectionChange('general', null, tpl); } }, render: function(){ var step1, step2, step3; if(this.props.wizardType == 'workspace'){ // TEMPLATES SELECTOR var driverOrTemplate = ( <div> <ReactMUI.RadioButtonGroup name="driv_or_tpl" onChange={this.dropChangeDriverOrTemplate} defaultSelected={this.state.subStep1}> <ReactMUI.RadioButton value="template" label={this.context.getMessage('ws.8')} /> <ReactMUI.RadioButton value="driver" label={this.context.getMessage('ws.9')}/> </ReactMUI.RadioButtonGroup> </div> ); var templateSelector = null; if(this.state.step == 1 && this.state.subStep1 == "template"){ templateSelector = ( <PydioComponents.PaperEditorNavEntry label={this.context.getMessage('ws.10')} selectedKey={this.state.edit} keyName="template" onClick={this.setEditState} dropDown={true} dropDownData={this.props.driversLoaded?Workspace.TEMPLATES:null} dropDownChange={this.dropDownChangeTpl} dropDownDefaultItems={[]} /> ); } step1 = ( <div> <PydioComponents.PaperEditorNavHeader key="tpl-k" label={"1 - " + this.context.getMessage('ws.11')}/> {driverOrTemplate} {templateSelector} </div> ); } // DRIVER SELECTOR STEP if(this.state.step > 1 || this.props.wizardType == 'template'){ if(this.props.wizardType == 'workspace' && this.state.selectedTemplate){ // Display remaining template options instead of generic + driver var tplLabel = Workspace.TEMPLATES.get(this.state.selectedTemplate).label; step2 = ( <div> <PydioComponents.PaperEditorNavHeader key="parameters-k" label={"2 - " + this.context.getMessage('ws.12').replace('%s', tplLabel)}/> <PydioComponents.PaperEditorNavEntry keyName='general' key='general' selectedKey={this.state.edit} label={this.context.getMessage('ws.13')} onClick={this.setEditState} /> </div> ); }else{ step2 = <div> <PydioComponents.PaperEditorNavHeader key="parameters-k" label={"2 - " + this.context.getMessage('ws.14')}/> <PydioComponents.PaperEditorNavEntry keyName='general' key='general' selectedKey={this.state.edit} label={this.context.getMessage('ws.15')} onClick={this.setEditState} /> <PydioComponents.PaperEditorNavHeader key="driver-k" label={"3 - " + this.context.getMessage('ws.16')}/> <PydioComponents.PaperEditorNavEntry label={this.context.getMessage(this.props.driversLoaded?'ws.17':'ws.18')} selectedKey={this.state.edit} keyName="driver" onClick={this.setEditState} dropDown={true} dropDownData={this.props.driversLoaded?Workspace.DRIVERS:null} dropDownChange={this.dropDownChange} /> </div>; } } // SAVE / CANCEL BUTTONS if(this.state.step > 2 || (this.state.step > 1 && this.props.wizardType == 'workspace' && this.state.selectedTemplate) ){ var stepNumber = 4; if(this.state.selectedTemplate) stepNumber = 3; step3 = <div> <PydioComponents.PaperEditorNavHeader key="save-k" label={stepNumber + " - " + this.context.getMessage('ws.19')}/> <div style={{textAlign:'center'}}> <RaisedButton primary={false} label={this.context.getMessage('54', '')} onTouchTap={this.props.close} /> &nbsp;&nbsp;&nbsp; <RaisedButton primary={true} label={this.context.getMessage('ws.20')} onTouchTap={this.props.save} disabled={this.props.disableCreateButton}/> </div> </div>; }else{ step3 = <div style={{textAlign:'center', marginTop: 50}}> <RaisedButton primary={false} label={this.context.getMessage('54', '')} onTouchTap={this.props.close} /> </div>; } return ( <div> {step1} {step2} {this.props.additionalComponents} {step3} </div> ); } });
src-client/scripts/modal-window.js
VeryBarry/iLuggit
import React from 'react' let ModalWindow = React.createClass({ render:function(){ let modalClassName = 'modal-container' if (this.props.modalSettings.isShowing ===false){ modalClassName = 'modal-container is-hidden ' } console.log(this.props); return( <div className={modalClassName}> <div className="overlay"> </div> <div className="window"> <ul> <li>{this.props.modalSettings.payload.first_name} {this.props.modalSettings.payload.last_name}</li> <li>{this.props.modalSettings.payload.phone_number}</li> <li>{this.props.modalSettings.payload.email}</li> <li>{this.props.modalSettings.payload.bedSize}</li> </ul> </div> </div> ) } }) module.exports=ModalWindow
app/assets/javascripts/src/components/sharedComponents/InstagramIcon.js
talum/creamery
import React from 'react' const InstagramIcon = () => ( <div className="svg-container svg-container--small"> <svg viewBox="0 0 32 32"> <path d="M16 2.881c4.275 0 4.781 0.019 6.462 0.094 1.563 0.069 2.406 0.331 2.969 0.55 0.744 0.288 1.281 0.638 1.837 1.194 0.563 0.563 0.906 1.094 1.2 1.838 0.219 0.563 0.481 1.412 0.55 2.969 0.075 1.688 0.094 2.194 0.094 6.463s-0.019 4.781-0.094 6.463c-0.069 1.563-0.331 2.406-0.55 2.969-0.288 0.744-0.637 1.281-1.194 1.837-0.563 0.563-1.094 0.906-1.837 1.2-0.563 0.219-1.413 0.481-2.969 0.55-1.688 0.075-2.194 0.094-6.463 0.094s-4.781-0.019-6.463-0.094c-1.563-0.069-2.406-0.331-2.969-0.55-0.744-0.288-1.281-0.637-1.838-1.194-0.563-0.563-0.906-1.094-1.2-1.837-0.219-0.563-0.481-1.413-0.55-2.969-0.075-1.688-0.094-2.194-0.094-6.463s0.019-4.781 0.094-6.463c0.069-1.563 0.331-2.406 0.55-2.969 0.288-0.744 0.638-1.281 1.194-1.838 0.563-0.563 1.094-0.906 1.838-1.2 0.563-0.219 1.412-0.481 2.969-0.55 1.681-0.075 2.188-0.094 6.463-0.094zM16 0c-4.344 0-4.887 0.019-6.594 0.094-1.7 0.075-2.869 0.35-3.881 0.744-1.056 0.412-1.95 0.956-2.837 1.85-0.894 0.888-1.438 1.781-1.85 2.831-0.394 1.019-0.669 2.181-0.744 3.881-0.075 1.713-0.094 2.256-0.094 6.6s0.019 4.887 0.094 6.594c0.075 1.7 0.35 2.869 0.744 3.881 0.413 1.056 0.956 1.95 1.85 2.837 0.887 0.887 1.781 1.438 2.831 1.844 1.019 0.394 2.181 0.669 3.881 0.744 1.706 0.075 2.25 0.094 6.594 0.094s4.888-0.019 6.594-0.094c1.7-0.075 2.869-0.35 3.881-0.744 1.050-0.406 1.944-0.956 2.831-1.844s1.438-1.781 1.844-2.831c0.394-1.019 0.669-2.181 0.744-3.881 0.075-1.706 0.094-2.25 0.094-6.594s-0.019-4.887-0.094-6.594c-0.075-1.7-0.35-2.869-0.744-3.881-0.394-1.063-0.938-1.956-1.831-2.844-0.887-0.887-1.781-1.438-2.831-1.844-1.019-0.394-2.181-0.669-3.881-0.744-1.712-0.081-2.256-0.1-6.6-0.1v0z"></path> <path d="M16 7.781c-4.537 0-8.219 3.681-8.219 8.219s3.681 8.219 8.219 8.219 8.219-3.681 8.219-8.219c0-4.537-3.681-8.219-8.219-8.219zM16 21.331c-2.944 0-5.331-2.387-5.331-5.331s2.387-5.331 5.331-5.331c2.944 0 5.331 2.387 5.331 5.331s-2.387 5.331-5.331 5.331z"></path> <path d="M26.462 7.456c0 1.060-0.859 1.919-1.919 1.919s-1.919-0.859-1.919-1.919c0-1.060 0.859-1.919 1.919-1.919s1.919 0.859 1.919 1.919z"></path> </svg> </div> ) export default InstagramIcon
app/containers/LanguageProvider/index.js
anhldbk/react-boilerplate
/* * * LanguageProvider * * this component connects the redux state language locale to the * IntlProvider component and i18n messages (loaded from `app/translations`) */ import React from 'react'; import { connect } from 'react-redux'; import { createSelector } from 'reselect'; import { IntlProvider } from 'react-intl'; import { makeSelectLocale } from './selectors'; export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function render() { return ( <IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}> {React.Children.only(this.props.children)} </IntlProvider> ); } } LanguageProvider.propTypes = { locale: React.PropTypes.string, messages: React.PropTypes.object, children: React.PropTypes.element.isRequired, }; const mapStateToProps = createSelector( makeSelectLocale(), (locale) => ({ locale }) ); export default connect(mapStateToProps)(LanguageProvider);
src/docs/examples/TextInput/ExampleEmail.js
MallikarjunaMG/react-components
import React from 'react' import TextInput from 'comps-root/TextInput'; /** * Email Textinput Field - Optional */ export default function ExampleEmail() { return <TextInput htmlId='example-email' label='Email' name='Email' type='email' placeholder='Enter Email' onChange={() => {}} /> }
app/javascript/mastodon/features/ui/components/column_link.js
rutan/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; const ColumnLink = ({ icon, text, to, href, method, badge }) => { const badgeElement = typeof badge !== 'undefined' ? <span className='column-link__badge'>{badge}</span> : null; if (href) { return ( <a href={href} className='column-link' data-method={method}> <i className={`fa fa-fw fa-${icon} column-link__icon`} /> {text} {badgeElement} </a> ); } else { return ( <Link to={to} className='column-link'> <i className={`fa fa-fw fa-${icon} column-link__icon`} /> {text} {badgeElement} </Link> ); } }; ColumnLink.propTypes = { icon: PropTypes.string.isRequired, text: PropTypes.string.isRequired, to: PropTypes.string, href: PropTypes.string, method: PropTypes.string, badge: PropTypes.node, }; export default ColumnLink;
app/src/navigation/index.js
BlackBoxVision/react-native-redux-todo
import React from 'react'; import addNavigationHelpers from 'react-navigation/lib/addNavigationHelpers'; import connect from 'react-redux/lib/connect/connect'; import Navigator from './routes'; const mapStateToProps = state => ({ navigate: state.navigate }); @connect(mapStateToProps) export default class ScreenManager extends React.Component { render() { return ( <Navigator navigation={addNavigationHelpers({ dispatch: this.props.dispatch, state: this.props.navigate })} /> ); } }