path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/Pagination.js
adampickeral/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import PaginationButton from './PaginationButton'; import CustomPropTypes from './utils/CustomPropTypes'; import SafeAnchor from './SafeAnchor'; const Pagination = React.createClass({ mixins: [BootstrapMixin], propTypes: { activePage: React.PropTypes.number, items: React.PropTypes.number, maxButtons: React.PropTypes.number, ellipsis: React.PropTypes.bool, first: React.PropTypes.bool, last: React.PropTypes.bool, prev: React.PropTypes.bool, next: React.PropTypes.bool, onSelect: React.PropTypes.func, /** * You can use a custom element for the buttons */ buttonComponentClass: CustomPropTypes.elementType }, getDefaultProps() { return { activePage: 1, items: 1, maxButtons: 0, first: false, last: false, prev: false, next: false, ellipsis: true, buttonComponentClass: SafeAnchor, bsClass: 'pagination' }; }, renderPageButtons() { let pageButtons = []; let startPage, endPage, hasHiddenPagesAfter; let { maxButtons, activePage, items, onSelect, ellipsis, buttonComponentClass } = this.props; if(maxButtons){ let hiddenPagesBefore = activePage - parseInt(maxButtons / 2, 10); startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1; hasHiddenPagesAfter = startPage + maxButtons <= items; if(!hasHiddenPagesAfter){ endPage = items; startPage = items - maxButtons + 1; if(startPage < 1){ startPage = 1; } } else { endPage = startPage + maxButtons - 1; } } else { startPage = 1; endPage = items; } for(let pagenumber = startPage; pagenumber <= endPage; pagenumber++){ pageButtons.push( <PaginationButton key={pagenumber} eventKey={pagenumber} active={pagenumber === activePage} onSelect={onSelect} buttonComponentClass={buttonComponentClass}> {pagenumber} </PaginationButton> ); } if(maxButtons && hasHiddenPagesAfter && ellipsis){ pageButtons.push( <PaginationButton key='ellipsis' disabled buttonComponentClass={buttonComponentClass}> <span aria-label='More'>...</span> </PaginationButton> ); } return pageButtons; }, renderPrev() { if(!this.props.prev){ return null; } return ( <PaginationButton key='prev' eventKey={this.props.activePage - 1} disabled={this.props.activePage === 1} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Previous'>&lsaquo;</span> </PaginationButton> ); }, renderNext() { if(!this.props.next){ return null; } return ( <PaginationButton key='next' eventKey={this.props.activePage + 1} disabled={this.props.activePage >= this.props.items} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Next'>&rsaquo;</span> </PaginationButton> ); }, renderFirst() { if(!this.props.first){ return null; } return ( <PaginationButton key='first' eventKey={1} disabled={this.props.activePage === 1 } onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='First'>&laquo;</span> </PaginationButton> ); }, renderLast() { if(!this.props.last){ return null; } return ( <PaginationButton key='last' eventKey={this.props.items} disabled={this.props.activePage >= this.props.items} onSelect={this.props.onSelect} buttonComponentClass={this.props.buttonComponentClass}> <span aria-label='Last'>&raquo;</span> </PaginationButton> ); }, render() { return ( <ul {...this.props} className={classNames(this.props.className, this.getBsClassSet())}> {this.renderFirst()} {this.renderPrev()} {this.renderPageButtons()} {this.renderNext()} {this.renderLast()} </ul> ); } }); export default Pagination;
archimate-frontend/src/main/javascript/components/view/nodes/model_m/outcome.js
zhuj/mentha-web-archimate
import React from 'react' import { BaseMotivationWidget } from './_base' export const TYPE='outcome'; export class OutcomeWidget extends BaseMotivationWidget { getClassName(node) { return 'a-node model_m outcome'; } }
src/components/Modal.js
Minishlink/DailyScrum
// @flow import React, { Component } from 'react'; import { StyleSheet, View, Modal as RCTModal, TouchableWithoutFeedback } from 'react-native'; export default class Modal extends Component<Props> { // FUTURE remove shouldComponentUpdate if children can change shouldComponentUpdate(nextProps: Props) { return nextProps.visible !== this.props.visible; } render() { const { onRequestClose, visible, children, backgroundStyle, ...rest } = this.props; return ( <RCTModal animationType="fade" transparent visible={visible} onRequestClose={onRequestClose} {...rest}> <TouchableWithoutFeedback onPress={onRequestClose}> <View style={[styles.background, backgroundStyle]} /> </TouchableWithoutFeedback> {children} </RCTModal> ); } } type Props = { onRequestClose: Function, visible: boolean, children?: any, style: any, backgroundStyle: any, }; const styles = StyleSheet.create({ background: { flex: 1, backgroundColor: 'black', opacity: 0.8, }, });
web/src/components/Footer.js
MauriceMahan/FocusOverlay
import React from 'react'; import { Link } from 'gatsby'; const Footer = props => ( <footer id="footer"> <section> <h2>Aliquam sed mauris</h2> <p> Sed lorem ipsum dolor sit amet et nullam consequat feugiat consequat magna adipiscing tempus etiam dolore veroeros. eget dapibus mauris. Cras aliquet, nisl ut viverra sollicitudin, ligula erat egestas velit, vitae tincidunt odio. </p> <ul className="actions"> <li> <Link to="/generic" className="button"> Learn More </Link> </li> </ul> </section> <section> <h2>Etiam feugiat</h2> <dl className="alt"> <dt>Address</dt> <dd>1234 Somewhere Road &bull; Nashville, TN 00000 &bull; USA</dd> <dt>Phone</dt> <dd>(000) 000-0000 x 0000</dd> <dt>Email</dt> <dd> <a href="#">[email protected]</a> </dd> </dl> <ul className="icons"> <li> <a href="#" className="icon fa-twitter alt"> <span className="label">Twitter</span> </a> </li> <li> <a href="#" className="icon fa-facebook alt"> <span className="label">Facebook</span> </a> </li> <li> <a href="#" className="icon fa-instagram alt"> <span className="label">Instagram</span> </a> </li> <li> <a href="#" className="icon fa-github alt"> <span className="label">GitHub</span> </a> </li> <li> <a href="#" className="icon fa-dribbble alt"> <span className="label">Dribbble</span> </a> </li> </ul> </section> <p className="copyright"> &copy; Untitled. Design: <a href="https://html5up.net">HTML5 UP</a>. </p> </footer> ); export default Footer;
src/pages/Home.js
mtomcal/reactjs-hooligans-tv
import React, { Component } from 'react'; import { Jumbotron, Button } from 'react-bootstrap'; import Player from '../player'; import { Containers } from '../data'; import { Card } from '../cards'; import {api_url} from '../config.js'; var Home = React.createClass({ propTypes: { queryData: React.PropTypes.object.isRequired }, render() { var style = {}; const videos = this.props.queryData.data.map(function (res, index) { return (<div className="col-lg-4"> <Player key={index} source={res.snippet.resourceId.videoId} title={res.snippet.title} autoplay={true} imageURL={res.snippet.thumbnails.high.url} /> </div>); }); const offense = videos.filter((item, index) => { return index < 6; }); const defense = videos.filter((item, index) => { return index >= 6 && index < 12; }); return ( <div> <div className="container-fluid" style={style}> <div className="row"> <div className="col-lg-12"> <Card title="Home" /> </div> </div> <div className="row"> <div className="col-lg-6"> <Card title="Offense"> {offense} </Card> </div> <div className="col-lg-6"> <Card title="Defense"> {defense} </Card> </div> </div> <div className="row"> <div className="col-lg-6"> <Card title="Offense"> {offense} </Card> </div> <div className="col-lg-6"> <Card title="Defense"> {defense} </Card> </div> </div> </div> </div> ); } }); export default Containers.query.createContainer(Home, { method: 'get', route: api_url + '/videos', })
src/routes/login/index.js
cineindustria/site
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Login from './Login'; const title = 'Log In'; export default { path: '/login', action() { return { title, component: <Layout><Login title={title} /></Layout>, }; }, };
docs/src/app/components/pages/components/Avatar/ExampleSimple.js
igorbt/material-ui
import React from 'react'; import Avatar from 'material-ui/Avatar'; import FileFolder from 'material-ui/svg-icons/file/folder'; import FontIcon from 'material-ui/FontIcon'; import List from 'material-ui/List/List'; import ListItem from 'material-ui/List/ListItem'; import { blue300, indigo900, orange200, deepOrange300, pink400, purple500, } from 'material-ui/styles/colors'; const style = {margin: 5}; /** * Examples of `Avatar` using an image, [Font Icon](/#/components/font-icon), [SVG Icon](/#/components/svg-icon) * and "Letter" (string), with and without custom colors at the default size (`40dp`) and an alternate size (`30dp`). */ const AvatarExampleSimple = () => ( <List> <ListItem disabled={true} leftAvatar={ <Avatar src="images/uxceo-128.jpg" /> } > Image Avatar </ListItem> <ListItem disabled={true} leftAvatar={ <Avatar src="images/uxceo-128.jpg" size={30} style={style} /> } > Image Avatar with custom size </ListItem> <ListItem disabled={true} leftAvatar={ <Avatar icon={<FontIcon className="muidocs-icon-communication-voicemail" />} /> } > FontIcon Avatar </ListItem> <ListItem disabled={true} leftAvatar={ <Avatar icon={<FontIcon className="muidocs-icon-communication-voicemail" />} color={blue300} backgroundColor={indigo900} size={30} style={style} /> } > FontIcon Avatar with custom colors and size </ListItem> <ListItem disabled={true} leftAvatar={ <Avatar icon={<FileFolder />} /> } > SvgIcon Avatar </ListItem> <ListItem disabled={true} leftAvatar={ <Avatar icon={<FileFolder />} color={orange200} backgroundColor={pink400} size={30} style={style} /> } > SvgIcon Avatar with custom colors and size </ListItem> <ListItem disabled={true} leftAvatar={<Avatar>A</Avatar>} > Letter Avatar </ListItem> <ListItem disabled={true} leftAvatar={ <Avatar color={deepOrange300} backgroundColor={purple500} size={30} style={style} > A </Avatar> } > Letter Avatar with custom colors and size </ListItem> </List> ); export default AvatarExampleSimple;
examples/js/column/column-title-table.js
echaouchna/react-bootstrap-tab
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class ColumnAlignTable extends React.Component { render() { return ( <BootstrapTable data={ products }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' headerTitle={ false } columnTitle={ true }>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price' columnTitle={ true }>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/routes/index.js
hirako2000/react-hackathon-board
import React from 'react'; import { Route } from 'react-router'; // NOTE: here we're making use of the `resolve.root` configuration // option in webpack, which allows us to specify import paths as if // they were from the root of the ~/src directory. This makes it // very easy to navigate to files regardless of how deeply nested // your current file is. import CoreLayout from 'layouts/CoreLayout/CoreLayout'; import LoginView from 'views/LoginView/LoginView'; import SignupView from 'views/LoginView/SignupView'; import ProfileView from 'views/ProfileView/ProfileView'; import HackathonsView from 'views/HackathonsView/HackathonsView'; import HackathonView from 'views/HackathonsView/HackathonView'; import EditHackathonView from 'views/HackathonsView/EditHackathonView'; import HacksView from 'views/HacksView/HacksView'; import MyHacksView from 'views/HacksView/MyHacksView'; import UserHacksView from 'views/HacksView/UserHacksView'; import NominatedView from 'views/HacksView/NominatedView'; import HackView from 'views/HacksView/HackView'; import EditHackView from 'views/HacksView/EditHackView'; import UsersView from 'views/UsersView/UsersView'; import UserView from 'views/UsersView/UserView'; import RulesView from 'views/HackathonsView/RulesView'; import PrizesView from 'views/HackathonsView/PrizesView'; import BeautifierView from 'views/BeautifierView/BeautifierView'; export default (store) => ( <Route component={CoreLayout}> <Route name='login' path='/login' component={LoginView} /> <Route name='signup' path='/signup' component={SignupView} /> <Route name='profile' path='/profile' component={ProfileView} /> <Route name='home' path='/' component={HacksView} /> <Route name='hackathons' path='/hackathons' component={HackathonsView} /> <Route name='editHackathon' path='/hackathons/edit/:id' component={EditHackathonView} /> <Route name='hackathon' path='/hackathons/:id' component={HackathonView} /> <Route name='createHackathon' path='/hackathons/create/new/' component={EditHackathonView} /> <Route name='hacks' path='/hacks' component={HacksView} /> <Route name='myHacks' path='/hacks/my' component={MyHacksView} /> <Route name='userHacks' path='/hacks/user/:id' component={UserHacksView} /> <Route name='judging' path='/judging' component={NominatedView} /> <Route name='hack' path="/hacks"> <Route path=":id" component={HackView}/> </Route> <Route name='editHack' path='/hacks/edit/:id' component={EditHackView} /> <Route name='createHack' path='/hacks/create/new/' component={EditHackView} /> <Route name='people' path='/people' component={UsersView} /> <Route name='otherUser' path='/people/:id' component={UserView} /> <Route name='rules' path='/rules' component={RulesView} /> <Route name='prizes' path='/prizes' component={PrizesView} /> <Route name='beautifier' path='/beautifier' component={BeautifierView} /> </Route> );
docs/src/pages/style/TypographyTheme.js
AndriusBil/material-ui
// @flow weak import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; const styles = theme => ({ root: theme.typography.button, }); function TypograpghyTheme(props) { return <div className={props.classes.root}>{'This div looks like a button.'}</div>; } TypograpghyTheme.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(TypograpghyTheme);
src/react/jsx/样式.js
huangming1994/react-tutorial
import React from 'react' import ReactDOM from 'react-dom' const h1Style = { color: red } ReactDOM.render( <h1 style={h1Style}>Hello World</h1>, document.getElementById('root') )
src/lib/components/Example.js
thepixelninja/react-component-test
import React from 'react'; import './Example.scss'; const Example = () => ( <div className="Example"> <h1 className="Example-text">Create React Libraries</h1> </div> ); export default Example;
packages/react-scripts/fixtures/kitchensink/src/features/webpack/CssInclusion.js
IamJoseph/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React from 'react'; import './assets/style.css'; export default () => <p id="feature-css-inclusion">We love useless text.</p>;
src/core/requireAuth.js
yanivefraim/mobile-device-manager
import React from 'react'; import auth from './auth'; var requireAuth = (Component) => { return class Authenticated extends React.Component { static willTransitionTo(transition) {debugger; if (!auth.loggedIn()) { transition.redirect('/login', {}, {'nextPath' : transition.path}); } } render () { return <Component {...this.props}/> } } }; export default requireAuth;
docs/app/Examples/modules/Popup/Usage/PopupExampleControlled.js
vageeshb/Semantic-UI-React
import React from 'react' import { Button, Grid, Header, Popup } from 'semantic-ui-react' const timeoutLength = 2500 class PopupExampleControlled extends React.Component { state = { isOpen: false } handleOpen = () => { this.setState({ isOpen: true }) this.timeout = setTimeout(() => { this.setState({ isOpen: false }) }, timeoutLength) } handleClose = () => { this.setState({ isOpen: false }) clearTimeout(this.timeout) } render() { return ( <Grid> <Grid.Column width={8}> <Popup trigger={<Button content='Open controlled popup' />} content={`This message will self-destruct in ${timeoutLength / 1000} seconds!`} on='click' open={this.state.isOpen} onClose={this.handleClose} onOpen={this.handleOpen} positioning='top right' /> </Grid.Column> <Grid.Column width={8}> <Header>State</Header> <pre>{JSON.stringify(this.state, null, 2)}</pre> </Grid.Column> </Grid> ) } } export default PopupExampleControlled
src/js/ui/components/welcome/footerBar.js
hiddentao/heartnotes
import React from 'react'; import Icon from '../icon'; import ExternalLink from '../externalLink'; import Loading from '../loading'; import { connectRedux, routing } from '../../helpers/decorators'; import Footer from '../footer'; class Component extends React.Component { constructor() { super(); } render() { let { app } = this.props.data; let newVersionMsg = null; if (app.newVersionAvailable) { newVersionMsg = ( <ExternalLink href={app.downloadLink}>new version available!</ExternalLink> ); } else if (app.checkingForUpdate.inProgress) { newVersionMsg = ( <Loading /> ); } return ( <Footer className="welcome-footer-bar"> <div className="meta"> <span className="version"> <span className="new-version">{newVersionMsg}</span> v{this.props.data.app.version} </span> <span className="home"> <ExternalLink href="https://heartnotes.me"><Icon name="home" /></ExternalLink> </span> </div> </Footer> ); } } module.exports = connectRedux()(routing()(Component));
src/components/mobile/AdOne/AdOne.js
pppp22591558/ChinaPromotion
import React, { Component } from 'react'; import reactDOM from 'react-dom'; import styles from './AdOne.css'; import withStyles from '../../../decorators/withStyles'; import Modal from '../Modal'; import { get as getContent } from '../../../constants/ABTest'; @withStyles(styles) class AdOne extends Component{ constructor(){ super(); this.handleClick = this.handleClick.bind(this); this.addScale = this.addScale.bind(this); this.removeScale = this.removeScale.bind(this); this.showModal = this.showModal.bind(this); this.hideModal = this.hideModal.bind(this); } static propTypes = { next: React.PropTypes.func.isRequired } state = { isModalActive: false, modalType: '', os: null } componentWillUpdate(nextProps, nextState) { if (nextProps.active) { TweenMax.fromTo(this.header, 0.4, {top: -40, color: '#69D6D8'}, {top: 0, color: 'white'}); this.tl.to(this.icon1, 0.2, {WebkitTransform: 'translateY(0%)'}) .to(this.icon2, 0.2, {WebkitTransform: 'translateY(0%)'}); } else { TweenMax.fromTo(this.header, 0.4, {top: -40, color: '#69D6D8'}, {top: 0, color: 'white', reversed: true}); this.tl.to(this.icon1, 0, {WebkitTransform: 'translateY(300%)'}) .to(this.icon2, 0, {WebkitTransform: 'translateY(300%)'}); } } componentDidMount() { const land = reactDOM.findDOMNode(this.refs.land); const mark = reactDOM.findDOMNode(this.refs.mark); this.header = reactDOM.findDOMNode(this.refs.header); this.icon1 = reactDOM.findDOMNode(this.refs.icon1); this.icon2 = reactDOM.findDOMNode(this.refs.icon2); TweenMax.to(mark, 0.5, {top: '34%' ,yoyo: true, repeat: -1}); this.tl = new TimelineMax(); } handleClick(){ this.props.next(); } addScale(e){ TweenMax.to(e.target, 0, {WebkitTransform: 'scale(1.2)'}); } removeScale(e){ TweenMax.to(e.target, 0, {WebkitTransform: 'scale(1)'}); } showModal(type){ let downloadType = type; // this.setState({isModalActive: true, modalType: downloadType}); //send the download data to GA ga('send', { hitType: 'event', eventCategory: 'Download', eventAction: 'click the icon', eventLabel: downloadType }); } hideModal(){ this.setState({isModalActive: false}); } getAndroidDownloadLink() { const { version } = this.props return version == 'us'? 'https://play.google.com/store/apps/details?id=com.boniotw.global.pagamo' : '/download' } render(){ let styles = { header: { position: 'relative', color: '#69D6D8', top: -40 }, land: { width: '100%' }, mark: { width: '15%', zIndex: 1, position: 'absolute', display: 'block', top: '40%', left: '45%' } }; const { version } = this.props const content = getContent(version).scene1 const { header_1, header_2, subtitle, long_press, other_browsers, switch_version } = content let img_type; if (version === 'us'){ img_type = '_us'; } else if (version === 'tw'){ img_type = '_tw' } else { img_type = ''; } const { isModalActive } = this.state const { os, ua, isWx } = this.props return( <div className="AdOne"> <div className="AdOne-header" ref="header" style={styles.header}> <img className="palm palm-left" alt={header_1} src={require('./palm-left.png')}></img> <img className="palm palm-right" src={require('./palm-right.png')} alt={header_2}></img> <h2 className={`${version}`}>{header_1}<br/>{header_2}<br/></h2> <h3 dangerouslySetInnerHTML={{ __html: subtitle }} /> </div> <div className="view"> <img ref="land" onClick={this.handleClick} style={styles.land} src={require('./land-08.png')} alt={subtitle}></img> <img ref="mark" onClick={this.handleClick} style={styles.mark} src={require('./mark-08.png')}></img> <div className={`download ${version}`}> <a href={`/ios-download?version=${version}`} className={`ios ${(os != 'AndroidOS') && 'active'}`} data-download="ios"> <img ref="icon1" src={isWx? require('./ios_qr_code.png') : require('./apple' + img_type + '.png')} data-download="ios"/> { isWx && <span className="long-press">{long_press}</span> } </a> <a href={this.getAndroidDownloadLink()} className={`android ${(os != 'iOS' || version == 'us') && 'active'}`} data-download="android"> <img ref="icon2" src={require('./android' + img_type + '.png')} data-download="android"/> { isWx && <span className="other-browsers">{other_browsers}</span> } </a> <a className="switch-version" href={`/switch?to=${version === 'us'? '/tw' : '/us'}`}> {switch_version} </a> </div> </div> <Modal active = {isModalActive} hide = {this.hideModal} version = {this.props.version}/> </div> ) } } // <img ref="icon3" onTouchStart={this.addScale} onTouchEnd={this.removeScale} onClick={this.showModal} src={require('./official' + img_type +'.png')} data-download="official"></img> export default AdOne;
modules/Header.js
marquesarthur/learning_react
import React from 'react'; import { Router, Route, browserHistory, IndexRoute } from 'react-router'; import { Link } from 'react-router' import { Nav, NavItem, NavDropdown, Glyphicon, DropdownButton, MenuItem, ProgressBar, Grid, Row, Col } from 'react-bootstrap'; import Navbar, {Brand} from 'react-bootstrap/lib/Navbar'; var LogoImg = require('../imgs/ubc-logo-final.png'); const logoStyle = { margin: "17 auto", marginLeft: "20px", float: "left" } const navStyle = { backgroundColor: "#002145", color: "#ffffff" } const menuStyle = { paddingTop: "15px", paddingRight: "25px" } const gearIcon = <Glyphicon glyph="th-list" />; const html = ( <Nav className="navbar navbar-fixed-top" style={navStyle}> <Link to="/"><img style={logoStyle} src={LogoImg}/></Link> <div> <h1 className="text-center"> CPSC 410 - Software Engineering <div className="pull-right" style={menuStyle}> <DropdownButton bsStyle="default" bsSize="medium" title={gearIcon} id="menu" pullRight> <MenuItem eventKey="1"><Link to="/">App Store</Link></MenuItem> <MenuItem eventKey="2"><Link to="/students">Students</Link></MenuItem> <MenuItem eventKey="3"><Link to="/teams">Teams</Link></MenuItem> </DropdownButton> </div> </h1> </div> </Nav> ); export default React.createClass({ render() { return html; } });
examples/huge-apps/routes/Grades/components/Grades.js
chrisirhc/react-router
import React from 'react'; class Grades extends React.Component { render () { return ( <div> <h2>Grades</h2> </div> ); } } export default Grades;
src/components/Feedback/Feedback.js
egut/react-docker-demo
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Feedback.css'; class Feedback extends React.Component { render() { return ( <div className={s.root}> <div className={s.container}> <a className={s.link} href="https://gitter.im/egut/react-docker-demo" >Ask a question</a> <span className={s.spacer}>|</span> <a className={s.link} href="https://github.com/egut/react-docker-demo/issues/new" >Report an issue</a> </div> </div> ); } } export default withStyles(s)(Feedback);
src/StyleButton.js
isuttell/react-texteditor
/** * @file Text Editor StyleButton * @author Isaac Suttell <[email protected]> */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; // CSS Module import css from './StyleButton.css'; export default class StyleButton extends Component { /** * Make Render * @return {React} */ render() { return ( <div className={classNames(this.props.className, 'text-editor---btn', css.btn, this.props.iconClass, { [css.icon] : typeof this.props.iconClass === 'string', 'text-editor--btn-active': this.props.active, [css.active]: this.props.active })} onMouseDown={this.props.onMouseDown} title={this.props.title} > {typeof this.props.iconClass !== 'string' ? this.props.label : null} </div> ); } } /** * Type checking * @type {Object} */ StyleButton.propTypes = { iconClass: PropTypes.string, style: PropTypes.string.isRequired, label: PropTypes.string.isRequired, active: PropTypes.bool.isRequired, className: PropTypes.string, title: PropTypes.string };
src/js/views/form.js
unidevel/touchstonejs-starter
import Container from 'react-container'; import dialogs from 'cordova-dialogs'; import React from 'react'; import Tappable from 'react-tappable'; import { UI } from 'touchstonejs'; const scrollable = Container.initScrollable(); // html5 input types for testing // omitted: button, checkbox, radio, image, hidden, reset, submit const HTML5_INPUT_TYPES = ['color', 'date', 'datetime', 'datetime-local', 'email', 'file', 'month', 'number', 'password', 'range', 'search', 'tel', 'text', 'time', 'url', 'week']; const FLAVOURS = [ { label: 'Vanilla', value: 'vanilla' }, { label: 'Chocolate', value: 'chocolate' }, { label: 'Caramel', value: 'caramel' }, { label: 'Strawberry', value: 'strawberry' } ]; module.exports = React.createClass({ statics: { navigationBar: 'main', getNavigation () { return { title: 'Forms' } } }, getInitialState () { return { flavourLabelSelect: 'chocolate', flavourRadioList: 'chocolate', switchValue: true } }, handleRadioListChange (key, newValue) { console.log('handleFlavourChange:', key, newValue); let newState = {}; newState[key] = newValue; this.setState(newState); }, handleLabelSelectChange (key, event) { console.log('handleFlavourChange:', key, event.target.value); let newState = {}; newState[key] = event.target.value; this.setState(newState); }, handleSwitch (key, event) { let newState = {}; newState[key] = !this.state[key]; this.setState(newState); }, alert (message) { dialogs.alert(message, function() {}, null) }, // used for testing renderInputTypes () { return HTML5_INPUT_TYPES.map(type => { return <UI.LabelInput key={type} type={type} label={type} placeholder={type} />; }); }, showDatePicker () { this.setState({datePicker: true}); }, handleDatePickerChange (d) { this.setState({datePicker: false, date: d}); }, formatDate (date) { if (date) { return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(); } }, render () { return ( <Container fill> <Container scrollable={scrollable}> {/*<UI.Group> <UI.GroupHeader>Input Type Experiment</UI.GroupHeader> <UI.GroupBody> {this.renderInputTypes()} </UI.GroupBody> </UI.Group>*/} <UI.Group> <UI.GroupHeader>Checkbox</UI.GroupHeader> <UI.GroupBody> <UI.Item> <UI.ItemInner> <UI.FieldLabel>Switch</UI.FieldLabel> <UI.Switch onTap={this.handleSwitch.bind(this, 'switchValue')} on={this.state.switchValue} /> </UI.ItemInner> </UI.Item> <UI.Item> <UI.ItemInner> <UI.FieldLabel>Disabled</UI.FieldLabel> <UI.Switch disabled /> </UI.ItemInner> </UI.Item> </UI.GroupBody> </UI.Group> <UI.Group> <UI.GroupHeader>Radio</UI.GroupHeader> <UI.GroupBody> <UI.RadioList value={this.state.flavourRadioList} onChange={this.handleRadioListChange.bind(this, 'flavourRadioList')} options={FLAVOURS} /> </UI.GroupBody> </UI.Group> <UI.Group> <UI.GroupHeader>Inputs</UI.GroupHeader> <UI.GroupBody> <UI.Input placeholder="Default" /> <UI.Input defaultValue="With Value" placeholder="Placeholder" /> <UI.Textarea defaultValue="Longtext is good for bios etc." placeholder="Longtext" /> </UI.GroupBody> </UI.Group> <UI.Group> <UI.GroupHeader>Labelled Inputs</UI.GroupHeader> <UI.GroupBody> <UI.LabelInput type="email" label="Email" placeholder="[email protected]" /> <Tappable component="label" onTap={this.showDatePicker}> <UI.LabelValue label="Date" value={this.formatDate(this.state.date)} placeholder="Select a date" /> </Tappable> <UI.LabelInput type="url" label="URL" placeholder="http://www.yourwebsite.com" /> <UI.LabelInput noedit label="No Edit" defaultValue="Un-editable, scrollable, selectable content" /> <UI.LabelSelect label="Flavour" value={this.state.flavourLabelSelect} onChange={this.handleLabelSelectChange.bind(this, 'flavourLabelSelect')} options={FLAVOURS} /> </UI.GroupBody> </UI.Group> <UI.Button type="primary" onTap={this.alert.bind(this, 'You clicked the Primary Button')}> Primary Button </UI.Button> <UI.Button onTap={this.alert.bind(this, 'You clicked the Default Button')}> Default Button </UI.Button> <UI.Button type="danger" onTap={this.alert.bind(this, 'You clicked the Danger Button')}> Danger Button </UI.Button> <UI.Button type="danger" onTap={this.alert.bind(this, 'You clicked the Danger Button')} disabled> Disabled Button </UI.Button> </Container> <UI.DatePickerPopup visible={this.state.datePicker} date={this.state.date} onChange={this.handleDatePickerChange}/> </Container> ); } });
src/tools/web/client/src/utils.js
e1528532/libelektra
import React from 'react' export const toElektraBool = (val) => val ? '1' : '0' export const fromElektraBool = (val) => (val === '1') ? true : false export const RANGE_REGEX = /([-+]?[0-9]*\.?[0-9]+)-([-+]?[0-9]*\.?[0-9]+)/ export const HOST_REGEX = /(https?:\/\/[^/]+)(\/.*)?/ export const ARRAY_KEY_REGEX = /#(_*)([0-9]+)/ export const prettyPrintArrayIndex = (str) => { const match = str.match(ARRAY_KEY_REGEX) if (!match) return str const [ , prefix, index ] = match return ( <span> <span style={{ opacity: 0.4 }}>#</span> <span style={{ opacity: 0.3 }}>{prefix}</span> <span style={{ fontWeight: 'bold' }}>{index}</span> </span> ) } export const isNumberType = (type) => { switch (type) { case 'short': case 'unsigned_short': case 'long': case 'unsigned_long': case 'long_long': case 'unsigned_long_long': case 'float': case 'double': return true default: return false } } export const VISIBILITY_LEVELS = { critical: 7, important: 6, user: 5, advanced: 4, developer: 3, internal: 2, } export const visibility = (name) => VISIBILITY_LEVELS[name]
src/components/Sample2/Sample2.js
tinkertrain/qsenseistyleguide
import React, { Component } from 'react'; import CodeBlock from '../CodeBlock'; import './Sample2.scss'; export class Sample2 extends Component { state = { classSize: 'qs_Base--16' }; render() { return ( <div className={this.state.classSize}> <div className="fontSizeSwitcher qs_Bg--lightgray"> <label htmlFor="fontSizeOptions">Base:</label> <div className="qs_Input qs_Select"> <select name="fontSizeOptions" id="fontSizeOptions" onChange={this.switchFontSize.bind(this)}> <option value="16">16px</option> <option value="18">18px</option> <option value="20">20px</option> </select> </div> </div> <section className="qs_PageSection qs_Center qs_Bg--darkgray"> <div className="qs_PageSection__container"> <h1 className="qs_PageTitle">Get Fuse</h1> </div> </section> <section className="qs_PageSection qs_Bg--white"> <div className="qs_PageSection__container qs_Center"> <p className="qs_Entry">Fuse Free is the free edition of our data platform that you can use for non-commercial purposes. You can use it at no cost for as long as you want.</p> <p className="qs_Entry">Your Access Token is:</p> <div className="qs_Input"> <input className="qs_Center" type="text" name="example1" id="example1" value="08896316e74945129367c4d123456789"/> </div> </div> </section> <section className="qs_PageSection qs_Bg--lightgray"> <div className="qs_PageSection__container"> <h2 className="qs_Center">Get Started</h2> <p className="qs_Entry qs_Center">To get and run Fuse, you need to have Docker installed on your system *. Follow the instructions on the Docker website.</p> <ol> <li> <p>Login to our Docker registry</p> <div className="qs_CodeBlock"> <CodeBlock language="bash"> { `$ docker login -u 'token' -p 08896316e74945129367c4d123456789 -e '[email protected]' docker.qsensei.com` } </CodeBlock> </div> </li> <li> <p>What’s next?</p> <p>To get you started easily we provide a step by step Tutorial to guide you through the process of creating your first Fuse powered data app. In addition, take a look at our Documentation to get a more in depth view into the basics of deploying and setting up Fuse.</p> <p className="qs_Mediumgray qs_Center"><em>* Other System requirements can be found <a href="#">here</a> in our Documentation.</em></p> </li> </ol> </div> </section> <section className="qs_PageSection qs_Bg--white"> <div className="qs_PageSection__container qs_Center"> <h2>Discover Fuse Professional</h2> <p className="qs_Entry">Want to build data apps with replication over several servers? Want to understand the impact your data apps have on your organization? Want to use advanced Data Services to improve data ingest and data preparation? Fuse Professional is our solution for advanced data needs.</p> <div className="button-row"> <button className="qs_Button qs_Button--dark qs_Button--outline">browse all features</button> <button className="qs_Button qs_Button--dark qs_Button--outline">view pricing plans</button> </div> </div> </section> <section className="qs_PageSection qs_Bg--darkgray"> <div className="qs_PageSection__container qs_Center"> Footer… </div> </section> </div> ); } switchFontSize(event) { this.setState({ classSize: `qs_Base--${event.target.value}` }); } }
templates/rubix/rails/rails-example/src/common/sidebar.js
jeffthemaximum/Teachers-Dont-Pay-Jeff
import React from 'react'; import { Sidebar, SidebarNav, SidebarNavItem, SidebarControls, SidebarControlBtn, LoremIpsum, Grid, Row, Col, FormControl, Label, Progress, Icon, SidebarDivider } from '@sketchpixy/rubix'; import { Link } from 'react-router'; class ApplicationSidebar extends React.Component { handleChange(e) { this._nav.search(e.target.value); } render() { return ( <div> <Grid> <Row> <Col xs={12}> <FormControl type='text' placeholder='Search...' onChange={::this.handleChange} className='sidebar-search' style={{border: 'none', background: 'none', margin: '10px 0 0 0', borderBottom: '1px solid #666', color: 'white'}} /> <div className='sidebar-nav-container'> <SidebarNav style={{marginBottom: 0}} ref={(c) => this._nav = c}> { /** Pages Section */ } <div className='sidebar-header'>PAGES</div> <SidebarNavItem glyph='icon-outlined-todolist' name='All Todos' href='/' /> <SidebarNavItem glyph='icon-outlined-pencil' name='Edit Todo' href='/todos/:id' /> </SidebarNav> </div> </Col> </Row> </Grid> </div> ); } } class DummySidebar extends React.Component { render() { return ( <Grid> <Row> <Col xs={12}> <div className='sidebar-header'>DUMMY SIDEBAR</div> <LoremIpsum query='1p' /> </Col> </Row> </Grid> ); } } export default class SidebarContainer extends React.Component { render() { return ( <div id='sidebar'> <div id='avatar'> <Grid> <Row className='fg-white'> <Col xs={4} collapseRight> <img src='/imgs/app/avatars/avatar0.png' width='40' height='40' /> </Col> <Col xs={8} collapseLeft id='avatar-col'> <div style={{top: 23, fontSize: 16, lineHeight: 1, position: 'relative'}}>Anna Sanchez</div> <div> <Progress id='demo-progress' value={30} color='#ffffff'/> <Icon id='demo-icon' bundle='fontello' glyph='lock-5' /> </div> </Col> </Row> </Grid> </div> <SidebarControls> <SidebarControlBtn bundle='fontello' glyph='docs' sidebar={0} /> <SidebarControlBtn bundle='fontello' glyph='chat-1' sidebar={1} /> <SidebarControlBtn bundle='fontello' glyph='chart-pie-2' sidebar={2} /> <SidebarControlBtn bundle='fontello' glyph='th-list-2' sidebar={3} /> <SidebarControlBtn bundle='fontello' glyph='bell-5' sidebar={4} /> </SidebarControls> <div id='sidebar-container'> <Sidebar sidebar={0}> <ApplicationSidebar /> </Sidebar> <Sidebar sidebar={1}> <DummySidebar /> </Sidebar> <Sidebar sidebar={2}> <DummySidebar /> </Sidebar> <Sidebar sidebar={3}> <DummySidebar /> </Sidebar> <Sidebar sidebar={4}> <DummySidebar /> </Sidebar> </div> </div> ); } }
examples/auth-with-shared-root/app.js
zenlambda/react-router
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router } from 'react-router' import routes from './config/routes' render(<Router history={browserHistory} routes={routes}/>, document.getElementById('example'))
src/pages/resume/education/index.fr.js
angeloocana/angeloocana
import React from 'react'; import EducationsPage from '../../../components/Resume/EducationsPage'; import graphql from 'graphql'; export default (props) => <EducationsPage {...props} />; export const pageQuery = graphql` query ResumeEducationsFr { site { siteMetadata { resume { menu { label link } educations { name subject { fr } needWhiteBg link fullName years img } } } } } `;
src/ShallowTraversal.js
dustinsanders/enzyme
import React from 'react'; import isEmpty from 'lodash/isEmpty'; import isSubset from 'is-subset'; import { coercePropValue, propsOfNode, splitSelector, isCompoundSelector, selectorType, AND, SELECTOR, nodeHasType, } from './Utils'; export function childrenOfNode(node) { if (!node) return []; const maybeArray = propsOfNode(node).children; const result = []; React.Children.forEach(maybeArray, child => { if (child !== null && child !== false && typeof child !== 'undefined') { result.push(child); } }); return result; } export function hasClassName(node, className) { let classes = propsOfNode(node).className || ''; classes = classes.replace(/\s/g, ' '); return ` ${classes} `.indexOf(` ${className} `) > -1; } export function treeForEach(tree, fn) { if (tree !== null && tree !== false && typeof tree !== 'undefined') { fn(tree); } childrenOfNode(tree).forEach(node => treeForEach(node, fn)); } export function treeFilter(tree, fn) { const results = []; treeForEach(tree, node => { if (fn(node)) { results.push(node); } }); return results; } function pathFilter(path, fn) { return path.filter(tree => treeFilter(tree, fn).length !== 0); } export function pathToNode(node, root) { const queue = [root]; const path = []; const hasNode = (testNode) => node === testNode; while (queue.length) { const current = queue.pop(); const children = childrenOfNode(current); if (current === node) return pathFilter(path, hasNode); path.push(current); if (children.length === 0) { // leaf node. if it isn't the node we are looking for, we pop. path.pop(); } queue.push.apply(queue, children); } return null; } export function parentsOfNode(node, root) { return pathToNode(node, root).reverse(); } export function nodeHasId(node, id) { return propsOfNode(node).id === id; } export function nodeHasProperty(node, propKey, stringifiedPropValue) { const nodeProps = propsOfNode(node); const propValue = coercePropValue(propKey, stringifiedPropValue); const descriptor = Object.getOwnPropertyDescriptor(nodeProps, propKey); if (descriptor && descriptor.get) { return false; } const nodePropValue = nodeProps[propKey]; if (nodePropValue === undefined) { return false; } if (propValue) { return nodePropValue === propValue; } return nodeProps.hasOwnProperty(propKey); } export function nodeMatchesObjectProps(node, props) { return isSubset(propsOfNode(node), props); } export function buildPredicate(selector) { switch (typeof selector) { case 'function': // selector is a component constructor return node => node && node.type === selector; case 'string': if (isCompoundSelector.test(selector)) { return AND(splitSelector(selector).map(buildPredicate)); } switch (selectorType(selector)) { case SELECTOR.CLASS_TYPE: return node => hasClassName(node, selector.substr(1)); case SELECTOR.ID_TYPE: return node => nodeHasId(node, selector.substr(1)); case SELECTOR.PROP_TYPE: { const propKey = selector.split(/\[([a-zA-Z\-]*?)(=|\])/)[1]; const propValue = selector.split(/=(.*?)\]/)[1]; return node => nodeHasProperty(node, propKey, propValue); } default: // selector is a string. match to DOM tag or constructor displayName return node => nodeHasType(node, selector); } case 'object': if (!Array.isArray(selector) && selector !== null && !isEmpty(selector)) { return node => nodeMatchesObjectProps(node, selector); } throw new TypeError( 'Enzyme::Selector does not support an array, null, or empty object as a selector' ); default: throw new TypeError('Enzyme::Selector expects a string, object, or Component Constructor'); } } export function getTextFromNode(node) { if (node === null || node === undefined) { return ''; } if (typeof node === 'string' || typeof node === 'number') { return String(node); } if (node.type && typeof node.type === 'function') { return `<${node.type.displayName || node.type.name} />`; } return childrenOfNode(node).map(getTextFromNode).join('').replace(/\s+/, ' '); }
src/components/ImgFigure.js
movingStars/gallery-by-react-from-xiongjiao
require('normalize.css/normalize.css'); import React from 'react'; class ImgFigure extends React.Component { render(){ let { data } = this.props; return( <figure className="img-figure"> <img className="img-img" src={data.imageURL} alt={data.title}/> <figcaption> <h2 className="img-title">{data.title}</h2> </figcaption> </figure> ); } }; ImgFigure.defaultProps = { }; export default ImgFigure;
src/svg-icons/av/forward-10.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvForward10 = (props) => ( <SvgIcon {...props}> <path d="M4 13c0 4.4 3.6 8 8 8s8-3.6 8-8h-2c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6v4l5-5-5-5v4c-4.4 0-8 3.6-8 8zm6.8 3H10v-3.3L9 13v-.7l1.8-.6h.1V16zm4.3-1.8c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5s-.1-.2-.1-.3-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/> </SvgIcon> ); AvForward10 = pure(AvForward10); AvForward10.displayName = 'AvForward10'; AvForward10.muiName = 'SvgIcon'; export default AvForward10;
docs/app/Examples/elements/Button/Usage/index.js
shengnian/shengnian-ui-react
import React from 'react' import { Message } from 'shengnian-ui-react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const ButtonUsageExamples = () => ( <ExampleSection title='Usage'> <ComponentExample title='Focus' description='A button can be focused.' examplePath='elements/Button/Usage/ButtonExampleFocus' /> <ComponentExample title='Attached events' description='A button can be handle all events.' examplePath='elements/Button/Usage/ButtonExampleAttachedEvents' > <Message warning> <p> When <code>Button</code> is <code>attached</code> or rendered as non-<code>button</code> element, it losses ability to handle keyboard events when it focused. </p> <p> However, <code>button</code> behaviour can be replicated with <code>onKeyPress</code> handler. You can find out more details on {' '} <a href='https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role' rel='noopener noreferrer' target='_blank' > MDN </a>. </p> </Message> </ComponentExample> </ExampleSection> ) export default ButtonUsageExamples
src/Paper/Paper.js
AndriusBil/material-ui
// @flow import React from 'react'; import type { ComponentType } from 'react'; import classNames from 'classnames'; import warning from 'warning'; import withStyles from '../styles/withStyles'; export const styles = (theme: Object) => { const shadows = {}; theme.shadows.forEach((shadow, index) => { shadows[`shadow${index}`] = { boxShadow: shadow, }; }); return { root: { backgroundColor: theme.palette.background.paper, }, rounded: { borderRadius: 2, }, ...shadows, }; }; type DefaultProps = { classes: Object, component: string, elevation: number, square: boolean, }; export type Props = { /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component?: string | ComponentType<*>, /** * Shadow depth, corresponds to `dp` in the spec. * It's accepting values between 0 and 24 inclusive. */ elevation?: number, /** * If `true`, rounded corners are disabled. */ square?: boolean, }; type AllProps = DefaultProps & Props; function Paper(props: AllProps) { const { classes, className: classNameProp, component: ComponentProp, square, elevation, ...other } = props; warning( elevation >= 0 && elevation < 25, `Material-UI: this elevation \`${elevation}\` is not implemented.`, ); const className = classNames( classes.root, classes[`shadow${elevation >= 0 ? elevation : 0}`], { [classes.rounded]: !square, }, classNameProp, ); return <ComponentProp className={className} {...other} />; } Paper.defaultProps = { component: 'div', elevation: 2, square: false, }; export default withStyles(styles, { name: 'MuiPaper' })(Paper);
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js
gale320/actor-platform
import _ from 'lodash'; import React from 'react'; import mixpanel from 'utils/Mixpanel'; import ReactMixin from 'react-mixin'; import { IntlMixin, FormattedMessage } from 'react-intl'; import classNames from 'classnames'; import MyProfileActions from 'actions/MyProfileActions'; import LoginActionCreators from 'actions/LoginActionCreators'; import HelpActionCreators from 'actions/HelpActionCreators'; import AddContactActionCreators from 'actions/AddContactActionCreators'; import AvatarItem from 'components/common/AvatarItem.react'; import MyProfileModal from 'components/modals/MyProfile.react'; import ActorClient from 'utils/ActorClient'; import AddContactModal from 'components/modals/AddContact.react'; import PreferencesModal from '../modals/Preferences.react'; import PreferencesActionCreators from 'actions/PreferencesActionCreators'; var getStateFromStores = () => { return { dialogInfo: null }; }; @ReactMixin.decorate(IntlMixin) class HeaderSection extends React.Component { constructor(props) { super(props); this.state = _.assign({ isOpened: false }, getStateFromStores()); } componentDidMount() { ActorClient.bindUser(ActorClient.getUid(), this.setUser); } componentWillUnmount() { ActorClient.unbindUser(ActorClient.getUid(), this.setUser); } setUser = (user) => { this.setState({user: user}); }; setLogout = () => { LoginActionCreators.setLoggedOut(); }; openMyProfile = () => { MyProfileActions.modalOpen(); mixpanel.track('My profile open'); }; openHelpDialog = () => { HelpActionCreators.open(); mixpanel.track('Click on HELP'); }; openAddContactModal = () => { AddContactActionCreators.openModal(); }; onSettingsOpen = () => { PreferencesActionCreators.show(); }; toggleHeaderMenu = () => { const isOpened = this.state.isOpened; if (!isOpened) { this.setState({isOpened: true}); mixpanel.track('Open sidebar menu'); document.addEventListener('click', this.closeHeaderMenu, false); } else { this.closeHeaderMenu(); } }; closeHeaderMenu = () => { this.setState({isOpened: false}); document.removeEventListener('click', this.closeHeaderMenu, false); }; render() { const user = this.state.user; if (user) { let headerClass = classNames('sidebar__header', 'sidebar__header--clickable', { 'sidebar__header--opened': this.state.isOpened }); let menuClass = classNames('dropdown', { 'dropdown--opened': this.state.isOpened }); return ( <header className={headerClass}> <div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}> <AvatarItem image={user.avatar} placeholder={user.placeholder} size="tiny" title={user.name} /> <span className="sidebar__header__user__name col-xs">{user.name}</span> <div className={menuClass}> <span className="dropdown__button"> <i className="material-icons">arrow_drop_down</i> </span> <ul className="dropdown__menu dropdown__menu--right"> <li className="dropdown__menu__item hide"> <i className="material-icons">photo_camera</i> <FormattedMessage message={this.getIntlMessage('setProfilePhoto')}/> </li> <li className="dropdown__menu__item" onClick={this.openMyProfile}> <i className="material-icons">edit</i> <FormattedMessage message={this.getIntlMessage('editProfile')}/> </li> <li className="dropdown__menu__item" onClick={this.openAddContactModal}> <i className="material-icons">person_add</i> Add contact </li> <li className="dropdown__menu__separator"></li> <li className="dropdown__menu__item hide"> <svg className="icon icon--dropdown" dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#integration"/>'}}/> <FormattedMessage message={this.getIntlMessage('configureIntegrations')}/> </li> <li className="dropdown__menu__item" onClick={this.openHelpDialog}> <i className="material-icons">help</i> <FormattedMessage message={this.getIntlMessage('helpAndFeedback')}/> </li> <li className="dropdown__menu__item hide" onClick={this.onSettingsOpen}> <i className="material-icons">settings</i> <FormattedMessage message={this.getIntlMessage('preferences')}/> </li> <li className="dropdown__menu__item dropdown__menu__item--light" onClick={this.setLogout}> <FormattedMessage message={this.getIntlMessage('signOut')}/> </li> </ul> </div> </div> <MyProfileModal/> <AddContactModal/> <PreferencesModal/> </header> ); } else { return null; } } } export default HeaderSection;
ui/src/components/role/AddMemberToRoles.js
yahoo/athenz
/* * Copyright 2020 Verizon Media * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React from 'react'; import AddModal from '../modal/AddModal'; import FlatPicker from '../flatpicker/FlatPicker'; import { colors } from '../denali/styles'; import Input from '../denali/Input'; import InputLabel from '../denali/InputLabel'; import styled from '@emotion/styled'; import Checkbox from '../denali/CheckBox'; import DateUtils from '../utils/DateUtils'; import NameUtils from '../utils/NameUtils'; import RequestUtils from '../utils/RequestUtils'; const SectionsDiv = styled.div` width: 800px; text-align: left; background-color: ${colors.white}; `; const SectionDiv = styled.div` align-items: flex-start; display: flex; flex-flow: row nowrap; padding: 10px 30px; `; const ContentDiv = styled.div` flex: 1 1; display: flex; flex-flow: row wrap; `; const StyledInputLabel = styled(InputLabel)` flex: 0 0 150px; font-weight: 600; line-height: 36px; `; const StyledInput = styled(Input)` max-width: 500px; margin-right: 10px; width: 300px; `; const FlatPickrInputDiv = styled.div` margin-right: 10px; max-width: 500px; width: 260px; & > div input { position: relative; font: 300 14px HelveticaNeue-Reg, Helvetica, Arial, sans-serif; background-color: rgba(53, 112, 244, 0.05); box-shadow: none; color: rgb(48, 48, 48); height: 16px; min-width: 50px; text-align: left; border-width: 2px; border-style: solid; border-color: transparent; border-image: initial; border-radius: 2px; flex: 1 0 auto; margin: 0; margin-right: 10px; outline: none; padding: 0.6em 12px; transition: background-color 0.2s ease-in-out 0s, color 0.2s ease-in-out 0s, border 0.2s ease-in-out 0s; width: 80%; } `; const StyledRoleContainer = styled.div` width: 100%; `; const StyledRoles = styled.div` border-top: 1px solid #d8dade; height: 60%; `; const StyledRole = styled.div` background-color: rgba(53, 112, 244, 0.06); padding: 10px; width: calc(100% - 10px); `; const StyledJustification = styled(Input)` width: 300px; margin-top: 5px; `; export default class AddMemberToRoles extends React.Component { constructor(props) { super(props); this.api = this.props.api; this.onSubmit = this.onSubmit.bind(this); this.state = { showModal: !!this.props.showAddMemberToRoles, checkedRoles: [], }; this.dateUtils = new DateUtils(); } onSubmit() { if (!this.state.memberName || this.state.memberName === '') { this.setState({ errorMessage: 'Member name is required.', }); return; } if (!this.state.checkedRoles || this.state.checkedRoles.length === 0) { this.setState({ errorMessage: 'Should select at least one role to add members.', }); return; } if ( this.props.justificationRequired && (this.state.justification === undefined || this.state.justification.trim() === '') ) { this.setState({ errorMessage: 'Justification is required to add a member.', }); return; } let member = { memberName: this.state.memberName, expiration: this.state.memberExpiry && this.state.memberExpiry.length > 0 ? this.dateUtils.uxDatetimeToRDLTimestamp( this.state.memberExpiry ) : '', reviewReminder: this.state.memberReviewReminder && this.state.memberReviewReminder.length > 0 ? this.dateUtils.uxDatetimeToRDLTimestamp( this.state.memberReviewReminder ) : '', }; // send api call and then reload existing members component this.api .addMemberToRoles( this.props.domain, this.state.checkedRoles, this.state.memberName, member, this.state.justification ? this.state.justification : 'added using Athenz UI', this.props._csrf ) .then(() => { this.setState({ showModal: false, justification: '', }); const successRoles = this.state.checkedRoles.join(', '); this.props.onSubmit( `Successfully added ${this.state.memberName} to roles: ${successRoles}` ); }) .catch((err) => { this.setState({ errorMessage: RequestUtils.xhrErrorCheckHelper(err), }); }); } inputChanged(key, evt) { this.setState({ [key]: evt.target.value }); } onCheckboxChanged(role, event) { let checkedRoles = this.state.checkedRoles; if (checkedRoles.includes(role) && !event.target.checked) { checkedRoles = checkedRoles.filter((checkedRole) => { return checkedRole !== role; }); } else { checkedRoles.push(role); } this.setState({ checkedRoles }); } render() { let roleCheckboxes = []; this.props.roles.forEach((role) => { const roleName = NameUtils.getShortName(':role.', role.name); let onCheckboxChanged = this.onCheckboxChanged.bind(this, roleName); roleCheckboxes.push( <StyledRole key={roleName}> <Checkbox checked={this.state.checkedRoles.includes(roleName)} label={roleName} name={roleName} onChange={onCheckboxChanged} key={roleName} /> </StyledRole> ); }); let sections = ( <SectionsDiv autoComplete={'off'} data-testid='add-member-to-roles-form' > <SectionDiv> <StyledInputLabel htmlFor='member-name'> Member </StyledInputLabel> <ContentDiv> <StyledInput id='member-name' name='member-name' value={this.state.memberName} onChange={this.inputChanged.bind( this, 'memberName' )} placeholder='user.<shortid> or <domain>.<service>' /> <FlatPickrInputDiv> <FlatPicker onChange={(memberExpiry) => { this.setState({ memberExpiry }); }} id='addMemberToRoles' clear={this.state.memberExpiry} /> </FlatPickrInputDiv> <FlatPickrInputDiv> <FlatPicker onChange={(memberReviewReminder) => { this.setState({ memberReviewReminder }); }} placeholder='Reminder (Optional)' id='addMemberToRoles-reminder' clear={this.state.memberReviewReminder} /> </FlatPickrInputDiv> {this.props.justificationRequired && ( <StyledJustification id='justification' name='justification' value={this.state.justification} onChange={this.inputChanged.bind( this, 'justification' )} autoComplete={'off'} placeholder='Enter justification here' /> )} </ContentDiv> </SectionDiv> <SectionDiv> <StyledInputLabel htmlFor=''>Roles</StyledInputLabel> <ContentDiv> <StyledRoleContainer> <StyledRoles>{roleCheckboxes}</StyledRoles> </StyledRoleContainer> </ContentDiv> </SectionDiv> </SectionsDiv> ); return ( <div data-testid='add-member-to-roles-form'> <AddModal isOpen={this.state.showModal} cancel={this.props.onCancel} submit={this.onSubmit} title={'Add Member to Roles:'} errorMessage={this.state.errorMessage} sections={sections} /> </div> ); } }
fixtures/output/webpack-message-formatting/src/AppNoDefault.js
IamJoseph/create-react-app
import React, { Component } from 'react'; import myImport from './ExportNoDefault'; class App extends Component { render() { return <div className="App">{myImport}</div>; } } export default App;
example/src/index.js
romainberger/react-portal-tooltip
import React from 'react' import ReactDOM from 'react-dom' import App from './app' ReactDOM.render(<App />, document.querySelector('#root'))
node_modules/semantic-ui-react/dist/es/collections/Form/FormInput.js
SuperUncleCat/ServerMonitoring
import _extends from 'babel-runtime/helpers/extends'; import React from 'react'; import { customPropTypes, getElementType, getUnhandledProps, META } from '../../lib'; import Input from '../../elements/Input'; import FormField from './FormField'; /** * Sugar for <Form.Field control={Input} />. * @see Form * @see Input */ function FormInput(props) { var control = props.control; var rest = getUnhandledProps(FormInput, props); var ElementType = getElementType(FormInput, props); return React.createElement(ElementType, _extends({}, rest, { control: control })); } FormInput.handledProps = ['as', 'control']; FormInput._meta = { name: 'FormInput', parent: 'Form', type: META.TYPES.COLLECTION }; FormInput.propTypes = process.env.NODE_ENV !== "production" ? { /** An element type to render as (string or function). */ as: customPropTypes.as, /** A FormField control prop. */ control: FormField.propTypes.control } : {}; FormInput.defaultProps = { as: FormField, control: Input }; export default FormInput;
src/index.js
fmakdemir/react-boilerplate
import React from 'react'; import ReactDom from 'react-dom'; import App from 'containers/app'; import Pages from 'pages'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; // theming import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import theme from 'lib/theme'; // redux thingies import { Provider } from 'react-redux'; import { createStore, combineReducers} from 'redux'; import { syncHistoryWithStore, routerReducer } from 'react-router-redux'; import reducers from 'reducers'; // tap event plugin import injectTapEventPlugin from 'react-tap-event-plugin'; injectTapEventPlugin(); const combinedReducers = combineReducers({ ...reducers, routing: routerReducer, }); let store = createStore(combinedReducers, // combine reducers { // initial data for reducers sidebar: false, notif: {open: false, message: ''}, }, // enable redux monitor window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); const history = syncHistoryWithStore(browserHistory, store); ReactDom.render(( <MuiThemeProvider muiTheme={theme}> <Provider store={store}> <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Pages.Home}/> <Route path="about" component={Pages.About}/> </Route> </Router> </Provider> </MuiThemeProvider> ), document.getElementById('root'));
packages/component/src/Attachment/ImageAttachment.js
billba/botchat
import PropTypes from 'prop-types'; import React from 'react'; import ImageContent from './ImageContent'; import readDataURIToBlob from '../Utils/readDataURIToBlob'; const ImageAttachment = ({ attachment }) => { let imageURL = attachment.thumbnailUrl || attachment.contentUrl; // To support Content Security Policy, data URI cannot be used. // We need to parse the data URI into a blob: URL. const blob = readDataURIToBlob(imageURL); if (blob) { imageURL = URL.createObjectURL(blob); } return <ImageContent alt={attachment.name} src={imageURL} />; }; ImageAttachment.propTypes = { // Either attachment.contentUrl or attachment.thumbnailUrl must be specified. attachment: PropTypes.oneOfType([ PropTypes.shape({ contentUrl: PropTypes.string.isRequired, name: PropTypes.string, thumbnailUrl: PropTypes.string }), PropTypes.shape({ contentUrl: PropTypes.string, name: PropTypes.string, thumbnailUrl: PropTypes.string.isRequired }) ]).isRequired }; export default ImageAttachment;
src/ui/pages/App.js
notifapi/notifapi-web
import React from 'react'; import { Component } from 'react'; import AppContainer from '../containers/AppContainer'; import HeaderContainer from '../containers/HeaderContainer'; import FooterContainer from '../containers/FooterContainer'; export default class App extends Component { render() { return ( <div> <HeaderContainer /> <AppContainer> {this.props.children} </AppContainer> <FooterContainer /> </div> ); } }
src/encoded/static/components/item-pages/FileSetCalibrationView.js
4dn-dcic/fourfront
'use strict'; import React from 'react'; import _ from 'underscore'; import { FilesInSetTable } from './components/FilesInSetTable'; import DefaultItemView from './DefaultItemView'; /** * Page view for a FileSetCalibration Item. * Renders out a {@link module:item-pages/components.FilesInSetTable} Component. * * @module {Component} item-pages/file-set-calibration-view */ export default class FileSetCalibrationView extends DefaultItemView { getTabViewContents(){ var initTabs = []; if (Array.isArray(this.props.context.files_in_set)){ initTabs.push(FilesInSetTable.getTabObject(this.props.context)); } return initTabs.concat(_.filter(this.getCommonTabs(), function(tabObj){ if (tabObj.key === 'details') return false; return true; })); } }
src/components/Chat/Input/EmojiSuggestion.js
welovekpop/uwave-web-welovekpop.club
import React from 'react'; import PropTypes from 'prop-types'; import ListItemAvatar from '@material-ui/core/ListItemAvatar'; import ListItemText from '@material-ui/core/ListItemText'; import Suggestion from './Suggestion'; const shortcode = emoji => `:${emoji.shortcode}:`; const EmojiSuggestion = ({ value: emoji, ...props }) => ( <Suggestion {...props}> <ListItemAvatar> <span className="EmojiSuggestion-image" style={{ backgroundImage: `url(/assets/emoji/${emoji.image})` }} /> </ListItemAvatar> <ListItemText primary={shortcode(emoji)} /> </Suggestion> ); EmojiSuggestion.propTypes = { value: PropTypes.shape({ shortcode: PropTypes.string, image: PropTypes.string, }).isRequired, }; export default EmojiSuggestion;
examples/with-react-intl/components/Layout.js
sedubois/next.js
import React from 'react' import {defineMessages, injectIntl} from 'react-intl' import Head from 'next/head' import Nav from './Nav' const messages = defineMessages({ title: { id: 'title', defaultMessage: 'React Intl Next.js Example' } }) export default injectIntl(({intl, title, children}) => ( <div> <Head> <meta name='viewport' content='width=device-width, initial-scale=1' /> <title>{title || intl.formatMessage(messages.title)}</title> </Head> <header> <Nav /> </header> {children} </div> ))
source/common/components/App/App.js
shery15/react
import React from 'react'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; import CSSModules from 'react-css-modules'; import styles from '../../css/bulma.css'; import Greeter from '../Greeter'; import Todo from '../Todo'; import MarkdownEditor from '../MarkdownEditor'; import Info from '../Info'; import AuthExample from '../Login'; import Prompt from '../Prompt'; import Animation from '../Animation'; const OldSchoolMenuLink = ({ label, to, activeOnlyWhenExact }) => ( <Route path={to} exact={activeOnlyWhenExact} children={({ match }) => ( <div className={match ? 'active' : ''}> {match ? '> ' : ''}<Link to={to}>{label}</Link> </div> )}/> ); const App = () => ( <Router> <div className="tabs"> <ul> <li><OldSchoolMenuLink to="/" activeOnlyWhenExact={true} label="Home" /></li> <li><OldSchoolMenuLink to="/topics" label="Topics" /></li> <li><OldSchoolMenuLink to="/info" label="Info" /></li> <li><OldSchoolMenuLink to="/todo" label="Todo" /></li> <li><OldSchoolMenuLink to="/markdowneditor" label="MarkdownEditor" /></li> <li><OldSchoolMenuLink to="/auth" label="AuthExample" /></li> <li><OldSchoolMenuLink to="/prompt" label="Prompt" /></li> <li><OldSchoolMenuLink to="/animation" label="Animation" /></li> <li><OldSchoolMenuLink to="/404" label="404" /></li> </ul> <hr /> <Switch> <Route exact path="/" name="Router v4.0" component={Greeter} /> <Route path="/topics" component={Topics} /> <Route path="/todo" component={Todo} /> <Route path="/info" component={Info} /> <Route path="/markdowneditor" component={MarkdownEditor} /> <Route path="/auth" component={AuthExample} /> <Route path="/animation" component={Animation} /> <Route path="/prompt" component={Prompt} /> <Route component={NoMatch}/> </Switch> </div> </Router> ); const NoMatch = ({ location }) => ( <div> <h3>No match for <code>{location.pathname}</code></h3> </div> ) const Topics = ({ match }) => ( <div> <h2>Topics</h2> <ul> <li> <Link to={`${match.url}/rendering`}> Rendering with React </Link> </li> <li> <Link to={`${match.url}/component`}> Components </Link> </li> <li> <Link to={`${match.url}/props-v-state`}> Props v. State </Link> </li> </ul> <Route path={`${match.url}/:topicId`} component={Topic} /> <Route exact path={match.url} render={() => ( <h3>Please select a topic.</h3> )} /> </div> ); const Topic = ({ match }) => ( <div> <h3>{match.params.topicId}</h3> </div> ); export default CSSModules(App, styles, { allowMultiple: true });
src/svg-icons/action/delete.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionDelete = (props) => ( <SvgIcon {...props}> <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/> </SvgIcon> ); ActionDelete = pure(ActionDelete); ActionDelete.displayName = 'ActionDelete'; ActionDelete.muiName = 'SvgIcon'; export default ActionDelete;
src/Paper/Paper.js
dsslimshaddy/material-ui
// @flow import React from 'react'; import classNames from 'classnames'; import warning from 'warning'; import withStyles from '../styles/withStyles'; export const styles = (theme: Object) => { const shadows = {}; theme.shadows.forEach((shadow, index) => { shadows[`shadow${index}`] = { boxShadow: shadow, }; }); return { root: { backgroundColor: theme.palette.background.paper, }, rounded: { borderRadius: 2, }, ...shadows, }; }; type DefaultProps = { classes: Object, component: string, elevation: number, square: boolean, }; export type Props = { /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * The component used for the root node. * Either a string to use a DOM element or a component. */ component?: string | Function, /** * Shadow depth, corresponds to `dp` in the spec. * It's accepting values between 0 and 24 inclusive. */ elevation?: number, /** * If `true`, rounded corners are disabled. */ square?: boolean, }; type AllProps = DefaultProps & Props; function Paper(props: AllProps) { const { classes, className: classNameProp, component: ComponentProp, square, elevation, ...other } = props; warning( elevation >= 0 && elevation < 25, `Material-UI: this elevation \`${elevation}\` is not implemented.`, ); const className = classNames( classes.root, classes[`shadow${elevation >= 0 ? elevation : 0}`], { [classes.rounded]: !square, }, classNameProp, ); return <ComponentProp className={className} {...other} />; } Paper.defaultProps = { component: 'div', elevation: 2, square: false, }; export default withStyles(styles, { name: 'MuiPaper' })(Paper);
src/encoded/static/components/viz/components/Legend.js
4dn-dcic/fourfront
'use strict'; import React from 'react'; import _ from 'underscore'; import memoize from 'memoize-one'; import * as vizUtil from '@hms-dbmi-bgm/shared-portal-components/es/components/viz/utilities'; import { barplot_color_cycler } from './../ColorCycler'; import { console, isServerSide, object, logger } from '@hms-dbmi-bgm/shared-portal-components/es/components/util'; import { Schemas } from './../../util'; import { CursorViewBounds } from './../ChartDetailCursor'; import ReactTooltip from 'react-tooltip'; /** * @typedef {Object} FieldObject * @prop {string} field - Dot-separated field identifier string. * @prop {string} name - Human-readable title or name of field. * @prop {{ term: string, field: string, color: string, experiment_sets: number, experiments: number, files: number }[]} terms - List of terms in field. */ /** * React component which represents a Term item. * * @class Term * @prop {string} field - Name of field to which this term belongs, in object-dot-notation. * @prop {string} term - Name of term. * @prop {string|Object} color - Color to show next to term, should be string or RGBColor object. * @type Component */ class Term extends React.Component { constructor(props){ super(props); this.generateNode = this.generateNode.bind(this); this.onMouseEnter = this.onMouseEnter.bind(this); this.onMouseLeave = this.onMouseLeave.bind(this); this.onClick = this.onClick.bind(this); } componentWillUnmount(){ const { hoverTerm, selectedTerm, term } = this.props; if (hoverTerm === term || selectedTerm === term){ this.onMouseLeave(); } } generateNode(){ return _.pick(this.props, 'field', 'term', 'color', 'position', 'experiment_sets', 'experiments', 'files'); } onMouseEnter(e){ const { field, term, color, onNodeMouseEnter } = this.props; vizUtil.highlightTerm(field, term, color); if (typeof onNodeMouseEnter === 'function'){ onNodeMouseEnter(this.generateNode(), e); } } onMouseLeave(e){ if (typeof this.props.onNodeMouseLeave === 'function'){ this.props.onNodeMouseLeave(this.generateNode(), e); } } onClick(e){ if (typeof this.props.onNodeClick === 'function'){ this.props.onNodeClick(this.generateNode(), e); } } render(){ const { color: propColor, term, name, field, aggregateType } = this.props; const color = propColor || "transparent"; return ( <div className="term text-truncate"> <span onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} onClick={this.onClick} > <div className="color-patch no-highlight-color" data-term={term} style={{ backgroundColor : color }} /> { name || Schemas.Term.toName(field, term) } { aggregateType && this.props[aggregateType] ? <span className="text-300"> &nbsp;({ this.props[aggregateType] })</span> : null } </span> </div> ); } } /** * May have multiple terms. * * @prop {string} field - Field name, in object-dot-notation. * @prop {boolean} includeFieldTitle - Whether field title should be included at the top of list of terms. * @prop {Object[]} terms - Terms which belong to this field, in the form of objects. */ const Field = React.memo(function Field(props){ const { field, title, name, includeFieldTitle, terms } = props; return ( <div className="field" data-field={field} onMouseLeave={vizUtil.unhighlightTerms.bind(this, field)}> { includeFieldTitle ? <h5 className="text-500 legend-field-title">{ title || name || field }</h5> : null } { _.map(terms, (term, i) => <Legend.Term {...term} field={field} key={term.term} position={i} {..._.pick(props, 'onNodeMouseEnter', 'onNodeMouseLeave', 'onNodeClick', 'selectedTerm', 'hoverTerm', 'aggregateType')} /> )} </div> ); }); Field.defaultProps = { 'includeFieldTitle' : true }; class LegendViewContainer extends React.Component { static defaultProps = { 'expandable' : false, 'expandableAfter' : 5 }; constructor(props){ super(props); this.showToggleIcon = this.showToggleIcon.bind(this); this.toggleIcon = this.toggleIcon.bind(this); this.render = this.render.bind(this); } componentDidUpdate(){ if (this.showToggleIcon()){ ReactTooltip.rebuild(); } } showToggleIcon(){ return this.props.expandable && this.props.field.terms && this.props.field.terms.length > this.props.expandableAfter; } toggleIcon(){ if (!this.showToggleIcon()) return null; var iconClass = this.props.expanded ? 'compress' : 'expand'; return ( <div className="expand-toggle text-center" onClick={this.props.onToggleExpand} data-tip={this.props.expanded ? "Collapse" : "Expand" } data-place="left"> <i className={"icon icon-fw fas icon-" + iconClass}/> </div> ); } /** * @returns {JSX.Element} Div element containing props.title and list of {@link Legend.Field} components. */ render(){ if (!this.props.field || !this.props.field.field) return null; var className = 'legend ' + this.props.className; if (this.props && this.props.expanded) className += ' expanded'; return ( <div className={className} id={this.props.id} style={{ 'width' : this.props.width || null }}> { this.props.title } { this.toggleIcon() } <Legend.Field {...Legend.parseFieldName(this.props.field)} aggregateType={this.props.aggregateType} includeFieldTitle={this.props.includeFieldTitles} onNodeMouseEnter={this.props.onNodeMouseEnter} onNodeMouseLeave={this.props.onNodeMouseLeave} onNodeClick={this.props.onNodeClick} selectedTerm={this.props.selectedTerm} hoverTerm={this.props.hoverTerm} /> </div> ); } } /** * Legend components to use alongside Charts. Best to include within a UIControlsWrapper, and place next to chart, utilizing the same data. * * @class Legend * @type {Component} * @prop {FieldObject} field - Object containing at least 'field', in object dot notation, and 'terms'. * @prop {boolean} includeFieldTitle - Whether to show field title at top of terms. * @prop {string} className - Optional className to add to Legend's outermost div container. * @prop {number} width - How wide should the legend container element (<div>) be. * @prop {string|Element|Component} title - Optional title to display at top of legend. */ export class Legend extends React.PureComponent { static Term = Term; static Field = Field; static barPlotFieldDataToLegendFieldsData(field, sortBy = null, colorCycler = barplot_color_cycler){ if (Array.isArray(field) && field.length > 0 && field[0] && typeof field[0] === 'object'){ return field.map(function(f){ return Legend.barPlotFieldDataToLegendFieldsData(f, sortBy); }); } if (!field) return null; var terms = _.pairs(field.terms).map(function(p){ // p[0] = term, p[1] = term counts return { 'field' : field.field, 'name' : Schemas.Term.toName(field.field, p[0]), 'term' : p[0], 'color' : barplot_color_cycler.colorForNode({ 'term' : p[0], 'field' : field.field }), 'experiment_sets' : p[1].experiment_sets, 'experiments' : p[1].experiments, 'files' : p[1].files }; }); var adjustedField = _.extend({}, field, { 'terms' : terms }); _.extend(adjustedField, { 'terms' : Legend.sortLegendFieldTermsByColorPalette(adjustedField, colorCycler) }); if (sortBy){ adjustedField.terms = _.sortBy(adjustedField.terms, sortBy); } return adjustedField; } static sortLegendFieldTermsByColorPalette(field, colorCycler){ if (!colorCycler) { logger.error("No ColorCycler instance supplied."); return field.terms; } if (field.terms && field.terms[0] && field.terms[0].color === null){ console.warn("No colors assigned to legend terms, skipping sorting. BarPlot.UIControlsWrapper or w/e should catch lack of color and force update within 1s."); return field.terms; } return colorCycler.sortObjectsByColorPalette(field.terms); } /** * @param {FieldObject} field - Field object containing at least a title, name, or field. * @param {{Object}} schemas - Schemas object passed down from app.state. * @returns {FieldObject} Modified field object. */ static parseFieldName(field, schemas = null){ if (!field.title && !field.name) { return _.extend({} , field, { 'name' : Schemas.Field.toName(field.field, schemas) }); } return field; } static defaultProps = { 'hasPopover' : false, 'position' : 'absolute', 'id' : null, 'className' : 'chart-color-legend', 'width' : null, 'height' : null, 'expandable': false, 'expandableAfter' : 5, 'defaultExpanded' : false, 'aggregateType' : 'experiment_sets', 'title' : null //<h4 className="text-500">Legend</h4> }; render(){ return <LegendExpandContainer {...this.props} />; } } class LegendExpandContainer extends React.PureComponent { static clickCoordsCallback(node, containerPosition, boundsHeight, isOnRightSide){ var margin = 260; return { 'x' : !isOnRightSide ? containerPosition.left - margin : containerPosition.left + 30, 'y' : containerPosition.top - 10 + (16 * (node.position || 0)), }; } static defaultProps = { 'expandableAfter' : 5, 'expandable' : false, 'defaultExpanded' : false, 'hasPopover' : false }; constructor(props){ super(props); this.handleExpandToggle = _.throttle(this.handleExpandToggle.bind(this), 500); if (this.props.expandable){ this.state = { 'expanded' : props.defaultExpanded }; } } handleExpandToggle(evt){ this.setState(function({ expanded }){ return { 'expanded' : !expanded }; }); } legendComponent(){ var propsToPass = _.clone(this.props); propsToPass.onToggleExpand = this.handleExpandToggle; propsToPass.expanded = (this.state && this.state.expanded) || false; if (!this.props.hasPopover) return <LegendViewContainer {...propsToPass} />; return ( <CursorViewBounds eventCategory="BarPlotLegend" href={this.props.href} actions={this.props.cursorDetailActions} highlightTerm width={this.props.width} clickCoordsFxn={LegendExpandContainer.clickCoordsCallback}> <LegendViewContainer {...propsToPass} /> </CursorViewBounds> ); } render(){ if (!this.props.expandable || !this.state){ return this.legendComponent(); } else { var className = "legend-expand-container"; if (this.state.expanded) className += ' expanded'; return <div className={className} children={this.legendComponent()} />; } } }
1_simple_server_render/app.js
chkui/react-server-demo
'use strict'; import React from 'react' const s_contain = { width: '40rem', display: 'inline-block' },s_h3 = { display: 'inline-block' } const App = props => <div style={s_contain}> <h3 style={s_h3}>这是一个简单的服务器端渲染展示页面。</h3> <P /> <P2 /> </div> class P extends React.Component{ constructor(...props){ super(...props) } render(){ return( <p>这是用ES6的class实现的组件,当在服务器上运行时对其进行修改页面会同步进行更新。</p> ) } } const P2 = props => <p>这是用function实现的组件,当在服务器上运行时修改内容并不会刷新,需要手工F5。</p> export default App
tests/react_children/text.js
popham/flow
// @flow import React from 'react'; class Text extends React.Component<{children: string}, void> {} class TextOptional extends React.Component<{children?: string}, void> {} class TextLiteral extends React.Component<{children: 'foo' | 'bar'}, void> {} <Text />; // Error: `children` is required. <TextOptional />; // OK: `children` is optional. <TextLiteral />; // Error: `children` is required. <Text>Hello, world!</Text>; // OK: `children` is a single string. <Text></Text>; // Error: `children` does not exist. <Text> </Text>; // OK: `children` is some space. <Text>{}</Text>; // Error: `children` is required. <Text>{/* Hello, world! */}</Text>; // Error: `children` is required. <Text>{undefined}</Text>; // Error: `undefined` is not allowed. <Text>{null}</Text>; // Error: `null` is not allowed. <Text>{true}</Text>; // Error: `boolean`s are not allowed. <Text>{false}</Text>; // Error: `boolean`s are not allowed. <Text>{0}</Text>; // Error: `number`s are not allowed. <Text>{42}</Text>; // Error: `number`s are not allowed. <Text><intrinsic/></Text>; // Error: elements are not allowed. // OK: Text across multiple lines is fine. <Text> Hello, world! Multiline. </Text>; <Text>{'Hello, world!'}</Text>; // OK: Single string in an expression container. <Text>{'Hello, '}{'world!'}</Text>; // Error: We did not allow an array. <Text>Hello, {'world!'}</Text>; // Error: We did not allow an array. <Text>{'Hello, world!'} </Text>; // Error: Spaces cause there to be an array. <Text> {'Hello, world!'}</Text>; // Error: Spaces cause there to be an array. // OK: Newlines are trimmed. <Text> {'Hello, world!'} </Text>; <TextLiteral>foo</TextLiteral>; // OK: Text literal is fine. <TextLiteral>bar</TextLiteral>; // OK: Text literal is fine. <TextLiteral>{'foo'}</TextLiteral>; // OK: Text literal is fine. <TextLiteral>buz</TextLiteral>; // Error: `buz` is not allowed. <TextLiteral>{'buz'}</TextLiteral>; // Error: `buz` is not allowed. <TextLiteral>foo </TextLiteral>; // Error: Spaces are not trimmed. <TextLiteral> foo</TextLiteral>; // Error: Spaces are not trimmed. <TextLiteral>{'foo'} </TextLiteral>; // Error: Spaces are not trimmed. <TextLiteral> {'foo'}</TextLiteral>; // Error: Spaces are not trimmed. // OK: Newlines are trimmed. <TextLiteral> foo </TextLiteral>;
blueocean-material-icons/src/js/components/svg-icons/hardware/keyboard-arrow-up.js
jenkinsci/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const HardwareKeyboardArrowUp = (props) => ( <SvgIcon {...props}> <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"/> </SvgIcon> ); HardwareKeyboardArrowUp.displayName = 'HardwareKeyboardArrowUp'; HardwareKeyboardArrowUp.muiName = 'SvgIcon'; export default HardwareKeyboardArrowUp;
app/javascript/mastodon/components/dropdown_menu.js
MitarashiDango/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import IconButton from './icon_button'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import { supportsPassiveEvents } from 'detect-passive-events'; import classNames from 'classnames'; import { CircularProgress } from 'mastodon/components/loading_indicator'; const listenerOptions = supportsPassiveEvents ? { passive: true } : false; let id = 0; class DropdownMenu extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { items: PropTypes.oneOfType([PropTypes.array, ImmutablePropTypes.list]).isRequired, loading: PropTypes.bool, scrollable: PropTypes.bool, onClose: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, openedViaKeyboard: PropTypes.bool, renderItem: PropTypes.func, renderHeader: PropTypes.func, onItemClick: PropTypes.func.isRequired, }; static defaultProps = { style: {}, placement: 'bottom', }; state = { mounted: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('keydown', this.handleKeyDown, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); if (this.focusedItem && this.props.openedViaKeyboard) { this.focusedItem.focus({ preventScroll: true }); } this.setState({ mounted: true }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('keydown', this.handleKeyDown, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } setFocusRef = c => { this.focusedItem = c; } handleKeyDown = e => { const items = Array.from(this.node.querySelectorAll('a, button')); const index = items.indexOf(document.activeElement); let element = null; switch(e.key) { case 'ArrowDown': element = items[index+1] || items[0]; break; case 'ArrowUp': element = items[index-1] || items[items.length-1]; break; case 'Tab': if (e.shiftKey) { element = items[index-1] || items[items.length-1]; } else { element = items[index+1] || items[0]; } break; case 'Home': element = items[0]; break; case 'End': element = items[items.length-1]; break; case 'Escape': this.props.onClose(); break; } if (element) { element.focus(); e.preventDefault(); e.stopPropagation(); } } handleItemKeyPress = e => { if (e.key === 'Enter' || e.key === ' ') { this.handleClick(e); } } handleClick = e => { const { onItemClick } = this.props; onItemClick(e); } renderItem = (option, i) => { if (option === null) { return <li key={`sep-${i}`} className='dropdown-menu__separator' />; } const { text, href = '#', target = '_blank', method } = option; return ( <li className='dropdown-menu__item' key={`${text}-${i}`}> <a href={href} target={target} data-method={method} rel='noopener noreferrer' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyPress={this.handleItemKeyPress} data-index={i}> {text} </a> </li> ); } render () { const { items, style, placement, arrowOffsetLeft, arrowOffsetTop, scrollable, renderHeader, loading } = this.props; const { mounted } = this.state; let renderItem = this.props.renderItem || this.renderItem; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( // It should not be transformed when mounting because the resulting // size will be used to determine the coordinate of the menu by // react-overlays <div className={`dropdown-menu ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}> <div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} /> <div className={classNames('dropdown-menu__container', { 'dropdown-menu__container--loading': loading })}> {loading && ( <CircularProgress size={30} strokeWidth={3.5} /> )} {!loading && renderHeader && ( <div className='dropdown-menu__container__header'> {renderHeader(items)} </div> )} {!loading && ( <ul className={classNames('dropdown-menu__container__list', { 'dropdown-menu__container__list--scrollable': scrollable })}> {items.map((option, i) => renderItem(option, i, { onClick: this.handleClick, onKeyPress: this.handleItemKeyPress }))} </ul> )} </div> </div> )} </Motion> ); } } export default class Dropdown extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { children: PropTypes.node, icon: PropTypes.string, items: PropTypes.oneOfType([PropTypes.array, ImmutablePropTypes.list]).isRequired, loading: PropTypes.bool, size: PropTypes.number, title: PropTypes.string, disabled: PropTypes.bool, scrollable: PropTypes.bool, status: ImmutablePropTypes.map, isUserTouching: PropTypes.func, onOpen: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, dropdownPlacement: PropTypes.string, openDropdownId: PropTypes.number, openedViaKeyboard: PropTypes.bool, renderItem: PropTypes.func, renderHeader: PropTypes.func, onItemClick: PropTypes.func, }; static defaultProps = { title: 'Menu', }; state = { id: id++, }; handleClick = ({ target, type }) => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } else { const { top } = target.getBoundingClientRect(); const placement = top * 2 < innerHeight ? 'bottom' : 'top'; this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click'); } } handleClose = () => { if (this.activeElement) { this.activeElement.focus({ preventScroll: true }); this.activeElement = null; } this.props.onClose(this.state.id); } handleMouseDown = () => { if (!this.state.open) { this.activeElement = document.activeElement; } } handleButtonKeyDown = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleMouseDown(); break; } } handleKeyPress = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleClick(e); e.stopPropagation(); e.preventDefault(); break; } } handleItemClick = e => { const { onItemClick } = this.props; const i = Number(e.currentTarget.getAttribute('data-index')); const item = this.props.items[i]; this.handleClose(); if (typeof onItemClick === 'function') { e.preventDefault(); onItemClick(item, i); } else if (item && typeof item.action === 'function') { e.preventDefault(); item.action(); } else if (item && item.to) { e.preventDefault(); this.context.router.history.push(item.to); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } componentWillUnmount = () => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } } close = () => { this.handleClose(); } render () { const { icon, items, size, title, disabled, loading, scrollable, dropdownPlacement, openDropdownId, openedViaKeyboard, children, renderItem, renderHeader, } = this.props; const open = this.state.id === openDropdownId; const button = children ? React.cloneElement(React.Children.only(children), { ref: this.setTargetRef, onClick: this.handleClick, onMouseDown: this.handleMouseDown, onKeyDown: this.handleButtonKeyDown, onKeyPress: this.handleKeyPress, }) : ( <IconButton icon={icon} title={title} active={open} disabled={disabled} size={size} ref={this.setTargetRef} onClick={this.handleClick} onMouseDown={this.handleMouseDown} onKeyDown={this.handleButtonKeyDown} onKeyPress={this.handleKeyPress} /> ); return ( <React.Fragment> {button} <Overlay show={open} placement={dropdownPlacement} target={this.findTarget}> <DropdownMenu items={items} loading={loading} scrollable={scrollable} onClose={this.handleClose} openedViaKeyboard={openedViaKeyboard} renderItem={renderItem} renderHeader={renderHeader} onItemClick={this.handleItemClick} /> </Overlay> </React.Fragment> ); } }
src/components/Dashboard.js
jainvabhi/PWD
import React from 'react'; import PropTypes from 'prop-types'; import Webcam from '../actions/webcam'; import TimeTable from './TimeTable'; const Dashboard = ({user, logout}) => { Webcam.reset(); const userImage = { backgroundImage: `url(${user.webcam.image})`, }; return ( <div className="medical-portal dashboard"> <div className="medical-portal-header"> <div className="medical-logo"> <svg version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 309.665 309.665" xmlSpace="preserve" className="svgLogo"> <g xmlns="http://www.w3.org/2000/svg"> <path className="svgWhite" d="M309.665,94.734c0,15.903-10.797,29.301-25.496,33.562v136.653 c0,22.342-18.374,40.521-40.976,40.521c-21.984,0-39.968-17.269-40.879-38.83h-0.065v-1.594c0-0.033-0.033-0.065-0.033-0.098 h0.033v-81.173c0-13.106-10.797-23.773-24.033-23.773c-13.171,0-23.87,10.537-24.001,23.513v81.335 c0,22.374-18.407,40.554-40.976,40.554c-21.919,0-39.838-17.106-40.879-38.537h-0.098v-1.919c0-0.033,0-0.065,0-0.098 l-0.033-96.035C31.708,164.589,0,130.604,0,89.4V36.196c0-4.618,3.805-8.39,8.488-8.39h20.423v-15.22 c0-4.618,3.805-8.39,8.488-8.39h21.952c4.683,0,8.455,3.772,8.455,8.39v45.139c0,4.651-3.772,8.39-8.455,8.39H37.399 c-4.683,0-8.488-3.74-8.488-8.39V44.586H16.943V89.4c0,34.798,28.619,63.091,63.774,63.091s63.774-28.293,63.774-63.091V44.586 h-13.106v13.138c0,4.651-3.805,8.39-8.488,8.39h-21.952c-4.683,0-8.455-3.74-8.455-8.39V12.586c0-4.618,3.772-8.39,8.455-8.39 h21.952c4.683,0,8.488,3.772,8.488,8.39v15.22h21.561c4.683,0,8.488,3.772,8.488,8.39V89.4 c0,41.204-31.708,75.189-72.229,79.416v96.132c0.033,13.073,10.797,23.675,24.033,23.675s24.001-10.667,24.001-23.773v-81.075 c0-0.098,0-0.163,0-0.26v-2.732h0.163c1.528-20.944,19.22-37.562,40.814-37.562c22.602,0,40.977,18.212,40.977,40.554v81.27 c0.065,13.073,10.797,23.675,24.001,23.675c13.269,0,24.033-10.667,24.033-23.773v-135.97 c-16.098-3.252-28.228-17.366-28.228-34.245c0-19.285,15.838-34.96,35.318-34.96C293.795,59.774,309.665,75.449,309.665,94.734z M292.722,94.734c0-10.016-8.26-18.179-18.407-18.179s-18.374,8.163-18.374,18.179c0,10.049,8.228,18.179,18.374,18.179 C284.461,112.913,292.722,104.783,292.722,94.734z M114.442,49.334V20.976h-5.008v28.358H114.442z M50.863,49.334V20.976h-5.008 v28.358H50.863z"/> <path className="svgBlue" d="M274.315,76.555c10.147,0,18.407,8.163,18.407,18.179c0,10.049-8.26,18.179-18.407,18.179 s-18.374-8.13-18.374-18.179C255.941,84.717,264.168,76.555,274.315,76.555z M283.974,94.734c0-5.268-4.325-9.529-9.659-9.529 c-5.333,0-9.626,4.26-9.626,9.529s4.293,9.561,9.626,9.561S283.974,100.002,283.974,94.734z"/> <path className="svgWhite" d="M274.315,85.205c5.333,0,9.659,4.26,9.659,9.529s-4.325,9.561-9.659,9.561 c-5.333,0-9.626-4.293-9.626-9.561C264.689,89.465,268.981,85.205,274.315,85.205z"/> <rect x="109.433" y="20.976" className="svgBlue" width="5.008" height="28.358"/> <rect x="45.855" y="20.976" className="svgBlue" width="5.008" height="28.358"/> </g> </svg> <h1>Welcome Dr. {user.webcam.name}</h1> </div> <button onClick={logout} className="logout"> Logout <svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 471.2 471.2" xmlSpace="preserve"> <g> <path d="M227.619,444.2h-122.9c-33.4,0-60.5-27.2-60.5-60.5V87.5c0-33.4,27.2-60.5,60.5-60.5h124.9c7.5,0,13.5-6,13.5-13.5 s-6-13.5-13.5-13.5h-124.9c-48.3,0-87.5,39.3-87.5,87.5v296.2c0,48.3,39.3,87.5,87.5,87.5h122.9c7.5,0,13.5-6,13.5-13.5 S235.019,444.2,227.619,444.2z"/> <path d="M450.019,226.1l-85.8-85.8c-5.3-5.3-13.8-5.3-19.1,0c-5.3,5.3-5.3,13.8,0,19.1l62.8,62.8h-273.9c-7.5,0-13.5,6-13.5,13.5 s6,13.5,13.5,13.5h273.9l-62.8,62.8c-5.3,5.3-5.3,13.8,0,19.1c2.6,2.6,6.1,4,9.5,4s6.9-1.3,9.5-4l85.8-85.8 C455.319,239.9,455.319,231.3,450.019,226.1z"/> </g> </svg> </button> </div> <div className="content"> <div className="row"> <div className="col-sm-12 col-md-4"> <div className="card card-dashboard"> <div className="card-header userHeader" style={userImage}></div> <div className="card-content"> <div className="card-content-member"> <h4 className="m-t-0">{user.webcam.name}</h4> <p className="m-0"><i className="fa fa-map-marker"></i>{user.webcam.detail}</p> </div> <div className="card-content-summary"> <p>Specialties are Creative UI, HTML5, CSS3, Semantic Web, Responsive Layouts, Web Standards Compliance, Performance Optimization, Cross Device Troubleshooting.</p> </div> </div> <div className="card-footer"> <div className="card-footer-stats"> <div> <p>PROJECTS:</p><i className="fa fa-users"></i><span>241</span> </div> <div> <p>MESSAGES:</p><i className="fa fa-coffee"></i><span>350</span> </div> <div> <p>Last online</p><span className="stats-small">3 days ago</span> </div> </div> <div className="card-footer-message"> <h4><i className="fa fa-comments"></i> Message me</h4> </div> </div> </div> </div> <div className="col-sm-12 col-md-4"> <div className="card normal"> <div className="card-header"> <h2>Recently Viewed Patients</h2> </div> <div className="card-content patient-list"> <ul> <li>David Caresoniwski</li> <li>Deborah Smeerkat</li> <li>Geregory Steinberg</li> <li>Shantell Blakeson-Smith</li> <li>Kanye Eastern</li> </ul> </div> <div className="card-footer"> <div className="card-footer-message"> <h4><i className="fa fa-comments"></i> Look Up Patients </h4> </div> </div> </div> </div> <div className="col-sm-12 col-md-4"> <div className="card normal"> <div className="card-header"> <h2>Recently Viewed Claims</h2> </div> <div className="card-content patient-list"> <ul> <li><div>ID# 113478512-03 - Caresoniwski</div> <span className="badge badge-success">Processing</span></li> <li><div>ID# 178890231-01 - Smeerkat</div> <span className="badge badge-paid">Paid</span></li> <li><div>ID# 100021537-00 - Steinberg</div> <span className="badge badge-danger">Denied</span></li> <li><div>ID# 100006942-03 - Blakeson-Smith</div> <span className="badge badge-default">Adjusted</span></li> <li><div>ID# 178890231-00 - Eastern</div> <span className="badge badge-success">Processing</span></li> </ul> </div> <div className="card-footer"> <div className="card-footer-message"> <h4><i className="fa fa-comments"></i> Manage Claims </h4> </div> </div> </div> </div> </div> </div> <TimeTable /> </div> ); }; Dashboard.propTypes = { user: PropTypes.object, logout: PropTypes.func, }; export default Dashboard;
popup-study/components/StyledText.js
Morhaus/popupstudy
import React from 'react'; import { Text } from 'react-native'; export class MonoText extends React.Component { render() { return ( <Text {...this.props} style={[this.props.style, {fontFamily: 'space-mono'}]} /> ); } }
src/js/components/ui/FullWidthButton.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import shouldPureComponentUpdate from 'react-pure-render/function'; export default class FullWidthButton extends Component { shouldComponentUpdate = shouldPureComponentUpdate; static propTypes = { disabled: PropTypes.bool, onClick : PropTypes.func, }; render() { const {disabled, onClick} = this.props; return ( <button disabled={disabled} className="button button-fill button-big button-round" onClick={onClick}> {this.props.children} </button> ); } } FullWidthButton.defaultProps = { disabled: false, onClick : () => { }, };
app/jsx/gradezilla/default_gradebook/components/ComingSoonContent.js
venturehive/canvas-lms
/* * Copyright (C) 2017 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import SVGWrapper from 'jsx/shared/SVGWrapper'; import Typography from 'instructure-ui/lib/components/Typography'; import I18n from 'i18n!gradebook'; export default function ContentComingSoon () { return ( <div className="ComingSoonContent__Container"> <div className="ComingSoonContent__Body"> <SVGWrapper url="/images/gift_closed.svg" /> <Typography size="xx-large" weight="light">{I18n.t('New goodies coming soon!')}</Typography> <br /> <Typography weight="bold">{I18n.t('Check back in a little while.')}</Typography> </div> </div> ); }
front/src/utils/ebetsCategories.js
ethbets/ebets
/* Copyright (C) 2017 ethbets * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ import React from 'react'; const ebetsCategories = [ { name: 'Fighting', subcategory: [ { name: 'Boxing', path: 'fighting/boxing' }, { name: 'MMA', subcategory: [ { name: 'UFC', path: 'fighting/ufc' }, { name: 'Bellator', path: 'fighting/bellator' }, { name: 'Invicta FC', path: 'fighting/invictafc' } ] } ] }, { name: 'E-Sports', subcategory: [ { name: 'CS-GO', path: 'esports/csgo' }, { name: 'League of Legends', path: 'esports/lol' }, // { // name: 'League of Legends', // subcategory: [ // { // category: 'foo', // subcategory: [ // { // name: 'Bar', // path: 'esports/lol/foo/bar' // } // ] // }, // { // name: 'EU League', // path: 'esports/lol/eu_league' // }, // { // name: 'US League', // path: 'esports/lol/us_league' // }, // ] // } ] }, { name: 'Football', subcategory: [ { name: 'UEFA Champions League', path: 'football/uefachampionsleague' }, { name: 'UEFA Europa League', path: 'football/uefaeuropaleague' }, { name: 'La Liga', path: 'football/laliga' }, { name: 'Bundesliga', path: 'football/bundesliga' }, { name: 'Brasileirão', path: 'football/brasileirao' }, { name: 'Premier League', path: 'football/premierleague' }, { name: 'Serie A', path: 'football/seriea' }, { name: 'Ligue 1', path: 'football/ligue1' } ] } ] const getParsedCategories = () => { const getCategoriesRecursive = (category) => { if (!category.subcategory) return [category]; return category.subcategory.map(cat => ( getCategoriesRecursive(cat) )).reduce((a, b) => { return a.concat(b); }, []); } return ebetsCategories.map(categoryList => { const cat = getCategoriesRecursive(categoryList); return cat.map(category => { return <div key={category.path}> {category.name} </div> }); }).reduce((a, b) => { return a.concat(b); }, []); } export { getParsedCategories, ebetsCategories };
local_modules/react-component-redux/decorators/pure.js
pashaigood/react-component-redux
/** * @author PBelugin */ import React from 'react'; import container from './container'; import {functionName} from '../helpers/functions'; /** * * @param {React.Component} Component * @param {{actions: Object, state: Object, name: String, reducers: String, view: Function}} params * @returns {Container} */ export default function (Component, params) { if (! arguments[1]) { params = Component; Component = params.view; delete params.view; } const state = params.state || params.reducers.state; const actions = params.actions || params.reducers; @container class Container extends React.PureComponent { state = state; actions = actions; constructor(props) { super(props); this.name = params.name || (functionName(Component)); if (! this.name) { throw new Error('Component should have a name.'); } } render() { return <Component {...Object.assign({}, this.props, this.state, this.actions)}/>; } } return Container; };
packages/material-ui-icons/src/PhotoSizeSelectLarge.js
dsslimshaddy/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let PhotoSizeSelectLarge = props => <SvgIcon {...props}> <path d="M21 15h2v2h-2v-2zm0-4h2v2h-2v-2zm2 8h-2v2c1 0 2-1 2-2zM13 3h2v2h-2V3zm8 4h2v2h-2V7zm0-4v2h2c0-1-1-2-2-2zM1 7h2v2H1V7zm16-4h2v2h-2V3zm0 16h2v2h-2v-2zM3 3C2 3 1 4 1 5h2V3zm6 0h2v2H9V3zM5 3h2v2H5V3zm-4 8v8c0 1.1.9 2 2 2h12V11H1zm2 8l2.5-3.21 1.79 2.15 2.5-3.22L13 19H3z" /> </SvgIcon>; PhotoSizeSelectLarge = pure(PhotoSizeSelectLarge); PhotoSizeSelectLarge.muiName = 'SvgIcon'; export default PhotoSizeSelectLarge;
docs/src/components/Homepage/Heading/index.js
rhalff/storybook
import React from 'react'; import './style.css'; import storybookLogo from '../../../design/homepage/storybook-logo.svg'; const Heading = () => ( <div id="heading" className="row"> <div className="col-xs-12"> <img className="sb-title" src={storybookLogo} alt="Storybook Logo" /> <h3 className="sb-tagline"> The UI Development Environment <br /> You'll ♥️ to use </h3> </div> </div> ); export default Heading;
src/components/concent/steps/Step5.js
golemfactory/golem-electron
import React from 'react'; import Lottie from 'react-lottie'; import animData from './../../../assets/anims/Concent05'; const defaultOptions = { loop: false, autoplay: true, animationData: animData, rendererSettings: { preserveAspectRatio: 'xMidYMid slice' } }; export default class Step5 extends React.Component { constructor(props) { super(props); this.state = { isStopped: false, isPaused: false }; } render() { return ( <div className="concent-onboarding__container-step"> <div className="concent-onboarding__section-image"> <Lottie options={defaultOptions} isStopped={this.state.isStopped} isPaused={this.state.isPaused}/> </div> <div className="concent-onboarding__desc"> <h2>FAQ</h2> <span className="concent-info"> If you have any more questions regarding Concent Service and it's usage, please head over to our <a href="https://docs.golem.network/#/Products/Clay-Beta/Usage?id=concent-service">docs</a>, where we try to answer most of the questions you might have. <br/> <br/> You can also talk with us via <a href="https://chat.golem.network">chat</a>. </span> </div> </div> ); } }
example/MyMousetrap.js
georgeOsdDev/react-mousetrap-mixin
'use strict'; import React from 'react'; import {MousetrapMixin} from '../index.js'; let MyMousetrap = React.createClass({ mixins: [MousetrapMixin], getInitialState(){ return { color: 'red', greenChecked: false } }, getMousetrap(){ return { 'y e l l o w':() => { this.setState({ color: 'yellow' }); }, 'b l u e':() => { this.setState({ color: 'blue' }); } }; }, onChange(event){ this.setState({ greenChecked: event.target.checked }, () => { event.target.blur(); if (this.state.greenChecked){ this.addMousetrap('g r e e n', () => { this.setState({ color: 'green' }); }); } else { this.removeMousetrap('g r e e n'); } }); }, render() { let style = { backgroundColor: this.state.color } return ( <div> <div style={style}> Type 'yellow' or 'blue' </div> <input type='checkbox' onChange={this.onChange} checked={this.state.greenChecked} /> Enable 'green' </div> ); } }); export default MyMousetrap;
index.js
l-urence/react-native-autocomplete-input
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FlatList, Platform, StyleSheet, Text, TextInput, View, ViewPropTypes as RNViewPropTypes } from 'react-native'; // Keep this line for downwards compatibility with RN. // eslint-disable-next-line react/forbid-foreign-prop-types const ViewPropTypes = RNViewPropTypes || View.propTypes; class Autocomplete extends Component { static propTypes = { ...TextInput.propTypes, /** * These styles will be applied to the container which * surrounds the autocomplete component. */ containerStyle: ViewPropTypes.style, /** * Assign an array of data objects which should be * rendered in respect to the entered text. */ data: PropTypes.array, /** * Set to `true` to hide the suggestion list. */ hideResults: PropTypes.bool, /* * These styles will be applied to the container which surrounds * the textInput component. */ inputContainerStyle: ViewPropTypes.style, /* * Set `keyboardShouldPersistTaps` to true if RN version is <= 0.39. */ keyboardShouldPersistTaps: PropTypes.oneOfType([ PropTypes.string, PropTypes.bool ]), /* * These styles will be applied to the container which surrounds * the result list. */ listContainerStyle: ViewPropTypes.style, /** * These style will be applied to the result list. */ listStyle: ViewPropTypes.style, /** * `onShowResults` will be called when list is going to * show/hide results. */ onShowResults: PropTypes.func, /** * method for intercepting swipe on ListView. Used for ScrollView support on Android */ onStartShouldSetResponderCapture: PropTypes.func, /** * `renderItem` will be called to render the data objects * which will be displayed in the result view below the * text input. */ renderItem: PropTypes.func, keyExtractor: PropTypes.func, /** * `renderSeparator` will be called to render the list separators * which will be displayed between the list elements in the result view * below the text input. */ renderSeparator: PropTypes.func, /** * renders custom TextInput. All props passed to this function. */ renderTextInput: PropTypes.func, flatListProps: PropTypes.object }; static defaultProps = { data: [], keyboardShouldPersistTaps: 'always', onStartShouldSetResponderCapture: () => false, renderItem: ({ item }) => <Text>{item}</Text>, renderSeparator: null, renderTextInput: props => <TextInput {...props} />, flatListProps: {} }; constructor(props) { super(props); this.resultList = null; this.textInput = null; this.onRefListView = this.onRefListView.bind(this); this.onRefTextInput = this.onRefTextInput.bind(this); this.onEndEditing = this.onEndEditing.bind(this); } onEndEditing(e) { this.props.onEndEditing && this.props.onEndEditing(e); } onRefListView(resultList) { this.resultList = resultList; } onRefTextInput(textInput) { this.textInput = textInput; } /** * Proxy `blur()` to autocomplete's text input. */ blur() { const { textInput } = this; textInput && textInput.blur(); } /** * Proxy `focus()` to autocomplete's text input. */ focus() { const { textInput } = this; textInput && textInput.focus(); } /** * Proxy `isFocused()` to autocomplete's text input. */ isFocused() { const { textInput } = this; return textInput && textInput.isFocused(); } renderResultList() { const { data, listStyle, renderItem, keyExtractor, renderSeparator, keyboardShouldPersistTaps, flatListProps, onEndReached, onEndReachedThreshold } = this.props; return ( <FlatList ref={this.onRefListView} data={data} keyboardShouldPersistTaps={keyboardShouldPersistTaps} renderItem={renderItem} keyExtractor={keyExtractor} renderSeparator={renderSeparator} onEndReached={onEndReached} onEndReachedThreshold={onEndReachedThreshold} style={[styles.list, listStyle]} {...flatListProps} /> ); } renderTextInput() { const { renderTextInput, style } = this.props; const props = { style: [styles.input, style], ref: this.onRefTextInput, onEndEditing: this.onEndEditing, ...this.props }; return renderTextInput(props); } render() { const { data, containerStyle, hideResults, inputContainerStyle, listContainerStyle, onShowResults, onStartShouldSetResponderCapture } = this.props; const showResults = data.length > 0; // Notify listener if the suggestion will be shown. onShowResults && onShowResults(showResults); return ( <View style={[styles.container, containerStyle]}> <View style={[styles.inputContainer, inputContainerStyle]}> {this.renderTextInput()} </View> {!hideResults && ( <View style={listContainerStyle} onStartShouldSetResponderCapture={onStartShouldSetResponderCapture} > {showResults && this.renderResultList()} </View> )} </View> ); } } const border = { borderColor: '#b9b9b9', borderRadius: 1, borderWidth: 1 }; const androidStyles = { container: { flex: 1 }, inputContainer: { ...border, marginBottom: 0 }, list: { ...border, backgroundColor: 'white', borderTopWidth: 0, margin: 10, marginTop: 0 } }; const iosStyles = { container: { zIndex: 1 }, inputContainer: { ...border }, input: { backgroundColor: 'white', height: 40, paddingLeft: 3 }, list: { ...border, backgroundColor: 'white', borderTopWidth: 0, left: 0, position: 'absolute', right: 0 } }; const styles = StyleSheet.create({ input: { backgroundColor: 'white', height: 40, paddingLeft: 3 }, ...Platform.select({ android: { ...androidStyles }, ios: { ...iosStyles } }) }); export default Autocomplete;
011/src/components/app.js
StephenGrider/RallyCodingWeekly
import React, { Component } from 'react'; import { Link } from 'react-router'; export default class App extends Component { render() { return ( <div> <h4>App</h4> <Link to="/users">Users</Link> <hr /> {this.props.children} </div> ); } }
src/components/login/login.js
ndxm/nd-react-scaffold
/** * Created by hjx on 11/3/2015. */ import styles from './login.css'; import React from 'react'; import Router from 'react-router'; const { Navigation } = Router; export default React.createClass({ mixins: [ Navigation ], getInitialState: function () { return { username: '', password: '', showPassword: false, userClick: false, loginErr: '', isFocusPassword: false }; }, componentDidMount() { if (this.props.isLoggedIn) { this.props.redirect(); } }, componentWillReceiveProps(nextProps) { if (nextProps.isLoggedIn) { nextProps.redirect(); } }, handleUsernameChange: function (e) { this.setState({ username: e.currentTarget.value.trim() }); }, handlePasswordChange: function (e) { this.setState({ password: e.currentTarget.value.trim() }); }, handleToggle: function (e) { this.setState({ showPassword: e.currentTarget.checked }); }, handleFormSubmit: function (e) { e.preventDefault(); this.setState({ userClick: true, loginErr: '' }); if (this.state.username === '' || this.state.password === '') { return; } this.props.onLogin({ name: (/@/.test(this.state.username)?this.state.username:this.state.username + '@ndtest'), password: this.state.password }); }, blurPassword: function () { this.setState({ isFocusPassword: false }); }, focusPassword: function () { if (this.state.showPassword) { return; } this.setState({ isFocusPassword: true }); }, render: function () { let errForUsername, errForPassword; if (this.state.userClick === true) { errForUsername = this.state.username === '' ? '请输入用户名' : ''; errForPassword = this.state.password === '' ? '请输入密码' : ''; } return ( <div> <div className={styles.loginBody}> <div className={styles.loginRoad}></div> </div> <div className={styles.loginPanel}> <div className={styles.loginHi + ' ' + (this.state.isFocusPassword?styles.focusPassword:'')}></div> <h1 className={styles.siteTitle}>微博</h1> <form noValidate onSubmit={this.handleFormSubmit} className={`${styles['c-form']}`}> <div> <div className={`${styles['c-form__input']}`}> <span className={styles['c-form__label']+' '+styles['c-form-name']}></span> <input className={errForUsername ? `${styles['c-form__inputBox']} ${styles['c-form__inputBox--err']}` : `${styles['c-form__inputBox']}`} placeholder="工号/学号" type='text' value={this.state.username} onChange={this.handleUsernameChange}/> <span className={`${styles['c-form__err']}`}>{errForUsername}</span> </div> <div className={`${styles['c-form__input']}`}> <span className={styles['c-form__label'] +' '+styles['c-form-pwd']}></span> <input className={errForPassword ? `${styles['c-form__inputBox']} ${styles['c-form__inputBox--err']}` : `${styles['c-form__inputBox']}`} type={this.state.showPassword ? 'text' : 'password'} value={this.state.password} placeholder="密码" onFocus={this.focusPassword} onBlur={this.blurPassword} onChange={this.handlePasswordChange}/> <span className={`${styles['c-form__err']}`}>{errForPassword}</span> </div> <div className={`${styles['c-form__input']}`}> <label><input type='checkbox' checked={this.state.showPassword} onChange={this.handleToggle}/>显示密码</label> </div> </div> <div className={styles.loginFormBtm}> <span className={styles['c-form__err']}>{this.props.loginErr}</span> <input type='submit' value='登录' className={`${styles['c-form__btn']}`}/> </div> </form> </div> </div> ); } });
packages/demos/demo/src/components/Project/card.js
garth/cerebral
import React from 'react' import { connect } from '@cerebral/react' import { signal } from 'cerebral/tags' import projectWithDetails from '../../compute/projectWithDetails' import { displayElapsed } from '../../helpers/dateTime' export default connect( { item: projectWithDetails, penClick: signal`projects.penClicked`, trashClick: signal`projects.trashClicked`, }, function ProjectCard({ item, itemKey, penClick, trashClick }) { return ( <div className="card"> <div className="card-content"> <div className="media"> <div className="media-left"> <span className="icon is-medium"> <i className="fa fa-folder" /> </span> </div> <div className="media-content"> <p className="title is-5"> {item.name} </p> <p className="subtitle is-6">{item.client && item.client.name}</p> </div> <div className="media-right"> {displayElapsed(item.elapsed)} </div> </div> <div className="content"> {item.notes} </div> <nav className="level" onClick={e => e.stopPropagation()}> <div className="level-left" /> <div className="level-right"> {item.$isDefaultItem !== true && <a className="level-item" onClick={() => penClick({ key: item.key })} > <span className="icon is-small"> <i className="fa fa-pencil" /> </span> </a>} {item.$isDefaultItem !== true && <a className="level-item" onClick={() => trashClick({ key: item.key })} > <span className="icon is-small"> <i className="fa fa-trash" /> </span> </a>} </div> </nav> </div> </div> ) } )
docs/src/app/components/pages/components/TimePicker/Page.js
ngbrown/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import timePickerReadmeText from './README'; import TimePickerExampleSimple from './ExampleSimple'; import timePickerExampleSimpleCode from '!raw!./ExampleSimple'; import TimePickerExampleComplex from './ExampleComplex'; import timePickerExampleComplexCode from '!raw!./ExampleComplex'; import TimePickerExampleInternational from './ExampleInternational'; import timePickerExampleInternationalCode from '!raw!./ExampleInternational'; import timePickerCode from '!raw!material-ui/TimePicker/TimePicker'; const descriptions = { simple: 'Time Picker supports 12 hour and 24 hour formats. In 12 hour format the AM and PM indicators toggle the ' + 'selected time period. You can also disable the Dialog passing true to the disabled property.', controlled: '`TimePicker` can be used as a controlled component.', localised: 'The buttons can be localised using the `cancelLabel` and `okLabel` properties.', }; const TimePickersPage = () => ( <div> <Title render={(previousTitle) => `Time Picker - ${previousTitle}`} /> <MarkdownElement text={timePickerReadmeText} /> <CodeExample title="Simple examples" description={descriptions.simple} code={timePickerExampleSimpleCode} > <TimePickerExampleSimple /> </CodeExample> <CodeExample title="Controlled examples" description={descriptions.controlled} code={timePickerExampleComplexCode} > <TimePickerExampleComplex /> </CodeExample> <CodeExample title="Localised example" description={descriptions.localised} code={timePickerExampleInternationalCode} > <TimePickerExampleInternational /> </CodeExample> <PropTypeDescription code={timePickerCode} /> </div> ); export default TimePickersPage;
RelayExample/src/Book.js
davidpaulmcintyre/graphql-stockticker
import React from 'react'; import Relay from 'react-relay'; import './Book.css'; function Book({ book }) { console.log(book.image) return ( <div className="book"> <img src={book.image} /> <div>{book.title}</div> </div> ); } export default Relay.createContainer(Book, { fragments: { book: () => Relay.QL` fragment on Book { title image } `, }, });
src/ui/auth/RegisterScreen.js
exponentjs/xde
/** * @flow */ import React from 'react'; import RegisterForm from './components/RegisterForm'; import { actions } from 'xde/state'; import { connectToData } from 'xde/state/utils'; import type { AppActions, AppState } from 'xde/state/types'; import type { UserOrLegacyUser } from 'xdl/build/User'; import type { RegisterFormData } from './components/RegisterForm'; type Props = { user: ?UserOrLegacyUser, isRegistering: boolean, actions: AppActions, }; class RegisterScreen extends React.Component { props: Props; static data = ({ auth }: AppState) => ({ user: auth.user, isRegistering: auth.pendingAction === 'REGISTER', }); render() { return ( <RegisterForm user={this.props.user} isRegistering={this.props.isRegistering} onRegister={this._handleRegister} onLogout={this._handleLogout} /> ); } _handleLogout = () => { this.props.actions.auth.logout(); }; _handleRegister = (formData: RegisterFormData) => { if (this.props.isRegistering) { return; } this.props.actions.auth.register({ ...formData, }); }; } export default connectToData(actions)(RegisterScreen);
src/components/HomeScreen.js
teamstrobe/mancreact-client
import React, { Component } from 'react'; import apiFetch from '../apiFetch'; import { eventsURI } from '../config/urls'; import UpcomingEventHero from './UpcomingEventHero'; import PreviousMeetupsList from './PreviousMeetupsList'; import Spinner from './Spinner'; class HomeScreen extends Component { state = { events: null, loading: false, }; componentWillMount() { this.fetchData(); } async fetchData() { this.setState({ loading: true, }); const events = await this.getEvents(); this.setState({ events, loading: false, }); } async getEvents() { return await apiFetch(eventsURI()); } render() { const { events, loading } = this.state; let upcomingEvent; let previousEvents; if (events != null) { upcomingEvent = events.filter(event => event.status === 'upcoming')[0]; previousEvents = events.filter(event => event.status === 'past'); } return ( <div> {loading ? <Spinner /> : <div> {upcomingEvent && <UpcomingEventHero event={upcomingEvent} />} {previousEvents && <PreviousMeetupsList events={previousEvents} />} </div>} </div> ); } } export default HomeScreen;
src/containers/CreateCategory.js
nickeblewis/walkapp
/** * Component for category creation */ import React from 'react' import { withRouter } from 'react-router' import { graphql } from 'react-apollo' import gql from 'graphql-tag' class CreateCategory extends React.Component { static propTypes = { router: React.PropTypes.object, addName: React.PropTypes.func, } state = { name: '', } render () { return ( <div className='w-100 pa4 flex justify-center'> <div style={{ maxWidth: 400 }} className=''> <input className='w-100 pa3 mv2' value={this.state.name} placeholder='Name' onChange={(e) => this.setState({name: e.target.value})} /> {this.state.name && <button className='pa3 bg-black-10 bn dim ttu pointer' onClick={this.handleCategory}>Category</button> } </div> </div> ) } handleCategory = () => { const {name} = this.state this.props.addCategory({ name }) .then(() => { this.props.router.push('/categories') }) } } const addMutation = gql` mutation addCategory($name: String!) { createCategory(name: $name) { id name } } ` const CategoryWithMutation = graphql(addMutation, { props: ({ ownProps, mutate }) => ({ addCategory: ({ name }) => mutate({ variables: { name }, updateQueries: { allCategories: (state, { mutationResult }) => { const newCategory = mutationResult.data.createCategory return { allCategories: [...state.allCategories, newCategory] } }, }, }) }) })(withRouter(CreateCategory)) export default CategoryWithMutation
assets/TopNav.js
rmccue/new-list-tables
import React from 'react'; const PageLink = props => { const { children, isActive } = props; if ( ! isActive ) { return <span className='tablenav-pages-navspan'>{ children }</span>; } // Remove the isActive prop. const otherProps = Object.assign( {}, props ); delete otherProps.isActive; return <a { ...otherProps } />; }; PageLink.propTypes = { isActive: React.PropTypes.bool.isRequired, }; export default class TopNav extends React.Component { constructor(props) { super(props); this.state = { page: null, }; } componentWillReceiveProps( nextProps ) { // If receiving page update, wipe input. if ( nextProps.page !== this.props.page ) { this.setState({ page: null }); } } render() { const { page, total, totalPages, onJump } = this.props; return <form className="tablenav top" onSubmit={ e => { e.preventDefault(); onJump( this.state.page ) } } > <h2 className="screen-reader-text">Comments list navigation</h2> { totalPages > 1 ? <div className="tablenav-pages"> <span className="displaying-num">{ total } items</span> <span className="pagination-links"> <PageLink className="first-page" isActive={ page !== 1 } onClick={ () => onJump( 1 ) } > <span className="screen-reader-text">First page</span> <span aria-hidden="true">«</span> </PageLink> { ' ' } <PageLink className="prev-page" isActive={ page !== 1 } onClick={ () => onJump( page - 1 ) } > <span className="screen-reader-text">Previous page</span> <span aria-hidden="true">‹</span> </PageLink> { ' ' } <span className="paging-input"> <label className="screen-reader-text">Current Page</label> <input aria-describedby="table-paging" className="current-page" id="current-page-selector" name="paged" size="2" type="text" value={ this.state.page === null ? page : this.state.page } onChange={ e => this.setState({ page: e.target.value }) } /> <span className="tablenav-paging-text"> { ' of ' } <span className="total-pages">{ totalPages }</span> </span> </span> { ' ' } <PageLink className="next-page" isActive={ page !== totalPages } onClick={ () => onJump( page + 1 ) } > <span className="screen-reader-text">Next page</span> <span aria-hidden="true">›</span> </PageLink> { ' ' } <PageLink className="last-page" isActive={ page !== totalPages } onClick={ () => onJump( totalPages ) } > <span className="screen-reader-text">Last page</span> <span aria-hidden="true">»</span> </PageLink> </span> </div> : null } <br className="clear" /> </form>; } }
docs/app/Examples/modules/Dropdown/Usage/DropdownExampleRemoveNoResultsMessage.js
Rohanhacker/Semantic-UI-React
import React from 'react' import { Dropdown } from 'semantic-ui-react' const DropdownExampleRemoveNoResultsMessage = () => ( <Dropdown options={[]} search selection placeholder='No message...' noResultsMessage={null} /> ) export default DropdownExampleRemoveNoResultsMessage
app/views/Watches/main.js
herereadthis/redwall
import React from 'react'; import Router from 'react-router'; import FluxComponent from 'flummox/component'; import AppFlux from 'AppFlux'; import AppStore from 'AppStore'; import Watches from './Watches'; var {DefaultRoute, Route} = Router, routes; const flux = new AppFlux(); routes = ( <Route> <Route name="watches" path="/watches/" handler={Watches}/> <DefaultRoute handler={Watches}/> </Route> ); // Router.HistoryLocation gets rid of the the /#/ hash by using html5 history // API for cleaner URLs // Router.run(routes, Router.HistoryLocation, (Handler) => { Router.run(routes, Router.HistoryLocation, (Handler) => { React.render( <FluxComponent flux={flux} connectToStores={[AppStore.ID]}> <Handler/> </FluxComponent>, document.getElementById('app') ); });
docs/src/app/components/pages/components/Checkbox/ExampleSimple.js
skarnecki/material-ui
import React from 'react'; import Checkbox from 'material-ui/Checkbox'; import ActionFavorite from 'material-ui/svg-icons/action/favorite'; import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border'; const styles = { block: { maxWidth: 250, }, checkbox: { marginBottom: 16, }, }; const CheckboxExampleSimple = () => ( <div style={styles.block}> <Checkbox label="Simple" style={styles.checkbox} /> <Checkbox label="Checked by default" defaultChecked={true} style={styles.checkbox} /> <Checkbox checkedIcon={<ActionFavorite />} uncheckedIcon={<ActionFavoriteBorder />} label="Custom icon" style={styles.checkbox} /> <Checkbox label="Disabled unchecked" disabled={true} style={styles.checkbox} /> <Checkbox label="Disabled checked" checked={true} disabled={true} style={styles.checkbox} /> <Checkbox label="Label on the left" labelPosition="left" style={styles.checkbox} /> </div> ); export default CheckboxExampleSimple;
dist/react-calendar-icon.esm.js
kkostov/react-calendar-icon
import React from 'react'; import styled from '@emotion/styled'; var themedConfig = (theme => ({ textColor: 'white', // text color of the header and footer primaryColor: '#e85650', // used as background of the header and footer backgroundColor: '#fafafa', ...(theme === null || theme === void 0 ? void 0 : theme.calendarIcon) })); const IconDiv = styled('div')(props => ({ fontSize: '0.7em', backgroundColor: themedConfig(props.theme).backgroundColor, height: '8em', width: '8em', borderRadius: '0.7em', overflow: 'hidden', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between' })); const HeaderDiv = styled('div')(props => ({ color: themedConfig(props.theme).textColor, backgroundColor: themedConfig(props.theme).primaryColor, width: '100%', textAlign: 'center', fontSize: '1.2em', lineHeight: '1.4em' })); const ValueDiv = styled('div')({ letterSpacing: '-0.05em', fontSize: '2.6rem', marginRight: '0.15em', marginTop: '0.1em' }); const FooterDiv = styled('div')(props => ({ color: themedConfig(props.theme).textColor, backgroundColor: themedConfig(props.theme).primaryColor, width: '100%', textAlign: 'center', fontSize: '1.2em', lineHeight: '1.4em' })); const defaultOptions = { header: { weekday: 'long' }, footer: { month: 'long' }, value: { day: '2-digit' }, locale: [] }; function formatDate(date, locale, formatOptions) { return date.toLocaleDateString(locale, formatOptions); } function CalendarIcon(_ref) { let { date, options = defaultOptions } = _ref; return /*#__PURE__*/React.createElement(IconDiv, null, /*#__PURE__*/React.createElement(HeaderDiv, null, formatDate(date, options.locale, options.header)), /*#__PURE__*/React.createElement(ValueDiv, null, formatDate(date, options.locale, options.value)), /*#__PURE__*/React.createElement(FooterDiv, null, formatDate(date, options.locale, options.footer))); } export { CalendarIcon, CalendarIcon as default };
src/views/Home/index.js
JounQin/1stg
import React from 'react' import PropTypes from 'prop-types' import { Grid } from './Grid' import styles from './index.scss' const GRIDS = [ { title: 'GitHub', link: 'https://github.com/JounQin', className: 'github', }, { title: 'Rubick', text: 'Vue SSR + TS', link: 'https://rubick.1stg.me/', className: 'rubick', }, { title: 'React Hackernews', text: 'View React HN', link: 'https://react-hn.now.sh', className: 'react-hn', }, { title: 'My Blog', text: 'Personal Website', link: 'https://blog.1stg.me', className: 'blog', }, ] export const Home = () => ( <main className={styles.main}> {GRIDS.map((info, index) => ( <Grid key={index} {...info} /> ))} </main> ) Home.propTypes = { style: PropTypes.object, }
app/assets/scripts/components/Curves/index.js
bartoszkrawczyk2/curves.js
import React, { Component } from 'react'; import { drawSpline } from '../../core'; import './style.scss'; class Curves extends Component { componentDidMount() { this.canvas = this.refs.canvas; this.canvas.width = 280; this.canvas.height = 280; this.ctx = this.canvas.getContext('2d'); drawSpline( this.canvas, this.ctx, this.props.currentCurves[this.props.currentChannel].xs, this.props.currentCurves[this.props.currentChannel].ys ); } componentWillUpdate(nextProps, nextState) { drawSpline( this.canvas, this.ctx, nextProps.currentCurves[nextProps.currentChannel].xs, nextProps.currentCurves[nextProps.currentChannel].ys ); } render() { return ( <div> <p>Select channel:</p> <select className='channel-select' value={this.props.currentChannel} onChange={(e) => this.props.changeChannel(e.target.value)}> <option value='a'>Brightness</option> <option value='r'>Red</option> <option value='g'>Green</option> <option value='b'>Blue</option> </select> <canvas ref='canvas' onMouseDown={(e) => this.props.mouseDown( e, this.canvas || null, this.props.currentCurves[this.props.currentChannel] )} onMouseMove={(e) => this.props.mouseMove( e, this.canvas || null, this.ctx || null )} onMouseUp={this.props.mouseUp} onDoubleClick={(e) => this.props.doubleClick(e, this.props.currentCurves[this.props.currentChannel])} /> <span className='curves-desc'>Double click to add point.</span> <span className='curves-desc'>Hold shift and click on point to remove.</span> </div> ); } } export default Curves;
src/modules/Rooms/components/Chat/Chat.js
prjctrft/mantenuto
/* eslint-disable */ import React from 'react'; import Messages from './Messages'; export default (props) => { const styles = require('./Chat.scss'); return ( <div className={styles.Chat}> <div className={styles.ChatHeader}> <button className={styles.closeChat} onClick={props.toggleChat}> <i className={`fa ${styles.faTimesThin} fa-2x`} aria-hidden="true"></i> </button> </div> <p className='text-center'> <button disabled={props.disableLoadMore} onClick={props.loadMore} className='btn btn-default btn-sm btn-outline-dark'> ... </button> </p> <Messages /> <div className={`${styles.MessageInput}`}> <textarea placeholder='Send some love.' onKeyPress={props.handleSubmit} onChange={props.handleChange} value={props.content} className={`${styles.flexItem} form-control`} /> {/* <button onClick={props.handleSubmit} className={`btn btn-primary`}>Send</button> */} </div> </div> ) }
client/views/omnichannel/components/Label.js
VoiSmart/Rocket.Chat
import { Box } from '@rocket.chat/fuselage'; import React from 'react'; const Label = (props) => <Box mbe='x8' fontScale='p2' color='default' {...props} />; export default Label;
node_modules/react-router-dom/es/NavLink.js
rwarr/futaba-db
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; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; 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; } import React from 'react'; import PropTypes from 'prop-types'; import Route from './Route'; import Link from './Link'; /** * A <Link> wrapper that knows if it's "active" or not. */ var NavLink = function NavLink(_ref) { var to = _ref.to, exact = _ref.exact, strict = _ref.strict, location = _ref.location, activeClassName = _ref.activeClassName, className = _ref.className, activeStyle = _ref.activeStyle, style = _ref.style, getIsActive = _ref.isActive, ariaCurrent = _ref.ariaCurrent, rest = _objectWithoutProperties(_ref, ['to', 'exact', 'strict', 'location', 'activeClassName', 'className', 'activeStyle', 'style', 'isActive', 'ariaCurrent']); return React.createElement(Route, { path: (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to.pathname : to, exact: exact, strict: strict, location: location, children: function children(_ref2) { var location = _ref2.location, match = _ref2.match; var isActive = !!(getIsActive ? getIsActive(match, location) : match); return React.createElement(Link, _extends({ to: to, className: isActive ? [className, activeClassName].filter(function (i) { return i; }).join(' ') : className, style: isActive ? _extends({}, style, activeStyle) : style, 'aria-current': isActive && ariaCurrent }, rest)); } }); }; NavLink.propTypes = { to: Link.propTypes.to, exact: PropTypes.bool, strict: PropTypes.bool, location: PropTypes.object, activeClassName: PropTypes.string, className: PropTypes.string, activeStyle: PropTypes.object, style: PropTypes.object, isActive: PropTypes.func, ariaCurrent: PropTypes.oneOf(['page', 'step', 'location', 'true']) }; NavLink.defaultProps = { activeClassName: 'active', ariaCurrent: 'true' }; export default NavLink;
examples/src/Examples.js
BD2KGenomics/react-autosuggest
require('./Examples.less'); require('./Autosuggest.less'); import React, { Component } from 'react'; import { findDOMNode } from 'react-dom'; import BasicExample from './BasicExample/BasicExample'; import CustomRenderer from './CustomRenderer/CustomRenderer'; import MultipleSections from './MultipleSections/MultipleSections'; import ControlledComponent from './ControlledComponent/ControlledComponent'; import EventsPlayground from './EventsPlayground/EventsPlayground'; import EventsLog from './EventsLog/EventsLog'; export default class Examples extends Component { constructor() { super(); this.examples = [ 'Basic example', 'Custom renderer', 'Multiple sections', 'Controlled component', 'Events playground' ]; this.eventsPlaceholder = { type: 'placeholder', text: 'Once you interact with the Autosuggest, events will appear here.' }; this.eventQueue = []; this.state = { activeExample: decodeURI(location.hash).split('#')[1] || this.examples[0], events: [this.eventsPlaceholder] }; } changeExample(example) { this.setState({ activeExample: example }); } renderMenu() { return ( <div className="examples__menu" role="menu"> {this.examples.map(example => { const classes = 'examples__menu-item' + (example === this.state.activeExample ? ' examples__menu-item--active' : ''); return ( <div className={classes} key={example} role="menuitem" tabIndex="0" onClick={this.changeExample.bind(this, example)}> {example} </div> ); })} </div> ); } clearEvents() { this.setState({ events: [this.eventsPlaceholder] }); } eventsExist() { return this.state.events[0].type !== 'placeholder'; } renderEventsLog() { if (this.state.activeExample === 'Events playground') { return ( <div className="examples__events-log-wrapper"> { this.eventsExist() && <button onClick={::this.clearEvents}>Clear</button> } <EventsLog ref="eventsLog" events={this.state.events} /> </div> ); } return null; } isEventQueueEmpty() { return this.eventQueue.length === 0; } processEvents() { if (this.isEventQueueEmpty()) { return; } const event = this.eventQueue[0]; this.setState({ events: this.eventsExist() ? this.state.events.concat([event]) : [event] }, () => { this.eventQueue.shift(); this.processEvents(); // Scroll to the bottom findDOMNode(this.refs.eventsLog.refs.eventsLogWrapper).scrollTop = Number.MAX_SAFE_INTEGER; }); } onEventAdded(event) { const eventQueueWasEmpty = this.isEventQueueEmpty(); this.eventQueue.push(event); if (eventQueueWasEmpty) { this.processEvents(); } } focusOn(id) { document.getElementById(id).focus(); } renderExample() { switch (this.state.activeExample) { case 'Basic example': return <BasicExample ref={() => this.focusOn('basic-example')} />; case 'Custom renderer': return <CustomRenderer ref={() => this.focusOn('custom-renderer')} />; case 'Multiple sections': return <MultipleSections ref={() => this.focusOn('multiple-sections')} />; case 'Controlled component': return <ControlledComponent ref={() => this.focusOn('controlled-component-from')} />; case 'Events playground': return <EventsPlayground onEventAdded={::this.onEventAdded} ref={() => this.focusOn('events-playground')} />; } } render() { return ( <div className="examples"> <div className="examples__column"> {this.renderMenu()} {this.renderEventsLog()} </div> <div className="examples__column"> {this.renderExample()} </div> </div> ); } }
src/containers/App.js
zackbleach/react-transform-boilerplate
import React, { Component } from 'react'; import { compose, createStore, combineReducers } from 'redux'; import { Provider } from 'react-redux'; import { devTools, persistState } from 'redux-devtools'; import { DevTools, DebugPanel, LogMonitor } from 'redux-devtools/lib/react'; import CounterApp from './CounterApp'; import * as reducers from '../reducers'; import {incrementCounter} from '../actions/Actions'; const reducer = combineReducers(reducers); // TODO: refactor this out to own class which switches on config const finalCreateStore = compose( devTools(), persistState(window.location.href.match(/[?&]debug_session=([^&]+)\b/)) )(createStore); const store = finalCreateStore(reducer); export default class App extends Component { render() { return ( <div> <Provider store={store}> {() => <CounterApp /> } </Provider> <DebugPanel top right bottom> <DevTools store={store} monitor={LogMonitor} /> </DebugPanel> </div> ); } }
src/Alert.js
collinwu/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const Alert = React.createClass({ mixins: [BootstrapMixin], propTypes: { onDismiss: React.PropTypes.func, dismissAfter: React.PropTypes.number, closeLabel: React.PropTypes.string }, getDefaultProps() { return { bsClass: 'alert', bsStyle: 'info', closeLabel: 'Close Alert' }; }, renderDismissButton() { return ( <button type="button" className="close" aria-label={this.props.closeLabel} onClick={this.props.onDismiss}> <span aria-hidden="true">&times;</span> </button> ); }, render() { let classes = this.getBsClassSet(); let isDismissable = !!this.props.onDismiss; classes['alert-dismissable'] = isDismissable; return ( <div {...this.props} role='alert' className={classNames(this.props.className, classes)}> {isDismissable ? this.renderDismissButton() : null} {this.props.children} </div> ); }, componentDidMount() { if (this.props.dismissAfter && this.props.onDismiss) { this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter); } }, componentWillUnmount() { clearTimeout(this.dismissTimer); } }); export default Alert;
examples/redux-saga/cancellable-counter/src/components/Counter.js
ioof-holdings/redux-subspace
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { INCREMENT, DECREMENT, INCREMENT_IF_ODD, INCREMENT_ASYNC, CANCEL_INCREMENT_ASYNC } from '../actionTypes' function Counter({counter, countdown, dispatch}) { const action = (type, value) => () => dispatch({type, value}) return ( <div> Clicked: {counter} times {' '} <button onClick={action(INCREMENT)}>+</button> {' '} <button onClick={action(DECREMENT)}>-</button> {' '} <button onClick={action(INCREMENT_IF_ODD)}>Increment if odd</button> {' '} <button onClick={countdown ? action(CANCEL_INCREMENT_ASYNC) : action(INCREMENT_ASYNC, 5)} style={{color: countdown ? 'red' : 'black'}}> {countdown ? `Cancel increment (${countdown})` : 'increment after 5s'} </button> </div> ) } Counter.propTypes = { // dispatch actions dispatch: PropTypes.func.isRequired, // state counter: PropTypes.number.isRequired, countdown: PropTypes.number.isRequired } function mapStateToProps(state) { return { counter: state.counter, countdown: state.countdown } } export default connect(mapStateToProps)(Counter)
src/App.js
omerak/webpack-react-less-mocha-css-modules
import React, { Component } from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import router from './router'; import 'ui/less/main.less'; export default class App extends Component { constructor() { super(); this.state = { currentRoute: { component: 'div' } }; this.routeChange = this.routeChange.bind(this); } componentDidMount() { router(this.routeChange); } routeChange(route) { this.setState({ currentRoute: route }, () => { this.forceUpdate(); }); } renderComponent(component, props) { return component && React.createElement(component, props); } render() { const { component, props } = this.state.currentRoute; return ( <div className="appWrapper"> <ReactCSSTransitionGroup transitionName="anim-route" transitionAppear={true} transitionAppearTimeout={1000} transitionEnterTimeout={1000} transitionLeaveTimeout={1000} > <div> {this.renderComponent(component, props)} </div> </ReactCSSTransitionGroup> </div> ); } }
docs/src/app/components/pages/components/DropDownMenu/Page.js
spiermar/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import dropDownMenuReadmeText from './README'; import DropDownMenuSimpleExample from './ExampleSimple'; import dropDownMenuSimpleExampleCode from '!raw!./ExampleSimple'; import DropDownMenuOpenImmediateExample from './ExampleOpenImmediate'; import dropDownMenuOpenImmediateExampleCode from '!raw!./ExampleOpenImmediate'; import DropDownMenuLongMenuExample from './ExampleLongMenu'; import dropDownMenuLongMenuExampleCode from '!raw!./ExampleLongMenu'; import DropDownMenuLabeledExample from './ExampleLabeled'; import dropDownMenuLabeledExampleCode from '!raw!./ExampleLabeled'; import dropDownMenuCode from '!raw!material-ui/DropDownMenu/DropDownMenu'; const descriptions = { simple: '`DropDownMenu` is implemented as a controlled component, with the current selection set through the ' + '`value` property.', openImmediate: 'With `openImmediately` property set, the menu will open on mount.', long: 'With the `maxHeight` property set, the menu will be scrollable if the number of items causes the height ' + 'to exceed this limit.', label: 'With a `label` applied to each `MenuItem`, `DropDownMenu` displays a complementary description ' + 'of the selected item.', }; const DropDownMenuPage = () => ( <div> <Title render={(previousTitle) => `Drop Down Menu - ${previousTitle}`} /> <MarkdownElement text={dropDownMenuReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={dropDownMenuSimpleExampleCode} > <DropDownMenuSimpleExample /> </CodeExample> <CodeExample title="Open Immediate example" description={descriptions.openImmediate} code={dropDownMenuOpenImmediateExampleCode} > <DropDownMenuOpenImmediateExample /> </CodeExample> <CodeExample title="Long example" description={descriptions.long} code={dropDownMenuLongMenuExampleCode} > <DropDownMenuLongMenuExample /> </CodeExample> <CodeExample title="Label example" description={descriptions.label} code={dropDownMenuLabeledExampleCode} > <DropDownMenuLabeledExample /> </CodeExample> <PropTypeDescription code={dropDownMenuCode} /> </div> ); export default DropDownMenuPage;
packages/neos-ui-editors/src/Editors/Boolean/index.js
neos/neos-ui
import React from 'react'; import PropTypes from 'prop-types'; import mergeClassNames from 'classnames'; import CheckBox from '@neos-project/react-ui-components/src/CheckBox/'; import Label from '@neos-project/react-ui-components/src/Label/'; import I18n from '@neos-project/neos-ui-i18n'; import style from './style.css'; // ToDo: Move into re-usable fn - Maybe into `util-helpers`? const toBoolean = val => { if (typeof val === 'string') { switch (true) { case val.toLowerCase() === 'true': case val.toLowerCase() === 'on': case val.toLowerCase() === '1': return true; default: return false; } } return Boolean(val); }; const defaultOptions = { disabled: false }; const BooleanEditor = props => { const {value, label, commit, options, className} = props; const finalOptions = Object.assign({}, defaultOptions, options); const wrapperClassName = mergeClassNames({ [className]: true, [style.boolean__wrapper]: true }); const finalClassName = mergeClassNames({ [style.boolean__disabled]: finalOptions.disabled, [style.boolean__label]: true }); return ( <div className={wrapperClassName}> <Label className={finalClassName}> <CheckBox isChecked={toBoolean(value)} disabled={finalOptions.disabled} onChange={commit}/> <span> <I18n id={label}/> {props.renderHelpIcon ? props.renderHelpIcon() : ''} </span> </Label> </div> ); }; BooleanEditor.propTypes = { className: PropTypes.string, identifier: PropTypes.string.isRequired, label: PropTypes.string.isRequired, value: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]), commit: PropTypes.func.isRequired, renderHelpIcon: PropTypes.func, options: PropTypes.object }; export default BooleanEditor;
src/shared/Home/Home.js
kashisau/enroute
/** * Home.js * */ import React from 'react'; import ArticleHero from '../ArticleHero/ArticleHero'; import HeroPicker from '../HeroPicker/HeroPicker'; import classnames from 'classnames'; import './Home.scss'; class Home extends React.Component { constructor(props) { super(props); this.state = { active: false, activeArticle: 0, nextArticle: undefined, sliding: false }; this.changeArticle = this.changeArticle.bind(this); this.initHeroTransition = this.initHeroTransition.bind(this); } /** * Switches to the article indicated. * @param {Number} index The index of the article to switch to. */ changeArticle(index) { if (this.state.activeArticle === index) return; this.setState({ activeArticle: index, sliding: true }); } initHeroTransition(e) { if ( ! e.target.classList.contains("ArticleHero")) return; this.setState({ sliding: false }); } render() { var articles = this.props.articles; return <div className={ classnames( "Home", "Home-article-" + this.state.activeArticle, { "is-sliding" : this.state.sliding } ) } onTransitionEnd={this.initHeroTransition} ref={ homeContainer => this.homeContainer = homeContainer }> {articles.map((article, key) => <ArticleHero article={article} key={key} active={this.state.activeArticle === key} />)} <HeroPicker changeArticle={this.changeArticle} articles={articles} activeArticle={this.state.activeArticle} /> </div> } } export default Home;
app/javascript/mastodon/features/compose/index.js
tri-star/mastodon
import React from 'react'; import ComposeFormContainer from './containers/compose_form_container'; import NavigationContainer from './containers/navigation_container'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import { mountCompose, unmountCompose } from '../../actions/compose'; import { Link } from 'react-router-dom'; import { injectIntl, defineMessages } from 'react-intl'; import SearchContainer from './containers/search_container'; import Motion from '../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import SearchResultsContainer from './containers/search_results_container'; import { changeComposing } from '../../actions/compose'; import { openModal } from 'mastodon/actions/modal'; import elephantUIPlane from '../../../images/elephant_ui_plane.svg'; import { mascot } from '../../initial_state'; import Icon from 'mastodon/components/icon'; import { logOut } from 'mastodon/utils/log_out'; const messages = defineMessages({ start: { id: 'getting_started.heading', defaultMessage: 'Getting started' }, home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' }, notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' }, public: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' }, community: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, logout: { id: 'navigation_bar.logout', defaultMessage: 'Logout' }, compose: { id: 'navigation_bar.compose', defaultMessage: 'Compose new toot' }, logoutMessage: { id: 'confirmations.logout.message', defaultMessage: 'Are you sure you want to log out?' }, logoutConfirm: { id: 'confirmations.logout.confirm', defaultMessage: 'Log out' }, }); const mapStateToProps = (state, ownProps) => ({ columns: state.getIn(['settings', 'columns']), showSearch: ownProps.multiColumn ? state.getIn(['search', 'submitted']) && !state.getIn(['search', 'hidden']) : ownProps.isSearchPage, }); export default @connect(mapStateToProps) @injectIntl class Compose extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, columns: ImmutablePropTypes.list.isRequired, multiColumn: PropTypes.bool, showSearch: PropTypes.bool, isSearchPage: PropTypes.bool, intl: PropTypes.object.isRequired, }; componentDidMount () { const { isSearchPage } = this.props; if (!isSearchPage) { this.props.dispatch(mountCompose()); } } componentWillUnmount () { const { isSearchPage } = this.props; if (!isSearchPage) { this.props.dispatch(unmountCompose()); } } handleLogoutClick = e => { const { dispatch, intl } = this.props; e.preventDefault(); e.stopPropagation(); dispatch(openModal('CONFIRM', { message: intl.formatMessage(messages.logoutMessage), confirm: intl.formatMessage(messages.logoutConfirm), onConfirm: () => logOut(), })); return false; } onFocus = () => { this.props.dispatch(changeComposing(true)); } onBlur = () => { this.props.dispatch(changeComposing(false)); } render () { const { multiColumn, showSearch, isSearchPage, intl } = this.props; let header = ''; if (multiColumn) { const { columns } = this.props; header = ( <nav className='drawer__header'> <Link to='/getting-started' className='drawer__tab' title={intl.formatMessage(messages.start)} aria-label={intl.formatMessage(messages.start)}><Icon id='bars' fixedWidth /></Link> {!columns.some(column => column.get('id') === 'HOME') && ( <Link to='/timelines/home' className='drawer__tab' title={intl.formatMessage(messages.home_timeline)} aria-label={intl.formatMessage(messages.home_timeline)}><Icon id='home' fixedWidth /></Link> )} {!columns.some(column => column.get('id') === 'NOTIFICATIONS') && ( <Link to='/notifications' className='drawer__tab' title={intl.formatMessage(messages.notifications)} aria-label={intl.formatMessage(messages.notifications)}><Icon id='bell' fixedWidth /></Link> )} {!columns.some(column => column.get('id') === 'COMMUNITY') && ( <Link to='/timelines/public/local' className='drawer__tab' title={intl.formatMessage(messages.community)} aria-label={intl.formatMessage(messages.community)}><Icon id='users' fixedWidth /></Link> )} {!columns.some(column => column.get('id') === 'PUBLIC') && ( <Link to='/timelines/public' className='drawer__tab' title={intl.formatMessage(messages.public)} aria-label={intl.formatMessage(messages.public)}><Icon id='globe' fixedWidth /></Link> )} <a href='/settings/preferences' className='drawer__tab' title={intl.formatMessage(messages.preferences)} aria-label={intl.formatMessage(messages.preferences)}><Icon id='cog' fixedWidth /></a> <a href='/auth/sign_out' className='drawer__tab' title={intl.formatMessage(messages.logout)} aria-label={intl.formatMessage(messages.logout)} onClick={this.handleLogoutClick}><Icon id='sign-out' fixedWidth /></a> </nav> ); } return ( <div className='drawer' role='region' aria-label={intl.formatMessage(messages.compose)}> {header} {(multiColumn || isSearchPage) && <SearchContainer /> } <div className='drawer__pager'> {!isSearchPage && <div className='drawer__inner' onFocus={this.onFocus}> <NavigationContainer onClose={this.onBlur} /> <ComposeFormContainer /> <div className='drawer__inner__mastodon'> <img alt='' draggable='false' src={mascot || elephantUIPlane} /> </div> </div>} <Motion defaultStyle={{ x: isSearchPage ? 0 : -100 }} style={{ x: spring(showSearch || isSearchPage ? 0 : -100, { stiffness: 210, damping: 20 }) }}> {({ x }) => ( <div className='drawer__inner darker' style={{ transform: `translateX(${x}%)`, visibility: x === -100 ? 'hidden' : 'visible' }}> <SearchResultsContainer /> </div> )} </Motion> </div> </div> ); } }
docs/tutorial/DO_NOT_TOUCH/09/src/index.js
idream3/cerebral
import React from 'react' import {render} from 'react-dom' import {Controller} from 'cerebral' import App from './components/App' import {Container} from 'cerebral/react' import Devtools from 'cerebral/devtools' import HttpProvider from 'cerebral-provider-http' import {set, debounce} from 'cerebral/operators' import {state, input, string} from 'cerebral/tags' import starsSum from './computeds/starsSum' const toastDebounce = debounce.shared() function showToast (message, ms, type = null) { return [ set(state`toast`, {type}), set(state`toast.message`, message), toastDebounce(ms), { continue: [ set(state`toast`, null) ], discard: [] } ] } function getRepo (repoName) { function get ({http, path}) { return http.get(`/repos/cerebral/${repoName}`) .then(response => path.success({data: response.result})) .catch(error => path.error({data: error.result})) } return get } const controller = Controller({ devtools: Devtools(), state: { title: 'Hello from Cerebral!', subTitle: 'Working on my state management', toast: null, repos: {}, starsSum: 0 }, signals: { buttonClicked: [ [ ...showToast('Loading data for repos', 2000), getRepo('cerebral'), { success: [set(state`repos.cerebral`, input`data`)], error: [] }, getRepo('addressbar'), { success: [set(state`repos.addressbar`, input`data`)], error: [] } ], ...showToast(string`The repos has a total star count of ${starsSum}`, 4000, 'success') ] }, providers: [ HttpProvider({ baseUrl: 'https://api.github.com' }) ] }) render(( <Container controller={controller}> <App /> </Container> ), document.querySelector('#root'))
src/components/tooltips/Tooltips.js
metasfresh/metasfresh-webui-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; /** * @file Class based component. * @module Filters * @extends Component */ class Tooltips extends Component { constructor(props) { super(props); this.state = { opacity: 0, }; } /** * @method componentDidMount * @summary ToDo: Describe the method. */ componentDidMount() { const { delay } = this.props; this.timeout = setTimeout( () => { this.setState({ opacity: 1, }); }, delay ? delay : 1000 ); } /** * @method componentWillUnmount * @summary ToDo: Describe the method. */ componentWillUnmount() { clearTimeout(this.timeout); } /** * @method render * @summary ToDo: Describe the method. */ render() { const { name, action, type, extraClass, tooltipOnFirstlevelPositionLeft, className, } = this.props; const cx = classNames( 'tooltip-wrapp', { [`tooltip-${type}`]: type }, { [`${extraClass}`]: extraClass }, { [`${className}`]: className } ); const { opacity } = this.state; return ( <div style={{ opacity: opacity }}> <div className={cx} style={{ left: tooltipOnFirstlevelPositionLeft + 'px' }} > <div className="tooltip-shortcut">{name}</div> <div className="tooltip-name">{action}</div> </div> </div> ); } } /** * @typedef {object} Props Component props * @prop {*} action * @prop {*} className * @prop {*} delay * @prop {*} extraClass * @prop {*} name * @prop {*} tooltipOnFirstlevelPositionLeft * @prop {*} type */ Tooltips.propTypes = { action: PropTypes.any, className: PropTypes.any, delay: PropTypes.any, extraClass: PropTypes.any, name: PropTypes.any, tooltipOnFirstlevelPositionLeft: PropTypes.any, type: PropTypes.any, }; export default Tooltips;
client/src/containers/AssetAdmin/AssetAdminRouter.js
silverstripe/silverstripe-asset-admin
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import AssetAdmin from 'containers/AssetAdmin/AssetAdmin'; import { decodeQuery } from 'lib/DataFormat'; import qs from 'qs'; import CONSTANTS from 'constants/index'; import configShape from 'lib/configShape'; const sectionConfigKey = 'SilverStripe\\AssetAdmin\\Controller\\AssetAdmin'; const actions = Object.keys(CONSTANTS.ACTIONS).map((key) => CONSTANTS.ACTIONS[key]); /** * Build URL from raw components * * @param {String} base * @param {Number} folderId * @param {Number} fileId * @param {Object} query * @param {String} action * @return {String} */ function buildUrl({ base, folderId, fileId, query, action }) { if (action && actions.indexOf(action) === -1) { throw new Error(`Invalid action provided: ${action}`); } let url = null; if (fileId) { url = `${base}/show/${folderId}/${CONSTANTS.ACTIONS.EDIT_FILE}/${fileId}`; } else if (folderId) { url = `${base}/show/${folderId}`; } else { url = `${base}/`; } if (action === CONSTANTS.ACTIONS.CREATE_FOLDER) { url = `${base}/show/${folderId || 0}/${action}`; } const hasQuery = query && Object.keys(query).length > 0; if (hasQuery) { url = `${url}?${qs.stringify(query)}`; } return url; } class AssetAdminRouter extends Component { constructor(props) { super(props); this.handleBrowse = this.handleBrowse.bind(this); this.handleReplaceUrl = this.handleReplaceUrl.bind(this); this.getUrl = this.getUrl.bind(this); } /** * Generates the Url for a given folder and file ID. * * @param {Number} folderId * @param {Number} fileId * @param {Object} query * @param {String} action * @returns {String} */ getUrl(folderId = 0, fileId = null, query = {}, action = CONSTANTS.ACTIONS.EDIT_FILE) { const newFolderId = parseInt(folderId || 0, 10); const newFileId = parseInt(fileId || 0, 10); // Remove pagination selector if already on first page, or changing folder const hasFolderChanged = newFolderId !== this.getFolderId(); const newQuery = Object.assign({}, query); if (hasFolderChanged || newQuery.page <= 1) { delete newQuery.page; } return buildUrl({ base: `/${this.props.sectionConfig.url}`, folderId: newFolderId, fileId: newFileId, query: newQuery, action, }); } /** * @return {Number} Folder ID being viewed */ getFolderId() { if (this.props.match.params && this.props.match.params.folderId) { return parseInt(this.props.match.params.folderId, 10); } return 0; } /** * @return {Number} File ID being viewed */ getFileId() { if (this.props.match.params && this.props.match.params.fileId) { return parseInt(this.props.match.params.fileId, 10); } return 0; } getViewAction() { if (this.props.match.params && this.props.match.params.viewAction) { return this.props.match.params.viewAction; } return CONSTANTS.ACTIONS.EDIT_FILE; } /** * Generates the properties for this section * * @returns {object} */ getSectionProps() { return { sectionConfig: this.props.sectionConfig, type: 'admin', folderId: this.getFolderId(), viewAction: this.getViewAction(), fileId: this.getFileId(), query: this.getQuery(), getUrl: this.getUrl, onBrowse: this.handleBrowse, onReplaceUrl: this.handleReplaceUrl, }; } /** * Get decoded query object * * @returns {Object} */ getQuery() { return decodeQuery(this.props.location.search); } /** * Handle browsing with the router. * * @param {number} [folderId] * @param {number} [fileId] * @param {object} [query] * @param {string} [action] */ handleBrowse(folderId, fileId, query, action) { const pathname = this.getUrl(folderId, fileId, query, action); this.props.history.push(pathname); } /** * Handle browsing with the router but does not add to history, useful for * cases when the user is redirected to a correct url. * * @param {number} [folderId] * @param {number} [fileId] * @param {object} [query] * @param {string} [action] */ handleReplaceUrl(folderId, fileId, query, action) { const pathname = this.getUrl(folderId, fileId, query, action); this.props.history.replace(pathname); } render() { if (!this.props.sectionConfig) { return null; } return ( <AssetAdmin {...this.getSectionProps()} /> ); } } AssetAdminRouter.propTypes = { sectionConfig: configShape, location: PropTypes.shape({ pathname: PropTypes.string, query: PropTypes.object, search: PropTypes.string, }), params: PropTypes.object, router: PropTypes.object, }; function mapStateToProps(state) { const sectionConfig = state.config.sections.find((section) => section.name === sectionConfigKey); return { sectionConfig, }; } export { AssetAdminRouter as Component, buildUrl }; export default withRouter(connect(mapStateToProps)(AssetAdminRouter));
app/ecoModules/forms/static-input.js
aoshmyanskaya/tko
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; class StaticInput extends Component { render() { const formControl = <FormControl.Static> {this.props.value} </FormControl.Static>; return ( <FormGroup> <ControlLabel className={this.props.labelClass}>{this.props.label}</ControlLabel> {!this.props.horizontal && formControl} {this.props.horizontal && <div className={this.props.wrapClass}> {formControl} </div> } </FormGroup> ) } } StaticInput.defaultProps = { horizontal: false, }; StaticInput.propTypes = { horizontal: PropTypes.bool, wrapClass: PropTypes.string, labelClass: PropTypes.string, label: PropTypes.string, }; export default StaticInput;
src/router.js
mansters/fetch-request
import React from 'react'; import { Router, Route } from 'dva/router'; import IndexPage from './routes/IndexPage'; function RouterConfig ( { history } ) { return ( <Router history={ history }> <Route path="/" component={ IndexPage }/> </Router> ); } export default RouterConfig;
app/javascript/mastodon/components/avatar_overlay.js
alarky/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class AvatarOverlay extends React.PureComponent { static propTypes = { staticSrc: PropTypes.string.isRequired, overlaySrc: PropTypes.string.isRequired, }; render() { const { staticSrc, overlaySrc } = this.props; const baseStyle = { backgroundImage: `url(${staticSrc})`, }; const overlayStyle = { backgroundImage: `url(${overlaySrc})`, }; return ( <div className='account__avatar-overlay'> <div className='account__avatar-overlay-base' style={baseStyle} /> <div className='account__avatar-overlay-overlay' style={overlayStyle} /> </div> ); } }
stories/shared/Spinner.stories.js
buildkite/frontend
/* global module */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { boolean, number } from '@storybook/addon-knobs'; import Spinner from '../../app/components/shared/Spinner'; storiesOf('Spinner', module) .add('Standard', () => <Spinner color={boolean('Color', true)} size={number('Size', 20)} />) .add('Mono', () => <Spinner color={boolean('Color', false)} size={number('Size', 20)} />);
src/main.js
gravitron07/brentayersV6
/** * App entry point */ // Polyfill import 'babel-polyfill'; // Libraries import React from 'react'; import ReactDOM from 'react-dom'; import { Router, browserHistory } from 'react-router'; // Routes import Routes from './common/components/Routes'; // Base styling import './common/base.css'; // ID of the DOM element to mount app on const DOM_APP_EL_ID = 'app'; // Render the router ReactDOM.render(( <Router history={browserHistory}> {Routes} </Router> ), document.getElementById(DOM_APP_EL_ID));
src/mongostick/frontend/src/screens/Settings.js
RockingRolli/mongostick
import React from 'react' import { Menu, Icon, Row, Col } from 'antd' import { Link, Route, withRouter } from 'react-router-dom' import { TransitionGroup } from 'react-transition-group' import OperationSettings from './OperationSettings' import SettingsHome from './SettingsHome' class Settings extends React.Component { render() { const { location } = this.props; const currentPath = location.pathname return ( <Row gutter={16}> <Col xs={4}> <Menu mode="inline" defaultSelectedKeys={[currentPath]}> <Menu.Item key="/settings/operations"> <Link to="/settings/operations"><Icon type="rocket" /> Operations</Link> </Menu.Item> </Menu> </Col> <Col xs={20}> <Route render={({ location }) => ( <TransitionGroup> <Route key='settings_home' exact path='/settings' component={SettingsHome} /> <Route key='operations_settings' exact path='/settings/operations' component={OperationSettings} /> </TransitionGroup> )} /> </Col> </Row> ) } } export default withRouter(Settings)
src/index.js
panlw/react-lab
import './theme'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import App from './app/app'; import { configStore, getDevTools } from './lib/createStore'; const store = configStore(); const DevTools = getDevTools(); render( <Provider store={store}> <div> <App renderOnly /> <DevTools /> </div> </Provider>, document.getElementById('root') );
packages/material-ui-icons/src/SmokingRooms.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let SmokingRooms = props => <SvgIcon {...props}> <path d="M2 16h15v3H2zm18.5 0H22v3h-1.5zM18 16h1.5v3H18zm.85-8.27c.62-.61 1-1.45 1-2.38C19.85 3.5 18.35 2 16.5 2v1.5c1.02 0 1.85.83 1.85 1.85S17.52 7.2 16.5 7.2v1.5c2.24 0 4 1.83 4 4.07V15H22v-2.24c0-2.22-1.28-4.14-3.15-5.03zm-2.82 2.47H14.5c-1.02 0-1.85-.98-1.85-2s.83-1.75 1.85-1.75v-1.5c-1.85 0-3.35 1.5-3.35 3.35s1.5 3.35 3.35 3.35h1.53c1.05 0 1.97.74 1.97 2.05V15h1.5v-1.64c0-1.81-1.6-3.16-3.47-3.16z" /> </SvgIcon>; SmokingRooms = pure(SmokingRooms); SmokingRooms.muiName = 'SvgIcon'; export default SmokingRooms;