path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
js/Player/Players.js
olegk101/test
import React from 'react' import { connect } from 'react-redux' // import io from 'socket.io-client' import Radium, { StyleRoot } from 'radium' import style from '../style/liveplayer' class Players extends React.Component { constructor(props) { super(props) this.state = { playing: false, song: '', loaded: false, } this.audio = null; this.togglePlay = this.togglePlay.bind(this) } togglePlay () { if (this.state.playing) { this.audio.pause() } else { this.audio.play() } this.setState({ playing: !this.state.playing }) } componentDidMount () { this.audio = document.createElement('audio'); this.audio.preload = 'metadata'; // this.audio.addEventListener('play', console.log); // this.audio.addEventListener('pause', this.audioPauseListener); // this.audio.addEventListener('ended', this.audioEndListener); this.audio.addEventListener('loadedmetadata', this.audioMetadataLoadedListener); this.audio.addEventListener('canplay', this.setState({ loaded: true }), false); this.audio.src = 'http://46.32.69.199:8000/live96'; this.togglePlay = this.togglePlay.bind(this) } render () { let element if (this.state.playing) { element = (<svg fill="#fff" viewBox="0 0 24 24" height="100%" xmlns="http://www.w3.org/2000/svg"> <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg>) } else { element = (<svg fill="#fff" viewBox="0 0 24 24" height="100%" xmlns="http://www.w3.org/2000/svg"> <path d="M8 5v14l11-7z"/> <path d="M0 0h24v24H0z" fill="none"/> </svg>) } return ( <StyleRoot> <div style={style.button} onClick={this.togglePlay} > {element} </div> </StyleRoot> ) } } const mapStateToProps = (state) => { return { fuck: state.searchTerm } } Players = Radium(Players) export default connect(mapStateToProps)(Players)
app/components/AudioPlayer.js
jrhalchak/BeatsPM
import React, { Component } from 'react'; import styles from './AudioPlayer.css'; export default class AudioPlayer extends Component { handleRangeChange(e) { this.props.timeChange(e.target.value / e.target.max); } render() { const { toggleAudio, pauseAudio, isPlaying, audioSrc, currentTime, duration, audioChange, fileName, isDetecting, } = this.props; const toggleText = isPlaying ? 'Stop' : 'Play'; const toggleClass = isPlaying ? styles.stopButton : null; const currentVal = (currentTime / duration) * 100; const detecting = isDetecting ? <Detecting /> : null; if (!audioSrc) { return ( <div className="pad-v"> <FileInput audioChange={audioChange} isAlone={true} /> </div> ); } return ( <div className={styles.audioContainer}> {detecting} <div className={styles.audioControls}> <div className="pad-h-half float-right"> <button className={`${styles.audioButton} ${toggleClass}`} onClick={toggleAudio}>{toggleText}</button> <button className={styles.audioButton} onClick={pauseAudio}>Pause</button> </div> <FileInput audioChange={audioChange} fileName={fileName} isAlone={false} /> </div> <div className={styles.waveContainer}> {this.props.children} <progress className={styles.progressOverlay} value={currentVal} max="100" /> <input type="range" min="0" max="100" className={styles.slider} onChange={this.handleRangeChange.bind(this)} value={currentVal} /> </div> </div> ); } } function Detecting() { return ( <div className={styles.detectingMessage}>Attempting BPM Auto-Detect...</div> ); } function FileInput({ audioChange, fileName, isAlone }) { const divAlignment = isAlone ? 'text-center' : 'text-left'; const labelClass = isAlone ? styles.audioInputLabelBig : ''; return ( <div className={`pad-h-half ${divAlignment}`}> <label htmlFor="audio_input"> <span className={`${styles.audioInputLabel} ${labelClass}`}> {fileName ? 'Change Song' : 'Open a Song' } </span> {fileName ? <small className={styles.fileName}>- {fileName}</small> : ''} </label> <input id="audio_input" className={styles.audioInput} type="file" accept="audio/*" onChange={audioChange} /> </div> ); }
12-route-to-modal-gallery/components/Gallery/Gallery.js
nodeyu/jason-react-router-demos-v4
import React from 'react'; import { Link } from 'react-router-dom'; import IMAGES from '../../images/images'; import Thumbnail from '../Thumbnail/Thumbnail'; class Gallery extends React.Component { render() { return ( <div> <h2>Gallery</h2> { IMAGES.map((img) => ( <Link key={img.id} to={{ pathname: `/img/${img.id}`, state: { modal: true } }} > <Thumbnail color={img.color}/> <p style={{ marginTop: 0 }}>{img.title}</p> </Link> )) } </div> ); } } export default Gallery;
BUILD/js/components_js/product-card.js
kevincaicedo/MyStore-Front-end
import React from 'react' export default class CardProduct extends React.Component { render(){ return <div className="col-sm-4 col-lg-4 col-md-4 card-product"> <div className="thumbnail"> <img src={this.props.urlimg} alt="" /> <div className="caption"> <h4 className="pull-right price">$ {this.props.price}</h4> <h4><a href="#">{this.props.name}</a></h4> <p>{this.props.despcription}</p> </div> <div className="ratings"> <p className="pull-right fechap">{this.props.fecha}</p> <p> <a href="#about" className="btn btn-primary btn-xl page-scroll verbtn">ver</a> </p> </div> </div> </div> } }
src/svg-icons/content/add-box.js
ichiohta/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentAddBox = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/> </SvgIcon> ); ContentAddBox = pure(ContentAddBox); ContentAddBox.displayName = 'ContentAddBox'; ContentAddBox.muiName = 'SvgIcon'; export default ContentAddBox;
src/index.js
amsb/storybook_styled-components_example
import 'core-js/es6/symbol'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; ReactDOM.render( <App />, document.getElementById('root') );
client/src/components/Listing/ListingsContainer.js
wolnewitz/raptor-ads
import React, { Component } from 'react'; import { Container, Search } from 'semantic-ui-react'; class ListingsContainer extends Component { constructor(props) { super(props); } handleSearchChange(e) { // dispatch controlled input update searchValue } render() { <Container> <Search loading={isLoading} onSearchChange={() => this.handleSearchChange()} value={searchValue} {...this.props} /> </Container> } }
client/share_trader/js/components/share_trader.js
bigchaindb/bigchaindb-examples
import React from 'react'; import { Navbar, Row, Col, Button } from 'react-bootstrap/lib'; import AccountList from '../../../lib/js/react/components/account_list'; import AccountDetail from '../../../lib/js/react/components/account_detail'; import Assets from './assets'; import AssetMatrix from './asset_matrix'; import AssetActions from '../../../lib/js/react/actions/asset_actions'; import BigchainDBConnection from '../../../lib/js/react/components/bigchaindb_connection'; const ShareTrader = React.createClass({ propTypes: { // Injected through BigchainDBConnection accountList: React.PropTypes.array, activeAccount: React.PropTypes.object, activeAsset: React.PropTypes.object, assetList: React.PropTypes.object, handleAccountChange: React.PropTypes.func, handleAssetChange: React.PropTypes.func, resetActiveAccount: React.PropTypes.func }, fetchAssetList({ account }) { AssetActions.fetchAssetList({ account, blockWhenFetching: false }); }, mapAccountsOnStates(accountList) { const states = { 'default': 'available' }; if (!accountList) { return states; } for (let i = 0; i < accountList.length; i++) { states[accountList[i].vk] = `state${i}`; } return states; }, flattenAssetList(assetList) { return [].concat(...Object.values(assetList)); }, render() { const { activeAccount, accountList, activeAsset, assetList, handleAccountChange, handleAssetChange, resetActiveAccount } = this.props; const states = this.mapAccountsOnStates(accountList); const assetListForAccount = activeAccount && assetList.hasOwnProperty(activeAccount.vk) ? assetList[activeAccount.vk] : this.flattenAssetList(assetList); return ( <div> <Navbar fixedTop inverse> <h1 style={{ textAlign: 'center', color: 'white' }}>Share Trader</h1> </Navbar> <div id="wrapper"> <div id="sidebar-wrapper"> <div className="sidebar-nav"> <div style={{ textAlign: 'center' }}> <Button onClick={resetActiveAccount}> Select All </Button> </div> <br /> <AccountList activeAccount={activeAccount} appName="sharetrader" handleAccountClick={handleAccountChange}> <AccountDetail /> </AccountList> </div> </div> <div id="page-content-wrapper"> <div className="page-content"> <Row> <Col className="asset-matrix" md={8} xs={6}> <div className="vertical-align-outer"> <div className="vertical-align-inner"> <AssetMatrix assetList={assetListForAccount} cols={8} handleAssetClick={handleAssetChange} rows={8} states={states} /> </div> </div> </Col> <Col className="asset-history" md={4} xs={6}> <Assets accountList={accountList} activeAccount={activeAccount} activeAsset={activeAsset} assetClasses={states} assetList={assetListForAccount} handleAssetClick={handleAssetChange} /> </Col> </Row> </div> </div> </div> </div> ); } }); export default BigchainDBConnection(ShareTrader);
docs/app/Examples/modules/Dropdown/Variations/DropdownExampleMenuDirection.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' const DropdownExampleMenuDirection = () => ( <Dropdown text='Menu' floating labeled button className='icon'> {/* <i class="dropdown icon"></i> */} <Dropdown.Menu> <Dropdown.Item> <i className='left dropdown icon'></i> <span className='text'>Left</span> <div className='left menu'> <Dropdown.Item>1</Dropdown.Item> <Dropdown.Item>2</Dropdown.Item> <Dropdown.Item>3</Dropdown.Item> </div> </Dropdown.Item> <Dropdown.Item> <i className='dropdown icon'></i> <span className='text'>Right</span> <div className='right menu'> <Dropdown.Item>1</Dropdown.Item> <Dropdown.Item>2</Dropdown.Item> <Dropdown.Item>3</Dropdown.Item> </div> </Dropdown.Item> </Dropdown.Menu> </Dropdown> ) export default DropdownExampleMenuDirection
examples/wrapper/index.js
sskyy/react-lego
import React from 'react' import ReactDom from 'react-dom' import { wrap } from '@cicada/react-lego' import Case from '../Case' import Card from './Card' const Root = Card.Root.extend` border: 1px dashed black; ` const Text = ({children}) => { return <div>{children.map(child => { if (/^name:/.test(child) ) return '姓名: ' if (/^age:/.test(child)) return '年龄: ' return child })}</div> } ReactDom.render(( <div> <Case title="普通 Card"> <Card name="jim" age={11} /> </Case> <Case title="传入了 Root, 简单演示替换样式"> <Card name="jim" age={11} Root={Root}/> </Case> <Case title="传入了 Text, 简单演示替换文案"> <Card name="jim" age={11} Text={Text}/> </Case> </div> ), document.getElementById('root'))
src/index.js
vikramarka/contacts
import React from 'react'; import ReactDOM from 'react-dom'; import {BrowserRouter} from 'react-router-dom'; import App from './App'; import './index.css'; ReactDOM.render( <BrowserRouter><App /></BrowserRouter>, document.getElementById('root') );
src/index.js
tasking/firebase-react-paginated
// react import React, { Component } from 'react'; // utils import getRef from './utils/getFirebaseRef'; import getDisplayName from './utils/getComponentDisplayName'; import getItems from './utils/getSnapshotItems'; const withFirebasePages = (firebase) => { const ref = getRef(firebase); return (options) => { if (!options || !options.path) { throw new Error('withFirebasePages - must receive an options object with a valid path prop.'); } return (WrappedComponent) => { return class extends Component { static displayName = `withFirebasePages(${getDisplayName(WrappedComponent)})` baseRef = null onNewItemCallStack = {} mounted = true front = true anchor = null listeners = {} options = {} state = { items: [], pageItems: [], hasNextPage: false, hasPrevPage: false } componentDidMount() { this.setupOptions(); this.setupRef(); this.goToNextPage(); } componentWillUnmount() { this.mounted = false; this.unbindListeners(); } setupOptions = () => { this.options = { ...options }; if (typeof this.options.path === 'function') this.options.path = this.options.path(this.props); if (typeof this.options.orderBy === 'function') this.options.orderBy = this.options.orderBy(this.props); if (!this.options.orderBy) this.options.orderBy = '.value'; if (!this.options.length) this.options.length = 10; if (this.options.onNewItem) this.options.onNewItem = this.options.onNewItem(this.props); if (this.options.onNewPage) this.options.onNewPage = this.options.onNewPage(this.props); } setupRef = () => { switch (this.options.orderBy) { case '.value': this.baseRef = ref.child(this.options.path).orderByValue(); break; case '.priority': this.baseRef = ref.child(this.options.path).orderByPriority(); break; default: this.baseRef = ref.child(this.options.path).orderByChild(this.options.orderBy); break; } } getAnchorValue = (idx) => { const anchorItem = this.state.items[idx]; switch (this.options.orderBy) { case '.value': return anchorItem.value; case '.priority': return anchorItem.priority; default: return anchorItem.value[this.options.orderBy]; } } preBindListeners = () => { const items = this.state.items; if (!items.length) { this.anchor = null; return; } this.anchor = ( this.front ? this.getAnchorValue(items.length - 1) : items.length > this.options.length + 1 ? this.getAnchorValue(1) : this.getAnchorValue(0) ); } bindListeners = () => { this.setState({ isLoading: true }); const curRef = ( this.front ? this.anchor !== null ? this.baseRef.endAt(this.anchor).limitToLast(this.options.length + 1) : this.baseRef.limitToLast(this.options.length + 1) : this.baseRef.startAt(this.anchor).limitToFirst(this.options.length + 2) ); const curListener = curRef.on('value', (snap) => { if (!this.mounted) return; let newState = { items: getItems(snap, this.options.onNewItem, this.onNewItemCallStack), isLoading: false }; if (this.front) { newState.hasNextPage = newState.items.length > this.options.length; newState.pageItems = newState.items.slice(0, this.options.length); } else { newState.hasPrevPage = newState.items.length > this.options.length + 1; newState.pageItems = newState.items.slice(-1 + (this.options.length * -1), -1); } this.options.onNewPage && this.options.onNewPage(newState.pageItems); this.setState(newState); }); this.listeners.current = { ref: curRef, listener: curListener }; if (this.anchor !== null) { const tailRef = ( this.front ? this.baseRef.startAt(this.anchor).limitToFirst(2) : this.baseRef.endAt(this.anchor).limitToLast(2) ); const tailListener = tailRef.on('value', (snap) => { if (!this.mounted) return; let newState = {}; if (this.front) { newState.hasPrevPage = snap.numChildren() === 2; } else { newState.hasNextPage = snap.numChildren() === 2; } this.setState(newState); }); this.listeners.tail = { ref: tailRef, listener: tailListener }; } } unbindListeners = () => { Object.keys(this.listeners).forEach((key) => { if (this.listeners[key]) { this.listeners[key].ref.off('value', this.listeners[key].listener); this.listeners[key] = null; } }); } goToNextPage = () => { this.front = true; this.unbindListeners(); this.preBindListeners(); this.bindListeners(); } goToPrevPage = () => { this.front = false; this.unbindListeners(); this.preBindListeners(); this.bindListeners(); } render() { return ( <WrappedComponent {...this.props} pageItems={this.state.pageItems} isLoading={this.state.isLoading} hasNextPage={this.state.hasNextPage} hasPrevPage={this.state.hasPrevPage} onNextPage={this.goToNextPage} onPrevPage={this.goToPrevPage} /> ); } }; }; }; } export default withFirebasePages;
test/integration/Table/MultiSelectTable.js
mmrtnz/material-ui
import React from 'react'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'src/Table'; const tableData = [ { name: 'John Smith', selected: true, }, { name: 'Randal White', selected: true, }, { name: 'Olivier', }, ]; function TableMutliSelect() { return ( <Table selectable={true} multiSelectable={true} > <TableHeader displaySelectAll={true} adjustForCheckbox={true} enableSelectAll={true} > <TableRow> <TableHeaderColumn> Name </TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={true}> {tableData.map( (row, index) => ( <TableRow key={index} selected={row.selected}> <TableRowColumn> {row.name} </TableRowColumn> </TableRow> ))} </TableBody> </Table> ); } export default TableMutliSelect;
client/src/components/AlbumsGrid.js
HoussamOtarid/fb-photos-downloader
import React from 'react'; import _ from 'lodash'; import Album from './Album'; import Pagination from '../components/Pagination'; import Spinner from 'react-spinner-material'; export default props => { const { albums, paging } = props; if (_.isEmpty(albums)) { return ( <div className="spinner-container"> <Spinner size={80} spinnerColor={'#868e96'} spinnerWidth={2} visible={true} /> </div> ); } return ( <div className="container"> <Pagination paging={paging} onPaginationClick={props.onPaginationClick} /> <div className="row albums"> {_.map(albums, album => <Album album={album} key={album.id} onDownloadClick={props.onDownloadClick} />)} </div> </div> ); };
examples/with-jsxstyle/src/server.js
jaredpalmer/react-production-starter
import { cache } from 'jsxstyle'; import App from './App'; import React from 'react'; import { StaticRouter } from 'react-router-dom'; import express from 'express'; import { renderToString } from 'react-dom/server'; const assets = require(process.env.RAZZLE_ASSETS_MANIFEST); const server = express(); server .disable('x-powered-by') .use(express.static(process.env.RAZZLE_PUBLIC_DIR)) .get('/*', (req, res) => { cache.reset(); let styles = ''; cache.injectOptions({ onInsertRule(css) { styles += css; }, }); const context = {}; const markup = renderToString( <StaticRouter context={context} location={req.url}> <App /> </StaticRouter> ); if (context.url) { res.redirect(context.url); } else { res.send( `<!doctype html> <html lang=""> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charSet='utf-8' /> <title>Welcome to Razzle</title> <meta name="viewport" content="width=device-width, initial-scale=1"> ${ assets.client.css ? `<link rel="stylesheet" href="${assets.client.css}">` : '' } ${styles ? `<style type="text/css">${styles}</style>` : ''} ${ process.env.NODE_ENV === 'production' ? `<script src="${assets.client.js}" defer></script>` : `<script src="${assets.client.js}" defer crossorigin></script>` } </head> <body> <div id="root">${markup}</div> </body> </html>` ); } }); export default server;
test/test_helper.js
Ridou/ReactTutorials
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/svg-icons/device/battery-charging-60.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryCharging60 = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h3.87L13 7v4h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9l1.87-3.5H7v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11h-4v1.5z"/> </SvgIcon> ); DeviceBatteryCharging60 = pure(DeviceBatteryCharging60); DeviceBatteryCharging60.displayName = 'DeviceBatteryCharging60'; DeviceBatteryCharging60.muiName = 'SvgIcon'; export default DeviceBatteryCharging60;
modules/RouteUtils.js
joeyates/react-router
import React from 'react' import warning from 'warning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (const propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { const error = propTypes[propName](props, propName, componentName) if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { const type = element.type const route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { const childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { const routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { const route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (!Array.isArray(routes)) { routes = [ routes ] } return routes }
app/containers/NotFoundPage/index.js
tzibur/site
/** * NotFoundPage * * This is the page we show when the user visits a url that doesn't have a route * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a neccessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; /* eslint-disable react/prefer-stateless-function */ export default class NotFound extends React.Component { render() { return ( <h1>Page Not Found</h1> ); } }
test/test_helper.js
PhyrionX/ReactJS2
import _$ from 'jquery'; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import jsdom from 'jsdom'; import chai, { expect } from 'chai'; import chaiJquery from 'chai-jquery'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import reducers from '../src/reducers'; global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = global.window.navigator; const $ = _$(window); chaiJquery(chai, chai.util, $); function renderComponent(ComponentClass, props = {}, state = {}) { const componentInstance = TestUtils.renderIntoDocument( <Provider store={createStore(reducers, state)}> <ComponentClass {...props} /> </Provider> ); return $(ReactDOM.findDOMNode(componentInstance)); } $.fn.simulate = function(eventName, value) { if (value) { this.val(value); } TestUtils.Simulate[eventName](this[0]); }; export {renderComponent, expect};
src/components/App/routes.js
Cloudoki/hackforgood-paar
import React from 'react' import { Route, Switch } from 'react-router' import requireAuth from 'containers/Auth' import Login from 'containers/Auth/Login' import HomePage from 'containers/HomePage' import Filter from 'containers/Filter' import Protected from 'components/Protected' import NotFound from '../NotFound' export default () => ( <Switch> <Route path='/' exact component={HomePage} /> <Route path='/login' component={Login} /> <Route path='/filter' component={Filter} /> <Route path='/protected' component={requireAuth(Protected, 'user')} /> <Route component={NotFound} /> </Switch> )
src/skeletons/SkeletonGroup.js
Bandwidth/shared-components
import React from 'react'; import PulseGroup from 'skeletons/PulseGroup'; import createArray from 'extensions/createArray'; const SkeletonGroup = ({ count = 1, children, ...rest }) => ( <React.Fragment> {createArray(count).map(rowIdx => ( <PulseGroup {...rest} key={rowIdx}> {children} </PulseGroup> ))} </React.Fragment> ); /** * @component */ export default SkeletonGroup;
examples/todomvc/src/Root/modules/Todo/UI.js
homkai/deef
import React from 'react'; import Header from './components/Header'; import Main from './components/Main'; import './style.less'; export default () => <div className="todo-app"> <Header /> <Main /> </div>;
src/parser/mage/arcane/modules/features/RuleOfThrees.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import { formatPercentage } from 'common/format'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import Analyzer from 'parser/core/Analyzer'; const debug = false; class RuleOfThrees extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, }; barrageWithRuleOfThrees = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.RULE_OF_THREES_TALENT.id); } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.ARCANE_BARRAGE.id) { return; } if (this.selectedCombatant.hasBuff(SPELLS.RULE_OF_THREES_BUFF.id,event.timestamp + 1)) { debug && this.log("Arcane Barrage with Rule of Threes Buff"); this.barrageWithRuleOfThrees += 1; } } get utilization() { return 1 - (this.barrageWithRuleOfThrees / this.abilityTracker.getAbility(SPELLS.ARCANE_BARRAGE.id).casts); } get suggestionThresholds() { return { actual: this.utilization, isLessThan: { minor: 0.95, average: 0.90, major: 0.80, }, style: 'percentage', }; } suggestions(when) { when(this.suggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You cast <SpellLink id={SPELLS.ARCANE_BARRAGE.id} /> {this.barrageWithRuleOfThrees} times while you had the <SpellLink id={SPELLS.RULE_OF_THREES_BUFF.id} /> buff. This buff makes your next <SpellLink id={SPELLS.ARCANE_BLAST.id} /> or <SpellLink id={SPELLS.ARCANE_MISSILES.id} /> free after you gain your third Arcane Charge, so you should ensure that you use the buff before clearing your charges.</>) .icon(SPELLS.RULE_OF_THREES_TALENT.icon) .actual(`${formatPercentage(this.utilization)}% Utilization`) .recommended(`${formatPercentage(recommended)}% is recommended`); }); } } export default RuleOfThrees;
src/interface/report/Results/Timeline/Cooldowns.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Abilities from 'parser/core/modules/Abilities'; import './Cooldowns.scss'; import Lane from './Lane'; class Cooldowns extends React.PureComponent { static propTypes = { start: PropTypes.number.isRequired, end: PropTypes.number.isRequired, secondWidth: PropTypes.number.isRequired, eventsBySpellId: PropTypes.instanceOf(Map).isRequired, abilities: PropTypes.instanceOf(Abilities).isRequired, }; getSortIndex([spellId, events]) { const ability = this.props.abilities.getAbility(spellId); if (!ability || ability.timelineSortIndex === undefined) { return 1000 - events.length; } else { return ability.timelineSortIndex; } } renderLanes(eventsBySpellId, growUp) { return Array.from(eventsBySpellId) .sort((a, b) => this.getSortIndex(growUp ? b : a) - this.getSortIndex(growUp ? a : b)) .map(item => this.renderLane(item)); } renderLane([spellId, events]) { return ( <Lane key={spellId} spellId={spellId} fightStartTimestamp={this.props.start} fightEndTimestamp={this.props.end} secondWidth={this.props.secondWidth} > {events} </Lane> ); } render() { const { eventsBySpellId } = this.props; return ( <div className="cooldowns"> {this.renderLanes(eventsBySpellId, false)} </div> ); } } export default Cooldowns;
__tests__/index.ios.js
neyko5/BalistosNative
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
wp-content/plugins/download-monitor/assets/blocks/src/components/DownloadInput/index.js
mandino/www.bloggingshakespeare.com
const {Component} = wp.element; import apiFetch from '@wordpress/api-fetch'; import React from 'react'; import Select from 'react-select'; export default class DownloadInput extends Component { constructor( props ) { super( props ); this.state = { downloads: [] }; } componentDidMount() { apiFetch( { url: dlmBlocks.ajax_getDownloads } ).then( results => { this.setState({downloads: results }); } ); } render() { const valueFromId = (opts, id) => opts.find(o => o.value === id); return ( <div> <Select value={valueFromId( this.state.downloads, this.props.selectedDownloadId )} onChange={(selectedOption) => this.props.onChange(selectedOption.value)} options={this.state.downloads} isSearchable="true" /> </div> ); } }
share/components/LogIn/LogIn.js
caojs/password-manager-server
import React from 'react'; import classNames from 'classnames'; import { Field } from 'redux-form/immutable'; import { Link } from 'react-router'; import FaUser from 'react-icons/lib/fa/user'; import FaLock from 'react-icons/lib/fa/lock'; import Button from '../Common/Button'; import ErrorMessages from '../Common/ErrorMessages'; import { injectProps } from '../../helpers/decorators'; import style from './LogIn.css'; function Form({ hasErrors, handleSubmit }) { return ( <form onSubmit={handleSubmit}> <div className={style.fieldArea}> <label className={style.label}> <FaUser className="icon"/> <Field className="input" name="username" component="input" placeholder="Username"/> </label> <label className={style.label}> <FaLock className="icon"/> <Field className="input" name="password" component="input" type="password" placeholder="Password"/> </label> </div> <Button className={classNames({ error: hasErrors })} type="submit"> Sign In </Button> </form> ); } export default class LogIn extends React.Component { @injectProps render({ errors, handleSubmit }) { const hasErrors = !!(errors && errors.size); let errorMessages = hasErrors ? <ErrorMessages errors={errors}/> : null; return ( <div className={style.main}> {errorMessages} <Form hasErrors={hasErrors} handleSubmit={handleSubmit}/> <div className={style.links}> <Link className="link" to="/signup">Sign up</Link> </div> </div> ); } }
fields/types/select/SelectField.js
andrewlinfoot/keystone
import Field from '../Field'; import React from 'react'; import Select from 'react-select'; import { FormInput } from '../../../admin/client/App/elemental'; /** * TODO: * - Custom path support */ module.exports = Field.create({ displayName: 'SelectField', statics: { type: 'Select', }, valueChanged (newValue) { // TODO: This should be natively handled by the Select component if (this.props.numeric && typeof newValue === 'string') { newValue = newValue ? Number(newValue) : undefined; } this.props.onChange({ path: this.props.path, value: newValue, }); }, renderValue () { const { ops, value } = this.props; const selected = ops.find(opt => opt.value === value); return ( <FormInput noedit> {selected ? selected.label : null} </FormInput> ); }, renderField () { const { numeric, ops, path, value: val } = this.props; // TODO: This should be natively handled by the Select component const options = (numeric) ? ops.map(function (i) { return { label: i.label, value: String(i.value) }; }) : ops; const value = (typeof val === 'number') ? String(val) : val; return ( <div> {/* This input element fools Safari's autocorrect in certain situations that completely break react-select */} <input type="text" style={{ position: 'absolute', width: 1, height: 1, zIndex: -1, opacity: 0 }} tabIndex="-1"/> <Select simpleValue name={this.getInputName(path)} value={value} options={options} onChange={this.valueChanged} /> </div> ); }, });
app/components/NowPlaying.js
robcalcroft/edison
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import { Button, Image, Modal, StyleSheet, TouchableHighlight, View, } from 'react-native'; import Slider from 'react-native-slider'; import Text from './Text'; import TouchableIcon from './TouchableIcon'; const styles = StyleSheet.create({ nowPlayingBar: { backgroundColor: 'lightgray', justifyContent: 'space-between', flexDirection: 'row', paddingLeft: 10, paddingRight: 10, borderTopColor: 'grey', borderTopWidth: 1, }, nowPlayingBar__inner: { flexDirection: 'row', alignItems: 'center', }, nowPlayingBar__inner__title: { paddingLeft: 10, fontSize: 18, }, nowPlayingBar__inner__image: { height: 40, width: 40, }, nowPlayingModal: { marginTop: 20, alignItems: 'center', justifyContent: 'space-around', flex: 1, }, nowPlayingImage: { flex: 0.85, width: '100%', }, nowPlayingSliderContainer: { width: '100%', paddingLeft: 15, paddingRight: 15, }, nowPlayingSliderInfo: { flexDirection: 'row', justifyContent: 'space-between', }, nowPlayingActions: { width: '100%', justifyContent: 'space-around', flexDirection: 'row', }, nowPlayingInfo: { fontSize: 22, }, }); // TODO convert to normal class to allow no updating of the value of the slider until the // onSlidingComplete has been called class NowPlaying extends Component { showNativePlayer() { this.props.setNowPlayingState({ modalVisible: false }, () => { this.props.performPlayerAction('presentFullscreenPlayer'); }); } render() { const { modalVisible, showModal, hideModal, activePathOrUri, paused, muted, title, author, artwork, setNowPlayingState, seekableDuration, currentTime, performPlayerAction, } = this.props; const formattedCurrentTime = moment(moment.duration(currentTime, 's').asMilliseconds()).format('HH:mm:ss'); const formattedSeekableDuration = moment(moment.duration(seekableDuration - currentTime, 's').asMilliseconds()).format('HH:mm:ss'); return [ activePathOrUri ? ( <TouchableHighlight key={1} onPress={showModal}> <View style={[styles.nowPlayingBar, { height: modalVisible ? 0 : 60 }]}> <View style={styles.nowPlayingBar__inner}> <Image source={{ uri: artwork }} style={styles.nowPlayingBar__inner__image} /> <Text style={styles.nowPlayingBar__inner__title}>{title}</Text> </View> <View style={styles.nowPlayingBar__inner}> <Button onPress={() => setNowPlayingState({ paused: !paused })} title={paused ? 'Play' : 'Pause'} /> </View> </View> </TouchableHighlight> ) : null, <Modal animationType="slide" onRequestClose={hideModal} visible={modalVisible} key={2} > <View style={styles.nowPlayingModal}> <Image resizeMode="contain" source={{ uri: artwork }} style={styles.nowPlayingImage} /> <Text style={styles.nowPlayingInfo}>{title} by {author}</Text> <View style={styles.nowPlayingSliderContainer}> <Slider value={currentTime} maximumValue={seekableDuration} onSlidingComplete={value => performPlayerAction('seek', value)} style={styles.nowPlayingSlider} /> <View style={styles.nowPlayingSliderInfo}> <Text>{formattedCurrentTime}</Text> <Text>-{formattedSeekableDuration}</Text> </View> </View> {/* We are not using this as you can use the phone's volume control */} {/* <Slider onValueChange={value => setNowPlayingState({ volume: value })} /> */} <View style={styles.nowPlayingActions}> <TouchableIcon name={muted ? 'ios-volume-off' : 'ios-volume-up'} onPress={() => setNowPlayingState({ muted: !muted })} /> <TouchableIcon name="ios-skip-backward" onPress={() => performPlayerAction('seek', 0)} /> <TouchableIcon name={`ios-${paused ? 'play' : 'pause'}`} onPress={() => setNowPlayingState({ paused: !paused })} /> <TouchableIcon name="ios-contract" onPress={hideModal} /> <TouchableIcon name="ios-expand" onPress={() => this.showNativePlayer()} /> </View> </View> </Modal>, ]; } } NowPlaying.propTypes = { modalVisible: PropTypes.bool.isRequired, paused: PropTypes.bool.isRequired, muted: PropTypes.bool.isRequired, title: PropTypes.string.isRequired, author: PropTypes.string.isRequired, artwork: PropTypes.string.isRequired, showModal: PropTypes.func.isRequired, hideModal: PropTypes.func.isRequired, activePathOrUri: PropTypes.string.isRequired, seekableDuration: PropTypes.number.isRequired, currentTime: PropTypes.number.isRequired, setNowPlayingState: PropTypes.func.isRequired, performPlayerAction: PropTypes.func.isRequired, }; export default NowPlaying;
src/home/root.component.js
joeldenning/single-spa-examples
import React from 'react'; import Technology from './technology.component.js'; import Walkthroughs from './walkthroughs.component.js'; import {getBorder, showFrameworkObservable} from 'src/common/colored-border.js'; export default class HomeRoot extends React.Component { constructor() { super(); this.state = { frameworkInspector: false, }; } componentWillMount() { this.subscription = showFrameworkObservable.subscribe(newValue => this.setState({frameworkInspector: newValue})); } render() { return ( <div style={this.state.frameworkInspector ? {border: getBorder('react')} : {}}> {this.state.frameworkInspector && <div>(built with React)</div> } <div className="container"> <div className="row"> <h4 className="light"> Introduction </h4> <p className="caption"> Single-spa is a javascript libary that allows for many small applications to coexist in one single page application. This website is a demo application that shows off what single-spa can do. For more information about single-spa, go to the <a href="https://github.com/CanopyTax/single-spa" target="_blank">single-spa Github page</a>. Additionally, this website's code can be found at the <a href="https://github.com/CanopyTax/single-spa-examples" target="_blank">single-spa-examples Github</a>. While you're here, check out the following features: </p> <Walkthroughs /> </div> <div className="row"> <h4 className="light"> Framework examples </h4> <p className="caption"> Single-spa allows for multiple frameworks to coexist in the same single page application. </p> <div className="row"> <Technology imgSrc="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyMyAyMC40NjM0OCI+PHRpdGxlPmxvZ288L3RpdGxlPjxwYXRoIGQ9Ik0xOC45MTA3LDYuNjMyNTdoMHEtLjM2NzIxLS4xMjYtLjc0MDQyLS4yMzMzLjA2MTg3LS4yNTE0MS4xMTQ0MS0uNTA1Yy41NjA0NS0yLjcyMDY0LjE5NC00LjkxMjM3LTEuMDU3MzktNS42MzM4Ni0xLjE5OTgtLjY5Mi0zLjE2MjEuMDI5NTItNS4xNDM5NCwxLjc1NDE0cS0uMjkyOTMuMjU1NS0uNTcyNjcuNTI1NTQtLjE4NzI3LS4xNzk1MS0uMzgxMS0uMzUyQzkuMDUyNTcuMzQzOSw2Ljk3MDY2LS40MzMxNiw1LjcyMDU4LjI5MDQ2LDQuNTIxOTEuOTg0MzYsNC4xNjY4NiwzLjA0NDg5LDQuNjcxNDQsNS42MjMyMnEuMDc1My4zODMuMTcuNzYxNzljLS4yOTQ1OC4wODM2Ny0uNTc5MDguMTcyODQtLjg1MTI3LjI2NzcxQzEuNTU1MTQsNy41MDE2NSwwLDguODMyMjUsMCwxMC4yMTIzMWMwLDEuNDI1NDYsMS42NjkzNSwyLjg1NTIsNC4yMDU3NSwzLjcyMnEuMzA4NS4xMDQ5NC42MjE5My4xOTQ0Mi0uMTAxNzkuNDA4LS4xODA2OC44MjExNGMtLjQ4MTA2LDIuNTMzNTQtLjEwNTM1LDQuNTQ1MjEsMS4wOTAxNyw1LjIzNDg0LDEuMjM0ODEuNzEyLDMuMzA3MjUtLjAxOTg1LDUuMzI1MzMtMS43ODM4N3EuMjM5MjYtLjIwOTE3LjQ3OTk0LS40NDIzOC4zMDI5LjI5MjI1LjYyMTczLjU2NzI3YzEuOTU0NzcsMS42ODIwNywzLjg4NTMxLDIuMzYxMzIsNS4wNzk4MiwxLjY2OTg2LDEuMjMzNjktLjcxNDE2LDEuNjM0NTQtMi44NzUyNSwxLjExNC01LjUwNDU5cS0uMDU5NTUtLjMwMTI0LS4xMzc5Mi0uNjE0ODEuMjE4MzQtLjA2NDQzLjQyNzcyLS4xMzM1NUMyMS4yODQ1NCwxMy4wNjkxNSwyMywxMS42NTY4MSwyMywxMC4yMTIzMiwyMyw4LjgyNzI2LDIxLjM5NDc4LDcuNDg3NzEsMTguOTEwNyw2LjYzMjU3Wk0xMi43Mjg0LDIuNzU1ODFDMTQuNDI2NDYsMS4yNzgsMTYuMDEzNDYuNjk0NTcsMTYuNzM2NTcsMS4xMTE2aDBjLjc3MDE0LjQ0NDIxLDEuMDY5NzEsMi4yMzU0LjU4NTgsNC41ODQ0MXEtLjA0NzU4LjIyOTUzLS4xMDM0Mi40NTcyNGEyMy41Mzc1MiwyMy41Mzc1MiwwLDAsMC0zLjA3NTI3LS40ODU4NEEyMy4wODEyOCwyMy4wODEyOCwwLDAsMCwxMi4xOTk1LDMuMjQwOTRRMTIuNDU3ODgsMi45OTE4NCwxMi43Mjg0LDIuNzU1ODFaTTYuNzkxMTEsMTEuMzkxMjRxLjMxMi42MDI2NS42NTIwNywxLjE5MDEzLjM0NjkyLjU5OTExLjcyMjEsMS4xODExN2EyMC45MjE2OCwyMC45MjE2OCwwLDAsMS0yLjExOTY3LS4zNDA4QzYuMjQ4NjcsMTIuNzY2LDYuNDk4ODcsMTIuMDg0NDMsNi43OTExMSwxMS4zOTEyNFpNNi43OSw5LjA4MDQxYy0uMjg2MTMtLjY3ODYzLS41MzA5My0xLjM0NTg2LS43MzA4NS0xLjk5MDE5LjY1NjI0LS4xNDY4OCwxLjM1Ni0uMjY2ODksMi4wODUxNi0uMzU4cS0uMzY2MTEuNTcxLS43MDUxLDEuMTU4NzdRNy4xMDA3Niw4LjQ3OCw2Ljc5LDkuMDgwNDFabS41MjIyOCwxLjE1NTUycS40NTQxMS0uOTQ1MTcuOTc4My0xLjg1NDJ2LjAwMDJxLjUyMzY5LS45MDg1NywxLjExNTIxLTEuNzc1NDJjLjY4NC0uMDUxNzEsMS4zODUzNi0uMDc4NzksMi4wOTQzMi0uMDc4NzkuNzEyMTIsMCwxLjQxNDM3LjAyNzI4LDIuMDk4MTkuMDc5NHEuNTg1MTQuODY0ODcsMS4xMDgxOCwxLjc2OTQxLjUyNTY1LjkwNjM1Ljk5MTUzLDEuODQ1NDUtLjQ2MDgzLjk0ODE3LS45ODgyOCwxLjg2MTczaC0uMDAwMXEtLjUyMjYxLjkwNzg2LTEuMTAzNCwxLjc4MDNjLS42ODI0LjA0ODc2LTEuMzg3Ni4wNzM5LTIuMTA2MjMuMDczOS0uNzE1NjgsMC0xLjQxMTkzLS4wMjIyOS0yLjA4MjQxLS4wNjU3NXEtLjU5NTU1LS44Njk5NS0xLjEyNDA2LTEuNzgzMDVRNy43Njc4OSwxMS4xODE0OCw3LjMxMjI3LDEwLjIzNTkzWm04LjI0ODUzLDIuMzM4NjJxLjM0Ny0uNjAxODIuNjY3LTEuMjE4NjNoMGEyMC44NjY3MSwyMC44NjY3MSwwLDAsMSwuNzcyMzgsMi4wMjMyNywyMC44NTE2NCwyMC44NTE2NCwwLDAsMS0yLjE0NTUyLjM2NTczUTE1LjIxOTM1LDEzLjE2NjgyLDE1LjU2MDgsMTIuNTc0NTVabS42NTc2Ny0zLjQ5MzQzcS0uMzE4ODMtLjYwNS0uNjYxNjMtMS4xOTY4NGgwcS0uMzM3MjctLjU4MjU4LS42OTk0LTEuMTUwMjJjLjczMzkuMDkyNjMsMS40MzcuMjE1NzksMi4wOTcxNy4zNjY1NEEyMC45NTkwOSwyMC45NTkwOSwwLDAsMSwxNi4yMTg0Nyw5LjA4MTEyWk0xMS41MTEsMy45NDM1OWEyMS4wMTI4OCwyMS4wMTI4OCwwLDAsMSwxLjM1MzUsMS42MzM5M3EtMS4zNTg0My0uMDY0MTktMi43MTg0LS4wMDA2MUMxMC41OTMsNC45ODc2NSwxMS4wNTA3LDQuNDQwMjIsMTEuNTExLDMuOTQzNTlaTTYuMjEyODQsMS4xNDA4MWMuNzY5NTMtLjQ0NTQzLDIuNDcwOTUuMTg5NzMsNC4yNjQyOCwxLjc4Mi4xMTQ2MS4xMDE3OS4yMjk3NC4yMDgzNi4zNDUwNy4zMTg2QTIzLjU0NTQyLDIzLjU0NTQyLDAsMCwwLDguODYyOTQsNS42NjYwOGEyNC4wMDgsMjQuMDA4LDAsMCwwLTMuMDY5MTYuNDc3cS0uMDg4LS4zNTIyOC0uMTU4MDgtLjcwODY2di4wMDAxQzUuMjAzMzksMy4yMjUzNiw1LjQ5MDQ0LDEuNTU5LDYuMjEyODQsMS4xNDA4MVpNNS4wOTEzMiwxMy4xODIzM3EtLjI4Ni0uMDgxODctLjU2Nzc4LS4xNzc3M0E4LjMyMzcxLDguMzIzNzEsMCwwLDEsMS44NDEsMTEuNTc5NTVhMi4wMzA3MiwyLjAzMDcyLDAsMCwxLS44NTg0OS0xLjM2NzI0YzAtLjgzNzQyLDEuMjQ4NjUtMS45MDU3MSwzLjMzMTE3LTIuNjMxNzhxLjM5MjA4LS4xMzYxLjc5MTYyLS4yNDkwOGEyMy41NjQ1NSwyMy41NjQ1NSwwLDAsMCwxLjEyMSwyLjkwNDc4QTIzLjkyMjQ3LDIzLjkyMjQ3LDAsMCwwLDUuMDkxMzIsMTMuMTgyMzNaTTEwLjQxNTk0LDE3LjY2MWE4LjMyMTYxLDguMzIxNjEsMCwwLDEtMi41NzQ2NywxLjYxMTg0aC0uMDAwMWEyLjAzMDQyLDIuMDMwNDIsMCwwLDEtMS42MTMwNi4wNjA2N2MtLjcyNTU2LS40MTgzNi0xLjAyNzA2LTIuMDMzNzYtLjYxNTczLTQuMjAwMzVxLjA3MzM3LS4zODQwNy4xNjgtLjc2MzYzYTIzLjEwNDQ0LDIzLjEwNDQ0LDAsMCwwLDMuMDk5NS40NDg2OSwyMy45MDk1NCwyMy45MDk1NCwwLDAsMCwxLjk3NDMxLDIuNDM5MjlRMTAuNjQsMTcuNDY0NTksMTAuNDE1OTQsMTcuNjYxWm0xLjEyMjIzLTEuMTEwNTNjLS40NjU2OS0uNTAyNTMtLjkzMDE1LTEuMDU4MzEtMS4zODM4My0xLjY1NjEycS42NjA1MS4wMjYsMS4zNDU2Ni4wMjYwNi43MDMyNiwwLDEuMzg4NDEtLjAzMDg0QTIwLjg5NDI1LDIwLjg5NDI1LDAsMCwxLDExLjUzODE3LDE2LjU1MDQ1Wm01Ljk2NjUxLDEuMzY3YTIuMDMwMzksMi4wMzAzOSwwLDAsMS0uNzUzLDEuNDI3OGMtLjcyNDg1LjQxOTU4LTIuMjc1LS4xMjU4MS0zLjk0NjU5LTEuNTY0MzFxLS4yODc1LS4yNDczNS0uNTc4MzctLjUyNzI3YTIzLjA4OTE0LDIzLjA4OTE0LDAsMCwwLDEuOTI3OS0yLjQ0OCwyMi45MzY0NywyMi45MzY0NywwLDAsMCwzLjExNTA3LS40ODAxNHEuMDcwMjQuMjg0LjEyNDQ5LjU1NjM4aDBBOC4zMiw4LjMyLDAsMCwxLDE3LjUwNDY4LDE3LjkxNzQ5Wm0uODM0MTctNC45MDczOWgtLjAwMDFjLS4xMjU3MS4wNDE2My0uMjU0NzguMDgxODQtLjM4NjI5LjEyMDgyYTIzLjA2MTIxLDIzLjA2MTIxLDAsMCwwLTEuMTY0NjgtMi45MTM3MywyMy4wNTExMiwyMy4wNTExMiwwLDAsMCwxLjExOTM4LTIuODcxMjhjLjIzNTI0LjA2ODIuNDYzNjUuMTQuNjgzNzIuMjE1NzksMi4xMjg0Mi43MzI1OCwzLjQyNjY1LDEuODE1OTMsMy40MjY2NSwyLjY1MDYxQzIyLjAxNzUzLDExLjEwMTQ1LDIwLjYxNTM4LDEyLjI1NTc0LDE4LjMzODg1LDEzLjAxMDFaIiBmaWxsPSIjNjFkYWZiIi8+PHBhdGggZD0iTTExLjUsOC4xNTg1YTIuMDUzODYsMi4wNTM4NiwwLDEsMS0yLjA1MzgxLDIuMDUzODFBMi4wNTM4MSwyLjA1MzgxLDAsMCwxLDExLjUsOC4xNTg1IiBmaWxsPSIjNjFkYWZiIi8+PC9zdmc+" imgBackgroundColor="#222222" cardTitle="React" href="/react" explanation={`Yep we've got a React example. We actually just borrowed it from the react-router examples, to show how easy it is to migrate an existing app into single-spa`} /> <Technology imgSrc="https://angularjs.org/img/ng-logo.png" cardTitle="AngularJS" href="/angularjs" explanation={`AngularJS has some quirks, but works just fine when you use the single-spa-angularjs npm library to help you set up your app`} /> <Technology imgSrc="/images/angular.svg" imgBackgroundColor="#1976D2" cardTitle="Angular" href="/angular" explanation={`Angular is compatible with single-spa, check out a simple 'Hello World' in the example.`} /> <Technology imgSrc="https://vuejs.org/images/logo.png" cardTitle="Vue.js" href="/vue" explanation={`Vue.js is compatible with single-spa. Easily get started with the single-spa-vue plugin.`} /> <Technology imgSrc="/images/svelte.jpg" cardTitle="Svelte" href="/svelte" explanation={`Svelte is compatible with single-spa. Easily get started with the single-spa-svelte plugin.`} /> <Technology imgSrc="https://cycle.js.org/img/cyclejs_logo.svg" cardTitle="CycleJS" href="/cyclejs" explanation={`CycleJS is compatible with single-spa. Easily get started with the single-spa-cycle plugin.`} /> <Technology imgSrc="https://camo.githubusercontent.com/31415a8c001234dbf4875c2c5a44b646fb9338b4/68747470733a2f2f63646e2e7261776769742e636f6d2f646576656c6f7069742f62343431366435633932623734336462616563316536386263346332376364612f7261772f333233356463353038663765623833346562663438343138616561323132613035646631336462312f7072656163742d6c6f676f2d7472616e732e737667" cardTitle="Preact" href="/preact" explanation={`Preact is compatible with single-spa. Easily get started with the single-spa-preact plugin.`} /> <Technology imgSrc="http://xitrus.es/blog/imgs/vnll.jpg" cardTitle="Vanilla" href="/vanilla" explanation={` If you want to write single-spa applications in vanilla javascript, that's fine too. `} /> <Technology imgSrc="/images/inferno-logo.png" cardTitle="Inferno" href="/inferno" explanation={` Inferno is compatible with single-spa. Easily get started with the single-spa-inferno plugin. `} /> </div> </div> <div className="row"> <h4 className="light"> Build system examples </h4> <p className="caption"> Each application chooses it's own build system, which will fit into the root single-spa application at runtime. </p> <div className="row"> <Technology imgSrc="https://avatars0.githubusercontent.com/webpack?&s=256" cardTitle="Webpack" href="/react" explanation={`The React example is built with Webpack, and even uses require.ensure for extra lazy loading.`} /> <Technology imgSrc="https://avatars3.githubusercontent.com/u/3802108?v=3&s=200" cardTitle="SystemJS" href="/angularjs" explanation={`The navbar app, home app, and AngularJS app are all built with JSPM / SystemJS.`} /> <Technology imgSrc="http://4.bp.blogspot.com/-rI6g4ZgVqBA/Uv8fPnl9TLI/AAAAAAAAMZU/tbylo5ngisg/s1600/iFrame+Generator.jpg" cardTitle="Iframe" href="/vanilla" explanation={` Putting things in iframes is the wrong thing to do many times, but there are valid use cases for it. If you put a single-spa application into an iframe, you get a whole new DOM and global namespace for variables. But the cons include degraded performance and trickier inter-app communication. `} /> </div> </div> </div> </div> ); } componentWillUnmount() { this.subscription.dispose(); } }
src/js/components/privKey/PrivKeyBox.js
safexio/safexweb
import React from 'react'; var PrivKeyImport = require('./PrivKeyImport'); var PrivKeyTable = require('./PrivKeyTable'); var privKeyActions = require('actions/privKeyActions'); var PrivKeyBox = React.createClass({ _generateNewKeypair: function() { privKeyActions.addPrivKey(); }, render: function() { var button = <button onClick={this._generateNewKeypair} className="btn btn-warning btn-xs pull-right" type="input">Generate <span className="hidden-xs">New </span>Keypair</button>; return ( <div className="panel panel-default"> <div className="panel-heading"><span className="hidden-xs">Bitcoin </span>Private Keys {button}</div> <div className="panel-body"> <PrivKeyImport /> <PrivKeyTable /> </div> </div> ); } }); module.exports = PrivKeyBox;
src/stories/2017-12-15-cretan-sunsets.js
danpersa/remindmetolive-react
import React from 'react'; import PostImageResp from '../components/story/PostImageResp'; import TwoPostImageResp from '../components/story/TwoPostImageResp'; import StoryPage from '../components/story/StoryPage'; import StoryTextBlock from '../components/story/StoryTextBlock'; import StoryImages from '../components/story/StoryImages'; import StoryIntro from '../components/story/StoryIntro'; import FullImageResp from '../components/story/FullImageResp'; const imgDirPath = "stories/2017-12-15-cretan-sunsets"; class CretanSunsetsStory extends React.Component { constructor() { super(); } render() { return ( <StoryPage logoDirPath={imgDirPath} logoPrefix="wide" logoNumber="11" altLogo="Sunset in Crete" title="Cretan Sunsets" author="Dan" location="Crete, Greece" tags="travel, island, Greece"> <StoryIntro> We traveled to Crete this summer. The island is like a paradise, it has everything tourists like us want: great beaches, nice mountains, great towns. We were really impressed by the island, but one thing is for sure: <br/><br/> <blockquote>In Crete we&apos;ve seen the best sunsets of our lives!</blockquote> Let&apos;s try to recreate our trip and remember all of our favorite places here. </StoryIntro> <StoryTextBlock title="Chania"> <a href="https://en.wikipedia.org/wiki/Chania" trget="_blank">Chania</a> is a must visit place. It&apos;s the second largest city in Crete, it has a nice shopping area in the Old Town and a harbor with a Lighthouse. From the pier we were able to watch an amazing sunset. </StoryTextBlock> <StoryImages> <PostImageResp dirPath={imgDirPath} number="01" alt="Sunset, Lighthouse in Chania"/> <PostImageResp dirPath={imgDirPath} number="02" alt="Chania Port"/> <PostImageResp dirPath={imgDirPath} number="03" alt="Buildings in Chania"/> </StoryImages> <FullImageResp dirPath={imgDirPath} prefix="image" number="04" alt="Chania Pier and Lighthouse" /> <StoryImages> <TwoPostImageResp dirPath={imgDirPath} number1="05" alt1="Chania Horse Carrige" number2="06" alt2="Old Man in Crete" /> <TwoPostImageResp dirPath={imgDirPath} number1="07" alt1="Cretan Painter" number2="08" alt2="Cretan Painter" /> <PostImageResp dirPath={imgDirPath} number="09" alt="Watching the Chania sunset"/> </StoryImages> <StoryTextBlock title="Heraklion"> Heraklion is the largest city in Crete and the administrative capital of the island. The first thing we visited here was the Knossos Palace. Then we headed to the center of the city and had lunch at a nice restaurant near the Koules Fortress, near the seaside. We also liked the Saint Minas Cathedral and the Church of Saint Titus. </StoryTextBlock> <FullImageResp dirPath={imgDirPath} prefix="wide" number="05" alt="Knossos Palace" /> <StoryImages> <TwoPostImageResp dirPath={imgDirPath} number1="11" alt1="Knossos Palace" number2="12" alt2="Knossos Palace" /> <PostImageResp dirPath={imgDirPath} number="13" alt="Koules Fortress"/> <TwoPostImageResp dirPath={imgDirPath} number1="14" alt1="Saint Minas Cathedral, Heraklion" number2="15" alt2="Church of Saint Titus, Heraklion" /> </StoryImages> <StoryTextBlock title="Rethimno"> Rethimno is one of the smaller but really animated cities. There are lots of really nice sea food restaurants here. In the center there is a fortress. We witnessed an amazing sunset from the fortress. </StoryTextBlock> <FullImageResp dirPath={imgDirPath} prefix="wide" number="06" alt="Rethimno Lighthouse, Crete" /> <StoryTextBlock title="Agia Galini"> Agia Galini is another nice town. It has a nice harbor with lots of ships and a pier. It&apos;s been built on hill which gives an interesting view when photographed from the pier. </StoryTextBlock> <FullImageResp dirPath={imgDirPath} prefix="image" number="17" alt="Agia Galini, Crete" /> <StoryTextBlock title="Seitan Limania Beach"> It was really challenging to reach to the Seitan Limania Beach. You have to get down on a rocky way which looks really dangerous. We put some effort into getting there. But it&apos;s totally worth it. The water and sand are amazing and you can see goats doing jumps on the rocks around. </StoryTextBlock> <FullImageResp dirPath={imgDirPath} prefix="image" number="18" alt="Mountains in Crete" /> <StoryImages> <PostImageResp dirPath={imgDirPath} number="19" alt="The Road to Seitan Limania Beach"/> <PostImageResp dirPath={imgDirPath} number="20" alt="Seitan Limania Beach, Crete"/> <PostImageResp dirPath={imgDirPath} number="21" alt="Seitan Limania Beach, Crete"/> <PostImageResp dirPath={imgDirPath} number="22" alt="Cretan Goat"/> </StoryImages> <StoryTextBlock title="Matala Beach"> The Matala Beach is really accessible, there is a big parking lot right next to it. I did some snorkeling here and I&apos;ve seen lots of colorful fishes. The view with the yellow rocks is amazing. </StoryTextBlock> <FullImageResp dirPath={imgDirPath} prefix="image" number="23" alt="Matala Beach, Crete" /> <StoryTextBlock title="Praveli Beach"> Praveli Beach is special because it has lots of palm trees, directly on the beach. So you can enjoy the shade during the really hot summer days. </StoryTextBlock> <StoryImages> <PostImageResp dirPath={imgDirPath} number="24" alt="Preveli Beach, Crete"/> </StoryImages> <StoryTextBlock title="Balos Beach"> The Balos beach is one of the most amazing places I&apos;ve seen! The lagoon has white sand and turquoise water. The contrast is amazing! <br/><br/> Getting to the beach was not easy, we had to go on a rocky way. Another way of getting there is by boat. I still recommend the rocky path, as from the hills there, you get the best view of the lagoon. </StoryTextBlock> <StoryImages> <PostImageResp dirPath={imgDirPath} number="25" alt="Rocky Landscape, Crete" /> </StoryImages> <FullImageResp dirPath={imgDirPath} prefix="image" number="26" alt="Balos Beach, Crete" /> <StoryImages> <PostImageResp dirPath={imgDirPath} number="27" alt="Balos Beach, Crete" /> </StoryImages> <StoryTextBlock title="Other Beaches"> Crete has lots of other beaches: small ones, cute one, rocky ones, also private ones. </StoryTextBlock> <StoryImages> <PostImageResp dirPath={imgDirPath} number="28" alt="Cretan Beach" /> <PostImageResp dirPath={imgDirPath} number="29" alt="Royal Blue Resort Beach, Crete" /> <PostImageResp dirPath={imgDirPath} number="30" alt="Cretan Beach" /> <PostImageResp dirPath={imgDirPath} number="31" alt="Rocky Cretan Beach" /> <PostImageResp dirPath={imgDirPath} number="32" alt="Cretan Beach and Mountains" /> </StoryImages> <StoryTextBlock title="The Mountains"> Crete is not only about beaches, and urban landscapes: it has amazing hills and mountains as well. The combination and richness of colors is just breathtaking. <br/><br/> <blockquote> Seeing both mountains and sea in the same place makes me think about how paradise can look like! </blockquote> </StoryTextBlock> <FullImageResp dirPath={imgDirPath} prefix="image" number="33" alt="Crete Sea and Mountains" /> <StoryImages> <PostImageResp dirPath={imgDirPath} number="34" alt="Mountains in Crete" /> <PostImageResp dirPath={imgDirPath} number="35" alt="Cretan Mountains" /> <PostImageResp dirPath={imgDirPath} number="36" alt="Sunset in Cretan Mountains" /> </StoryImages> <StoryTextBlock title="The Sunsets"> I kept the best for the end. The sunsets! Every evening we watched one and every time it got better! Enjoy! </StoryTextBlock> <FullImageResp dirPath={imgDirPath} prefix="image" number="37" alt="Sunset, Crete" /> <StoryImages> <PostImageResp dirPath={imgDirPath} number="38" alt="Cretan sunset" /> <PostImageResp dirPath={imgDirPath} number="39" alt="Fortezza Castle, Rethimno" /> <PostImageResp dirPath={imgDirPath} number="40" alt="Santa Maria delle Grazie, Milan" /> </StoryImages> </StoryPage>); } } export default CretanSunsetsStory;
imports/ui/pages/profile.js
irvinlim/free4all
import { Meteor } from 'meteor/meteor'; import React from 'react'; import ProfileComponent from '../containers/profile/profile'; export class Profile extends React.Component { render() { return ( <div id="page-profile" className="page-container profile" style={{ overflow: "hidden" }}> <div className="container"> <div className="flex-row nopad" style={{ padding: "0 0 5px" }}> <div className="col col-xs-12"> <ProfileComponent userId={ this.props.params.userId ? this.props.params.userId : Meteor.userId() } /> </div> </div> </div> </div> ); } }
src/components/user/auth/login/Login.js
huyhoangtb/reactjs
/** * Created by Peter Hoang Nguyen on 3/31/2017. */ import * as css from './stylesheet.scss'; import React from 'react' import {Field, reduxForm} from 'redux-form' import InputText from 'components/forms/elements/input-text'; import CheckBox from 'components/forms/elements/check-box'; import AuthPanel from 'components/user/auth/AuthPanel'; import RaisedButton from 'material-ui/RaisedButton'; import {injectI18N, t, t1, t2, t3, t4} from "utils/I18nUtils"; /** * Created by Peter Hoang Nguyen * Email: [email protected] * Tel: 0966298666 * created date 30/03/2017 **/ class LoginForm extends React.Component { constructor(props) { super(props); this.state = {} } render() { let {intl} =this.props; return ( <AuthPanel> <div className="ui-auth-panel"> <div className="ui-auth-header"> <a className="active"> { t1(intl, 'Login')} <span>/</span> </a> <a> <span>/</span> { t1(intl, 'Logout') } </a> </div> <InputText fullWidth={true} name="username" label={ t1(intl, 'Username')}/> <InputText fullWidth={true} name="password" label={ t1(intl, 'Password')}/> <div className="remember-me-panel"> <CheckBox labelStyle={{color: "#9d9d9d"}} iconStyle={{fill: "#9d9d9d"}} name="remember_me" label={ t1(intl, 'remember_me')}/> </div> <div className="ui-button-group clearfix center-block"> <div className="pull-left"> <RaisedButton label={t1(intl,"Đăng nhập")} className="button" primary={true} /> </div> <div className="pull-right"> <a className="forgot-password"> { t1(intl, 'Forgot password?') }</a> </div> <div className="login-by-another-tools"> HaHAaaaaaaaaa </div> </div> </div> </AuthPanel> ); } } export default reduxForm({ form: 'LoginForm', // a unique identifier for this form })(injectI18N(LoginForm))
public/products/src/components/UI.js
dolchi21/open-prices
import React from 'react' export function List(props){ return <div {...props} className="list-group"></div> } export function ListItem(props){ return <div {...props} className="list-group-item"></div> }
components/ui/dropdown/dropdown.js
bannik/hole
import React from 'react'; import ReactDOM from 'react-dom'; class Dropdown extends React.Component{ constructor(props){ super(props); let selectedItem = props.selectedItem ? props.selectedItem : null; this.state = { active: false, items: [], selectedItem: selectedItem, hcontent: {} }; } // Toggle functionality of the dropdown menu _handleDropToggle(){ if(this.state.active){ this.setState({ active: false }); }else { this.setState({ active: true }); } } // Handles sending the data of the selected menu item back to // parent component _handleClick(data){ if(this.props.onSelect){ this.props.onSelect(data); } } componentWillMount(){ let onClick; let self = this; for (var i = 0; i < this.props.items.length; i++) { // Setting onClick for each item of the menu if(self.props.items[i].exData){ onClick = self.onClick.bind(self, self.props.items[i].exData); }else{ onClick = self.onClick.bind(self, self.props.items[i].label); } // Checks if you have setted an image and a holder in your array // and sets them as header if(self.props.items[i].type === 'image' && !self.state.hcontent.image){ self.setState({ hcontent:{ image: self.props.items[i].src } }); }if(self.props.items[i].type === 'holder' && !self.state.hcontent.holder) { self.setState({ hcontent:{ holder: self.props.items[i].label } }); } // Here We take all the items of the if(self.props.items[i].type === 'item' && self.props.items[i].label != self.state.selectedItem){ self.state.items.push(<li onClick={onClick} key={i}>{self.props.items[i].label}</li>); } } } componentDidMount(){ if(!this.state.selectedItem && !this.state.hcontent.image && !this.state.hcontent.holder){ this.setState({ selectedItem: this.state.items[0].props.children }); } } render(){ let hcontent = {}; let items = []; let holder = []; let styles = this.props.styles ? this.props.styles : {}; let onClick; let menuClass = ['dropContent', this.props.className]; let arrowClass = this.state.active ? 'fa fa-angle-up' : 'fa fa-angle-down'; if(this.state.active){ menuClass.push('dropActive'); } menuClass = menuClass.join(' '); for (var i = 0; i < this.state.items.length; i++) { if(this.state.items[i].props.children != this.state.selectedItem){ items.push(this.state.items[i]); } } // Here we check if there was something in our array to add to header of // the menu if(!this.state.selectedItem){ if(!this.state.hcontent.holder && this.state.hcontent.image || this.props.hidden === "holder"){ let imageClass = 'fa ' + this.state.hcontent.image; holder = [ <span style={styles.title ? styles.title : {}}> <i className={imageClass}/> </span> ]; }else if(!this.state.hcontent.image && this.state.hcontent.holder || this.props.hidden === "image"){ holder = [ <span style={styles.title ? styles.title : {}}> {this.state.hcontent['holder']} </span> ]; }else if(this.state.hcontent.image && this.state.hcontent.holder && !this.props.hidden){ let imageClass = 'fa ' + hcontent.image; holder = [ <span> <i className={imageClass}/>{hcontent['holder']} </span> ]; } }else{ holder = [ <span> {this.state.selectedItem} </span> ]; } return( <div className="dropWrap"> {this.props.label ? ( <span className="dropLabel">{this.props.label}</span> ): null} <div onMouseEnter={this.onDropToggle} onMouseLeave={this.onDropToggle} className="dropdown"> <div className="dropHead"> {holder} <i className={arrowClass}></i> </div> <ul className={menuClass} style={styles.body ? styles.body : {}}> {items} </ul> </div> </div> ); } } module.exports = Dropdown;
web/src/js/components/Search/ErrorBoundarySearchResults.js
gladly-team/tab
import React from 'react' import logger from 'js/utils/logger' import { getUrlParameters } from 'js/utils/utils' import SearchResultErrorMessage from 'js/components/Search/SearchResultErrorMessage' class ErrorBoundary extends React.Component { constructor(props) { super(props) this.state = { hasError: false } } static getDerivedStateFromError(error) { return { hasError: true } } componentDidCatch(error, info) { logger.error(error) } render() { if (this.state.hasError) { const query = getUrlParameters().q || null return <SearchResultErrorMessage query={query} /> } return this.props.children } } ErrorBoundary.propTypes = {} ErrorBoundary.defaultProps = {} export default ErrorBoundary
Study/Udemy Docker and Kubernetes/Section09/deployment-09-finished/frontend/src/components/UI/Card.js
tarsoqueiroz/Docker
import React from 'react'; import './Card.css'; function Card(props) { return <div className='card'>{props.children}</div>; } export default Card;
docs/app/Examples/elements/Button/Types/ButtonExampleLabeled.js
mohammed88/Semantic-UI-React
import React from 'react' import { Button } from 'semantic-ui-react' const ButtonExampleLabeled = () => ( <div> <Button content='Like' icon='heart' label={{ as: 'a', basic: true, content: '2,048' }} labelPosition='right' /> <Button content='Like' icon='heart' label={{ as: 'a', basic: true, pointing: 'right', content: '2,048' }} labelPosition='left' /> <Button icon='fork' label={{ as: 'a', basic: true, content: '2,048' }} labelPosition='left' /> </div> ) export default ButtonExampleLabeled
source/CustomWindowScroller/WindowScroller.jest.js
Vitamen/geneviz
/* global Element */ import React from 'react' import { findDOMNode } from 'react-dom' import { render } from '../TestUtils' import { IS_SCROLLING_TIMEOUT } from './utils/onScroll' import WindowScroller from './WindowScroller' function ChildComponent ({ scrollTop, isScrolling, height }) { return ( <div>{`scrollTop:${scrollTop}, isScrolling:${isScrolling}, height:${height}`}</div> ) } function mockGetBoundingClientRectForHeader ({ documentOffset = 0, height }) { // Mock the WindowScroller element and window separately // The only way to mock the former (before its created) is globally Element.prototype.getBoundingClientRect = jest.fn(() => ({ top: height })) document.documentElement.getBoundingClientRect = jest.fn(() => ({ top: documentOffset })) } function getMarkup ({ headerElements, documentOffset, ...props } = {}) { const windowScroller = ( <WindowScroller {...props}> {({ height, isScrolling, scrollTop }) => ( <ChildComponent height={height} isScrolling={isScrolling} scrollTop={scrollTop} /> )} </WindowScroller> ) // JSDome doesn't implement a working getBoundingClientRect() // But WindowScroller requires it mockGetBoundingClientRectForHeader({ documentOffset, height: headerElements ? headerElements.props.style.height : 0 }) if (headerElements) { return ( <div> {headerElements} {windowScroller} </div> ) } else { return windowScroller } } function simulateWindowScroll ({ scrollY = 0 }) { document.body.style.height = '10000px' window.scrollY = scrollY document.dispatchEvent(new window.Event('scroll', { bubbles: true })) document.body.style.height = '' } function simulateWindowResize ({ height = 0 }) { window.innerHeight = height document.dispatchEvent(new window.Event('resize', { bubbles: true })) } describe('WindowScroller', () => { // Set default window height and scroll position between tests beforeEach(() => { window.scrollY = 0 window.innerHeight = 500 }) // Starts updating scrollTop only when the top position is reached it('should have correct top property to be defined on :_positionFromTop', () => { const component = render(getMarkup()) const rendered = findDOMNode(component) const top = rendered.getBoundingClientRect().top expect(component._positionFromTop).toEqual(top) }) // Test edge-case reported in bvaughn/react-virtualized/pull/346 it('should have correct top property to be defined on :_positionFromTop if documentElement is scrolled', () => { render.unmount() // Simulate scrolled documentElement const component = render(getMarkup({ documentOffset: -100 })) const rendered = findDOMNode(component) const top = rendered.getBoundingClientRect().top expect(component._positionFromTop).toEqual(top + 100) // Reset override delete document.documentElement.getBoundingClientRect }) it('inherits the window height and passes it to child component', () => { const component = render(getMarkup()) const rendered = findDOMNode(component) expect(component.state.height).toEqual(window.innerHeight) expect(component.state.height).toEqual(500) expect(rendered.textContent).toContain('height:500') }) it('should restore pointerEvents on body after IS_SCROLLING_TIMEOUT', async (done) => { render(getMarkup()) document.body.style.pointerEvents = 'all' simulateWindowScroll({ scrollY: 5000 }) expect(document.body.style.pointerEvents).toEqual('none') await new Promise(resolve => setTimeout(resolve, IS_SCROLLING_TIMEOUT)) expect(document.body.style.pointerEvents).toEqual('all') done() }) it('should restore pointerEvents on body after unmount', () => { render(getMarkup()) document.body.style.pointerEvents = 'all' simulateWindowScroll({ scrollY: 5000 }) expect(document.body.style.pointerEvents).toEqual('none') render.unmount() expect(document.body.style.pointerEvents).toEqual('all') }) describe('onScroll', () => { it('should trigger callback when window scrolls', async done => { const onScrollCalls = [] render(getMarkup({ onScroll: params => onScrollCalls.push(params) })) simulateWindowScroll({ scrollY: 5000 }) // Allow scrolling timeout to complete so that the component computes state await new Promise(resolve => setTimeout(resolve, 150)) expect(onScrollCalls.length).toEqual(1) expect(onScrollCalls[0]).toEqual({ scrollTop: 5000 }) done() }) it('should update :scrollTop when window is scrolled', async done => { const component = render(getMarkup()) const rendered = findDOMNode(component) // Initial load of the component should have 0 scrollTop expect(rendered.textContent).toContain('scrollTop:0') simulateWindowScroll({ scrollY: 5000 }) // Allow scrolling timeout to complete so that the component computes state await new Promise(resolve => setTimeout(resolve, 150)) const componentScrollTop = window.scrollY - component._positionFromTop expect(component.state.scrollTop).toEqual(componentScrollTop) expect(rendered.textContent).toContain(`scrollTop:${componentScrollTop}`) done() }) it('should specify :isScrolling when scrolling and reset after scrolling', async (done) => { const component = render(getMarkup()) const rendered = findDOMNode(component) simulateWindowScroll({ scrollY: 5000 }) expect(rendered.textContent).toContain('isScrolling:true') await new Promise(resolve => setTimeout(resolve, 250)) expect(rendered.textContent).toContain('isScrolling:false') done() }) }) describe('onResize', () => { it('should trigger callback when window resizes', () => { const onResizeCalls = [] render(getMarkup({ onResize: params => onResizeCalls.push(params) })) simulateWindowResize({ height: 1000 }) expect(onResizeCalls.length).toEqual(1) expect(onResizeCalls[0]).toEqual({ height: 1000 }) }) it('should update height when window resizes', () => { const component = render(getMarkup()) const rendered = findDOMNode(component) // Initial load of the component should have the same window height = 500 expect(component.state.height).toEqual(window.innerHeight) expect(component.state.height).toEqual(500) expect(rendered.textContent).toContain('height:500') simulateWindowResize({ height: 1000 }) expect(component.state.height).toEqual(window.innerHeight) expect(component.state.height).toEqual(1000) expect(rendered.textContent).toContain('height:1000') }) }) describe('updatePosition', () => { it('should calculate the initial offset from the top of the page when mounted', () => { let windowScroller render(getMarkup({ headerElements: <div style={{ height: 100 }}></div>, ref: (ref) => { windowScroller = ref } })) expect(windowScroller._positionFromTop).toBe(100) }) it('should recalculate the offset from the top when the window resizes', () => { let windowScroller render(getMarkup({ headerElements: <div id='header' style={{ height: 100 }}></div>, ref: (ref) => { windowScroller = ref } })) expect(windowScroller._positionFromTop).toBe(100) mockGetBoundingClientRectForHeader({ height: 200 }) expect(windowScroller._positionFromTop).toBe(100) simulateWindowResize({ height: 1000 }) expect(windowScroller._positionFromTop).toBe(200) }) it('should recalculate the offset from the top if called externally', () => { let windowScroller render(getMarkup({ headerElements: <div id='header' style={{ height: 100 }}></div>, ref: (ref) => { windowScroller = ref } })) expect(windowScroller._positionFromTop).toBe(100) mockGetBoundingClientRectForHeader({ height: 200 }) windowScroller.updatePosition() expect(windowScroller._positionFromTop).toBe(200) }) }) })
src/svg-icons/editor/short-text.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorShortText = (props) => ( <SvgIcon {...props}> <path d="M4 9h16v2H4zm0 4h10v2H4z"/> </SvgIcon> ); EditorShortText = pure(EditorShortText); EditorShortText.displayName = 'EditorShortText'; EditorShortText.muiName = 'SvgIcon'; export default EditorShortText;
src/redux/utils/createDevToolsWindow.js
mleonard87/merknera-ui
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import DevTools from '../../containers/DevToolsWindow'; export default function createDevToolsWindow (store) { const win = window.open( null, 'redux-devtools', // give it a name so it reuses the same window `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no` ); // reload in case it's reusing the same window with the old content win.location.reload(); // wait a little bit for it to reload, then render setTimeout(() => { // Wait for the reload to prevent: // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element." win.document.write('<div id="react-devtools-root"></div>'); win.document.body.style.margin = '0'; ReactDOM.render( <Provider store={store}> <DevTools /> </Provider> , win.document.getElementById('react-devtools-root') ); }, 10); }
app/client/modules/App/__tests__/Components/Footer.spec.js
nittmurugan/finddriver
import React from 'react'; import test from 'ava'; import { shallow } from 'enzyme'; import { Footer } from '../../components/Footer/Footer'; test('renders the footer properly', t => { const wrapper = shallow( <Footer /> ); t.is(wrapper.find('p').length, 2); t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.'); });
src/components/loading/LoadingHome/LoadingHome.js
CtrHellenicStudies/Commentary
import React from 'react'; const LoadingHome = () => ( <div className="loading home"> <div className="loading-mock home-filler home-filler-header" /> <div className="content primary"> <section className="header cover fullscreen parallax"> <div className="container v-align-transform wow fadeIn" data-wow-duration="1s" data-wow-delay="0.1s" > <div className="grid inner"> <div className="center-content"> <div className="site-title-wrap"> <div className="loading-mock home-filler home-filler-1" /> <div className="loading-mock home-filler home-filler-1" /> <div className="loading-mock home-filler home-filler-2" /> <div> <div className="loading-mock home-filler home-filler-3" /> <div className="loading-mock home-filler home-filler-3" /> </div> </div> </div> </div> </div> </section> </div> <div className="loading-mock home-filler home-filler-scroll-down" /> </div> ); export default LoadingHome;
es/components/MediaList/Row.js
welovekpop/uwave-web-welovekpop.club
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import _assertThisInitialized from "@babel/runtime/helpers/builtin/assertThisInitialized"; import _inheritsLoose from "@babel/runtime/helpers/builtin/inheritsLoose"; import cx from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { DragSource } from 'react-dnd'; import { getEmptyImage } from 'react-dnd-html5-backend'; import formatDuration from 'format-duration'; import { MEDIA } from '../../constants/DDItemTypes'; import MediaLoadingIndicator from './MediaLoadingIndicator'; import MediaThumbnail from './MediaThumbnail'; import Actions from './Actions'; var inSelection = function inSelection(selection, media) { return selection.some(function (item) { return item._id === media._id; }); }; var mediaSource = { beginDrag: function beginDrag(_ref) { var selection = _ref.selection, media = _ref.media; return { media: inSelection(selection, media) ? selection : [media] }; } }; var collect = function collect(connect) { return { connectDragSource: connect.dragSource(), connectDragPreview: connect.dragPreview() }; }; var enhance = DragSource(MEDIA, mediaSource, collect); var _ref2 = /*#__PURE__*/ _jsx(MediaLoadingIndicator, { className: "MediaListRow-loader" }); var Row = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(Row, _React$Component); function Row() { var _temp, _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return (_temp = _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this, _this.handleKeyPress = function (event) { if (event.code === 'Space') { _this.props.onClick(); } }, _this.handleDoubleClick = function () { _this.props.onOpenPreviewMediaDialog(_this.props.media); }, _temp) || _assertThisInitialized(_this); } var _proto = Row.prototype; _proto.componentDidMount = function componentDidMount() { this.props.connectDragPreview(getEmptyImage()); }; _proto.render = function render() { var _this$props = this.props, className = _this$props.className, media = _this$props.media, selection = _this$props.selection, selected = _this$props.selected, connectDragSource = _this$props.connectDragSource, makeActions = _this$props.makeActions, onClick = _this$props.onClick; var selectedClass = selected ? 'is-selected' : ''; var loadingClass = media.loading ? 'is-loading' : ''; var duration = 'start' in media // playlist item ? media.end - media.start // search result : media.duration; return connectDragSource( // Bit uneasy about this, but turning the entire row into a button seems // wrong as well! Since we nest media action <button>s inside it, too. // // eslint-disable-next-line jsx-a11y/no-static-element-interactions _jsx("div", { className: cx('MediaListRow', className, selectedClass, loadingClass), onDoubleClick: this.handleDoubleClick, onKeyPress: this.handleKeyPress, onClick: onClick }, void 0, media.loading ? _ref2 : _jsx(MediaThumbnail, { url: media.thumbnail }), _jsx("div", { className: "MediaListRow-artist", title: media.artist }, void 0, media.artist), _jsx("div", { className: "MediaListRow-title", title: media.title }, void 0, media.title), _jsx("div", { className: "MediaListRow-duration" }, void 0, formatDuration(duration * 1000)), _jsx(Actions, { className: cx('MediaListRow-actions', selectedClass), selection: selection, media: media, makeActions: makeActions }))); }; return Row; }(React.Component); Row.defaultProps = { selected: false }; Row.propTypes = process.env.NODE_ENV !== "production" ? { className: PropTypes.string, connectDragSource: PropTypes.func.isRequired, connectDragPreview: PropTypes.func.isRequired, media: PropTypes.object, selected: PropTypes.bool, selection: PropTypes.array, onOpenPreviewMediaDialog: PropTypes.func, onClick: PropTypes.func, makeActions: PropTypes.func } : {}; export default enhance(Row); //# sourceMappingURL=Row.js.map
fields/components/columns/IdColumn.js
suryagh/keystone
import React from 'react'; import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell'; import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue'; var IdColumn = React.createClass({ displayName: 'IdColumn', propTypes: { col: React.PropTypes.object, data: React.PropTypes.object, list: React.PropTypes.object, }, renderValue () { const value = this.props.data.id; if (!value) return null; return ( <ItemsTableValue padded interior title={value} href={Keystone.adminPath + '/' + this.props.list.path + '/' + value} field={this.props.col.type}> {value} </ItemsTableValue> ); }, render () { return ( <ItemsTableCell> {this.renderValue()} </ItemsTableCell> ); }, }); module.exports = IdColumn;
src/components/App.js
franciskim722/crypy
import React from 'react'; import PropTypes from 'prop-types'; import { Switch, NavLink, Route } from 'react-router-dom'; import LandingPage from '../containers/Landing/LandingPage'; import RegisterPage from '../containers/Auth/RegisterPage'; import HomePage from '../containers/Home/HomePage'; import LoginPage from '../containers/Login/LoginPage'; import PortfolioPage from '../containers/Portfolio/PortfolioPage'; import { MuiThemeProvider } from 'material-ui/styles'; const isLoggedIn = () => { if(!sessionStorage.jwt_token){ return browserHistory.push('/login'); } }; class App extends React.Component { render() { return ( <MuiThemeProvider> <div className={"crypy-app"}> <Switch> <Route exact path="/" component={LandingPage}/> <Route path="login" component={LoginPage}/> <Route path="register" component={RegisterPage}/> <Route path="home" component={HomePage} onEnter={isLoggedIn}/> <Route path="portfolio" component={PortfolioPage}/> </Switch> </div> </MuiThemeProvider> ); } } App.propTypes = { children: PropTypes.element }; export default App;
app/containers/Steps/Thanks/index.js
nypl-spacetime/where
/* global __CONFIG__ */ import React from 'react' import { connect } from 'react-redux' import { createSelector } from 'reselect' import Button from 'components/Button' import Flex from 'components/Flex' import { selectLoggedIn } from 'containers/App/selectors' import { TextStep, Animal, TimerBarContainer, TimerBar } from '../styles' const configAnimals = __CONFIG__.animals const animalsByUuid = {} configAnimals.forEach((animal) => { animalsByUuid[animal.uuid] = animal }) function requireAll (r) { return r.keys().map((filename) => { const uuid = filename.match(/\.\/(.*)\.small\.png$/)[1] return { src: r(filename), ...animalsByUuid[uuid] } }) } const animals = requireAll(require.context('images/public-domain-animals/', false, /\.small\.png$/)) export class Step extends React.Component { intitialTimeout = null timerBarTimeout = null constructor (props) { super(props) this.state = { timerStarted: false, duration: 4, animal: this.randomAnimal() } } randomAnimal () { const animal = animals[Math.floor(Math.random() * animals.length)] return { src: animal.src, name: animal.name } } render () { const timerBarStyle = { width: this.state.timerStarted ? '100%' : 0, transitionDuration: `${this.state.duration}s` } let oauthQuestion if (!this.props.loggedIn) { oauthQuestion = ( <p> To save your score, please log in with Google, Facebook, Twitter or GitHub. </p> ) } const thanks = `The ${this.state.animal.name} says thanks!` return ( <TextStep> <div> <h2>Thank you!</h2> <p> Your submission has been recorded. </p> {oauthQuestion} <Animal src={this.state.animal.src} alt={thanks} /> </div> <div> <TimerBarContainer> <TimerBar style={timerBarStyle} /> </TimerBarContainer> <Flex justifyContent='flex-end'> <Button type='submit' onClick={this.next.bind(this)}>Next image</Button> </Flex> </div> </TextStep> ) } componentDidMount () { this.intitialTimeout = setTimeout(() => { this.setState({ timerStarted: true }) // Initialize timer which proceeds to first step this.timerBarTimeout = setTimeout(this.next.bind(this), this.state.duration * 1000) }, 100) } next () { if (this.intitialTimeout) { clearTimeout(this.intitialTimeout) } if (this.timerBarTimeout) { clearTimeout(this.timerBarTimeout) } this.props.next() } } export default connect(createSelector( selectLoggedIn(), (loggedIn) => ({ loggedIn }) ))(Step)
js/components/list/basic-list.js
soltrinox/MarketAuth.ReactNative
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { actions } from 'react-native-navigation-redux-helpers'; import { Container, Header, Title, Content, Button, Icon, List, ListItem, Text } from 'native-base'; import styles from './styles'; const { replaceAt, } = actions; class NHBasicList extends Component { static propTypes = { replaceAt: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } replaceAt(route) { this.props.replaceAt('basicList', { key: route }, this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Button transparent onPress={() => this.replaceAt('list')}> <Icon name="ios-arrow-back" /> </Button> <Title>Basic List</Title> </Header> <Content> <List> <ListItem > <Text>Simon Mignolet</Text> </ListItem> <ListItem> <Text>Nathaniel Clyne</Text> </ListItem> <ListItem> <Text>Dejan Lovren</Text> </ListItem> <ListItem> <Text>Mama Sakho</Text> </ListItem> <ListItem> <Text>Alberto Moreno</Text> </ListItem> <ListItem> <Text>Emre Can</Text> </ListItem> <ListItem> <Text>Joe Allen</Text> </ListItem> <ListItem> <Text>Phil Coutinho</Text> </ListItem> </List> </Content> </Container> ); } } function bindAction(dispatch) { return { replaceAt: (routeKey, route, key) => dispatch(replaceAt(routeKey, route, key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, }); export default connect(mapStateToProps, bindAction)(NHBasicList);
local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js
Maxwell2022/react-native
'use strict'; import React, { Component } from 'react'; import { ActivityIndicator, Image, ListView, Platform, StyleSheet, View, } from 'react-native'; import ListItem from '../../components/ListItem'; import Backend from '../../lib/Backend'; export default class ChatListScreen extends Component { static navigationOptions = { title: 'Chats', header: { visible: Platform.OS === 'ios', }, tabBar: { icon: ({ tintColor }) => ( <Image // Using react-native-vector-icons works here too source={require('./chat-icon.png')} style={[styles.icon, {tintColor: tintColor}]} /> ), }, } constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { isLoading: true, dataSource: ds, }; } async componentDidMount() { const chatList = await Backend.fetchChatList(); this.setState((prevState) => ({ dataSource: prevState.dataSource.cloneWithRows(chatList), isLoading: false, })); } // Binding the function so it can be passed to ListView below // and 'this' works properly inside renderRow renderRow = (name) => { return ( <ListItem label={name} onPress={() => { // Start fetching in parallel with animating this.props.navigation.navigate('Chat', { name: name, }); }} /> ); } render() { if (this.state.isLoading) { return ( <View style={styles.loadingScreen}> <ActivityIndicator /> </View> ); } return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} style={styles.listView} /> ); } } const styles = StyleSheet.create({ loadingScreen: { backgroundColor: 'white', paddingTop: 8, flex: 1, }, listView: { backgroundColor: 'white', }, icon: { width: 30, height: 26, }, });
js/src/dapps/dappreg.js
jesuscript/parity
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React from 'react'; import ReactDOM from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); import Application from './dappreg/Application'; import '../../assets/fonts/Roboto/font.css'; import '../../assets/fonts/RobotoMono/font.css'; import './style.css'; ReactDOM.render( <Application />, document.querySelector('#container') );
react-app/src/components/Results.js
tanykim/swimmers-history
import React, { Component } from 'react'; import scrollToComponent from 'react-scroll-to-component'; import Countries from '../data/countries.json'; class ResultsComponent extends Component { scroll() { //scroll to the result when a swimmer is selected scrollToComponent(this.refs.results, { offset: 0, align: 'top', duration: 400 }); } componentDidMount() { this.scroll(); } componentWillReceiveProps(nextProps) { if (nextProps.clicked && this.props.clickedIds !== nextProps.clickedIds) { this.scroll(); } } render() { const { clickedIds, sharedRaces, clickedObjs, sharedRacesWinner } = this.props; return (<div className="results" id="results"> <div className="remove-all" ref="results"> <a onClick={() => this.props.removeAllAthletes()}> <span className="typcn typcn-delete"></span> Remove all swimmers </a> </div> <div className="table-wrapper"> { sharedRaces.length === 0 && <div className="no-races"> These { clickedIds.length } swimmers did not compete with each other </div> } <table className="race-athlete-table"> { sharedRaces.length > 0 && <thead> <tr className="thead"> <th colSpan="2" className="result-summary"> <span className="result-number">{ clickedIds.length }</span> swimmer{ clickedIds.length > 1 ? 's' : '' } &amp; <span className="result-number">{ sharedRaces.length }</span> race{ sharedRaces.length > 1 ? 's' : '' } </th> { sharedRaces.map((r, i) => (<th className="record" key={i}> <span className="race-meet">{ r.split('-')[0].slice(1) }</span> { r.split('-')[1].slice(1) } <span className="dash">-</span> { r.split('-')[4].slice(1) } </th>))} </tr> </thead> } <tbody> { clickedObjs.map((a, i) => (<tr key={i}> <td className="close-icon"> <a onClick={() => this.props.removeAthlete(a)}> <span className="typcn typcn-delete"></span> </a> </td> <td className="athlete"> <div>{ a.name }</div> <div> <span className={`${Countries[a.country] ? `fl-icon flag-icon-${Countries[a.country].toLowerCase()}`: ''}`} /> <span className="country">{ a.country }</span> </div> </td> { sharedRaces.map((r, j) => (<td key={j} className={`record${sharedRacesWinner && sharedRacesWinner[j].indexOf(i) > -1 ? ' winner' : ''}`}> <div className="place-wrapper"> <span className={`place place${a.records[r].place}`}> { a.records[r].place } </span> </div> <div className="swimtime">{ a.records[r].swimtime }</div> </td>))} </tr>))} </tbody> </table> </div> </div>); } } export default ResultsComponent;
src/modules/items/containers/ItemEmbedContainer/ItemEmbedContainer.js
CtrHellenicStudies/Commentary
import React from 'react'; import PropTypes from 'prop-types'; import { compose } from 'react-apollo'; import _ from 'underscore'; import ItemEmbed from '../../components/ItemEmbed'; import itemDetailQuery from '../../graphql/queries/detail'; class ItemEmbedContainer extends React.Component { render() { let item = null; console.log(this.props); console.log(this.props); console.log(this.props); console.log(this.props); if ( this.props.itemDetailQuery && this.props.itemDetailQuery.ORPHEUS_project ) { item = this.props.itemDetailQuery.ORPHEUS_project.item; } if (!item) { return null; } return ( <ItemEmbed {...item} /> ); } } ItemEmbedContainer.propTypes = { itemDetailQuery: PropTypes.object, }; export default compose( itemDetailQuery, )(ItemEmbedContainer);
frontend-admin/src/pendingNum/index.js
OptimusCrime/youkok2
import React from 'react'; import ReactDOM from 'react-dom'; import { fetchAdminPendingNumRest } from "./api"; export const run = () => { // This is lazy fetchAdminPendingNumRest() .then(response => response.json()) .then(response => { ReactDOM.render(( `${response.num}` ), document.getElementById('admin-pending-num') ); }) };
src/PilotPhase.js
qiubit/wason-selection-parallel
import _ from 'lodash'; import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; import Markdown from 'react-markdown'; import './PilotPhase.css'; import SelectionExercise from './SelectionExercise'; class PilotPhase extends Component { constructor(props) { super(props); const experimentExercisesMap = props.settings.pilotPhase.experimentExercises; let experimentExercisesArr = []; for (var key in experimentExercisesMap) { if (Object.prototype.hasOwnProperty.call(experimentExercisesMap, key)) experimentExercisesArr.push(experimentExercisesMap[key]); } this.state = { helpMessageShown: true, experimentFinished: false, trainingExerciseShown: false, experimentExerciseInProgress: false, currentExercise: -1, experimentExercises: _.shuffle(experimentExercisesArr), experimentStats: [], }; this.onTrainingExerciseFinish = this.onTrainingExerciseFinish.bind(this); this.onCloseHelpMsg = this.onCloseHelpMsg.bind(this); this.onExerciseFinish = this.onExerciseFinish.bind(this); this.prepareExerciseStats = this.prepareExerciseStats.bind(this); } onTrainingExerciseFinish(stats) { this.setState({ trainingExerciseShown: false, experimentExerciseInProgress: true, currentExercise: 0, }); } onExerciseFinish(stats) { let experimentStats = this.state.experimentStats.slice(); experimentStats.push(this.prepareExerciseStats(stats)); this.setState({ experimentStats: experimentStats }); if (this.state.currentExercise + 1 < this.state.experimentExercises.length) { this.setState({ currentExercise: this.state.currentExercise + 1 }); } else { this.setState({ experimentExerciseInProgress: false }); if (this.props.onPhaseFinish) { this.props.onPhaseFinish(experimentStats); } } } prepareExerciseStats(exerciseStats) { // First calculate chosen cards (and their order based on choice time) let chosenCardsTstamps = new Map(); let cardsToChoose = ["P", "nP", "Q", "nQ"]; let chosenCards = []; for (var i = 0; i < cardsToChoose.length; i++) { let currentCard = cardsToChoose[i]; if (exerciseStats[currentCard]) { let cardClickTstamps = exerciseStats[currentCard + "tstamps"] chosenCardsTstamps.set(currentCard, cardClickTstamps[cardClickTstamps.length-1]); chosenCards.push(currentCard); } } chosenCards.sort(function(cardA, cardB) { return chosenCardsTstamps.get(cardA) - chosenCardsTstamps.get(cardB); }); let finalChoiceTstamp = chosenCardsTstamps.get(chosenCards[chosenCards.length-1]); // Now calculate finalStats object let finalStats = { phase: "pilot", chosenCards: chosenCards, cardsOrder: exerciseStats.cardsOrder, completionTime: exerciseStats.completionTime, solvingTime: exerciseStats.solvingTime, exerciseRelativeId: exerciseStats.exerciseRelativeId, exerciseAbsoluteId: exerciseStats.exerciseAbsoluteId, Ptstamps: exerciseStats.Ptstamps, nPtstamps: exerciseStats.nPtstamps, Qtstamps: exerciseStats.Qtstamps, nQtstamps: exerciseStats.nQtstamps, finalChoiceTstamp: finalChoiceTstamp, } return finalStats; } onCloseHelpMsg() { this.setState({ helpMessageShown: false, trainingExerciseShown: true }); } render() { let helpMsg = ""; if (this.props.settings.pilotPhase && this.props.settings.pilotPhase.helpMsg) helpMsg = this.props.settings.pilotPhase.helpMsg; return ( <div> {this.state.helpMessageShown && <div className="display"> <Markdown source={helpMsg}/> <Button className="pull-right" bsSize="large" onClick={this.onCloseHelpMsg}>Next</Button> </div> } {this.state.trainingExerciseShown && <SelectionExercise exerciseRelativeId={1} exerciseAbsoluteId={this.props.settings.pilotPhase.trainingExercise} exercises={this.props.exercises} onExerciseFinish={this.onTrainingExerciseFinish} trainingMode={true} /> } {this.state.experimentExerciseInProgress && <SelectionExercise key={this.state.currentExercise} exerciseRelativeId={this.state.currentExercise + 1} exerciseAbsoluteId={this.state.experimentExercises[this.state.currentExercise]} exercises={this.props.exercises} onExerciseFinish={this.onExerciseFinish} /> } </div> ); } } PilotPhase.propTypes = { exercises: React.PropTypes.array.isRequired, settings: React.PropTypes.object.isRequired, onPhaseFinish: React.PropTypes.func, }; export default PilotPhase;
shared/containers/Common/ContentContainer.js
kizzlebot/music_dev
import React from 'react'; import {NavLeft, NavRight} from '../../components/Common/Content'; export default class ContentContainer extends React.Component{ render(){ return ( <section className={'content'}> <NavLeft {...this.props} /> <div className={'content__middle'}> {this.props.children} </div> <NavRight {...this.props}/> </section> ) } }
src/components/posts_new.js
monsteronfire/redux-learning-blog
import React from 'react'; import { Field, reduxForm } from 'redux-form'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { createPost } from '../actions'; class PostsNew extends React.Component { renderField(field) { const className = `form-group ${field.meta.touched && field.meta.error ? 'has-danger' : ''}` return ( <div className={className}> <label>{field.label}</label> <input className='form-control' type='text' {...field.input} /> <div className='text-help'> {field.meta.touched ? field.meta.error : ''} </div> </div> ); } onSubmit(values) { this.props.createPost(values, () => { this.props.history.push('/'); }); } render() { const { handleSubmit } = this.props; return ( <form onSubmit={handleSubmit(this.onSubmit.bind(this))} className='posts-new'> <Field label='Title' name='title' component={this.renderField} /> <Field label='Categories' name='categories' component={this.renderField} /> <Field label='Post Content' name='content' component={this.renderField} /> <button type='submit' className='btn btn-primary'>Submit</button> <Link to='/' className='btn btn-danger'>Cancel</Link> </form> ); } } function validate(values) { const errors = {}; if (!values.title) { errors.title = "Enter a title"; } if (!values.categories) { errors.categories = "Enter categories"; } if (!values.content) { errors.content = "Enter content"; } return errors; } export default reduxForm({ validate: validate, form: 'PostsNewForm' })( connect(null, { createPost })(PostsNew) );
client/modules/core/components/options_dropdown/options_dropdown.js
bompi88/grand-view
// ////////////////////////////////////////////////////////////////////////////// // Document Table Dropdown Component // ////////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Concept // // 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'; class OptionsDropdown extends React.Component { handleClick(func, e) { const f = this.props[func]; f(e); } renderItem(item, index) { if (item.divider) { return <li key={index} role="presentation" className="divider" />; } const disabled = item.disabled; return ( <li role="presentation" key={index} className={disabled ? 'disabled' : null}> <a role="menuitem" tabIndex="-1" href="#" onClick={disabled ? null : this.handleClick.bind(this, item.func)} > <span className={item.icon} aria-hidden="true" /> {item.label} </a> </li> ); } renderItems() { const { items } = this.props; return items.map((item, index) => this.renderItem(item, index)); } render() { return ( <div className="pull-right btn-group" role="group"> <button aria-expanded="false" className="btn btn-default dropdown-toggle menu-button" data-toggle="dropdown" type="button" > <span className="glyphicon glyphicon-option-horizontal" /> </button> <ul className="dropdown-menu" role="menu"> {this.renderItems()} </ul> </div> ); } } OptionsDropdown.propTypes = { items: React.PropTypes.arrayOf(React.PropTypes.shape({ label: React.PropTypes.string, icon: React.PropTypes.string, func: React.PropTypes.string, disabledOn: React.PropTypes.string, divider: React.PropTypes.bool, })), }; export default OptionsDropdown;
src/components/cards/card_wild.js
camboio/yooneau
import React from 'react'; export default class CardWild extends React.Component{ render(){ const colour = this.props.card.colour ? this.props.card.colour : 'gray'; return( <svg className="card-wild-component" onClick={this.props.onClick} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 158.7 243.8"> <g id="Layer_3"> <path id="XMLID_5_" className="c0" d="M146.7 243.8H12c-6.6 0-12-5.4-12-12V12C0 5.4 5.4 0 12 0h134.7c6.6 0 12 5.4 12 12v219.8c0 6.6-5.4 12-12 12z"/> </g> <g id="Layer_1"> <path id="XMLID_19_" className={colour} d="M147.5 79.1c0-37.6-30.4-68-68-68h-68v153.2c0 37.6 30.4 68 68 68h68V79.1z"/> </g> <g id="Layer_8"> <g id="XMLID_43_"> <g id="XMLID_38_"> <text id="XMLID_42_" transform="translate(13.747 35.452)" className="wild1 wild2 wild3">W</text> </g> <g id="XMLID_32_"> <text id="XMLID_36_" transform="translate(15.165 34.035)" className="wild4 wild2 wild3">W</text> </g> </g> </g> <g id="Layer_9"> <g id="XMLID_45_"> <g id="XMLID_33_"> <text id="XMLID_35_" transform="rotate(180 72.547 104.114)" className="wild1 wild2 wild3">W</text> </g> <g id="XMLID_29_"> <text id="XMLID_31_" transform="rotate(180 71.84 104.823)" className="wild4 wild2 wild3">W</text> </g> </g> </g> <g id="Layer_13"> <g id="XMLID_53_"> <g id="XMLID_131_"> <path id="XMLID_136_" d="M76.393 67.488l26.94 26.94-26.94 26.94-26.94-26.94z"/> </g> <g id="XMLID_114_"> <path id="XMLID_130_" className="wild5" d="M77.857 66.142l26.94 26.94-26.94 26.94-26.94-26.94z"/> </g> </g> <g id="XMLID_54_"> <g id="XMLID_124_"> <path id="XMLID_132_" d="M105.8 150.9l-26.9-27L105.8 97z"/> </g> <g id="XMLID_113_"> <path id="XMLID_118_" className="wild6" d="M107.2 149.4l-26.9-26.9 26.9-26.9z"/> </g> </g> <g id="XMLID_60_"> <g id="XMLID_116_"> <path id="XMLID_134_" d="M47 97l26.9 26.9-26.9 27z"/> </g> <g id="XMLID_111_"> <path id="XMLID_115_" className="wild7" d="M48.4 95.6l26.9 26.9-26.9 26.9z"/> </g> </g> <g id="XMLID_55_"> <g id="XMLID_125_"> <path id="XMLID_135_" d="M76.358 126.373l26.94 26.94-26.94 26.94-26.94-26.94z"/> </g> <g id="XMLID_108_"> <path id="XMLID_123_" className="wild8" d="M77.822 125.027l26.94 26.94-26.94 26.94-26.94-26.94z"/> </g> </g> </g> </svg> ); } }
src/Containers/ChartContainer/Chart.js
sirjuan/harmonical-oscillation
import React from 'react'; import { Scatter } from 'react-chartjs-2'; const scatterChart = ({color = 'blue', values = [], keys = {}, title = ''}) => { const data = { datasets: [{ label: `${keys.x} / ${keys.y}`, fill: false, pointBackgroundColor: 'rgba(0, 0, 0, 0)', pointBorderColor: 'rgba(0, 0, 0, 0)', borderColor: color, data: values.map(line => ({x: line[keys.x], y: line[keys.y]})) }] } const options = { title: { display: title ? true : false, text: title, fontSize: 24 } } return <Scatter data={data} options={options} /> }; const charts = { scatter: props => scatterChart(props), }; const Chart = ({type, ...props}) => charts[type](props); export default Chart;
es/transitions/Slide.js
uplevel-technology/material-ui-next
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } // @inheritedComponent Transition import React from 'react'; import { findDOMNode } from 'react-dom'; import EventListener from 'react-event-listener'; import debounce from 'lodash/debounce'; import Transition from 'react-transition-group/Transition'; import withTheme from '../styles/withTheme'; import { duration } from '../styles/transitions'; const GUTTER = 24; // Translate the node so he can't be seen on the screen. // Later, we gonna translate back the node to his original location // with `translate3d(0, 0, 0)`.` function getTranslateValue(props, node) { const { direction } = props; const rect = node.getBoundingClientRect(); let transform; if (node.fakeTransform) { transform = node.fakeTransform; } else { const computedStyle = window.getComputedStyle(node); transform = computedStyle.getPropertyValue('-webkit-transform') || computedStyle.getPropertyValue('transform'); } let offsetX = 0; let offsetY = 0; if (transform && transform !== 'none' && typeof transform === 'string') { const transformValues = transform.split('(')[1].split(')')[0].split(','); offsetX = parseInt(transformValues[4], 10); offsetY = parseInt(transformValues[5], 10); } if (direction === 'left') { return `translateX(100vw) translateX(-${rect.left - offsetX}px)`; } else if (direction === 'right') { return `translateX(-${rect.left + rect.width + GUTTER - offsetX}px)`; } else if (direction === 'up') { return `translateY(100vh) translateY(-${rect.top - offsetY}px)`; } // direction === 'down return `translate3d(0, ${0 - (rect.top + rect.height)}px, 0)`; } export function setTranslateValue(props, node) { const transform = getTranslateValue(props, node); if (transform) { node.style.transform = transform; node.style.webkitTransform = transform; } } const reflow = node => node.scrollTop; class Slide extends React.Component { constructor(...args) { var _temp; return _temp = super(...args), this.state = { // We use this state to handle the server-side rendering. firstMount: true }, this.transition = null, this.handleResize = debounce(() => { // Skip configuration where the position is screen size invariant. if (this.props.in || this.props.direction === 'down' || this.props.direction === 'right') { return; } const node = findDOMNode(this.transition); if (node instanceof HTMLElement) { setTranslateValue(this.props, node); } }, 166), this.handleEnter = node => { setTranslateValue(this.props, node); reflow(node); if (this.props.onEnter) { this.props.onEnter(node); } }, this.handleEntering = node => { const { theme, timeout } = this.props; node.style.transition = theme.transitions.create('transform', { duration: typeof timeout === 'number' ? timeout : timeout.enter, easing: theme.transitions.easing.easeOut }); // $FlowFixMe - https://github.com/facebook/flow/pull/5161 node.style.webkitTransition = theme.transitions.create('-webkit-transform', { duration: typeof timeout === 'number' ? timeout : timeout.enter, easing: theme.transitions.easing.easeOut }); node.style.transform = 'translate3d(0, 0, 0)'; node.style.webkitTransform = 'translate3d(0, 0, 0)'; if (this.props.onEntering) { this.props.onEntering(node); } }, this.handleExit = node => { const { theme, timeout } = this.props; node.style.transition = theme.transitions.create('transform', { duration: typeof timeout === 'number' ? timeout : timeout.exit, easing: theme.transitions.easing.sharp }); // $FlowFixMe - https://github.com/facebook/flow/pull/5161 node.style.webkitTransition = theme.transitions.create('-webkit-transform', { duration: typeof timeout === 'number' ? timeout : timeout.exit, easing: theme.transitions.easing.sharp }); setTranslateValue(this.props, node); if (this.props.onExit) { this.props.onExit(node); } }, this.handleExited = node => { // No need for transitions when the component is hidden node.style.transition = ''; // $FlowFixMe - https://github.com/facebook/flow/pull/5161 node.style.webkitTransition = ''; if (this.props.onExited) { this.props.onExited(node); } }, _temp; } componentDidMount() { // state.firstMount handle SSR, once the component is mounted, we need // to properly hide it. if (!this.props.in) { // We need to set initial translate values of transition element // otherwise component will be shown when in=false. this.updatePosition(); } } componentWillReceiveProps() { this.setState({ firstMount: false }); } componentDidUpdate(prevProps) { if (prevProps.direction !== this.props.direction && !this.props.in) { // We need to update the position of the drawer when the direction change and // when it's hidden. this.updatePosition(); } } componentWillUnmount() { this.handleResize.cancel(); } updatePosition() { const element = findDOMNode(this.transition); if (element instanceof HTMLElement) { element.style.visibility = 'inherit'; setTranslateValue(this.props, element); } } render() { const _props = this.props, { children, onEnter, onEntering, onExit, onExited, style: styleProp, theme } = _props, other = _objectWithoutProperties(_props, ['children', 'onEnter', 'onEntering', 'onExit', 'onExited', 'style', 'theme']); const style = _extends({}, styleProp); if (!this.props.in && this.state.firstMount) { style.visibility = 'hidden'; } return React.createElement( EventListener, { target: 'window', onResize: this.handleResize }, React.createElement( Transition, _extends({ onEnter: this.handleEnter, onEntering: this.handleEntering, onExit: this.handleExit, onExited: this.handleExited, appear: true, style: style }, other, { ref: node => { this.transition = node; } }), children ) ); } } Slide.defaultProps = { timeout: { enter: duration.enteringScreen, exit: duration.leavingScreen } }; export default withTheme()(Slide);
app/imports/ui/pages/auth/Signup.js
mondrus/meteor-starter
/** * @Author: philip * @Date: 2017-05-27T16:51:26+00:00 * @Filename: Signup.js * @Last modified by: philip * @Last modified time: 2017-05-27T17:41:50+00:00 */ import React from 'react'; import { Link } from 'react-router-dom'; import { Row, Col, FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap'; import handleSignup from '../../../modules/signup'; export default class Signup extends React.Component { componentDidMount() { handleSignup({ component: this }); } handleSubmit(event) { event.preventDefault(); console.log(this.signupForm); } render() { return ( <div className="middle-box text-center loginscreen animated fadeInDown"> <div> <h1 className="logo-name">IN+</h1> </div> <h3>Register to IN+</h3> <p>Create account to see it in action.</p> <form ref={ form => (this.signupForm = form) } onSubmit={ this.handleSubmit } className="m-t" > <FormGroup> <FormControl type="text" ref="username" name="username" placeholder="Username" /> </FormGroup> <FormGroup> <FormControl type="text" ref="emailAddress" name="emailAddress" placeholder="Email Address" /> </FormGroup> <FormGroup> <FormControl type="password" ref="password" name="password" placeholder="Password" /> </FormGroup> <FormGroup> <ControlLabel><input type="checkbox" /><i></i> Agree the terms and policy</ControlLabel> </FormGroup> <Button type="submit" bsStyle="success" className="btn-primary block full-width m-b">Sign Up</Button> <p className="text-muted text-center"> <small>Already have an account?</small> </p> <Link to="/login" className="btn btn-sm btn-white btn-block">Log In</Link> </form> <p className="m-t"> <small>Inspinia we app framework base on Bootstrap 3 &copy; 2017</small> </p> </div> ); } }
src/routes/logout/Logout.js
AaronHartigan/DudeTruck
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Logout.css'; class Logout extends React.Component { componentDidMount() { setTimeout(() => { window.location.reload(); }, 1250); } render() { return <div className={s.text}>Logging out...</div>; } } export default withStyles(s)(Logout);
src/modules/connect/connectDetail/components/ConnectDetailTagBox.js
Florenz23/sangoo_04
import React, { Component } from 'react'; import { Container,List, Header, Title, Content, Button, Icon, IconNB, Card, CardItem, Text, Left, Right, Body, ListItem } from 'native-base'; import { View } from 'react-native' import styles from '../../styles/socialBox'; import contacts from '../../../../mock/contacts' import realm from '../../db_ini' const _getContact = (contactId) => { const contacts = realm.objects('User') const searchResult = contacts.filtered(`userId = "${contactId}"`) const recent_contact = searchResult[0] return recent_contact } const _getMatchingData = (arr1,arr2) => { arr1.prototype.diff = function(arr2) { var ret = []; for(var i in this) { if(arr2.indexOf( this[i] ) > -1){ ret.push( this[i] ); } } return ret; }; } const renderData = (contactId) => { const datas = contacts const contact = _getContact(contactId) return ( <View> <List dataArray={contact.publicSharedData[0].hashTagData} renderRow={data => <ListItem style={{backgroundColor:'white'}}> <Text>{data.tagDescription}</Text> <Right> <Text>{data.tagText}</Text> </Right> </ListItem> } /> </View> ) } const ConnectDetailTagBox = (props) => { const datas = contacts const {children} = props return ( <View> {renderData(children)} </View> ) } export default ConnectDetailTagBox
src/parser/mage/shared/modules/features/RuneOfPower.js
fyruna/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import SPECS from 'game/SPECS'; import SpellLink from 'common/SpellLink'; import { formatNumber, formatPercentage } from 'common/format'; import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox'; import AbilityTracker from 'parser/shared/modules/AbilityTracker'; import Analyzer from 'parser/core/Analyzer'; import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage'; import Events from 'parser/core/Events'; import { SELECTED_PLAYER } from 'parser/core/EventFilter'; import SUGGESTION_IMPORTANCE from 'parser/core/ISSUE_IMPORTANCE'; /* * If Rune of Power is substantially better than the rest of the row, enable * ROP talent suggestion. At time of writing, it's a substantial increase over * incanters flow for fire and arcane in all situations. */ const SUGGEST_ROP = { [SPECS.FROST_MAGE.id]: false, [SPECS.ARCANE_MAGE.id]: true, [SPECS.FIRE_MAGE.id]: true }; const DAMAGE_BONUS = 0.4; const RUNE_DURATION = 10; const INCANTERS_FLOW_EXPECTED_BOOST = 0.12; // FIXME due to interactions with Ignite, the damage boost number will be underrated for Fire Mages. Still fine for Arcane and Frost. class RuneOfPower extends Analyzer { static dependencies = { abilityTracker: AbilityTracker, }; hasROP = false; damage = 0; constructor(...args) { super(...args); if (this.selectedCombatant.hasTalent(SPELLS.RUNE_OF_POWER_TALENT.id)) { this.hasROP = true; this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onPlayerDamage); } } onPlayerDamage(event) { if (this.selectedCombatant.hasBuff(SPELLS.RUNE_OF_POWER_BUFF.id)) { this.damage += calculateEffectiveDamage(event, DAMAGE_BONUS); } } get damagePercent() { return this.owner.getPercentageOfTotalDamageDone(this.damage); } get damageIncreasePercent() { return this.damagePercent / (1 - this.damagePercent); } get uptimeMS() { return this.selectedCombatant.getBuffUptime(SPELLS.RUNE_OF_POWER_BUFF.id); } get roundedSecondsPerCast() { return ((this.uptimeMS / this.abilityTracker.getAbility(SPELLS.RUNE_OF_POWER_TALENT.id).casts) / 1000).toFixed(1); } get damageSuggestionThresholds() { return { actual: this.damageIncreasePercent, isLessThan: { minor: INCANTERS_FLOW_EXPECTED_BOOST, average: INCANTERS_FLOW_EXPECTED_BOOST, major: INCANTERS_FLOW_EXPECTED_BOOST - 0.03, }, style: 'percentage', }; } get roundedSecondsSuggestionThresholds() { return { actual: this.roundedSecondsPerCast, isLessThan: { minor: RUNE_DURATION, average: RUNE_DURATION - 1, major: RUNE_DURATION - 2, }, style: 'number', }; } showSuggestion = true; suggestions(when) { if (!this.hasROP) { when(SUGGEST_ROP[this.selectedCombatant.specId]).isTrue() .addSuggestion((suggest) => { return suggest( <> It is highly recommended to talent into <SpellLink id={SPELLS.RUNE_OF_POWER_TALENT.id} /> when playing this spec. While it can take some practice to master, when played correctly it outputs substantially more DPS than <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} /> or <SpellLink id={SPELLS.MIRROR_IMAGE_TALENT.id} />. </>) .icon(SPELLS.RUNE_OF_POWER_TALENT.icon) .staticImportance(SUGGESTION_IMPORTANCE.REGULAR); }); return; } if(!this.showSuggestion) { return; } when(this.damageSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Your <SpellLink id={SPELLS.RUNE_OF_POWER_TALENT.id} /> damage boost is below the expected passive gain from <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />. Either find ways to make better use of the talent, or switch to <SpellLink id={SPELLS.INCANTERS_FLOW_TALENT.id} />.</>) .icon(SPELLS.RUNE_OF_POWER_TALENT.icon) .actual(`${formatPercentage(this.damageIncreasePercent)}% damage increase from Rune of Power`) .recommended(`${formatPercentage(recommended)}% is the passive gain from Incanter's Flow`); }); if (this.abilityTracker.getAbility(SPELLS.RUNE_OF_POWER_TALENT.id).casts > 0) { when(this.roundedSecondsSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest(<>You sometimes aren't standing in your <SpellLink id={SPELLS.RUNE_OF_POWER_TALENT.id} /> for its full duration. Try to only use it when you know you won't have to move for the duration of the effect.</>) .icon(SPELLS.RUNE_OF_POWER_TALENT.icon) .actual(`Average ${this.roundedSecondsPerCast}s standing in each Rune of Power`) .recommended(`the full duration of ${formatNumber(RUNE_DURATION)}s is recommended`); }); } } showStatistic = true; statistic() { if (!this.hasROP || !this.showStatistic) return null; return ( <TalentStatisticBox talent={SPELLS.RUNE_OF_POWER_TALENT.id} position={STATISTIC_ORDER.CORE(100)} value={`${formatPercentage(this.damagePercent)} %`} label="Rune of Power damage" tooltip={<>This is the portion of your total damage attributable to Rune of Power's boost. Expressed as an increase vs never using Rune of Power, this is a <strong>{formatPercentage(this.damageIncreasePercent)}% damage increase</strong>. Note that this number does <em>not</em> factor in the opportunity cost of casting Rune of Power instead of another damaging spell.</>} /> ); } } export default RuneOfPower;
src/parser/shared/modules/spells/bfa/azeritetraits/BloodRite.js
sMteX/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import { formatPercentage } from 'common/format'; import { calculateAzeriteEffects } from 'common/stats'; import Analyzer from 'parser/core/Analyzer'; import TraitStatisticBox, { STATISTIC_ORDER } from 'interface/others/TraitStatisticBox'; import StatTracker from 'parser/shared/modules/StatTracker'; const bloodRiteStats = traits => Object.values(traits).reduce((obj, rank) => { const [haste] = calculateAzeriteEffects(SPELLS.BLOOD_RITE.id, rank); obj.haste += haste; return obj; }, { haste: 0, }); /** * Blood Rite * Gain x haste while active * * Example report: https://www.warcraftlogs.com/reports/k4bAJZKWVaGt12j9#fight=3&type=auras&source=14 */ class BloodRite extends Analyzer { static dependencies = { statTracker: StatTracker, }; haste = 0; bloodRiteProcs = 0; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTrait(SPELLS.BLOOD_RITE.id); if (!this.active) { return; } const { haste } = bloodRiteStats(this.selectedCombatant.traitsBySpellId[SPELLS.BLOOD_RITE.id]); this.haste = haste; this.statTracker.add(SPELLS.BLOOD_RITE_BUFF.id, { haste, }); } on_byPlayer_applybuff(event) { this.handleBuff(event); } on_byPlayer_refreshbuff(event) { this.handleBuff(event); } handleBuff(event) { if (event.ability.guid !== SPELLS.BLOOD_RITE_BUFF.id) { return; } this.bloodRiteProcs += 1; } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.BLOOD_RITE_BUFF.id) / this.owner.fightDuration; } get averageHaste() { return (this.haste * this.uptime).toFixed(0); } statistic() { return ( <TraitStatisticBox position={STATISTIC_ORDER.OPTIONAL()} trait={SPELLS.BLOOD_RITE.id} value={`${this.averageHaste} average Haste`} tooltip={( <> {SPELLS.BLOOD_RITE.name} grants <strong>{this.haste} Haste</strong> while active.<br /> You had <strong>{this.bloodRiteProcs} {SPELLS.BLOOD_RITE.name} procs</strong> resulting in {formatPercentage(this.uptime)}% uptime. </> )} /> ); } } export default BloodRite;
__tests__/setup.js
brentvatne/react-conf-app
// @flow import React from 'react'; import { View } from 'react-native'; // ------------------------ // Javascript Built-Ins // ------------------------ // Ensure Date.now and new Date() give us the same date for snapshots. import timekeeper from 'timekeeper'; timekeeper.freeze(new Date(2017, 3, 1, 8, 0, 0)); // ------------------------ // React Native Built-Ins // ------------------------ // React Native UI Manager needs a focus function. // $FlowFixMe import { UIManager } from 'NativeModules'; UIManager.focus = jest.fn(); UIManager.createView = jest.fn(() => <View />); UIManager.updateView = jest.fn(); // ------------------------ // NPM Modules // ------------------------ // Provide a manual mock for native modules. jest.mock('react-native-maps');
tests/lib/rules/indent.js
gfxmonk/eslint
/** * @fileoverview This option sets a specific tab width for your code * @author Dmitriy Shekhovtsov * @copyright 2014 Dmitriy Shekhovtsov. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ var eslint = require("../../../lib/eslint"), ESLintTester = require("eslint-tester"); var fs = require("fs"); var path = require("path"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ var fixture = fs.readFileSync(path.join(__dirname, "../../fixtures/rules/indent/indent-invalid-fixture-1.js"), "utf8"); function expectedErrors(errors) { if (!errors[0].length) { errors = [errors]; } return errors.map(function (err) { return { message: "Expected indentation of " + err[1] + " characters.", type: "Program", line: err[0] }; }); } var eslintTester = new ESLintTester(eslint); eslintTester.addRuleTest("lib/rules/indent", { valid: [ { code: "switch (a) {\n" + " case \"foo\":\n" + " a();\n" + " break;\n" + " case \"bar\":\n" + " a(); break;\n" + " case \"baz\":\n" + " a(); break;\n" + "}" }, { code: "switch (0) {\n}" }, { code: "function foo() {\n" + " var a = \"a\";\n" + " switch(a) {\n" + " case \"a\":\n" + " return \"A\";\n" + " case \"b\":\n" + " return \"B\";\n" + " }\n" + "}\n" + "foo();" }, { code: "switch(value){\n" + " case \"1\":\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " a();\n" + " break;\n" + "}\n" + "switch(value){\n" + " case \"1\":\n" + " a();\n" + " break;\n" + " case \"2\":\n" + " break;\n" + " default:\n" + " break;\n" + "}", options: [4] }, { code: "var obj = {foo: 1, bar: 2};\n" + "with (obj) {\n" + " console.log(foo + bar);\n" + "}\n" }, { code: "if (a) {\n" + " (1 + 2 + 3);\n" + // no error on this line "}" }, { code: "switch(value){ default: a(); break; }\n" }, { code: "import {addons} from 'react/addons'\rimport React from 'react'", options: [2], ecmaFeatures: { modules: true } } ], invalid: [ { code: " var a = b;\n" + "if (a) {\n" + " b();\n" + "}\n", options: [2], errors: expectedErrors([[1, 0]]) }, { code: "if (array.some(function(){\n" + " return true;\n" + "})) {\n" + "a++; // ->\n" + " b++;\n" + " c++; // <-\n" + "}\n", options: [2], errors: expectedErrors([[4, 2], [6, 2]]) }, { code: "if (a){\n\tb=c;\n\t\tc=d;\ne=f;\n}", options: ["tab"], errors: expectedErrors([[3, 1], [4, 1]]) }, { code: "if (a){\n b=c;\n c=d;\n e=f;\n}", options: [4], errors: expectedErrors([[3, 4], [4, 4]]) }, { code: fixture, options: [2, {indentSwitchCase: true}], errors: expectedErrors([ [5, 2], [10, 4], [11, 2], [15, 4], [16, 2], [23, 2], [29, 2], [30, 4], [36, 4], [38, 2], [39, 4], [40, 2], [46, 0], [54, 2], [114, 4], [120, 4], [124, 4], [127, 4], [134, 4], [139, 2], [145, 2], [149, 2], [152, 2], [159, 2], [168, 4], [176, 4], [184, 4], [186, 4], [200, 2], [202, 2], [214, 2], [218, 6], [220, 6], [330, 6], [331, 6], [371, 2], [372, 2], [375, 2], [376, 2], [379, 2], [380, 2], [386, 2], [388, 2], [399, 2], [401, 2], [405, 4], [407, 4], [414, 2], [416, 2], [421, 2], [423, 2], [440, 2], [441, 2], [447, 2], [448, 2], [454, 2], [455, 2], [461, 6], [462, 6], [467, 6], [472, 6], [486, 2], [488, 2], [534, 6], [541, 6] ]) }, { code: "switch(value){\n" + " case \"1\":\n" + " a();\n" + " break;\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " a();\n" + " break;\n" + "}", options: [4, {indentSwitchCase: true}], errors: expectedErrors([10, 4]) }, { code: "switch(value){\n" + " case \"1\":\n" + " a();\n" + " break;\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " break;\n" + "}", options: [4, {indentSwitchCase: true}], errors: expectedErrors([9, 8]) }, { code: "switch(value){\n" + " case \"1\":\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " break;\n" + "}\n" + "switch(value){\n" + " case \"1\":\n" + " break;\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " a();\n" + " break;\n" + "}", options: [4, {indentSwitchCase: true}], errors: expectedErrors([[11, 8], [14, 8], [17, 8]]) }, { code: "switch(value){\n" + " case \"1\":\n" + " case \"2\":\n" + " a();\n" + " break;\n" + " default:\n" + " a();\n" + " break;\n" + "}\n" + "switch(value){\n" + " case \"1\":\n" + " a();\n" + " break;\n" + " case \"2\":\n" + " break;\n" + " default:\n" + " break;\n" + "}", options: [4, {indentSwitchCase: true}], errors: expectedErrors([[13, 4], [15, 4], [17, 4]]) }, { code: "var obj = {foo: 1, bar: 2};\n" + "with (obj) {\n" + "console.log(foo + bar);\n" + "}\n", args: [2], errors: expectedErrors([3, 4]) } ] });
Tutorial/AwesomeProject/__tests__/index.android.js
iyooooo/ReactNativeExpress
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
ui/app/components/layout/index.js
leapcode/bitmask-dev
import React from 'react' import './layout.less' class HorizontalLayout extends React.Component { static get defaultProps() {return{ equalWidths: false, className: '' }} constructor(props) { super(props) } render() { let className = "horizontal-layout " + this.props.className if (this.props.equalWidths) { className = className + " equal" + this.props.children.length } return ( <div className={className}> {this.props.children} </div> ) } } class Column extends React.Component { static get defaultProps() {return{ className: '' }} constructor(props) { super(props) } render() { let className = "layout-column " + this.props.className return ( <div className={className}> {this.props.children} </div> ) } } class VerticalLayout extends React.Component { static get defaultProps() {return{ equalWidths: false, className: '' }} constructor(props) { super(props) } render() { let className = "vertical-layout " + this.props.className if (this.props.equalWidths) { className = className + " equal" + this.props.children.length } return ( <div className={className}> {this.props.children} </div> ) } } class Row extends React.Component { static get defaultProps() {return{ className: '', size: 'expand', gutter: '' }} constructor(props) { super(props) } render() { let style = {} if (this.props.gutter) { style = {marginBottom: this.props.gutter} } let className = ["layout-row", this.props.className, this.props.size].join(" ") return ( <div style={style} className={className}> {this.props.children} </div> ) } } export {HorizontalLayout, VerticalLayout, Column, Row}
src/svg-icons/image/camera-rear.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraRear = (props) => ( <SvgIcon {...props}> <path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zm3-20H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zm-5 6c-1.11 0-2-.9-2-2s.89-2 1.99-2 2 .9 2 2C14 5.1 13.1 6 12 6z"/> </SvgIcon> ); ImageCameraRear = pure(ImageCameraRear); ImageCameraRear.displayName = 'ImageCameraRear'; ImageCameraRear.muiName = 'SvgIcon'; export default ImageCameraRear;
src/DataTable/Selectable.js
react-mdl/react-mdl
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import isEqual from 'lodash.isequal'; import TableHeader from './TableHeader'; import Checkbox from '../Checkbox'; const propTypes = { columns: (props, propName, componentName) => ( props[propName] && new Error(`${componentName}: \`${propName}\` is deprecated, please use the component \`TableHeader\` instead.`) ), data: (props, propName, componentName) => ( props[propName] && new Error(`${componentName}: \`${propName}\` is deprecated, please use \`rows\` instead. \`${propName}\` will be removed in the next major release.`) ), onSelectionChanged: PropTypes.func, rowKeyColumn: PropTypes.string, rows: PropTypes.arrayOf( PropTypes.object ).isRequired, selectable: PropTypes.bool, selectedRows: PropTypes.array }; const defaultProps = { onSelectionChanged: () => { // do nothing } }; export default Component => { class Selectable extends React.Component { constructor(props) { super(props); this.handleChangeHeaderCheckbox = this.handleChangeHeaderCheckbox.bind(this); this.handleChangeRowCheckbox = this.handleChangeRowCheckbox.bind(this); this.builRowCheckbox = this.builRowCheckbox.bind(this); if (props.selectable) { this.state = { headerSelected: false, selectedRows: props.selectedRows || [] }; } } componentWillReceiveProps(nextProps) { if (nextProps.selectable) { const { rows, data, rowKeyColumn } = nextProps; const rrows = rows || data; if (!isEqual(this.props.rows || this.props.data, rrows) || !isEqual(this.props.selectedRows, nextProps.selectedRows)) { // keep only existing rows const selectedRows = (nextProps.selectedRows || this.state.selectedRows) .filter(k => rrows .map((row, i) => row[rowKeyColumn] || row.key || i) .indexOf(k) > -1 ); this.setState({ headerSelected: selectedRows.length === rrows.length, selectedRows }); if (!nextProps.selectedRows) { nextProps.onSelectionChanged(selectedRows); } } } } handleChangeHeaderCheckbox(e) { const { rowKeyColumn, rows, data } = this.props; const selected = e.target.checked; const selectedRows = selected ? (rows || data).map((row, idx) => row[rowKeyColumn] || row.key || idx) : []; this.setState({ headerSelected: selected, selectedRows }); this.props.onSelectionChanged(selectedRows); } handleChangeRowCheckbox(e) { const { rows, data } = this.props; const rowId = JSON.parse(e.target.dataset ? e.target.dataset.reactmdl : e.target.getAttribute('data-reactmdl') ).id; const rowChecked = e.target.checked; const selectedRows = this.state.selectedRows; if (rowChecked) { selectedRows.push(rowId); } else { const idx = selectedRows.indexOf(rowId); selectedRows.splice(idx, 1); } this.setState({ headerSelected: (rows || data).length === selectedRows.length, selectedRows }); this.props.onSelectionChanged(selectedRows); } builRowCheckbox(content, row, idx) { const rowKey = row[this.props.rowKeyColumn] || row.key || idx; const isSelected = this.state.selectedRows.indexOf(rowKey) > -1; return ( <Checkbox className="mdl-data-table__select" data-reactmdl={JSON.stringify({ id: rowKey })} checked={isSelected} onChange={this.handleChangeRowCheckbox} /> ); } render() { const { rows, data, selectable, children, rowKeyColumn, ...otherProps } = this.props; // remove unwatned props // see https://github.com/Hacker0x01/react-datepicker/issues/517#issuecomment-230171426 delete otherProps.onSelectionChanged; delete otherProps.selectedRows; const realRows = selectable ? (rows || data).map((row, idx) => { const rowKey = row[rowKeyColumn] || row.key || idx; return { ...row, className: classNames({ 'is-selected': this.state.selectedRows.indexOf(rowKey) > -1 }, row.className) }; }) : (rows || data); return ( <Component rows={realRows} {...otherProps}> {selectable && ( <TableHeader name="mdl-header-select" cellFormatter={this.builRowCheckbox}> <Checkbox className="mdl-data-table__select" checked={this.state.headerSelected} onChange={this.handleChangeHeaderCheckbox} /> </TableHeader> )} {children} </Component> ); } } Selectable.propTypes = propTypes; Selectable.defaultProps = defaultProps; return Selectable; };
dashboard/src/index.js
lsumedia/lcr-web
import React from 'react'; import ReactDOM from 'react-dom'; import { createBrowserHistory } from 'history'; import { HashRouter, Route, Switch } from 'react-router-dom'; import App from './containers/App/App.jsx'; import './assets/css/bootstrap.min.css'; import './assets/css/animate.min.css'; import './assets/sass/light-bootstrap-dashboard.css'; import './assets/css/demo.css'; import './assets/css/pe-icon-7-stroke.css'; const history = createBrowserHistory(); ReactDOM.render(( <HashRouter history={history}> <Switch> <Route path="/" name="Home" component={App}/> </Switch> </HashRouter> ),document.getElementById('root'));
docs/app/Examples/addons/TextArea/Usage/TextAreaExampleAutoHeightMinHeight.js
aabustamante/Semantic-UI-React
import React from 'react' import { Form, TextArea } from 'semantic-ui-react' const TextAreaExampleAutoHeightMinHeight = () => ( <Form> <TextArea autoHeight placeholder='Try adding multiple lines' style={{ minHeight: 100 }} /> </Form> ) export default TextAreaExampleAutoHeightMinHeight
client/test/components/common/AccountMenu.spec.js
andela-pessien/libre-dms
/* eslint-disable react/jsx-filename-extension */ import React from 'react'; import { mount } from 'enzyme'; import { Provider } from 'react-redux'; import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import sinon from 'sinon'; import AccountMenu, { AccountMenuComponent } from '../../../components/common/AccountMenu'; import { getValidUser } from '../../../../scripts/data-generator'; const mockStore = configureMockStore([thunk]); describe('AccountMenu component', () => { let accountMenu; const user = getValidUser(); const store = mockStore({ userReducer: { '9e73286e-82ad-433f-9637-71766692dc5d': { user } } }); const props = { ownId: '9e73286e-82ad-433f-9637-71766692dc5d' }; beforeEach(() => { accountMenu = mount(<Provider store={store}><AccountMenu {...props} /></Provider>); }); it('renders without crashing', () => { expect(accountMenu.length).toBe(1); }); it('should have the right layout', () => { expect(accountMenu.find('#nav-mobile').length).toBe(1); expect(accountMenu.find('#nav-mobile').hasClass('right')).toBe(true); }); it('should display user\'s name', () => { expect(accountMenu.find('li > p').text()).toEqual(`Hi, ${user.name.split(' ')[0]}`); }); it('should display avatar icon', () => { expect(accountMenu.find('i.material-icons').text()).toEqual('person'); }); it('should display signout dropdown', () => { expect(accountMenu.find('#account-dropdown').length).toBe(1); expect(accountMenu.find('div') .filterWhere(item => (item.prop('data-activates') === 'account-dropdown')) .length).toBe(1); expect(accountMenu.find('.signout').text()).toEqual('Sign Out'); accountMenu.find('.signout').simulate('click'); }); it('should call signOut prop from onSignOutClick method on clicking "Sign Out', () => { const shallowProps = { user, signOut: sinon.spy(() => {}) }; accountMenu = mount(<AccountMenuComponent {...shallowProps} />); accountMenu.find('.signout').simulate('click'); expect(accountMenu.props().signOut.callCount).toBe(1); }); });
loc8-react-redux-front-end/src/components/Home/MainView.js
uberslackin/django-redux-loc8-ARweb
import ArticleList from '../ArticleList'; import React from 'react'; import agent from '../../agent'; import { connect } from 'react-redux'; const YourFeedTab = props => { if (props.token) { const clickHandler = ev => { ev.preventDefault(); props.onTabClick('feed', agent.Articles.feed()); } return ( <li className="nav-item"> <a href="" className={ props.tab === 'feed' ? 'nav-link active' : 'nav-link' } onClick={clickHandler}> Your Feed </a> </li> ); } return null; }; const GlobalFeedTab = props => { const clickHandler = ev => { ev.preventDefault(); props.onTabClick('all', agent.Articles.all()); }; return ( <li className="nav-item"> <a href="" className={ props.tab === 'all' ? 'nav-link active' : 'nav-link' } onClick={clickHandler}> Global Feed </a> </li> ); }; const TagFilterTab = props => { if (!props.tag) { return null; } return ( <li className="nav-item"> <a href="" className="nav-link active"> <i className="ion-pound"></i> {props.tag} </a> </li> ); }; const mapStateToProps = state => ({ ...state.articleList, tags: state.home.tags, token: state.common.token }); const mapDispatchToProps = dispatch => ({ onTabClick: (tab, payload) => dispatch({ type: 'CHANGE_TAB', tab, payload }) }); const MainView = props => { return ( <div className="col-md-9"> <div className="feed-toggle"> <ul className="nav nav-pills outline-active"> <YourFeedTab token={props.token} tab={props.tab} onTabClick={props.onTabClick} /> <GlobalFeedTab tab={props.tab} onTabClick={props.onTabClick} /> <TagFilterTab tag={props.tag} /> </ul> </div> <ArticleList articles={props.articles} loading={props.loading} articlesCount={props.articlesCount} currentPage={props.currentPage} /> </div> ); }; export default connect(mapStateToProps, mapDispatchToProps)(MainView);
app/routes.js
jbarabander/game-site
import { Route, IndexRoute } from 'react-router'; import App from 'containers/App'; import Home from 'containers/HomePage'; import React from 'react'; const routes = ( <Route path="/" component={App}> <IndexRoute component={Home} /> </Route> ); export default routes;
docs/src/app/components/pages/components/List/ExampleSettings.js
ArcanisCz/material-ui
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import Divider from 'material-ui/Divider'; import Checkbox from 'material-ui/Checkbox'; import Toggle from 'material-ui/Toggle'; const styles = { root: { display: 'flex', flexWrap: 'wrap', }, }; const ListExampleSettings = () => ( <div style={styles.root}> <MobileTearSheet> <List> <Subheader>General</Subheader> <ListItem primaryText="Profile photo" secondaryText="Change your Google+ profile photo" /> <ListItem primaryText="Show your status" secondaryText="Your status is visible to everyone you use with" /> </List> <Divider /> <List> <Subheader>Hangout Notifications</Subheader> <ListItem leftCheckbox={<Checkbox />} primaryText="Notifications" secondaryText="Allow notifications" /> <ListItem leftCheckbox={<Checkbox />} primaryText="Sounds" secondaryText="Hangouts message" /> <ListItem leftCheckbox={<Checkbox />} primaryText="Video sounds" secondaryText="Hangouts video call" /> </List> </MobileTearSheet> <MobileTearSheet> <List> <ListItem primaryText="When calls and notifications arrive" secondaryText="Always interrupt" /> </List> <Divider /> <List> <Subheader>Priority Interruptions</Subheader> <ListItem primaryText="Events and reminders" rightToggle={<Toggle />} /> <ListItem primaryText="Calls" rightToggle={<Toggle />} /> <ListItem primaryText="Messages" rightToggle={<Toggle />} /> </List> <Divider /> <List> <Subheader>Hangout Notifications</Subheader> <ListItem primaryText="Notifications" leftCheckbox={<Checkbox />} /> <ListItem primaryText="Sounds" leftCheckbox={<Checkbox />} /> <ListItem primaryText="Video sounds" leftCheckbox={<Checkbox />} /> </List> </MobileTearSheet> </div> ); export default ListExampleSettings;
src/browser/ui/EmptyArticle.react.js
syroegkin/mikora.eu
import Component from 'react-pure-render/component'; import React from 'react'; import { FormattedMessage, defineMessages } from 'react-intl'; import EditorFormatAlignLeft from 'material-ui/svg-icons/editor/format-align-left'; import { grey200 } from 'material-ui/styles/colors'; const _messages = defineMessages({ emptyArticle: { defaultMessage: 'No data so far', id: 'ui.emptyArticle.empty' } }); export default class EmptyList extends Component { render() { const emptyListContainerStyle = { width: '100%', height: '70vh', verticalAlign: 'middle', textAlign: 'center', color: grey200 }; const emptyListContentStyle = { position: 'relative', top: '50%', transform: 'translateY(-50%)' }; const iconStyle = { width: 300, height: 300 }; return ( <div style={emptyListContainerStyle}> <div style={emptyListContentStyle}> <EditorFormatAlignLeft color={grey200} style={iconStyle} /> <p> <FormattedMessage {..._messages.emptyArticle} /> </p> </div> </div> ); } }
Tutorial/__tests__/index.ios.js
onezens/react-native-repo
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/svg-icons/device/bluetooth-searching.js
kasra-co/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBluetoothSearching = (props) => ( <SvgIcon {...props}> <path d="M14.24 12.01l2.32 2.32c.28-.72.44-1.51.44-2.33 0-.82-.16-1.59-.43-2.31l-2.33 2.32zm5.29-5.3l-1.26 1.26c.63 1.21.98 2.57.98 4.02s-.36 2.82-.98 4.02l1.2 1.2c.97-1.54 1.54-3.36 1.54-5.31-.01-1.89-.55-3.67-1.48-5.19zm-3.82 1L10 2H9v7.59L4.41 5 3 6.41 8.59 12 3 17.59 4.41 19 9 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM11 5.83l1.88 1.88L11 9.59V5.83zm1.88 10.46L11 18.17v-3.76l1.88 1.88z"/> </SvgIcon> ); DeviceBluetoothSearching = pure(DeviceBluetoothSearching); DeviceBluetoothSearching.displayName = 'DeviceBluetoothSearching'; DeviceBluetoothSearching.muiName = 'SvgIcon'; export default DeviceBluetoothSearching;
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js
ketoo/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import AvatarItem from 'components/common/AvatarItem.react'; var ContactItem = React.createClass({ displayName: 'ContactItem', propTypes: { contact: React.PropTypes.object, onSelect: React.PropTypes.func }, mixins: [PureRenderMixin], _onSelect() { this.props.onSelect(this.props.contact); }, render() { let contact = this.props.contact; 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._onSelect}>add</a> </div> </li> ); } }); export default ContactItem;
example/custom/__tests__/index.android.js
fukuball/react-native-orientation-loading-overlay
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
admin/client/App/shared/Popout/index.js
Adam14Four/keystone
/** * A Popout component. * One can also add a Header (Popout/Header), a Footer * (Popout/Footer), a Body (Popout/Body) and a Pan (Popout/Pane). */ import React from 'react'; import Portal from '../Portal'; import Transition from 'react-addons-css-transition-group'; const SIZES = { arrowHeight: 12, arrowWidth: 16, horizontalMargin: 20, }; var Popout = React.createClass({ displayName: 'Popout', propTypes: { isOpen: React.PropTypes.bool, onCancel: React.PropTypes.func, onSubmit: React.PropTypes.func, relativeToID: React.PropTypes.string.isRequired, width: React.PropTypes.number, }, getDefaultProps () { return { width: 320, }; }, getInitialState () { return {}; }, componentWillReceiveProps (nextProps) { if (!this.props.isOpen && nextProps.isOpen) { window.addEventListener('resize', this.calculatePosition); this.calculatePosition(nextProps.isOpen); } else if (this.props.isOpen && !nextProps.isOpen) { window.removeEventListener('resize', this.calculatePosition); } }, getPortalDOMNode () { return this.refs.portal.getPortalDOMNode(); }, calculatePosition (isOpen) { if (!isOpen) return; let posNode = document.getElementById(this.props.relativeToID); const pos = { top: 0, left: 0, width: posNode.offsetWidth, height: posNode.offsetHeight, }; while (posNode.offsetParent) { pos.top += posNode.offsetTop; pos.left += posNode.offsetLeft; posNode = posNode.offsetParent; } let leftOffset = Math.max(pos.left + (pos.width / 2) - (this.props.width / 2), SIZES.horizontalMargin); let topOffset = pos.top + pos.height + SIZES.arrowHeight; var spaceOnRight = window.innerWidth - (leftOffset + this.props.width + SIZES.horizontalMargin); if (spaceOnRight < 0) { leftOffset = leftOffset + spaceOnRight; } const arrowLeftOffset = leftOffset === SIZES.horizontalMargin ? pos.left + (pos.width / 2) - (SIZES.arrowWidth / 2) - SIZES.horizontalMargin : null; const newStateAvaliable = this.state.leftOffset !== leftOffset || this.state.topOffset !== topOffset || this.state.arrowLeftOffset !== arrowLeftOffset; if (newStateAvaliable) { this.setState({ leftOffset: leftOffset, topOffset: topOffset, arrowLeftOffset: arrowLeftOffset, }); } }, renderPopout () { if (!this.props.isOpen) return; const { arrowLeftOffset, leftOffset, topOffset } = this.state; const arrowStyles = arrowLeftOffset ? { left: 0, marginLeft: arrowLeftOffset } : null; return ( <div className="Popout" style={{ left: leftOffset, top: topOffset, width: this.props.width, }} > <span className="Popout__arrow" style={arrowStyles} /> <div className="Popout__inner"> {this.props.children} </div> </div> ); }, renderBlockout () { if (!this.props.isOpen) return; return <div className="blockout" onClick={this.props.onCancel} />; }, render () { return ( <Portal className="Popout-wrapper" ref="portal"> <Transition className="Popout-animation" transitionEnterTimeout={190} transitionLeaveTimeout={190} transitionName="Popout" component="div" > {this.renderPopout()} </Transition> {this.renderBlockout()} </Portal> ); }, }); module.exports = Popout; // expose the child to the top level export module.exports.Header = require('./PopoutHeader'); module.exports.Body = require('./PopoutBody'); module.exports.Footer = require('./PopoutFooter'); module.exports.Pane = require('./PopoutPane');
__tests__/Navbar-test.js
akonwi/bundles
import React from 'react' import {shallow} from 'enzyme' import Navbar from '../src/components/Navbar' import NewBundleInput from '../src/components/NewBundleInput' import EditBundleInput from '../src/components/EditBundleInput' describe("Navbar", () => { const dispatch = new Function const navbar = shallow(<Navbar dispatch={dispatch} isEditing={false}/>) it("renders", () => { expect(navbar.matchesElement( <div> <div></div> <div> <h2>Bundles</h2> </div> <div> <a href='#'>New</a> </div> </div> )).toBe(true) }) describe("when the create button is clicked", () => { beforeAll(() => { navbar.find('#nav-btn').simulate('click') }) it("sets state.isCreating to true", () => expect(navbar.state().isCreating).toBe(true)) it("renders a NewBundleInput", () => { expect(navbar.find(NewBundleInput).props().dispatch).toBe(dispatch) }) it("renders a CancelButton", () => { expect(navbar.find('#nav-btn').text()).toBe('Cancel') }) }) describe("when props.isEditing is true", () => { const toggleEditing = new Function const editProps = { id: 'foo', name: 'Foobar' } it("renders an EditBundleInput", () => { let navbar = shallow(<Navbar dispatch={dispatch} toggleEditing = {toggleEditing} isEditing={true} editProps={editProps}/>) expect(navbar.find(EditBundleInput).props().dispatch).toBe(dispatch) expect(navbar.find(EditBundleInput).props().onComplete).toBe(toggleEditing) expect(navbar.find(EditBundleInput).props().editProps).toBe(editProps) }) }) })
admin/client/App/index.js
joerter/keystone
/** * The App component is the component that is rendered around all views, and * contains common things like navigation, footer, etc. */ import React from 'react'; import Lists from '../utils/ListsByKey'; import MobileNavigation from './components/Navigation/Mobile'; import PrimaryNavigation from './components/Navigation/Primary'; import SecondaryNavigation from './components/Navigation/Secondary'; import Footer from './components/Footer'; const App = (props) => { // If we're on either a list or an item view let currentList, currentSection; if (props.params.listId) { currentList = Lists[props.params.listId]; // Get the current section we're in for the navigation currentSection = Keystone.nav.by.list[currentList.key]; } // Default current section key to dashboard const currentSectionKey = (currentSection && currentSection.key) || 'dashboard'; return ( <div className="keystone-wrapper"> <header className="keystone-header"> <MobileNavigation brand={Keystone.brand} currentListKey={props.params.listId} currentSectionKey={currentSectionKey} sections={Keystone.nav.sections} signoutUrl={Keystone.signoutUrl} /> <PrimaryNavigation currentSectionKey={currentSectionKey} brand={Keystone.brand} sections={Keystone.nav.sections} signoutUrl={Keystone.signoutUrl} /> {/* If a section is open currently, show the secondary nav */} {(currentSection) ? ( <SecondaryNavigation currentListKey={props.params.listId} lists={currentSection.lists} /> ) : null} </header> <div className="keystone-body"> {props.children} </div> <Footer appversion={Keystone.appversion} backUrl={Keystone.backUrl} brand={Keystone.brand} User={Keystone.User} user={Keystone.user} version={Keystone.version} /> </div> ); }; module.exports = App;
src/docs/Components.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Paragraph from 'grommet/components/Paragraph'; import DocsArticle from '../components/DocsArticle'; export default class Components extends Component { render () { return ( <DocsArticle title="Components"> <Paragraph> Whether it's structuring content, controlling interaction, or visualizing data, Grommet provides a wide range of components for a variety of situations. And, all components are fully responsive and accessible. </Paragraph> </DocsArticle> ); } };
test/common/components/App-test.js
LandyCandy/beHeard
import test from 'ava'; import React from 'react'; import { shallow } from 'enzyme'; import App from '../../../src/common/components/App'; test('render with container div', t => { const wrapper = shallow(React.createElement(App)); t.is(wrapper.find('#container').length, 1); });
client/src/components/dashboard/profile/edit-info.js
mikelearning91/seeme-starter
import React, { Component } from 'react'; import Female from '../../../icons/female'; import Male from '../../../icons/male'; import FaBicycle from 'react-icons/lib/fa/bicycle'; import FaBed from 'react-icons/lib/fa/bed'; import FaNewspaperO from 'react-icons/lib/fa/newspaper-o'; import FaMotorcycle from 'react-icons/lib/fa/motorcycle'; import FaBank from 'react-icons/lib/fa/bank'; import FaAutomobile from 'react-icons/lib/fa/automobile'; import FaBriefcase from 'react-icons/lib/fa/briefcase'; import FaPlane from 'react-icons/lib/fa/plane'; import FaLightbulbO from 'react-icons/lib/fa/lightbulb-o'; import FaGavel from 'react-icons/lib/fa/gavel'; import FaPaintBrush from 'react-icons/lib/fa/paint-brush'; import FaCalculator from 'react-icons/lib/fa/calculator'; import FaGraduationCap from 'react-icons/lib/fa/graduation-cap'; import FaCamera from 'react-icons/lib/fa/camera'; import FaMusic from 'react-icons/lib/fa/music'; import FaSpoon from 'react-icons/lib/fa/spoon'; import FaTree from 'react-icons/lib/fa/tree'; import { RadioGroup, Radio } from 'react-radio-group'; const axios = require('axios'), cookie = require('react-cookie'); class EditInfo extends React.Component { constructor (props) { super(props); let user = cookie.load('user'); console.log(user.interests); this.state = { firstName: user.firstName, is_male: user.is_male, seeking_male: user.seeking_male, age: user.age, age_pref_min: user.age_pref_min, age_pref_max: user.age_pref_max, cycling: user.interests.cycling, news: user.interests.news, sleeping: user.interests.sleeping, motorcycles: user.interests.motorcycles, cars: user.interests.cars, photography: user.interests.photography, learning: user.interests.learning, traveling: user.interests.traveling, innovating: user.interests.innovating, art: user.interests.art, music: user.interests.music, cooking: user.interests.cooking, outdoors: user.interests.outdoors } this.handleChange = this.handleChange.bind(this) this.handleRadioIsChange = this.handleRadioIsChange.bind(this); this.handleRadioSeekingChange = this.handleRadioSeekingChange.bind(this); this.handleFormSubmit = this.handleFormSubmit.bind(this); } handleFormSubmit (e) { e.preventDefault(); const user = cookie.load('user'); const emailQuery = user.email; axios.put('https://seemedate.herokuapp.com/api/see/update', { emailQuery: emailQuery, firstName: this.state.firstName, is_male: this.state.is_male, seeking_male: this.state.seeking_male, age: this.state.age, age_pref_min: this.state.age_pref_min, age_pref_max: this.state.age_pref_max, cycling: this.state.cycling, news: this.state.news, sleeping: this.state.sleeping, politics: this.state.politics, motorcycles: this.state.motorcycles, cars: this.state.cars, working: this.state.working, photography: this.state.photography, learning: this.state.learning, traveling: this.state.traveling, innovating: this.state.innovating, law: this.state.law, art: this.state.art, math: this.state.math, school: this.state.school, music: this.state.music, cooking: this.state.cooking, outdoors: this.state.outdoors }, { headers: { Authorization: cookie.load('token') } }) .then((response) => { cookie.save('token', response.data.token, { path: '/' }); cookie.save('user', response.data.user, { path: '/' }); window.location.href = 'https://seemedate.herokuapp.com/my-profile'; }) .catch((error) => { console.log(error); }); } handleRadioIsChange(value) { this.setState({ is_male: value }); } handleRadioSeekingChange(value) { this.setState({ seeking_male: value }); } render () { return ( <div className="edit-info"> <form id="edit-info" onSubmit={this.handleFormSubmit}> <div className="app-section"> <div className="form-section-row"> <span className="form-section-title">The Basics</span> </div> <div className="form-row"> <span className="form-label">Name</span> <input className="form-text" onChange={this.handleChange} name="firstName" type="text" placeholder={this.state.firstName} defaultValue={this.state.firstName} /> </div> <div className="form-row"> <span className="form-label">Age</span> <input className="form-text" onChange={this.handleChange} name="age" type="number" placeholder={this.state.age} defaultValue={this.state.age} /> </div> <div className="form-row"> <span className="form-label">Gender</span> <RadioGroup className="radio-group" name="is_male" is_male={this.state.is_male} onChange={this.handleRadioIsChange}> <Radio id="imale" value="true" defaultChecked={this.state.is_male === true} /><label htmlFor="imale" className="radio-label"><i><Male /></i>Guy</label> <Radio id="ifemale" value="false" defaultChecked={this.state.is_male === false} /><label htmlFor="ifemale" className="radio-label"><i><Female /></i>Girl</label> </RadioGroup> </div> </div> <div className="app-section"> <div className="form-section-row"> <span className="form-section-title">Match Preferences</span> </div> <div className="form-row"> <span className="form-label">Interested In</span> <RadioGroup className="radio-group" name="seeking_male" seeking_male={this.state.seeking_male} onChange={this.handleRadioSeekingChange}> <Radio id="smale" value="true" defaultChecked={this.state.seeking_male === true} /><label htmlFor="smale" className="radio-label"><i><Male /></i>Guy</label> <Radio id="sfemale" value="false" defaultChecked={this.state.seeking_male === false} /><label htmlFor="sfemale" className="radio-label"><i><Female /></i>Girl</label> </RadioGroup> </div> <div className="form-row"> <span className="form-label">Age Range</span> <input onChange={this.handleChange} name="age_pref_min" id="min" className="inline" type="number" placeholder={this.state.age_pref_min} defaultValue={this.state.age_pref_min} /> <span className="inline-label">to</span> <input onChange={this.handleChange} name="age_pref_max" id="max" className="inline" type="number" placeholder={this.state.age_pref_max} defaultValue={this.state.age_pref_max} /> </div> </div> <div className="app-section interests"> <div className="form-section-row"> <span className="form-section-title">The Things I Love</span> </div> <div className="form-col"> <div> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="cycling" name="cycling" defaultChecked={this.state.cycling === true} /><label htmlFor="cycling" className="radio-label"><i><FaBicycle /></i>Cycling</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="sleeping" name="sleeping" defaultChecked={this.state.sleeping === true} /><label htmlFor="sleeping" className="radio-label"><i><FaBed /></i>Sleeping</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="motorcycles" name="motorcycles" defaultChecked={this.state.motorcycles === true} /><label htmlFor="motorcycles" className="radio-label"><i><FaMotorcycle /></i>Motorcycles</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="learning" name="learning" defaultChecked={this.state.learning === true} /><label htmlFor="learning" className="radio-label"><i><FaGraduationCap /></i>Learning</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="traveling" name="traveling" defaultChecked={this.state.traveling === true} /><label htmlFor="traveling" className="radio-label"><i><FaPlane /></i>Traveling</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="innovating" name="innovating" defaultChecked={this.state.innovating === true} /><label htmlFor="innovating" className="radio-label"><i><FaLightbulbO /></i>Innovating</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="photography" name="photography" defaultChecked={this.state.photography === true} /><label htmlFor="photography" className="radio-label"><i><FaCamera /></i>Photography</label> </span> </div> <div> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="cars" name="cars" defaultChecked={this.state.cars === true} /><label htmlFor="cars" className="radio-label"><i><FaAutomobile /></i>Cars</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="news" name="news" defaultChecked={this.state.news === true} /><label htmlFor="news" className="radio-label"><i><FaNewspaperO /></i>News</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="art" name="art" defaultChecked={this.state.art === true} /><label htmlFor="art" className="radio-label"><i><FaPaintBrush /></i>Art</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="music" name="music" defaultChecked={this.state.music === true} /><label htmlFor="music" className="radio-label"><i><FaMusic /></i>Music</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="cooking" name="cooking" defaultChecked={this.state.cooking === true} /><label htmlFor="cooking" className="radio-label"><i><FaSpoon /></i>Cooking</label> </span> <span> <input className="interest-box" onChange={this.handleChange} type="checkbox" id="outdoors" name="outdoors" defaultChecked={this.state.outdoors === true} /><label htmlFor="outdoors" className="radio-label"><i><FaTree /></i>Outdoors</label> </span> </div> </div> </div> <div className="form-row"> <button id="save-profile" type="submit" className="btn btn-lg btn-success">Save Profile Info</button> </div> </form> </div> ); } handleChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; console.log(name, value); this.setState({ [name]: value }); } }; export default EditInfo;
src/icons/LabelIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class LabelIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M35.27 11.69C34.54 10.67 33.35 10 32 10l-22 .02c-2.21 0-4 1.77-4 3.98v20c0 2.21 1.79 3.98 4 3.98L32 38c1.35 0 2.54-.67 3.27-1.69L44 24l-8.73-12.31z"/></svg>;} };
docs/app/Examples/collections/Grid/Types/GridExampleCelledInternally.js
clemensw/stardust
import React from 'react' import { Grid, Image } from 'semantic-ui-react' const GridExampleCelledInternally = () => ( <Grid celled='internally'> <Grid.Row> <Grid.Column width={3}> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column width={10}> <Image src='http://semantic-ui.com/images/wireframe/centered-paragraph.png' /> </Grid.Column> <Grid.Column width={3}> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column width={3}> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> <Grid.Column width={10}> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column width={3}> <Image src='http://semantic-ui.com/images/wireframe/image.png' /> </Grid.Column> </Grid.Row> </Grid> ) export default GridExampleCelledInternally
client/extensions/woocommerce/app/order/order-customer/dialog.js
Automattic/woocommerce-connect-client
/** @format */ /** * External dependencies */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import emailValidator from 'email-validator'; import { find, get, isEmpty, noop } from 'lodash'; import { localize } from 'i18n-calypso'; /** * Internal dependencies */ import AddressView from 'woocommerce/components/address-view'; import { areLocationsLoaded, getAllCountries, } from 'woocommerce/state/sites/data/locations/selectors'; import { areSettingsGeneralLoaded, getStoreLocation, } from 'woocommerce/state/sites/settings/general/selectors'; import Button from 'components/button'; import Dialog from 'components/dialog'; import { fetchLocations } from 'woocommerce/state/sites/data/locations/actions'; import { fetchSettingsGeneral } from 'woocommerce/state/sites/settings/general/actions'; import FormCheckbox from 'components/forms/form-checkbox'; import FormFieldset from 'components/forms/form-fieldset'; import FormInputValidation from 'components/forms/form-input-validation'; import FormLabel from 'components/forms/form-label'; import FormLegend from 'components/forms/form-legend'; import FormPhoneMediaInput from 'components/forms/form-phone-media-input'; import FormTextInput from 'components/forms/form-text-input'; import getAddressViewFormat from 'woocommerce/lib/get-address-view-format'; import getCountries from 'state/selectors/get-countries'; import QueryPaymentCountries from 'components/data/query-countries/payments'; const defaultAddress = { street: '', street2: '', city: '', postcode: '', email: '', first_name: '', last_name: '', phone: '', }; class CustomerAddressDialog extends Component { static propTypes = { address: PropTypes.shape( { address_1: PropTypes.string, address_2: PropTypes.string, city: PropTypes.string, state: PropTypes.string, country: PropTypes.string, postcode: PropTypes.string, email: PropTypes.string, first_name: PropTypes.string, last_name: PropTypes.string, phone: PropTypes.string, } ), areLocationsLoaded: PropTypes.bool, closeDialog: PropTypes.func, countries: PropTypes.arrayOf( PropTypes.shape( { code: PropTypes.string.isRequired, name: PropTypes.string.isRequired, states: PropTypes.arrayOf( PropTypes.shape( { code: PropTypes.string.isRequired, name: PropTypes.string.isRequired, } ) ), } ) ), countriesList: PropTypes.array.isRequired, isBilling: PropTypes.bool, isVisible: PropTypes.bool, siteId: PropTypes.number, updateAddress: PropTypes.func.isRequired, }; static defaultProps = { address: defaultAddress, closeDialog: noop, isBilling: false, isVisible: false, updateAddress: noop, }; state = {}; maybeFetchLocations() { const { siteId } = this.props; if ( siteId && ! this.props.areLocationsLoaded ) { this.props.fetchLocations( siteId ); } } componentDidMount() { this.initializeState(); this.maybeFetchLocations(); } UNSAFE_componentWillMount() { this.fetchData( this.props ); } UNSAFE_componentWillReceiveProps( newProps ) { if ( newProps.siteId !== this.props.siteId ) { this.fetchData( newProps ); } } componentDidUpdate( prevProps ) { // Modal was just opened if ( this.props.isVisible && ! prevProps.isVisible ) { this.initializeState(); } this.maybeFetchLocations(); } initializeState = () => { const { defaultCountry, defaultState } = this.props; const address = { ...defaultAddress, country: defaultCountry, state: defaultState, ...this.props.address, }; this.setState( { address, phoneCountry: address.country || defaultCountry, emailValidMessage: false, } ); }; fetchData = ( { siteId, areSettingsLoaded } ) => { if ( ! siteId ) { return; } if ( ! areSettingsLoaded ) { this.props.fetchSettingsGeneral( siteId ); } }; updateAddress = () => { this.props.updateAddress( this.state.address ); this.props.closeDialog(); }; closeDialog = () => { this.props.closeDialog(); }; onPhoneChange = phone => { this.setState( prevState => { const { address } = prevState; const newState = { ...address, phone: phone.value }; return { address: newState, phoneCountry: phone.countryCode }; } ); }; onChange = event => { const value = event.target.value; let name = event.target.name; if ( 'street' === name ) { name = 'address_1'; } else if ( 'street2' === name ) { name = 'address_2'; } this.setState( prevState => { const { address } = prevState; const newState = { address: { ...address, [ name ]: value } }; // Users of AddressView isEditable must always update the state prop // passed to AddressView in the event of country changes if ( 'country' === name ) { const countryData = find( this.props.countries, { code: value } ); if ( ! isEmpty( countryData.states ) ) { newState.address.state = countryData.states[ 0 ].code; } else { newState.address.state = ''; } } return newState; } ); }; validateEmail = event => { const { translate } = this.props; if ( ! emailValidator.validate( event.target.value ) ) { this.setState( { emailValidMessage: translate( 'Please enter a valid email address.' ), } ); } else { this.setState( { emailValidMessage: false, } ); } }; toggleShipping = () => { this.setState( prevState => { const { address } = prevState; const newState = { ...address, copyToShipping: ! prevState.address.copyToShipping }; return { address: newState }; } ); }; renderBillingFields = () => { const { isBilling, translate } = this.props; const { address, emailValidMessage } = this.state; if ( ! isBilling ) { return null; } return ( <div className="order-customer__billing-fields"> <FormFieldset> <QueryPaymentCountries /> <FormPhoneMediaInput label={ translate( 'Phone Number' ) } onChange={ this.onPhoneChange } countryCode={ this.state.phoneCountry } countriesList={ this.props.countriesList } value={ get( address, 'phone', '' ) } /> </FormFieldset> <FormFieldset> <FormLabel htmlFor="email">{ translate( 'Email address' ) }</FormLabel> <FormTextInput id="email" name="email" value={ get( address, 'email', '' ) } onChange={ this.onChange } onBlur={ this.validateEmail } /> { emailValidMessage && <FormInputValidation text={ emailValidMessage } isError /> } </FormFieldset> <FormFieldset> <FormLabel> <FormCheckbox checked={ get( address, 'copyToShipping', false ) } onChange={ this.toggleShipping } /> <span>{ translate( 'Copy changes to shipping' ) }</span> </FormLabel> </FormFieldset> </div> ); }; render() { const { countries, isBilling, isVisible, translate } = this.props; const { address, emailValidMessage } = this.state; if ( ! address || isEmpty( countries ) ) { return null; } const dialogButtons = [ <Button onClick={ this.closeDialog }>{ translate( 'Close' ) }</Button>, <Button primary onClick={ this.updateAddress } disabled={ !! emailValidMessage }> { translate( 'Save' ) } </Button>, ]; return ( <Dialog isVisible={ isVisible } onClose={ this.closeDialog } className="order-customer__dialog woocommerce" buttons={ dialogButtons } > <FormFieldset> <FormLegend className="order-customer__billing-details"> { isBilling ? translate( 'Billing Details' ) : translate( 'Shipping Details' ) } </FormLegend> <div className="order-customer__fieldset"> <div className="order-customer__field"> <FormLabel htmlFor="first_name">{ translate( 'First Name' ) }</FormLabel> <FormTextInput id="first_name" name="first_name" value={ get( address, 'first_name', '' ) } onChange={ this.onChange } /> </div> <div className="order-customer__field"> <FormLabel htmlFor="last_name">{ translate( 'Last Name' ) }</FormLabel> <FormTextInput id="last_name" name="last_name" value={ get( address, 'last_name', '' ) } onChange={ this.onChange } /> </div> </div> <AddressView address={ getAddressViewFormat( address ) } countries={ countries } isEditable onChange={ this.onChange } /> { this.renderBillingFields() } </FormFieldset> </Dialog> ); } } export default connect( state => { const address = getStoreLocation( state ); const locationsLoaded = areLocationsLoaded( state ); const areSettingsLoaded = areSettingsGeneralLoaded( state ); const countries = getAllCountries( state ); return { areLocationsLoaded: locationsLoaded, areSettingsLoaded, countries, countriesList: getCountries( state, 'payments' ), defaultCountry: address.country, defaultState: address.state, }; }, dispatch => bindActionCreators( { fetchLocations, fetchSettingsGeneral }, dispatch ) )( localize( CustomerAddressDialog ) );
examples/embeds/video.js
ashutoshrishi/slate
import React from 'react' /** * An video embed component. * * @type {Component} */ class Video extends React.Component { /** * When the input text changes, update the `video` data on the node. * * @param {Event} e */ onChange = e => { const video = e.target.value const { node, editor } = this.props editor.change(c => c.setNodeByKey(node.key, { data: { video } })) } /** * When clicks happen in the input, stop propagation so that the void node * itself isn't focused, since that would unfocus the input. * * @type {Event} e */ onClick = e => { e.stopPropagation() } /** * Render. * * @return {Element} */ render() { return ( <div {...this.props.attributes}> {this.renderVideo()} {this.renderInput()} </div> ) } /** * Render the Youtube iframe, responsively. * * @return {Element} */ renderVideo = () => { const { node, isSelected } = this.props const video = node.data.get('video') const wrapperStyle = { position: 'relative', outline: isSelected ? '2px solid blue' : 'none', } const maskStyle = { display: isSelected ? 'none' : 'block', position: 'absolute', top: '0', left: '0', height: '100%', width: '100%', cursor: 'cell', zIndex: 1, } const iframeStyle = { display: 'block', } return ( <div style={wrapperStyle}> <div style={maskStyle} /> <iframe id="ytplayer" type="text/html" width="640" height="476" src={video} frameBorder="0" style={iframeStyle} /> </div> ) } /** * Render the video URL input. * * @return {Element} */ renderInput = () => { const { node } = this.props const video = node.data.get('video') const style = { marginTop: '5px', boxSizing: 'border-box', } return ( <input value={video} onChange={this.onChange} onClick={this.onClick} style={style} /> ) } } /** * Export. */ export default Video
fields/types/color/ColorField.js
snowkeeper/keystone
import { SketchPicker } from 'react-color'; import { css, StyleSheet } from 'aphrodite/no-important'; import Field from '../Field'; import React from 'react'; import { Button, FormInput, InputGroup } from 'elemental'; import transparentSwatch from './transparent-swatch'; import theme from '../../../admin/client/theme'; const ColorField = Field.create({ displayName: 'ColorField', statics: { type: 'Color', }, propTypes: { onChange: React.PropTypes.func, path: React.PropTypes.string, value: React.PropTypes.string, }, getInitialState () { return { displayColorPicker: false, }; }, updateValue (value) { this.props.onChange({ path: this.props.path, value: value, }); }, handleInputChange (event) { var newValue = event.target.value; if (/^([0-9A-F]{3}){1,2}$/.test(newValue)) { newValue = '#' + newValue; } if (newValue === this.props.value) return; this.updateValue(newValue); }, handleClick () { this.setState({ displayColorPicker: !this.state.displayColorPicker }); }, handleClose () { this.setState({ displayColorPicker: false }); }, handlePickerChange (color) { var newValue = color.hex; if (newValue === this.props.value) return; this.updateValue(newValue); }, renderSwatch () { const className = `${css(classes.swatch)} e2e-type-color__swatch`; return (this.props.value) ? ( <span className={className} style={{ backgroundColor: this.props.value }} /> ) : ( <span className={className} dangerouslySetInnerHTML={{ __html: transparentSwatch }} /> ); }, renderField () { const { displayColorPicker } = this.state; const blockoutClassName = `${css(classes.blockout)} e2e-type-color__blockout`; const popoverClassName = `${css(classes.popover)} e2e-type-color__popover`; return ( <div className="e2e-type-color__wrapper" style={{ position: 'relative' }}> <InputGroup> <InputGroup.Section grow> <FormInput autoComplete="off" name={this.getInputName(this.props.path)} onChange={this.valueChanged} ref="field" value={this.props.value} /> </InputGroup.Section> <InputGroup.Section> <Button onClick={this.handleClick} className={`${css(classes.button)} e2e-type-color__button`}> {this.renderSwatch()} </Button> </InputGroup.Section> </InputGroup> {displayColorPicker && ( <div> <div className={blockoutClassName} onClick={this.handleClose} /> <div className={popoverClassName} onClick={e => e.stopPropagation()}> <SketchPicker color={this.props.value} onChangeComplete={this.handlePickerChange} onClose={this.handleClose} /> </div> </div> )} </div> ); }, }); /* eslint quote-props: ["error", "as-needed"] */ const classes = StyleSheet.create({ button: { background: 'white', padding: 4, width: theme.component.height, ':hover': { background: 'white', }, }, blockout: { bottom: 0, left: 0, position: 'fixed', right: 0, top: 0, zIndex: 1, }, popover: { marginTop: 10, position: 'absolute', right: 0, zIndex: 2, }, swatch: { borderRadius: 1, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,0.1)', display: 'block', height: '100%', width: '100%', }, }); module.exports = ColorField;
src/interface/icons/Haste.js
ronaldpereira/WoWAnalyzer
import React from 'react'; const icon = props => ( <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="16 16 32 32" className="icon" {...props}> <path d="M33.446,23.135c-0.89,0-1.612,0.722-1.612,1.612v8.049l-4.079,4.078c-0.63,0.629-0.63,1.65,0,2.28 c0.315,0.314,0.728,0.472,1.14,0.472c0.413,0,0.825-0.157,1.14-0.472l4.551-4.55c0.302-0.302,0.472-0.712,0.472-1.14v-8.716 C35.059,23.856,34.337,23.135,33.446,23.135z M32.111,16.668c-8.509,0-15.431,6.92-15.431,15.427 c0,8.506,6.922,15.426,15.431,15.426c8.509,0,15.431-6.92,15.431-15.426C47.542,23.588,40.62,16.668,32.111,16.668z M19.179,38.606c-1.025-2.031-1.545-4.222-1.545-6.511c0-7.981,6.495-14.473,14.477-14.473v2.097 c-6.826,0-12.379,5.552-12.379,12.376c0,1.959,0.444,3.831,1.32,5.566L19.179,38.606z M32.111,43.516 c-6.3,0-11.426-5.124-11.426-11.422c0-6.298,5.126-11.422,11.426-11.422s11.426,5.124,11.426,11.422 C43.537,38.392,38.411,43.516,32.111,43.516z" /> </svg> ); export default icon;
src/components/Main.js
surce2010/react-webpack-gallery
require('normalize.css/normalize.css'); require('styles/App.css'); require('styles/main.less'); import React from 'react'; import _ from 'lodash'; import classNames from 'classnames'; let CONSTANT = { centerPos: { //中间取值范围 left: 0, top: 0 }, hPosRange: { //水平方向取值范围 leftSecX: [0, 0], rightSecX: [0, 0], y: [0, 0] }, vPosRange: { //垂直方向取值范围 x: [0, 0], topY: [0, 0] } }; // 获取图片相关的数组 var imagesData = require('../data/imagesData.json'); // 利用自执行函数, 将图片名信息转成图片URL路径信息 imagesData = ((imagesDataArr) => { for (let i = 0, j = imagesDataArr.length; i < j; i++) { let singleImageData = imagesDataArr[i]; singleImageData.imageURL = require('../images/' + singleImageData.fileName); imagesDataArr[i] = singleImageData; } return imagesDataArr; })(imagesData); //图片组件 class ImageFigure extends React.Component { render() { let me = this, props = me.props, imgArrange = _.get(props, 'imgArrange'), styleObj = {}; _.set(styleObj, 'left', _.get(imgArrange, 'pos.left')); _.set(styleObj, 'top', _.get(imgArrange, 'pos.top')); _.get(imgArrange, 'rotate') && _.map(['Webkit', 'O', 'ms', 'Moz', 'Khtml'], (item) => { return styleObj[item + 'Transform'] = 'rotate(' + _.get(imgArrange, 'rotate') + 'deg)'; }); _.get(imgArrange, 'isCenter') && _.set(styleObj, 'zIndex', '101'); return ( <figure className={classNames('img-figure', {'is-inverse': _.get(imgArrange, 'isInverse')})} onClick={me.props.changeCenterIndex} ref={(c) => {this.figure = c}} style={styleObj} > <img src={_.get(props, 'imagesData.imageURL')} /> <figcaption className="img-title">{_.get(props, 'imagesData.fileName')}</figcaption> <div className='text'>{_.get(props, 'imagesData.desc')}</div> </figure> ); } } //控制组件 class ControllerUnit extends React.Component { constructor(props) { super(props); } render() { let me = this, props = me.props, imgArrange = _.get(props, 'imgArrange'); return ( <span className={classNames('controller-unit', {'is-center': _.get(imgArrange, 'isCenter')}, {'is-inverse': _.get(imgArrange, 'isInverse')})} onClick={me.props.changeCenterIndex} > </span> ); } } //舞台 class AppComponent extends React.Component { constructor(props) { super(props); this.state = { imgsArrangeArr: [{ pos: { //位置 left: '', top: '' }, rotate: '', //旋转角度 isInverse: false, //是否正面 isCenter: false //是否居中 }] }; } render() { let me = this, state = me.state, imgFiguresJSX = [], controllerUnits = []; _.map(imagesData, function (item, index) { if (!_.get(state, ['imgsArrangeArr', index])) { _.set(state, ['imgsArrangeArr', index], { pos: { left:0, top:0 }, rotate: 0, isInverse: false, isCenter: false }); } imgFiguresJSX.push( <ImageFigure key={'imgFigure'+index} imagesData={item} ref={'imgFigure' + index} changeCenterIndex={me.handleChangeCenterIndex.bind(me, index)} imgArrange={_.get(state, ['imgsArrangeArr', index])} /> ); controllerUnits.push( <ControllerUnit key={'controllerUnit'+index} imagesData={item} ref={'controllerUnit' + index} changeCenterIndex={me.handleChangeCenterIndex.bind(me, index)} imgArrange={_.get(state, ['imgsArrangeArr', index])} /> ); }.bind(me)); return ( <section className="stage" ref="stage"> <section className="img-sec"> {imgFiguresJSX} </section> <nav className="controller-nav"> {controllerUnits} </nav> </section> ); } //组件加载以后,为每一个图片计算位置取值区间 componentDidMount() { let me = this; //舞台大小 let stageDOM = me.refs.stage, stageW = stageDOM.scrollWidth, stageH = stageDOM.scrollHeight, halfStageW = Math.ceil(stageW / 2), halfStageH = Math.ceil(stageH / 2); //单个图片组件大小 let imgFigureDOM = me.refs.imgFigure0.figure, imgW = imgFigureDOM.scrollWidth, imgH = imgFigureDOM.scrollHeight, halfImgW = Math.ceil(imgW / 2), halfImgH = Math.ceil(imgH / 2); //计算中心图片的位置点 _.set(CONSTANT, 'centerPos.left', halfStageW - halfImgW); _.set(CONSTANT, 'centerPos.top', halfStageH - halfImgH); //计算左侧,右侧图片位置取值区间 _.set(CONSTANT, 'hPosRange.leftSecX', [-halfImgW, halfStageW - halfImgW * 3]); _.set(CONSTANT, 'hPosRange.rightSecX', [halfStageW + halfImgW, stageW - halfImgW]); _.set(CONSTANT, 'hPosRange.y', [-halfImgH, halfStageH - halfImgH]); //计算上侧图片位置取值区间 _.set(CONSTANT, 'vPosRange.x', [halfStageW - halfImgW, halfStageW]); _.set(CONSTANT, 'vPosRange.topY', [-halfImgH, halfStageH - halfImgH * 3]); me.hanlderLayoutPicture(2); } /** * 计算随机数 * @param low, high取值区间的端点值 */ calcRandomNumber (low, high) { return Math.floor(Math.random() * (high - low) + low); } /** * 旋转随机角度 * return 随机输出正负30Deg */ rotateRandomDeg () { return (Math.random() > 0.5 ? '-' : '') + Math.ceil(Math.random() * 30); } /** * 切换居中图片 * @param index 居中图片索引值 * 如果点击的图片不为居中图片,则居中;反之,则翻转; */ handleChangeCenterIndex (index) { let me = this, { state } = me, imgsArrangeArr = _.get(state, 'imgsArrangeArr'); let centerIndex = _.findIndex(imgsArrangeArr, (item) => { return item.isCenter === true; }); if (centerIndex === index) { if (_.get(imgsArrangeArr, [index, 'isInverse'])) { _.set(imgsArrangeArr, [index, 'isInverse'], false); } else { _.set(imgsArrangeArr, [index, 'isInverse'], true); } me.setState({ imgsArrangeArr: imgsArrangeArr }); } else { me.hanlderLayoutPicture(index); } } /** * 重新布局图片 * @param centerIndex 居中图片索引 */ hanlderLayoutPicture (centerIndex) { let me = this, state = me.state, imgsArrangeArr = _.get(state, 'imgsArrangeArr'); imgsArrangeArr.splice(centerIndex, 1); if (imgsArrangeArr.length > 0) { let topIndex = Math.floor(Math.random() * (imgsArrangeArr.length - 1)); imgsArrangeArr.splice(topIndex, 1); //重绘左,右侧图片 if (imgsArrangeArr.length) { let l = imgsArrangeArr.length; for (let i = 0, j = Math.floor(l / 2); i < j, j < l; i++, j++) { imgsArrangeArr[i] = { pos: { left: me.calcRandomNumber(_.get(CONSTANT, ['hPosRange', 'leftSecX', 0]), _.get(CONSTANT, ['hPosRange', 'leftSecX', 1])), top: me.calcRandomNumber(_.get(CONSTANT, ['hPosRange', 'y', 0]), _.get(CONSTANT, ['hPosRange', 'y', 1])) }, rotate: me.rotateRandomDeg() }; imgsArrangeArr[j] = { pos:{ left: me.calcRandomNumber(_.get(CONSTANT, ['hPosRange', 'rightSecX', 0]), _.get(CONSTANT, ['hPosRange', 'rightSecX', 1])), top: me.calcRandomNumber(_.get(CONSTANT, ['hPosRange', 'y', 0]), _.get(CONSTANT, ['hPosRange', 'y', 1])) }, rotate: me.rotateRandomDeg() }; } } imgsArrangeArr.splice(topIndex, 0, { pos: { left: me.calcRandomNumber(_.get(CONSTANT, ['vPosRange', 'x', 0]), _.get(CONSTANT, ['vPosRange', 'x', 1])), top: me.calcRandomNumber(_.get(CONSTANT, ['vPosRange', 'topY', 0]), _.get(CONSTANT, ['vPosRange', 'topY', 1])) }, rotate: me.rotateRandomDeg() }); } imgsArrangeArr.splice(centerIndex, 0, { pos: _.get(CONSTANT, 'centerPos'), isCenter: true }); me.setState({ imgsArrangeArr: imgsArrangeArr }, () => { console.log(state, 'imgsArrangeArr'); }); } } AppComponent.defaultProps = { }; export default AppComponent;
src/modules/pages/Header.js
lenxeon/react
require('../../css/header.less') import React from 'react'; import SearchBox from './SearchBox'; import {Link} from 'react-router'; var {createActiveRouteComponent} = require('./NavLink'); var NavLink = createActiveRouteComponent('li'); class Header extends React.Component { constructor(props, context){ super(props); context.router // will work } // contextTypes: { // router: React.PropTypes.object, // } state: { focus: false, value: '智能搜索...', } render(){ // console.log(this.context); return( <div id="header" className="fadeInDown"> <div className="home-menu pure-menu pure-menu-horizontal pure-menu-fixed clear"> <a className="pure-menu-heading" href="#"><i className="fa fa-xing"></i>workin.me</a> <ul className="pure-menu-list left-menus"> <NavLink to="/feeds" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-commenting-o mr-5"></i>动态 </NavLink> <NavLink to="/tasks" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-list mr-5"></i>任务 </NavLink> <NavLink to="/calendar" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-calendar mr-5"></i>日程 </NavLink> <NavLink to="/portals" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-coffee mr-5"></i>知识 </NavLink> <NavLink to="/org" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-sitemap mr-5"></i>组织 </NavLink> <li className="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <span className="pure-menu-link more">更多</span> <ul className="pure-menu-children"> <NavLink to="/hr" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-calendar-check-o mr-5"></i>考勤 </NavLink> <NavLink to="/skydrive" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa-cloud-upload mr-5"></i>网盘 </NavLink> <NavLink to="/crm" activeClassName="pure-menu-selected" className="pure-menu-item"> <i className="fa fa fa-user-secret mr-5"></i>客户 </NavLink> </ul> </li> </ul> <ul className="pure-menu-list right-menus rgt"> <li className="pure-menu-item pure-menu-has-children pure-menu-allow-hover user"> <span className="avatar"> <img src="https://dn-mdpic.qbox.me/UserAvatar/default.gif?imageView2/1/w/48/h/48/q/90" alt="头像" /> </span> <span className="name">冷馨</span> <ul className="pure-menu-children"> <li className="pure-menu-item"><a href="#" className="pure-menu-link">考勤</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">网盘</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">客户</a></li> </ul> </li> <li className="pure-menu-item pure-menu-has-children pure-menu-allow-hover message"> <i className="fa fa-bell"></i> <ul className="pure-menu-children"> <li className="pure-menu-item"><a href="#" className="pure-menu-link">考勤</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">网盘</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">客户</a></li> </ul> </li> <li className="pure-menu-item pure-menu-has-children pure-menu-allow-hover"> <span className="pure-menu-link more">新建</span> <ul className="pure-menu-children"> <li className="pure-menu-item"><a href="#" className="pure-menu-link">考勤</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">网盘</a></li> <li className="pure-menu-item"><a href="#" className="pure-menu-link">客户</a></li> </ul> </li> <li className="pure-menu-item search-box"> <SearchBox/> </li> </ul> </div> </div> ) } }; // Header.contextTypes = { // router: React.PropTypes.object.isRequired // }; export default Header;
src/modules/editor/components/popovers/tooltip/TooltipLIMC/TooltipLIMC.js
CtrHellenicStudies/Commentary
import React from 'react' import autoBind from 'react-autobind'; import { connect } from 'react-redux'; // redux import editorActions from '../../../../actions'; // component import TooltipItemButton from '../TooltipItemButton'; class TooltipLIMC extends React.Component { constructor(props) { super(props); autoBind(this); } async promptForLIMC(e) { e.preventDefault(); const { setTooltip, tooltip } = this.props; await setTooltip({ ...tooltip, mode: 'limc' }); } isActive() { const { editorState } = this.props; if (!editorState) { return null; } let selection = editorState.getSelection(); let activeBlockType = editorState .getCurrentContent() .getBlockForKey(selection.getStartKey()) .getType(); return 'LIMC' === activeBlockType; } render() { return ( <TooltipItemButton className={`${this.isActive() ? 'active' : ''}`} onClick={this.promptForLIMC} > LIMC </TooltipItemButton> ); } } const mapStateToProps = state => ({ ...state.editor, }); const mapDispatchToProps = dispatch => ({ setTooltip: (tooltip) => { dispatch(editorActions.setTooltip(tooltip)); }, }); export default connect( mapStateToProps, mapDispatchToProps, )(TooltipLIMC);
app/components/Store/Routes/CategoriesRoute/index.js
VineRelay/VineRelayStore
import React from 'react'; import PropTypes from 'prop-types'; import { QueryRenderer, graphql } from 'react-relay'; import relayEnvironment from 'app/config/relay'; import PageError from 'app/components/Common/PageError'; import PageLoader from 'app/components/Common/PageLoader'; import StoreLayout from 'app/components/Store/Main/StoreLayout'; import CategoriesGrid from 'app/components/Store/Category/CategoriesGrid'; import Paper from 'app/components/Store/Main/Paper'; const CategoriesRoute = ({ categories, history, notifier, viewer, }) => ( <StoreLayout notifier={notifier} viewer={viewer} > <Paper paddings={['top', 'bottom', 'left', 'right']}> <h1>Shop By Categories</h1> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.</p> </Paper> <Paper paddings={['bottom', 'left', 'right']}> <CategoriesGrid categories={categories} onCategoryClick={(id) => history.push(`category/${id}`)} /> </Paper> </StoreLayout> ); CategoriesRoute.propTypes = { viewer: PropTypes.object.isRequired, notifier: PropTypes.object.isRequired, history: PropTypes.object.isRequired, categories: PropTypes.object.isRequired, }; export default (props) => ( <QueryRenderer environment={relayEnvironment} query={graphql` query CategoriesRouteQuery { categories { ...CategoriesGrid_categories } notifier { ...StoreLayout_notifier } viewer { ...StoreLayout_viewer } } `} render={({ error, props: relayProps }) => { if (error) { return <PageError error={error} />; } if (relayProps) { return <CategoriesRoute {...relayProps} {...props} />; } return <PageLoader />; }} /> );